Merge branch 'HostServ' of ssh://git.pk910.de:16110/srvx into HostServ
[srvx.git] / src / tools.c
1 /* tools.c - miscellaneous utility functions
2  * Copyright 2000-2004 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "helpfile.h"
22 #include "log.h"
23 #include "nickserv.h"
24 #include "recdb.h"
25
26 #ifdef HAVE_NETDB_H
27 #include <netdb.h>
28 #endif
29 #ifdef HAVE_SYS_SOCKET_H
30 #include <sys/socket.h>
31 #endif
32 #ifdef HAVE_ARPA_INET_H
33 #include <arpa/inet.h>
34 #endif
35
36 #define NUMNICKLOG 6
37 #define NUMNICKBASE (1 << NUMNICKLOG)
38 #define NUMNICKMASK (NUMNICKBASE - 1)
39
40 /* Yes, P10's encoding here is almost-but-not-quite MIME Base64.  Yay
41  * for gratuitous incompatibilities. */
42 static const char convert2y[256] = {
43   'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
44   'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
45   'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
46   'w','x','y','z','0','1','2','3','4','5','6','7','8','9','[',']'
47 };
48
49 static const unsigned char convert2n[256] = {
50    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
51    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
52    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
53   52,53,54,55,56,57,58,59,60,61, 0, 0, 0, 0, 0, 0,
54    0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
55   15,16,17,18,19,20,21,22,23,24,25,62, 0,63, 0, 0,
56    0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
57   41,42,43,44,45,46,47,48,49,50,51, 0, 0, 0, 0, 0
58 };
59
60 static const unsigned char ctype[256] = {
61    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
62    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
63    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
64    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0,
65    0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
66    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
67    0,10,11,12,13,14,15, 0, 0, 0, 0, 0, 0, 0, 0, 0,
68 };
69
70 unsigned long int
71 base64toint(const char* s, int count)
72 {
73     unsigned int i = 0;
74     while (*s && count) {
75         i = (i << NUMNICKLOG) + convert2n[(unsigned char)*s++];
76         count--;
77     }
78     return i;
79 }
80
81 const char* inttobase64(char* buf, unsigned int v, unsigned int count)
82 {
83   buf[count] = '\0';
84   while (count > 0) {
85       buf[--count] = convert2y[(unsigned char)(v & NUMNICKMASK)];
86       v >>= NUMNICKLOG;
87   }
88   return buf;
89 }
90
91 unsigned int
92 irc_ntop(char *output, unsigned int out_size, const irc_in_addr_t *addr)
93 {
94     static const char hexdigits[] = "0123456789abcdef";
95     unsigned int pos;
96
97     assert(output);
98     assert(addr);
99
100     if (irc_in_addr_is_ipv4(*addr)) {
101         unsigned int ip4;
102
103         ip4 = (ntohs(addr->in6[6]) << 16) | ntohs(addr->in6[7]);
104         pos = snprintf(output, out_size, "%u.%u.%u.%u", (ip4 >> 24), (ip4 >> 16) & 255, (ip4 >> 8) & 255, ip4 & 255);
105    } else {
106         unsigned int part, max_start, max_zeros, curr_zeros, ii;
107
108         /* Find longest run of zeros. */
109         for (max_start = max_zeros = curr_zeros = ii = 0; ii < 8; ++ii) {
110             if (!addr->in6[ii])
111                 curr_zeros++;
112             else if (curr_zeros > max_zeros) {
113                 max_start = ii - curr_zeros;
114                 max_zeros = curr_zeros;
115                 curr_zeros = 0;
116             }
117         }
118         if (curr_zeros > max_zeros) {
119             max_start = ii - curr_zeros;
120             max_zeros = curr_zeros;
121         }
122
123         /* Print out address. */
124 #define APPEND(CH) do { if (pos < out_size) output[pos] = (CH); pos++; } while (0)
125         for (pos = 0, ii = 0; ii < 8; ++ii) {
126             if ((max_zeros > 0) && (ii == max_start)) {
127                 if (ii == 0)
128                     APPEND(':');
129                 APPEND(':');
130                 ii += max_zeros - 1;
131                 continue;
132             }
133             part = ntohs(addr->in6[ii]);
134             if (part >= 0x1000)
135                 APPEND(hexdigits[part >> 12]);
136             if (part >= 0x100)
137                 APPEND(hexdigits[(part >> 8) & 15]);
138             if (part >= 0x10)
139                 APPEND(hexdigits[(part >> 4) & 15]);
140             APPEND(hexdigits[part & 15]);
141             if (ii < 7)
142                 APPEND(':');
143         }
144 #undef APPEND
145         output[pos < out_size ? pos : out_size - 1] = '\0';
146     }
147
148     return pos;
149 }
150
151 unsigned int
152 irc_ntop_mask(char *output, unsigned int out_size, const irc_in_addr_t *addr, unsigned char bits)
153 {
154     char base_addr[IRC_NTOP_MAX_SIZE];
155     int len;
156
157     if (bits >= 128)
158         return irc_ntop(output, out_size, addr);
159     if (!irc_ntop(base_addr, sizeof(base_addr), addr))
160         return 0;
161     len = snprintf(output, out_size, "%s/%d", base_addr, bits);
162     if ((unsigned int)len >= out_size)
163         return 0;
164     return len;
165 }
166
167 static unsigned int
168 irc_pton_ip4(const char *input, unsigned char *pbits, uint32_t *output)
169 {
170     unsigned int dots = 0, pos = 0, part = 0, ip = 0, bits = 32;
171
172     /* Intentionally no support for bizarre IPv4 formats (plain
173      * integers, octal or hex components) -- only vanilla dotted
174      * decimal quads, optionally with trailing /nn.
175      */
176     if (input[0] == '.')
177         return 0;
178     while (1) switch (input[pos]) {
179     default:
180         if (dots < 3)
181             return 0;
182     out:
183         ip |= part << (24 - 8 * dots++);
184         *output = htonl(ip);
185         if (pbits)
186             *pbits = bits;
187         return pos;
188     case '.':
189         if (input[++pos] == '.')
190             return 0;
191         ip |= part << (24 - 8 * dots++);
192         part = 0;
193         if (input[pos] == '*') {
194             while (input[++pos] == '*') ;
195             if (input[pos] != '\0')
196                 return 0;
197             if (pbits)
198                 *pbits = dots * 8;
199             *output = htonl(ip);
200             return pos;
201         }
202         break;
203     case '/':
204         if (!pbits || !isdigit(input[pos + 1]))
205             return 0;
206         for (bits = 0; isdigit(input[++pos]); )
207             bits = bits * 10 + input[pos] - '0';
208         if (bits > 32)
209             return 0;
210         goto out;
211     case '0': case '1': case '2': case '3': case '4':
212     case '5': case '6': case '7': case '8': case '9':
213         part = part * 10 + input[pos++] - '0';
214         if (part > 255)
215             return 0;
216         break;
217     }
218 }
219
220 unsigned int
221 irc_pton(irc_in_addr_t *addr, unsigned char *bits, const char *input)
222 {
223     const char *part_start = NULL;
224     char *colon;
225     char *dot;
226     unsigned int part = 0, pos = 0, ii = 0, cpos = 8;
227
228     assert(input);
229     memset(addr, 0, sizeof(*addr));
230     colon = strchr(input, ':');
231     dot = strchr(input, '.');
232
233     if (colon && (!dot || (dot > colon))) {
234         /* Parse IPv6, possibly like ::127.0.0.1.
235          * This is pretty straightforward; the only trick is borrowed
236          * from Paul Vixie (BIND): when it sees a "::" continue as if
237          * it were a single ":", but note where it happened, and fill
238          * with zeros afterwards.
239          */
240         if (input[pos] == ':') {
241             if ((input[pos+1] != ':') || (input[pos+2] == ':'))
242                 return 0;
243             cpos = 0;
244             pos += 2;
245             part_start = input + pos;
246         }
247         while (ii < 8) switch (input[pos]) {
248         case '0': case '1': case '2': case '3': case '4':
249         case '5': case '6': case '7': case '8': case '9':
250         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
251         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
252             part = (part << 4) | (ctype[(unsigned char)input[pos++]] & 15);
253             if (part > 0xffff)
254                 return 0;
255             break;
256         case ':':
257             part_start = input + ++pos;
258             if (input[pos] == '.')
259                 return 0;
260             addr->in6[ii++] = htons(part);
261             part = 0;
262             if (input[pos] == ':') {
263                 if (cpos < 8)
264                     return 0;
265                 cpos = ii;
266             }
267             break;
268         case '.': {
269             uint32_t ip4;
270             unsigned int len;
271             len = irc_pton_ip4(part_start, bits, &ip4);
272             if (!len || (ii > 6))
273                 return 0;
274             memcpy(addr->in6 + ii, &ip4, sizeof(ip4));
275             if (bits)
276                 *bits += 96;
277             ii += 2;
278             pos = part_start + len - input;
279             goto finish;
280         }
281         case '/':
282             if (!bits || !isdigit(input[pos + 1]))
283                 return 0;
284             addr->in6[ii++] = htons(part);
285             for (part = 0; isdigit(input[++pos]); )
286                 part = part * 10 + input[pos] - '0';
287             if (part > 128)
288                 return 0;
289             *bits = part;
290             goto finish;
291         case '*':
292             while (input[++pos] == '*') ;
293             if (input[pos] != '\0' || cpos < 8)
294                 return 0;
295             if (bits)
296                 *bits = ii * 16;
297             return pos;
298         default:
299             addr->in6[ii++] = htons(part);
300             if (cpos == 8 && ii < 8)
301                 return 0;
302             if (bits)
303                 *bits = 128;
304             goto finish;
305         }
306     finish:
307         /* Shift stuff after "::" up and fill middle with zeros. */
308         if (cpos < 8) {
309             unsigned int jj;
310             for (jj = 0; jj < ii - cpos; jj++)
311                 addr->in6[7 - jj] = addr->in6[ii - jj - 1];
312             for (jj = 0; jj < 8 - ii; jj++)
313                 addr->in6[cpos + jj] = 0;
314         }
315     } else if (dot) {
316         uint32_t ip4;
317         pos = irc_pton_ip4(input, bits, &ip4);
318         if (pos) {
319 /* glibc's htons() macro is not -Wshadow-safe. */
320 #undef htons
321             addr->in6[5] = htons(65535);
322             addr->in6[6] = htons(ntohl(ip4) >> 16);
323             addr->in6[7] = htons(ntohl(ip4) & 65535);
324             if (bits)
325                 *bits += 96;
326         }
327     } else if (input[0] == '*') {
328         while (input[++pos] == '*') ;
329         if (input[pos] != '\0')
330             return 0;
331         if (bits)
332             *bits = 0;
333     }
334     return pos;
335 }
336
337 const char *irc_ntoa(const irc_in_addr_t *addr)
338 {
339     static char ntoa[IRC_NTOP_MAX_SIZE];
340     irc_ntop(ntoa, sizeof(ntoa), addr);
341     return ntoa;
342 }
343
344 unsigned int
345 irc_check_mask(const irc_in_addr_t *check, const irc_in_addr_t *mask, unsigned char bits)
346 {
347     unsigned int ii;
348
349     for (ii = 0; (ii < 8) && (bits > 16); bits -= 16, ++ii)
350         if (check->in6[ii] != mask->in6[ii])
351             return 0;
352     if (ii < 8 && bits > 0
353         && (ntohs(check->in6[ii] ^ mask->in6[ii]) >> (16 - bits)))
354         return 0;
355     return 1;
356 }
357
358 static char irc_tolower[256];
359 #undef tolower
360 #define tolower(X) irc_tolower[(unsigned char)(X)]
361
362 int
363 irccasecmp(const char *stra, const char *strb) {
364     while (*stra && (tolower(*stra) == tolower(*strb)))
365         stra++, strb++;
366     return tolower(*stra) - tolower(*strb);
367 }
368
369 int
370 ircncasecmp(const char *stra, const char *strb, unsigned int len) {
371     len--;
372     while (*stra && (tolower(*stra) == tolower(*strb)) && len)
373         stra++, strb++, len--;
374     return tolower(*stra) - tolower(*strb);
375 }
376
377 const char *
378 irccasestr(const char *haystack, const char *needle) {
379     unsigned int hay_len = strlen(haystack), needle_len = strlen(needle), pos;
380     if (hay_len < needle_len)
381         return NULL;
382     for (pos=0; pos<hay_len+1-needle_len; ++pos) {
383         if ((tolower(haystack[pos]) == tolower(*needle))
384             && !ircncasecmp(haystack+pos, needle, needle_len))
385             return haystack+pos;
386     }
387     return NULL;
388 }
389
390 char *
391 ircstrlower(char *str) {
392     size_t ii;
393     for (ii = 0; str[ii] != '\0'; ++ii)
394         str[ii] = tolower(str[ii]);
395     return str;
396 }
397
398 int
399 split_line(char *line, int irc_colon, int argv_size, char *argv[])
400 {
401     int argc = 0;
402     int n;
403     while (*line && (argc < argv_size)) {
404         while (*line == ' ')
405             *line++ = 0;
406         if (*line == ':' && irc_colon && argc > 0) {
407             /* the rest is a single parameter */
408             argv[argc++] = line + 1;
409             break;
410         }
411         if (!*line)
412             break;
413         argv[argc++] = line;
414         if (argc >= argv_size)
415             break;
416         while (*line != ' ' && *line)
417             line++;
418     }
419 #ifdef NDEBUG
420     n = 0;
421 #else
422     for (n=argc; n<argv_size; n++)
423         argv[n] = (char*)0xFEEDBEEF;
424 #endif
425     return argc;
426 }
427
428 /* This is ircu's mmatch() function, from match.c. */
429 int mmatch(const char *old_mask, const char *new_mask)
430 {
431   register const char *m = old_mask;
432   register const char *n = new_mask;
433   const char *ma = m;
434   const char *na = n;
435   int wild = 0;
436   int mq = 0, nq = 0;
437
438   while (1)
439   {
440     if (*m == '*')
441     {
442       while (*m == '*')
443         m++;
444       wild = 1;
445       ma = m;
446       na = n;
447     }
448
449     if (!*m)
450     {
451       if (!*n)
452         return 0;
453       for (m--; (m > old_mask) && (*m == '?'); m--)
454         ;
455       if ((*m == '*') && (m > old_mask) && (m[-1] != '\\'))
456         return 0;
457       if (!wild)
458         return 1;
459       m = ma;
460
461       /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
462       if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
463         ++na;
464
465       n = ++na;
466     }
467     else if (!*n)
468     {
469       while (*m == '*')
470         m++;
471       return (*m != 0);
472     }
473     if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?')))
474     {
475       m++;
476       mq = 1;
477     }
478     else
479       mq = 0;
480
481     /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
482     if ((*n == '\\') && ((n[1] == '*') || (n[1] == '?')))
483     {
484       n++;
485       nq = 1;
486     }
487     else
488       nq = 0;
489
490 /*
491  * This `if' has been changed compared to match() to do the following:
492  * Match when:
493  *   old (m)         new (n)         boolean expression
494  *    *               any             (*m == '*' && !mq) ||
495  *    ?               any except '*'  (*m == '?' && !mq && (*n != '*' || nq)) ||
496  * any except * or ?  same as m       (!((*m == '*' || *m == '?') && !mq) &&
497  *                                      toLower(*m) == toLower(*n) &&
498  *                                        !((mq && !nq) || (!mq && nq)))
499  *
500  * Here `any' also includes \* and \? !
501  *
502  * After reworking the boolean expressions, we get:
503  * (Optimized to use boolean shortcircuits, with most frequently occuring
504  *  cases upfront (which took 2 hours!)).
505  */
506     if ((*m == '*' && !mq) ||
507         ((!mq || nq) && tolower(*m) == tolower(*n)) ||
508         (*m == '?' && !mq && (*n != '*' || nq)))
509     {
510       if (*m)
511         m++;
512       if (*n)
513         n++;
514     }
515     else
516     {
517       if (!wild)
518         return 1;
519       m = ma;
520
521       /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
522       if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
523         ++na;
524
525       n = ++na;
526     }
527   }
528 }
529
530 int
531 match_ircglob(const char *text, const char *glob)
532 {
533     const char *m = glob, *n = text;
534     const char *m_tmp = glob, *n_tmp = text;
535     int star_p;
536
537     for (;;) switch (*m) {
538     case '\0':
539         if (!*n)
540             return 1;
541     backtrack:
542         if (m_tmp == glob)
543             return 0;
544         m = m_tmp;
545         n = ++n_tmp;
546         if (!*n)
547             return 0;
548         break;
549     case '\\':
550         m++;
551         /* allow escaping to force capitalization */
552         if (*m++ != *n++)
553             goto backtrack;
554         break;
555     case '*': case '?':
556         for (star_p = 0; ; m++) {
557             if (*m == '*')
558                 star_p = 1;
559             else if (*m == '?') {
560                 if (!*n++)
561                     goto backtrack;
562             } else break;
563         }
564         if (star_p) {
565             if (!*m)
566                 return 1;
567             else if (*m == '\\') {
568                 m_tmp = ++m;
569                 if (!*m)
570                     return 0;
571                 for (n_tmp = n; *n && *n != *m; n++) ;
572             } else {
573                 m_tmp = m;
574                 for (n_tmp = n; *n && tolower(*n) != tolower(*m); n++) ;
575             }
576         }
577         /* and fall through */
578     default:
579         if (!*n)
580             return *m == '\0';
581         if (tolower(*m) != tolower(*n))
582             goto backtrack;
583         m++;
584         n++;
585         break;
586     }
587 }
588
589 extern const char *hidden_host_suffix;
590
591 int
592 user_matches_glob(struct userNode *user, const char *orig_glob, int flags)
593 {
594     irc_in_addr_t mask;
595     char *glob, *marker;
596     unsigned char mask_bits;
597
598     /* Make a writable copy of the glob */
599     glob = alloca(strlen(orig_glob)+1);
600     strcpy(glob, orig_glob);
601     /* Check the nick, if it's present */
602     if (flags & MATCH_USENICK) {
603         if (!(marker = strchr(glob, '!'))) {
604             log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include a '!'", user->nick, orig_glob, flags);
605             return 0;
606         }
607         *marker = 0;
608         if (!match_ircglob(user->nick, glob)) return 0;
609         glob = marker + 1;
610     }
611     /* Check the ident */
612     if (!(marker = strchr(glob, '@'))) {
613         log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include an '@'", user->nick, orig_glob, flags);
614         return 0;
615     }
616     *marker = 0;
617     if (((IsFakeIdent(user) && IsHiddenHost(user) && (flags & MATCH_VISIBLE)) || !match_ircglob(user->ident, glob)) &&
618         !(IsFakeIdent(user) && match_ircglob(user->fakeident, glob)))
619         return 0;
620     glob = marker + 1;
621     /* Check for a fakehost match. */
622     if (IsFakeHost(user) && match_ircglob(user->fakehost, glob))
623         return 1;
624     /* Check for an account match. */
625     if (hidden_host_suffix && user->handle_info) {
626         char hidden_host[HOSTLEN+1];
627         snprintf(hidden_host, sizeof(hidden_host), "%s.%s", user->handle_info->handle, hidden_host_suffix);
628         if (match_ircglob(hidden_host, glob))
629             return 1;
630     }
631     /* If only matching the visible hostnames, bail early. */
632     if ((flags & MATCH_VISIBLE) && IsHiddenHost(user)
633         && (IsFakeHost(user) || (hidden_host_suffix && user->handle_info)))
634         return 0;
635     /* If it might be an IP glob, test that. */
636     if (irc_pton(&mask, &mask_bits, glob)
637         && irc_check_mask(&user->ip, &mask, mask_bits))
638         return 1;
639     /* None of the above; could only be a hostname match. */
640     return match_ircglob(user->hostname, glob);
641 }
642
643 int
644 is_ircmask(const char *text)
645 {
646     while (*text && (isalnum((char)*text) || strchr("-_[]|\\`^{}?*", *text)))
647         text++;
648     if (*text++ != '!')
649         return 0;
650     while (*text && *text != '@' && !isspace((char)*text))
651         text++;
652     if (*text++ != '@')
653         return 0;
654     while (*text && !isspace((char)*text))
655         text++;
656     return !*text;
657 }
658
659 int
660 is_gline(const char *text)
661 {
662     if (*text == '@')
663         return 0;
664     text += strcspn(text, "@!% \t\r\n");
665     if (*text++ != '@')
666         return 0;
667     if (!*text)
668         return 0;
669     while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
670         text++;
671     return !*text;
672 }
673
674 int
675 split_ircmask(char *text, char **nick, char **ident, char **host)
676 {
677     char *start;
678
679     start = text;
680     while (isalnum((char)*text) || strchr("=[]\\`^{}?*", *text))
681         text++;
682     if (*text != '!' || ((text - start) > NICKLEN))
683         return 0;
684     *text = 0;
685     if (nick)
686         *nick = start;
687
688     start = ++text;
689     while (*text && *text != '@' && !isspace((char)*text))
690         text++;
691     if (*text != '@' || ((text - start) > USERLEN))
692         return 0;
693     *text = 0;
694     if (ident)
695         *ident = start;
696
697     start = ++text;
698     while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
699         text++;
700     if (host)
701         *host = start;
702     return !*text && ((text - start) <= HOSTLEN) && nick && ident && host;
703 }
704
705 char *
706 sanitize_ircmask(char *input)
707 {
708     unsigned int length, flag;
709     char *mask, *start, *output;
710
711     /* Sanitize everything in place; input *must* be a valid
712        hostmask. */
713     output = input;
714     flag = 0;
715
716     /* The nick is truncated at the end. */
717     length = 0;
718     mask = input;
719     while(*input++ != '!')
720     {
721         length++;
722     }
723     if(length > NICKLEN)
724     {
725         mask += NICKLEN;
726         *mask++ = '!';
727
728         /* This flag is used to indicate following parts should
729            be shifted. */
730         flag = 1;
731     }
732     else
733     {
734         mask = input;
735     }
736
737     /* The ident and host must be truncated at the beginning and
738        replaced with a '*' to be compatible with ircu. */
739     length = 0;
740     start = input;
741     while(*input++ != '@')
742     {
743         length++;
744     }
745     if(length > USERLEN || flag)
746     {
747         if(length > USERLEN)
748         {
749             start = input - USERLEN;
750             *mask++ = '*';
751         }
752         while(*start != '@')
753         {
754             *mask++ = *start++;
755         }
756         *mask++ = '@';
757
758         flag = 1;
759     }
760     else
761     {
762         mask = input;
763     }
764
765     length = 0;
766     start = input;
767     while(*input++)
768     {
769         length++;
770     }
771     if(length > HOSTLEN || flag)
772     {
773         if(length > HOSTLEN)
774         {
775             start = input - HOSTLEN;
776             *mask++ = '*';
777         }
778         while(*start)
779         {
780             *mask++ = *start++;
781         }
782         *mask = '\0';
783     }
784
785     return output;
786 }
787
788 static long
789 TypeLength(char type)
790 {
791     switch (type) {
792     case 'y': return 365*24*60*60;
793     case 'M': return 31*24*60*60;
794     case 'w': return 7*24*60*60;
795     case 'd': return 24*60*60;
796     case 'h': return 60*60;
797     case 'm': return 60;
798     case 's': return 1;
799     default: return 0;
800     }
801 }
802
803 unsigned long
804 ParseInterval(const char *interval)
805 {
806     unsigned long seconds = 0;
807     int partial = 0;
808     char c;
809
810     /* process the string, resetting the count if we find a unit character */
811     while ((c = *interval++)) {
812         if (isdigit((int)c)) {
813             partial = partial*10 + c - '0';
814         } else if (strchr("yMwdhms", c)) {
815             seconds += TypeLength(c) * partial;
816             partial = 0;
817         } else {
818             return 0;
819         }
820     }
821     /* assume the last chunk is seconds (the normal case) */
822     return seconds + partial;
823 }
824
825 static long
826 GetSizeMultiplier(char type)
827 {
828     switch (type) {
829     case 'G': case 'g': return 1024*1024*1024;
830     case 'M': case 'm': return 1024*1024;
831     case 'K': case 'k': return 1024;
832     case 'B': case 'b': return 1;
833     default: return 0;
834     }
835 }
836
837 unsigned long
838 ParseVolume(const char *volume)
839 {
840     unsigned long accum = 0, partial = 0;
841     char c;
842     while ((c = *volume++)) {
843         if (isdigit((int)c)) {
844             partial = partial*10 + c - '0';
845         } else {
846             accum += GetSizeMultiplier(c) * partial;
847             partial = 0;
848         }
849     }
850     return accum + partial;
851 }
852
853 char *
854 unsplit_string(char *set[], unsigned int max, char *dest)
855 {
856     static char unsplit_buffer[MAXLEN*2];
857     unsigned int ii, jj, pos;
858
859     if (!dest)
860         dest = unsplit_buffer;
861     for (ii=pos=0; ii<max; ii++) {
862         for (jj=0; set[ii][jj]; jj++)
863             dest[pos++] = set[ii][jj];
864         dest[pos++] = ' ';
865     }
866     dest[--pos] = 0;
867     return dest;
868 }
869
870 char *
871 intervalString(char *output, unsigned long interval, struct handle_info *hi)
872 {
873     static const struct {
874         const char *msg_single;
875         const char *msg_plural;
876         unsigned long length;
877     } unit[] = {
878         { "MSG_YEAR",   "MSG_YEARS", 365 * 24 * 60 * 60 },
879         { "MSG_WEEK",   "MSG_WEEKS",   7 * 24 * 60 * 60 },
880         { "MSG_DAY",    "MSG_DAYS",        24 * 60 * 60 },
881         { "MSG_HOUR",   "MSG_HOURS",            60 * 60 },
882         { "MSG_MINUTE", "MSG_MINUTES",               60 },
883         { "MSG_SECOND", "MSG_SECONDS",                1 }
884     };
885     struct language *lang;
886     const char *msg;
887     unsigned int type, words, pos, count;
888
889     lang = hi ? hi->language : lang_C;
890     if(!interval)
891     {
892         msg = language_find_message(lang, "MSG_0_SECONDS");
893         return strcpy(output, msg);
894     }
895
896     for (type = 0, words = pos = 0;
897          interval && (words < 2) && (type < ArrayLength(unit));
898          type++) {
899         if (interval < unit[type].length)
900             continue;
901         count = interval / unit[type].length;
902         interval = interval % unit[type].length;
903
904         if (words++ == 1) {
905             msg = language_find_message(lang, "MSG_AND");
906             pos += sprintf(output + pos, " %s ", msg);
907         }
908         if (count == 1)
909             msg = language_find_message(lang, unit[type].msg_single);
910         else
911             msg = language_find_message(lang, unit[type].msg_plural);
912         pos += sprintf(output + pos, "%d %s", count, msg);
913     }
914
915     output[pos] = 0;
916     return output;
917 }
918
919 int
920 getipbyname(const char *name, unsigned long *ip)
921 {
922     struct hostent *he = gethostbyname(name);
923     if (!he)
924         return 0;
925     if (he->h_addrtype != AF_INET)
926         return 0;
927     memcpy(ip, he->h_addr_list[0], sizeof(*ip));
928     return 1;
929 }
930
931 DEFINE_LIST(string_buffer, char)
932
933 void
934 string_buffer_append_substring(struct string_buffer *buf, const char *tail, unsigned int len)
935 {
936     while (buf->used + len >= buf->size) {
937         if (!buf->size)
938             buf->size = 16;
939         else
940             buf->size <<= 1;
941         buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
942     }
943     memcpy(buf->list + buf->used, tail, len+1);
944     buf->used += len;
945 }
946
947 void
948 string_buffer_append_string(struct string_buffer *buf, const char *tail)
949 {
950     string_buffer_append_substring(buf, tail, strlen(tail));
951 }
952
953 void
954 string_buffer_append_vprintf(struct string_buffer *buf, const char *fmt, va_list args)
955 {
956     va_list working;
957     unsigned int len;
958     int ret;
959
960     VA_COPY(working, args);
961     len = strlen(fmt);
962     if (!buf->list || ((buf->used + buf->size) < len)) {
963         buf->size = buf->used + len;
964         buf->list = realloc(buf->list, buf->size);
965     }
966     ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working);
967     if (ret <= 0) {
968         /* pre-C99 behavior; double buffer size until it is big enough */
969         va_end(working);
970         VA_COPY(working, args);
971         while ((ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working)) <= 0) {
972             buf->size += len;
973             buf->list = realloc(buf->list, buf->size);
974             va_end(working);
975             VA_COPY(working, args);
976         }
977         buf->used += ret;
978     } else if (buf->used + ret < buf->size) {
979         /* no need to increase allocation size */
980         buf->used += ret;
981     } else {
982         /* now we know exactly how much space we need */
983         if (buf->size <= buf->used + ret) {
984             buf->size = buf->used + ret + 1;
985             buf->list = realloc(buf->list, buf->size);
986         }
987         va_end(working);
988         VA_COPY(working, args);
989         buf->used += vsnprintf(buf->list + buf->used, buf->size, fmt, working);
990     }
991     va_end(working);
992     va_end(args);
993 }
994
995 void string_buffer_append_printf(struct string_buffer *buf, const char *fmt, ...)
996 {
997     va_list args;
998     va_start(args, fmt);
999     string_buffer_append_vprintf(buf, fmt, args);
1000 }
1001
1002 void
1003 string_buffer_replace(struct string_buffer *buf, unsigned int from, unsigned int len, const char *repl)
1004 {
1005     unsigned int repl_len = strlen(repl);
1006     if (from > buf->used)
1007         return;
1008     if (len + from > buf->used)
1009         len = buf->used - from;
1010     buf->used = buf->used + repl_len - len;
1011     if (buf->size <= buf->used) {
1012         while (buf->used >= buf->size)
1013             buf->size <<= 1;
1014         buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
1015     }
1016     memmove(buf->list+from+repl_len, buf->list+from+len, strlen(buf->list+from+len));
1017     strcpy(buf->list+from, repl);
1018 }
1019
1020 struct string_list str_tab;
1021
1022 const char *
1023 strtab(unsigned int ii) {
1024     if (ii > 65536)
1025         return NULL;
1026     if (ii > str_tab.size) {
1027         unsigned int old_size = str_tab.size;
1028         while (ii >= str_tab.size)
1029             str_tab.size <<= 1;
1030         str_tab.list = realloc(str_tab.list, str_tab.size*sizeof(str_tab.list[0]));
1031         memset(str_tab.list+old_size, 0, (str_tab.size-old_size)*sizeof(str_tab.list[0]));
1032     }
1033     if (!str_tab.list[ii]) {
1034         str_tab.list[ii] = malloc(12);
1035         sprintf(str_tab.list[ii], "%u", ii);
1036     }
1037     return str_tab.list[ii];
1038 }
1039
1040 void
1041 tools_init(void)
1042 {
1043     unsigned int upr, lwr;
1044     for (lwr=0; lwr<256; ++lwr)
1045         tolower(lwr) = lwr;
1046     for (upr='A', lwr='a'; lwr <= 'z'; ++upr, ++lwr)
1047         tolower(upr) = lwr;
1048 #ifdef WITH_PROTOCOL_P10
1049     for (upr='[', lwr='{'; lwr <= '~'; ++upr, ++lwr)
1050         tolower(upr) = lwr;
1051     for (upr=0xc0, lwr=0xe0; lwr <= 0xf6; ++upr, ++lwr)
1052         tolower(upr) = lwr;
1053     for (upr=0xd8, lwr=0xf8; lwr <= 0xfe; ++upr, ++lwr)
1054         tolower(upr) = lwr;
1055 #endif
1056     str_tab.size = 1001;
1057     str_tab.list = calloc(str_tab.size, sizeof(str_tab.list[0]));
1058 }
1059
1060 void
1061 tools_cleanup(void)
1062 {
1063     unsigned int ii;
1064     for (ii=0; ii<str_tab.size; ++ii)
1065         free(str_tab.list[ii]);
1066     free(str_tab.list);
1067 }