added IPNode for storing real IP's of users
[NeonServV5.git] / src / tools.c
1 /* tools.c - NeonServ v5.3
2  * Copyright (C) 2011-2012  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17 #include "tools.h"
18 #include "UserNode.h"
19 #include "ChanNode.h"
20 #include "lang.h"
21 #include "ClientSocket.h"
22 #include "IPNode.h"
23
24 static const struct default_language_entry msgtab[] = {
25     {"TIME_MASK_2_ITEMS", "%s and %s"}, /* {ARGS: "2 days", "1 hour"} */
26     {"TIME_MASK_3_ITEMS", "%s, %s and %s"}, /* {ARGS: "2 days", "1 hour", "20 minutes"} */
27     {"TIME_YEAR", "year"},
28     {"TIME_YEARS", "years"},
29     {"TIME_MONTH", "month"},
30     {"TIME_MONTHS", "months"},
31     {"TIME_WEEK", "week"},
32     {"TIME_WEEKS", "weeks"},
33     {"TIME_DAY", "day"},
34     {"TIME_DAYS", "days"},
35     {"TIME_HOUR", "hour"},
36     {"TIME_HOURS", "hours"},
37     {"TIME_MINUTE", "minute"},
38     {"TIME_MINUTES", "minutes"},
39     {"TIME_SECOND", "second"},
40     {"TIME_SECONDS", "seconds"},
41     {NULL, NULL}
42 };
43
44 /* copied from IRCU 2.10.12 match.c */
45 /*
46  * Compare if a given string (name) matches the given
47  * mask (which can contain wild cards: '*' - match any
48  * number of chars, '?' - match any single character.
49  *
50  * return  0, if match
51  *         1, if no match
52  *
53  *  Originally by Douglas A Lewis (dalewis@acsu.buffalo.edu)
54  *  Rewritten by Timothy Vogelsang (netski), net@astrolink.org
55  */
56 int match(const char *mask, const char *name)
57 {
58   const char *m = mask, *n = name;
59   const char *m_tmp = mask, *n_tmp = name;
60   int star_p;
61
62   for (;;) switch (*m) {
63   case '\0':
64     if (!*n)
65       return 0;
66   backtrack:
67     if (m_tmp == mask)
68       return 1;
69     m = m_tmp;
70     n = ++n_tmp;
71     if (*n == '\0')
72       return 1;
73     break;
74   case '\\':
75     m++;
76     /* allow escaping to force capitalization */
77     if (*m++ != *n++)
78       goto backtrack;
79     break;
80   case '*': case '?':
81     for (star_p = 0; ; m++) {
82       if (*m == '*')
83         star_p = 1;
84       else if (*m == '?') {
85         if (!*n++)
86           goto backtrack;
87       } else break;
88     }
89     if (star_p) {
90       if (!*m)
91         return 0;
92       else if (*m == '\\') {
93         m_tmp = ++m;
94         if (!*m)
95           return 1;
96         for (n_tmp = n; *n && *n != *m; n++) ;
97       } else {
98         m_tmp = m;
99         for (n_tmp = n; *n && tolower(*n) != tolower(*m); n++) ;
100       }
101     }
102     /* and fall through */
103   default:
104     if (!*n)
105       return *m != '\0';
106     if (tolower(*m) != tolower(*n))
107       goto backtrack;
108     m++;
109     n++;
110     break;
111   }
112 }
113
114
115 //TABLES
116 struct Table *table_init(int width, int length, int flags) {
117     int row;
118     struct Table *table = malloc(sizeof(*table));
119     table->contents = malloc(length * sizeof(*table->contents));
120     for(row = 0; row < length; row++) {
121         table->contents[row] = calloc(width, sizeof(*table->contents[row]));
122     }
123     table->length = length;
124     table->width = width;
125     table->flags = flags;
126     table->col_flags = calloc(width, sizeof(int));
127     table->entrys = 0;
128     table->maxwidth = calloc(width, sizeof(int));
129     table->table_lines = NULL;
130     return table;
131 }
132
133 int table_add(struct Table *table, char **entry) {
134     int col;
135     if(table->entrys == table->length) return 0;
136     for(col = 0; col < table->width; col++) {
137         table->contents[table->entrys][col] = ((table->flags & TABLE_FLAG_USE_POINTER) || !entry[col] ? entry[col] : strdup(entry[col]));
138         if(table->contents[table->entrys][col])
139             table->col_flags[col] |= TABLE_FLAG_COL_CONTENTS;
140         if(entry[col] && strlen(entry[col]) > table->maxwidth[col])
141             table->maxwidth[col] = strlen(entry[col]);
142     }
143     table->entrys++;
144     return 1;
145 }
146
147 int table_change(struct Table *table, int row, char **entry) {
148     int col;
149     if(row >= table->length) return 0;
150     for(col = 0; col < table->width; col++) {
151         if(table->contents[row][col] && !(table->flags & TABLE_FLAG_USE_POINTER))
152             free(table->contents[row][col]);
153         table->contents[row][col] = ((table->flags & TABLE_FLAG_USE_POINTER) || !entry[col] ? entry[col] : strdup(entry[col]));
154         if(table->contents[row][col])
155             table->col_flags[col] |= TABLE_FLAG_COL_CONTENTS;
156         if(entry[col] && strlen(entry[col]) > table->maxwidth[col])
157             table->maxwidth[col] = strlen(entry[col]);
158     }
159     return 1;
160 }
161
162 int table_change_field(struct Table *table, int row, int col, char *entry) {
163     if(row >= table->length) return 0;
164     if(col >= table->width) return 0;
165     if(table->contents[row][col] && !(table->flags & TABLE_FLAG_USE_POINTER))
166         free(table->contents[row][col]);
167     table->contents[row][col] = (((table->flags & TABLE_FLAG_USE_POINTER) || !entry) ? entry : strdup(entry));
168     if(table->contents[row][col])
169         table->col_flags[col] |= TABLE_FLAG_COL_CONTENTS;
170     if(entry && strlen(entry) > table->maxwidth[col])
171         table->maxwidth[col] = strlen(entry);
172     return 1;
173 }
174
175 int table_set_bold(struct Table *table, int collum, int bold) {
176     if(bold)
177         table->col_flags[collum] |= TABLE_FLAG_COL_BOLD;
178     else
179         table->col_flags[collum] &= ~TABLE_FLAG_COL_BOLD;
180     return 1;
181 }
182
183 char **table_end(struct Table *table) {
184     int row, col, tablewidth = 0, pos,i,j,k;
185     if(!table->entrys) return NULL;
186     for(col = 0; col < table->width; col++) {
187         tablewidth += table->maxwidth[col]+1;
188         if(table->col_flags[col] & TABLE_FLAG_COL_BOLD)
189             tablewidth += 2;
190     }
191     table->table_lines = malloc(table->entrys * sizeof(table->table_lines));
192     for(row = 0; row < table->entrys; row++) {
193         table->table_lines[row] = malloc(tablewidth * sizeof(*table->table_lines[row]));
194         pos = 0;
195         for(col = 0; col < table->width; col++) {
196             if(!(table->col_flags[col] & TABLE_FLAG_COL_CONTENTS)) continue;
197             if(table->col_flags[col] & TABLE_FLAG_COL_BOLD)
198                 table->table_lines[row][pos++] = '\002';
199             i = 0;
200             j = 0;
201             if(table->contents[row][col]) {
202                 for(; i < strlen(table->contents[row][col]); i++) {
203                     table->table_lines[row][pos++] = table->contents[row][col][i];
204                     if(table->contents[row][col][i] == '\002') j++;
205                     else if(table->contents[row][col][i] == '\003') {
206                         j++;
207                         for(k = 1; k < 2; k++) {
208                             if(isdigit(table->contents[row][col][i+k]))
209                                 j++;
210                             else 
211                                 break;
212                         }
213                     }
214                 }
215             }
216             i -= j;
217             if(col < table->width-1) {
218                 for(;i < table->maxwidth[col]; i++) {
219                     table->table_lines[row][pos++] = ' ';
220                 }
221                 table->table_lines[row][pos++] = ' ';
222             } else
223                 table->table_lines[row][pos++] = '\0';
224             
225             if(table->col_flags[col] & TABLE_FLAG_COL_BOLD)
226                 table->table_lines[row][pos++] = '\002';
227         }
228     }
229     return table->table_lines;
230 }
231
232 void table_free(struct Table *table) {
233     int row, col;
234     for(row = 0; row < table->length; row++) {
235         if(!(table->flags & TABLE_FLAG_USE_POINTER) && table->entrys > row) {
236             for(col = 0; col < table->width; col++) {
237                 if(table->contents[row][col])
238                     free(table->contents[row][col]);
239             }
240         }
241         free(table->contents[row]);
242     }
243     free(table->contents);
244     free(table->col_flags);
245     free(table->maxwidth);
246     if(table->table_lines) {
247         for(row = 0; row < table->entrys; row++) {
248             free(table->table_lines[row]);
249         }
250         free(table->table_lines);
251     }
252     free(table);
253 }
254
255 char* timeToStr(struct UserNode *user, int seconds, int items, char *buf) {
256     char item[items][MAXLEN];
257     int tmp, citem = 0;
258     if(citem != items && seconds >= 31536000) { //60*60*24*365 = 31536000
259         
260         tmp = seconds / 31536000;
261         sprintf(item[citem++], "%d %s", tmp, get_language_string(user, tmp == 1 ? "TIME_YEAR" : "TIME_YEARS"));
262         seconds -= tmp * 31536000;
263     }
264     if(citem != items && seconds >= 86400) { //60*60*24 = 86400
265         tmp = seconds / 86400;
266         sprintf(item[citem++], "%d %s", tmp, get_language_string(user, tmp == 1 ? "TIME_DAY" : "TIME_DAYS"));
267         seconds -= tmp * 86400;
268     }
269     if(citem != items && seconds >= 3600) { //60*60 = 3600
270         tmp = seconds / 3600;
271         sprintf(item[citem++], "%d %s", tmp, get_language_string(user, tmp == 1 ? "TIME_HOUR" : "TIME_HOURS"));
272         seconds -= tmp * 3600;
273     }
274     if(citem != items && seconds >= 60) {
275         tmp = seconds / 60;
276         sprintf(item[citem++], "%d %s", tmp, get_language_string(user, tmp == 1 ? "TIME_MINUTE" : "TIME_MINUTES"));
277         seconds -= tmp * 60;
278     }
279     if(citem != items && seconds >= 1) {
280         sprintf(item[citem++], "%d %s", seconds, get_language_string(user, seconds == 1 ? "TIME_SECOND" : "TIME_SECONDS"));
281     }
282     if(citem == 2) {
283         build_language_string(user, buf, "TIME_MASK_2_ITEMS", item[0], item[1]);
284     } else if(citem == 3) {
285         build_language_string(user, buf, "TIME_MASK_3_ITEMS", item[0], item[1], item[2]);
286     } else {
287         int i, ii, p = 0;
288         for(i = 0; i < citem; i++) {
289             for(ii = 0; ii < strlen(item[i]); ii++) {
290                 buf[p++] = item[i][ii];
291             }
292             buf[p++] = ' ';
293         }
294         buf[(p ? p-1 : 0)] = '\0';
295     }
296     return buf;
297 }
298
299 int strToTime(struct UserNode *user, char *str) {
300     /*
301     * y = year = 365 days
302     * M = month = 30 days
303     * w = week = 7 days
304     * d = day
305     * h = hour
306     * m = minute
307     * (s) = second
308     */
309     int total_time = 0, cvalue;
310     char *p, tmpchar;
311     int unit_multiplikator;
312     while(*str) {
313         p = str;
314         while(*p && !isdigit(*p)) //skip leading chars
315             p++;
316         str = p;
317         while(*p && isdigit(*p)) //get the value
318             p++;
319         tmpchar = *p;
320         *p = '\0';
321         cvalue = isdigit(*str) ? atoi(str) : 0;
322         *p = tmpchar;
323         while(*p == ' ') //skip spaces
324             p++;
325         str = p;
326         while(*p && !isdigit(*p)) //get the unit
327             p++;
328         tmpchar = *p;
329         *p = '\0';
330         if(p - str > 1) { //unit has more than one char
331             if(!stricmp(str, "year") || !stricmp(str, "year") || !stricmp(str, get_language_string(user, "TIME_YEAR")) || !stricmp(str, get_language_string(user, "TIME_YEARS")))
332                 unit_multiplikator = 31536000; //60*60*24*365 = 31536000
333             else if(!stricmp(str, "month") || !stricmp(str, "months") || !stricmp(str, get_language_string(user, "TIME_MONTH")) || !stricmp(str, get_language_string(user, "TIME_MONTHS")))
334                 unit_multiplikator = 2592000; //60*60*24*30 = 2592000
335             else if(!stricmp(str, "week") || !stricmp(str, "weeks") || !stricmp(str, get_language_string(user, "TIME_WEEK")) || !stricmp(str, get_language_string(user, "TIME_WEEKS")))
336                 unit_multiplikator = 604800; //60*60*24*7 = 604800
337             else if(!stricmp(str, "day") || !stricmp(str, "days") || !stricmp(str, get_language_string(user, "TIME_DAY")) || !stricmp(str, get_language_string(user, "TIME_DAYS")))
338                 unit_multiplikator = 86400; //60*60*24 = 86400
339             else if(!stricmp(str, "hour") || !stricmp(str, "hours") || !stricmp(str, get_language_string(user, "TIME_HOUR")) || !stricmp(str, get_language_string(user, "TIME_HOURS")))
340                 unit_multiplikator = 3600; //60*60 = 3600
341             else if(!stricmp(str, "minute") || !stricmp(str, "minutes") || !stricmp(str, "min") || !stricmp(str, "mins") || !stricmp(str, get_language_string(user, "TIME_MINUTE")) || !stricmp(str, get_language_string(user, "TIME_MINUTES")))
342                 unit_multiplikator = 60;
343             else
344                 unit_multiplikator = 1;
345         } else {
346             switch(*str) {
347                 case 'y':
348                     unit_multiplikator = 31536000; //60*60*24*365 = 31536000
349                     break;
350                 case 'M':
351                     unit_multiplikator = 2592000; //60*60*24*30 = 2592000
352                     break;
353                 case 'w':
354                     unit_multiplikator = 604800; //60*60*24*7 = 604800
355                     break;
356                 case 'd':
357                     unit_multiplikator = 86400; //60*60*24 = 86400
358                     break;
359                 case 'h':
360                     unit_multiplikator = 3600; //60*60 = 3600
361                     break;
362                 case 'm':
363                     unit_multiplikator = 60;
364                     break;
365                 default:
366                     unit_multiplikator = 1;
367                     break;
368             }
369         }
370         total_time += (cvalue * unit_multiplikator);
371         *p = tmpchar;
372         str = p;
373     }
374     return total_time;
375 }
376
377 struct ModeBuffer* initModeBuffer(struct ClientSocket *client, struct ChanNode *chan) {
378     struct ModeBuffer *modeBuf = malloc(sizeof(*modeBuf));
379     if(!modeBuf) {
380         perror("malloc() failed");
381         return NULL;
382     }
383     modeBuf->client = client;
384     modeBuf->chan = chan;
385     modeBuf->addCount = 0;
386     modeBuf->delCount = 0;
387     return modeBuf;
388 }
389
390 void modeBufferSet(struct ModeBuffer *modeBuf, int add, char mode, char *param) {
391     if(add) {
392         modeBuf->addModes[modeBuf->addCount] = mode;
393         modeBuf->addModesParams[modeBuf->addCount] = (param ? strdup(param) : NULL);
394         modeBuf->addCount++;
395         modeBuf->addModes[modeBuf->addCount] = '\0';
396     } else {
397         modeBuf->delModes[modeBuf->delCount] = mode;
398         modeBuf->delModesParams[modeBuf->delCount] = (param ? strdup(param) : NULL);
399         modeBuf->delCount++;
400         modeBuf->delModes[modeBuf->delCount] = '\0';
401     }
402     if(modeBuf->addCount + modeBuf->delCount == MAXMODES)
403         flushModeBuffer(modeBuf);
404 }
405
406 void flushModeBuffer(struct ModeBuffer *modeBuf) {
407     char modeStr[MAXMODES+3];
408     int modePos = 0;
409     char paramStr[MAXLEN];
410     *paramStr = '\0';
411     int paramPos = 0;
412     int i;
413     if(modeBuf->addCount) {
414         modeStr[modePos++] = '+';
415         for(i = 0; i < modeBuf->addCount; i++) {
416             modeStr[modePos++] = modeBuf->addModes[i];
417             if(modeBuf->addModesParams[i]) {
418                 paramPos += sprintf(paramStr + paramPos, " %s", modeBuf->addModesParams[i]);
419             }
420         }
421         modeBuf->addCount = 0;
422     }
423     if(modeBuf->delCount) {
424         modeStr[modePos++] = '-';
425         for(i = 0; i < modeBuf->delCount; i++) {
426             modeStr[modePos++] = modeBuf->delModes[i];
427             if(modeBuf->delModesParams[i]) {
428                 paramPos += sprintf(paramStr + paramPos, " %s", modeBuf->delModesParams[i]);
429             }
430         }
431         modeBuf->delCount = 0;
432     }
433     modeStr[modePos++] = '\0';
434     putsock(modeBuf->client, "MODE %s %s%s", modeBuf->chan->name, modeStr, paramStr);
435 }
436
437 void freeModeBuffer(struct ModeBuffer *modeBuf) {
438     if(modeBuf->addCount + modeBuf->delCount)
439         flushModeBuffer(modeBuf);
440     free(modeBuf);
441 }
442
443 int is_ircmask(const char *text) {
444     while (*text && (isalnum((char)*text) || strchr("-_[]|\\`^{}?*", *text)))
445         text++;
446     if (*text++ != '!')
447         return 0;
448     while (*text && *text != '@' && !isspace((char)*text))
449         text++;
450     if (*text++ != '@')
451         return 0;
452     while (*text && !isspace((char)*text))
453         text++;
454     return !*text;
455 }
456
457 char* generate_banmask(struct UserNode *user, char *buffer) {
458     char *userhost = user->host;
459     
460     if(isFakeHost(user->host)) {
461         sprintf(buffer, "*!*@%s", userhost);
462         return buffer;
463     }
464     
465     //check if the hostname has more than 4 connections (trusted host)
466     if(countUsersWithHost(userhost) > 4) {
467         sprintf(buffer, "*!%s@%s", user->ident, userhost);
468         return buffer;
469     } else {
470         sprintf(buffer, "*!*@%s", userhost);
471         return buffer;
472     }
473 }
474
475 char* make_banmask(char *input, char* buffer) {
476     char *nick = NULL, *ident = NULL, *host = NULL;
477     char tmp[HOSTLEN];
478     char *p;
479     if((p = strstr(input, "!"))) {
480         nick = input;
481         *p = '\0';
482         ident = p+1;
483         if((p = strstr(ident, "@"))) {
484             *p = '\0';
485             host = p+1;
486         }
487     } else if((p = strstr(input, "@"))) {
488         ident = input;
489         *p = '\0';
490         host = p+1;
491     } else if((p = strstr(input, ".")) || (p = strstr(input, ":"))) {
492         host = input;
493     } else if(*input == '*' && input[1] != '\0' && !strstr(input+1, "*")) {
494         //AUTH MASK
495         p = getAuthFakehost(input+1);
496         if(p)
497             host = p;
498         else {
499             sprintf(tmp, "%s.*", input+1);
500             host = tmp;
501         }
502     } else {
503         struct UserNode *user = searchUserByNick(input);
504         if(user)
505             return generate_banmask(user, buffer);
506         else
507             nick = input;
508     }
509     if(nick && *nick == '\0') nick = NULL;
510     if(ident && *ident == '\0') ident = NULL;
511     if(host && *host == '\0') host = NULL;
512     sprintf(buffer, "%s!%s@%s", (nick ? nick : "*"), (ident ? ident : "*"), (host ? host : "*"));
513     return buffer;
514 }
515
516 int isFakeHost(char *host) {
517     char *p1, *p2 = host;
518     
519     //find the last dot to identify if the hostmask is a fake host
520     while((p1 = strstr(p2, "."))) {
521         p2 = p1 + 1;
522     }
523     //TLD database: http://www.iana.org/domains/root/db/
524     //the longest TLD i found was 6 chars long (ignoring the stange exotic ones :D)
525     //but we even ignore '.museum' and '.travel' so we can say that the TLD of our mask needs to be less than 4 chars to be a real domain
526     return (strlen(p2+1) > 4);
527 }
528
529 int mask_match(char *mask, struct UserNode *user) {
530     char usermask[NICKLEN+USERLEN+HOSTLEN+3];
531     char matchmask[strlen(mask)+3];
532     strcpy(matchmask, mask);
533     char *host = strchr(mask, '@');
534     if(host) {
535         struct IPNode *ip = createIPNode(host);
536         int bits = (ip->flags & IPNODE_IS_IPV6 ? 128 : 32);
537         if((host = strchr(host, '/'))) {
538             bits = atoi(host+1);
539         }
540         if(ip && user->ip&& !ipmatch(user->ip, ip, bits)) {
541             host[1] = '*';
542             host[2] = '\0';
543         }
544     }
545     sprintf(usermask, "%s!%s@%s", user->nick, user->ident, user->host);
546     return match(matchmask, usermask);
547 }
548
549 static unsigned long crc_table[256];
550
551 static void crc32_init() {
552     unsigned long crc;
553     int i, j;
554     for(i = 0; i < 256; i++) {
555         crc = i;
556         for(j = 8; j > 0; j--) {
557             if(crc & 1)
558                                 crc = (crc >> 1) ^ 0xEDB88320L;
559             else
560                 crc >>= 1;
561         }
562         crc_table[i] = crc;
563     }
564 }
565
566 unsigned long crc32(const char *text) {
567     register unsigned long crc = 0xFFFFFFFF;
568     unsigned int c, i = 0;
569     while((c = (unsigned int)text[i++]) != 0)
570         crc = ((crc >> 8) & 0x00FFFFFF) ^ crc_table[(crc^c) & 0xFF];
571     return (crc^0xFFFFFFFF);
572 }
573
574 void init_tools() {
575     register_default_language_table(msgtab);
576     crc32_init();
577 }