Add ircstrlower() function.
[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             addr->in6[5] = htons(65535);
320             addr->in6[6] = htons(ntohl(ip4) >> 16);
321             addr->in6[7] = htons(ntohl(ip4) & 65535);
322             if (bits)
323                 *bits += 96;
324         }
325     } else if (input[0] == '*') {
326         while (input[++pos] == '*') ;
327         if (input[pos] != '\0')
328             return 0;
329         if (bits)
330             *bits = 0;
331     }
332     return pos;
333 }
334
335 const char *irc_ntoa(const irc_in_addr_t *addr)
336 {
337     static char ntoa[IRC_NTOP_MAX_SIZE];
338     irc_ntop(ntoa, sizeof(ntoa), addr);
339     return ntoa;
340 }
341
342 unsigned int
343 irc_check_mask(const irc_in_addr_t *check, const irc_in_addr_t *mask, unsigned char bits)
344 {
345     unsigned int ii;
346
347     for (ii = 0; (ii < 8) && (bits > 16); bits -= 16, ++ii)
348         if (check->in6[ii] != mask->in6[ii])
349             return 0;
350     if (ii < 8 && bits > 0
351         && (ntohs(check->in6[ii] ^ mask->in6[ii]) >> (16 - bits)))
352         return 0;
353     return 1;
354 }
355
356 static char irc_tolower[256];
357 #undef tolower
358 #define tolower(X) irc_tolower[(unsigned char)(X)]
359
360 int
361 irccasecmp(const char *stra, const char *strb) {
362     while (*stra && (tolower(*stra) == tolower(*strb)))
363         stra++, strb++;
364     return tolower(*stra) - tolower(*strb);
365 }
366
367 int
368 ircncasecmp(const char *stra, const char *strb, unsigned int len) {
369     len--;
370     while (*stra && (tolower(*stra) == tolower(*strb)) && len)
371         stra++, strb++, len--;
372     return tolower(*stra) - tolower(*strb);
373 }
374
375 const char *
376 irccasestr(const char *haystack, const char *needle) {
377     unsigned int hay_len = strlen(haystack), needle_len = strlen(needle), pos;
378     if (hay_len < needle_len)
379         return NULL;
380     for (pos=0; pos<hay_len+1-needle_len; ++pos) {
381         if ((tolower(haystack[pos]) == tolower(*needle))
382             && !ircncasecmp(haystack+pos, needle, needle_len))
383             return haystack+pos;
384     }
385     return NULL;
386 }
387
388 char *
389 ircstrlower(char *str) {
390     size_t ii;
391     for (ii = 0; str[ii] != '\0'; ++ii)
392         str[ii] = tolower(str[ii]);
393     return str;
394 }
395
396 int
397 split_line(char *line, int irc_colon, int argv_size, char *argv[])
398 {
399     int argc = 0;
400     int n;
401     while (*line && (argc < argv_size)) {
402         while (*line == ' ')
403             *line++ = 0;
404         if (*line == ':' && irc_colon && argc > 0) {
405             /* the rest is a single parameter */
406             argv[argc++] = line + 1;
407             break;
408         }
409         if (!*line)
410             break;
411         argv[argc++] = line;
412         if (argc >= argv_size)
413             break;
414         while (*line != ' ' && *line)
415             line++;
416     }
417 #ifdef NDEBUG
418     n = 0;
419 #else
420     for (n=argc; n<argv_size; n++)
421         argv[n] = (char*)0xFEEDBEEF;
422 #endif
423     return argc;
424 }
425
426 /* This is ircu's mmatch() function, from match.c. */
427 int mmatch(const char *old_mask, const char *new_mask)
428 {
429   register const char *m = old_mask;
430   register const char *n = new_mask;
431   const char *ma = m;
432   const char *na = n;
433   int wild = 0;
434   int mq = 0, nq = 0;
435
436   while (1)
437   {
438     if (*m == '*')
439     {
440       while (*m == '*')
441         m++;
442       wild = 1;
443       ma = m;
444       na = n;
445     }
446
447     if (!*m)
448     {
449       if (!*n)
450         return 0;
451       for (m--; (m > old_mask) && (*m == '?'); m--)
452         ;
453       if ((*m == '*') && (m > old_mask) && (m[-1] != '\\'))
454         return 0;
455       if (!wild)
456         return 1;
457       m = ma;
458
459       /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
460       if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
461         ++na;
462
463       n = ++na;
464     }
465     else if (!*n)
466     {
467       while (*m == '*')
468         m++;
469       return (*m != 0);
470     }
471     if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?')))
472     {
473       m++;
474       mq = 1;
475     }
476     else
477       mq = 0;
478
479     /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
480     if ((*n == '\\') && ((n[1] == '*') || (n[1] == '?')))
481     {
482       n++;
483       nq = 1;
484     }
485     else
486       nq = 0;
487
488 /*
489  * This `if' has been changed compared to match() to do the following:
490  * Match when:
491  *   old (m)         new (n)         boolean expression
492  *    *               any             (*m == '*' && !mq) ||
493  *    ?               any except '*'  (*m == '?' && !mq && (*n != '*' || nq)) ||
494  * any except * or ?  same as m       (!((*m == '*' || *m == '?') && !mq) &&
495  *                                      toLower(*m) == toLower(*n) &&
496  *                                        !((mq && !nq) || (!mq && nq)))
497  *
498  * Here `any' also includes \* and \? !
499  *
500  * After reworking the boolean expressions, we get:
501  * (Optimized to use boolean shortcircuits, with most frequently occuring
502  *  cases upfront (which took 2 hours!)).
503  */
504     if ((*m == '*' && !mq) ||
505         ((!mq || nq) && tolower(*m) == tolower(*n)) ||
506         (*m == '?' && !mq && (*n != '*' || nq)))
507     {
508       if (*m)
509         m++;
510       if (*n)
511         n++;
512     }
513     else
514     {
515       if (!wild)
516         return 1;
517       m = ma;
518
519       /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
520       if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
521         ++na;
522
523       n = ++na;
524     }
525   }
526 }
527
528 int
529 match_ircglob(const char *text, const char *glob)
530 {
531     const char *m = glob, *n = text;
532     const char *m_tmp = glob, *n_tmp = text;
533     int star_p;
534
535     for (;;) switch (*m) {
536     case '\0':
537         if (!*n)
538             return 1;
539     backtrack:
540         if (m_tmp == glob)
541             return 0;
542         m = m_tmp;
543         n = ++n_tmp;
544         if (!*n)
545             return 0;
546         break;
547     case '\\':
548         m++;
549         /* allow escaping to force capitalization */
550         if (*m++ != *n++)
551             goto backtrack;
552         break;
553     case '*': case '?':
554         for (star_p = 0; ; m++) {
555             if (*m == '*')
556                 star_p = 1;
557             else if (*m == '?') {
558                 if (!*n++)
559                     goto backtrack;
560             } else break;
561         }
562         if (star_p) {
563             if (!*m)
564                 return 1;
565             else if (*m == '\\') {
566                 m_tmp = ++m;
567                 if (!*m)
568                     return 0;
569                 for (n_tmp = n; *n && *n != *m; n++) ;
570             } else {
571                 m_tmp = m;
572                 for (n_tmp = n; *n && tolower(*n) != tolower(*m); n++) ;
573             }
574         }
575         /* and fall through */
576     default:
577         if (!*n)
578             return *m == '\0';
579         if (tolower(*m) != tolower(*n))
580             goto backtrack;
581         m++;
582         n++;
583         break;
584     }
585 }
586
587 extern const char *hidden_host_suffix;
588
589 int
590 user_matches_glob(struct userNode *user, const char *orig_glob, int flags)
591 {
592     char *glob, *marker;
593
594     /* Make a writable copy of the glob */
595     glob = alloca(strlen(orig_glob)+1);
596     strcpy(glob, orig_glob);
597     /* Check the nick, if it's present */
598     if (flags & MATCH_USENICK) {
599         if (!(marker = strchr(glob, '!'))) {
600             log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include a '!'", user->nick, orig_glob, flags);
601             return 0;
602         }
603         *marker = 0;
604         if (!match_ircglob(user->nick, glob)) return 0;
605         glob = marker + 1;
606     }
607     /* Check the ident */
608     if (!(marker = strchr(glob, '@'))) {
609         log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include an '@'", user->nick, orig_glob, flags);
610         return 0;
611     }
612     *marker = 0;
613     if (!match_ircglob(user->ident, glob))
614         return 0;
615     glob = marker + 1;
616     /* Check for a fakehost match. */
617     if (IsFakeHost(user) && match_ircglob(user->fakehost, glob))
618         return 1;
619     /* Check for an account match. */
620     if (hidden_host_suffix && user->handle_info) {
621         char hidden_host[HOSTLEN+1];
622         snprintf(hidden_host, sizeof(hidden_host), "%s.%s", user->handle_info->handle, hidden_host_suffix);
623         if (match_ircglob(hidden_host, glob))
624             return 1;
625     }
626     /* If only matching the visible hostnames, bail early. */
627     if ((flags & MATCH_VISIBLE) && IsHiddenHost(user)
628         && (IsFakeHost(user) || (hidden_host_suffix && user->handle_info)))
629         return 0;
630     /* If it might be an IP glob, test that. */
631     if (!glob[strspn(glob, "0123456789./*?")]
632         && match_ircglob(irc_ntoa(&user->ip), glob))
633         return 1;
634     /* None of the above; could only be a hostname match. */
635     return match_ircglob(user->hostname, glob);
636 }
637
638 int
639 is_ircmask(const char *text)
640 {
641     while (*text && (isalnum((char)*text) || strchr("-_[]|\\`^{}?*", *text)))
642         text++;
643     if (*text++ != '!')
644         return 0;
645     while (*text && *text != '@' && !isspace((char)*text))
646         text++;
647     if (*text++ != '@')
648         return 0;
649     while (*text && !isspace((char)*text))
650         text++;
651     return !*text;
652 }
653
654 int
655 is_gline(const char *text)
656 {
657     if (*text == '@')
658         return 0;
659     text += strcspn(text, "@!% \t\r\n");
660     if (*text++ != '@')
661         return 0;
662     if (!*text)
663         return 0;
664     while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
665         text++;
666     return !*text;
667 }
668
669 int
670 split_ircmask(char *text, char **nick, char **ident, char **host)
671 {
672     char *start;
673
674     start = text;
675     while (isalnum((char)*text) || strchr("=[]\\`^{}?*", *text))
676         text++;
677     if (*text != '!' || ((text - start) > NICKLEN))
678         return 0;
679     *text = 0;
680     if (nick)
681         *nick = start;
682
683     start = ++text;
684     while (*text && *text != '@' && !isspace((char)*text))
685         text++;
686     if (*text != '@' || ((text - start) > USERLEN))
687         return 0;
688     *text = 0;
689     if (ident)
690         *ident = start;
691
692     start = ++text;
693     while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
694         text++;
695     if (host)
696         *host = start;
697     return !*text && ((text - start) <= HOSTLEN) && nick && ident && host;
698 }
699
700 char *
701 sanitize_ircmask(char *input)
702 {
703     unsigned int length, flag;
704     char *mask, *start, *output;
705
706     /* Sanitize everything in place; input *must* be a valid
707        hostmask. */
708     output = input;
709     flag = 0;
710
711     /* The nick is truncated at the end. */
712     length = 0;
713     mask = input;
714     while(*input++ != '!')
715     {
716         length++;
717     }
718     if(length > NICKLEN)
719     {
720         mask += NICKLEN;
721         *mask++ = '!';
722
723         /* This flag is used to indicate following parts should
724            be shifted. */
725         flag = 1;
726     }
727     else
728     {
729         mask = input;
730     }
731
732     /* The ident and host must be truncated at the beginning and
733        replaced with a '*' to be compatible with ircu. */
734     length = 0;
735     start = input;
736     while(*input++ != '@')
737     {
738         length++;
739     }
740     if(length > USERLEN || flag)
741     {
742         if(length > USERLEN)
743         {
744             start = input - USERLEN;
745             *mask++ = '*';
746         }
747         while(*start != '@')
748         {
749             *mask++ = *start++;
750         }
751         *mask++ = '@';
752
753         flag = 1;
754     }
755     else
756     {
757         mask = input;
758     }
759
760     length = 0;
761     start = input;
762     while(*input++)
763     {
764         length++;
765     }
766     if(length > HOSTLEN || flag)
767     {
768         if(length > HOSTLEN)
769         {
770             start = input - HOSTLEN;
771             *mask++ = '*';
772         }
773         while(*start)
774         {
775             *mask++ = *start++;
776         }
777         *mask = '\0';
778     }
779
780     return output;
781 }
782
783 static long
784 TypeLength(char type)
785 {
786     switch (type) {
787     case 'y': return 365*24*60*60;
788     case 'M': return 31*24*60*60;
789     case 'w': return 7*24*60*60;
790     case 'd': return 24*60*60;
791     case 'h': return 60*60;
792     case 'm': return 60;
793     case 's': return 1;
794     default: return 0;
795     }
796 }
797
798 unsigned long
799 ParseInterval(const char *interval)
800 {
801     unsigned long seconds = 0;
802     int partial = 0;
803     char c;
804
805     /* process the string, resetting the count if we find a unit character */
806     while ((c = *interval++)) {
807         if (isdigit((int)c)) {
808             partial = partial*10 + c - '0';
809         } else if (strchr("yMwdhms", c)) {
810             seconds += TypeLength(c) * partial;
811             partial = 0;
812         } else {
813             return 0;
814         }
815     }
816     /* assume the last chunk is seconds (the normal case) */
817     return seconds + partial;
818 }
819
820 static long
821 GetSizeMultiplier(char type)
822 {
823     switch (type) {
824     case 'G': case 'g': return 1024*1024*1024;
825     case 'M': case 'm': return 1024*1024;
826     case 'K': case 'k': return 1024;
827     case 'B': case 'b': return 1;
828     default: return 0;
829     }
830 }
831
832 unsigned long
833 ParseVolume(const char *volume)
834 {
835     unsigned long accum = 0, partial = 0;
836     char c;
837     while ((c = *volume++)) {
838         if (isdigit((int)c)) {
839             partial = partial*10 + c - '0';
840         } else {
841             accum += GetSizeMultiplier(c) * partial;
842             partial = 0;
843         }
844     }
845     return accum + partial;
846 }
847
848 char *
849 unsplit_string(char *set[], unsigned int max, char *dest)
850 {
851     static char unsplit_buffer[MAXLEN*2];
852     unsigned int ii, jj, pos;
853
854     if (!dest)
855         dest = unsplit_buffer;
856     for (ii=pos=0; ii<max; ii++) {
857         for (jj=0; set[ii][jj]; jj++)
858             dest[pos++] = set[ii][jj];
859         dest[pos++] = ' ';
860     }
861     dest[--pos] = 0;
862     return dest;
863 }
864
865 char *
866 intervalString(char *output, unsigned long interval, struct handle_info *hi)
867 {
868     static const struct {
869         const char *msg_single;
870         const char *msg_plural;
871         unsigned long length;
872     } unit[] = {
873         { "MSG_YEAR",   "MSG_YEARS", 365 * 24 * 60 * 60 },
874         { "MSG_WEEK",   "MSG_WEEKS",   7 * 24 * 60 * 60 },
875         { "MSG_DAY",    "MSG_DAYS",        24 * 60 * 60 },
876         { "MSG_HOUR",   "MSG_HOURS",            60 * 60 },
877         { "MSG_MINUTE", "MSG_MINUTES",               60 },
878         { "MSG_SECOND", "MSG_SECONDS",                1 }
879     };
880     struct language *lang;
881     const char *msg;
882     unsigned int type, words, pos, count;
883
884     lang = hi ? hi->language : lang_C;
885     if(!interval)
886     {
887         msg = language_find_message(lang, "MSG_0_SECONDS");
888         return strcpy(output, msg);
889     }
890
891     for (type = 0, words = pos = 0;
892          interval && (words < 2) && (type < ArrayLength(unit));
893          type++) {
894         if (interval < unit[type].length)
895             continue;
896         count = interval / unit[type].length;
897         interval = interval % unit[type].length;
898
899         if (words++ == 1) {
900             msg = language_find_message(lang, "MSG_AND");
901             pos += sprintf(output + pos, " %s ", msg);
902         }
903         if (count == 1)
904             msg = language_find_message(lang, unit[type].msg_single);
905         else
906             msg = language_find_message(lang, unit[type].msg_plural);
907         pos += sprintf(output + pos, "%d %s", count, msg);
908     }
909
910     output[pos] = 0;
911     return output;
912 }
913
914 int
915 getipbyname(const char *name, unsigned long *ip)
916 {
917     struct hostent *he = gethostbyname(name);
918     if (!he)
919         return 0;
920     if (he->h_addrtype != AF_INET)
921         return 0;
922     memcpy(ip, he->h_addr_list[0], sizeof(*ip));
923     return 1;
924 }
925
926 DEFINE_LIST(string_buffer, char)
927
928 void
929 string_buffer_append_substring(struct string_buffer *buf, const char *tail, unsigned int len)
930 {
931     while (buf->used + len >= buf->size) {
932         if (!buf->size)
933             buf->size = 16;
934         else
935             buf->size <<= 1;
936         buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
937     }
938     memcpy(buf->list + buf->used, tail, len+1);
939     buf->used += len;
940 }
941
942 void
943 string_buffer_append_string(struct string_buffer *buf, const char *tail)
944 {
945     string_buffer_append_substring(buf, tail, strlen(tail));
946 }
947
948 void
949 string_buffer_append_vprintf(struct string_buffer *buf, const char *fmt, va_list args)
950 {
951     va_list working;
952     unsigned int len;
953     int ret;
954
955     VA_COPY(working, args);
956     len = strlen(fmt);
957     if (!buf->list || ((buf->used + buf->size) < len)) {
958         buf->size = buf->used + len;
959         buf->list = realloc(buf->list, buf->size);
960     }
961     ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working);
962     if (ret <= 0) {
963         /* pre-C99 behavior; double buffer size until it is big enough */
964         va_end(working);
965         VA_COPY(working, args);
966         while ((ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working)) <= 0) {
967             buf->size += len;
968             buf->list = realloc(buf->list, buf->size);
969             va_end(working);
970             VA_COPY(working, args);
971         }
972         buf->used += ret;
973     } else if (buf->used + ret < buf->size) {
974         /* no need to increase allocation size */
975         buf->used += ret;
976     } else {
977         /* now we know exactly how much space we need */
978         if (buf->size <= buf->used + ret) {
979             buf->size = buf->used + ret + 1;
980             buf->list = realloc(buf->list, buf->size);
981         }
982         va_end(working);
983         VA_COPY(working, args);
984         buf->used += vsnprintf(buf->list + buf->used, buf->size, fmt, working);
985     }
986     va_end(working);
987     va_end(args);
988 }
989
990 void string_buffer_append_printf(struct string_buffer *buf, const char *fmt, ...)
991 {
992     va_list args;
993     va_start(args, fmt);
994     string_buffer_append_vprintf(buf, fmt, args);
995 }
996
997 void
998 string_buffer_replace(struct string_buffer *buf, unsigned int from, unsigned int len, const char *repl)
999 {
1000     unsigned int repl_len = strlen(repl);
1001     if (from > buf->used)
1002         return;
1003     if (len + from > buf->used)
1004         len = buf->used - from;
1005     buf->used = buf->used + repl_len - len;
1006     if (buf->size <= buf->used) {
1007         while (buf->used >= buf->size)
1008             buf->size <<= 1;
1009         buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
1010     }
1011     memmove(buf->list+from+repl_len, buf->list+from+len, strlen(buf->list+from+len));
1012     strcpy(buf->list+from, repl);
1013 }
1014
1015 struct string_list str_tab;
1016
1017 const char *
1018 strtab(unsigned int ii) {
1019     if (ii > 65536)
1020         return NULL;
1021     if (ii > str_tab.size) {
1022         unsigned int old_size = str_tab.size;
1023         while (ii >= str_tab.size)
1024             str_tab.size <<= 1;
1025         str_tab.list = realloc(str_tab.list, str_tab.size*sizeof(str_tab.list[0]));
1026         memset(str_tab.list+old_size, 0, (str_tab.size-old_size)*sizeof(str_tab.list[0]));
1027     }
1028     if (!str_tab.list[ii]) {
1029         str_tab.list[ii] = malloc(12);
1030         sprintf(str_tab.list[ii], "%u", ii);
1031     }
1032     return str_tab.list[ii];
1033 }
1034
1035 void
1036 tools_init(void)
1037 {
1038     unsigned int upr, lwr;
1039     for (lwr=0; lwr<256; ++lwr)
1040         tolower(lwr) = lwr;
1041     for (upr='A', lwr='a'; lwr <= 'z'; ++upr, ++lwr)
1042         tolower(upr) = lwr;
1043 #ifdef WITH_PROTOCOL_P10
1044     for (upr='[', lwr='{'; lwr <= '~'; ++upr, ++lwr)
1045         tolower(upr) = lwr;
1046     for (upr=0xc0, lwr=0xe0; lwr <= 0xf6; ++upr, ++lwr)
1047         tolower(upr) = lwr;
1048     for (upr=0xd8, lwr=0xf8; lwr <= 0xfe; ++upr, ++lwr)
1049         tolower(upr) = lwr;
1050 #endif
1051     str_tab.size = 1001;
1052     str_tab.list = calloc(str_tab.size, sizeof(str_tab.list[0]));
1053 }
1054
1055 void
1056 tools_cleanup(void)
1057 {
1058     unsigned int ii;
1059     for (ii=0; ii<str_tab.size; ++ii)
1060         free(str_tab.list[ii]);
1061     free(str_tab.list);
1062 }