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