1 /* tools.c - miscellaneous utility functions
2 * Copyright 2000-2004 srvx Development Team
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 2 of the License, or
7 * (at your option) any later version. Important limitations are
8 * listed in the COPYING file that accompanies this software.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, email srvx-maintainers@srvx.net.
26 #ifdef HAVE_SYS_SOCKET_H
27 #include <sys/socket.h>
29 #ifdef HAVE_ARPA_INET_H
30 #include <arpa/inet.h>
34 #define NUMNICKBASE (1 << NUMNICKLOG)
35 #define NUMNICKMASK (NUMNICKBASE - 1)
37 /* Yes, P10's encoding here is almost-but-not-quite MIME Base64. Yay
38 * for gratuitous incompatibilities. */
39 static const char convert2y[256] = {
40 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
41 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
42 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
43 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','[',']'
46 static const unsigned char convert2n[256] = {
47 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
48 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
49 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
50 52,53,54,55,56,57,58,59,60,61, 0, 0, 0, 0, 0, 0,
51 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
52 15,16,17,18,19,20,21,22,23,24,25,62, 0,63, 0, 0,
53 0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
54 41,42,43,44,45,46,47,48,49,50,51, 0, 0, 0, 0, 0
58 base64toint(const char* s, int count)
62 i = (i << NUMNICKLOG) + convert2n[(unsigned char)*s++];
68 const char* inttobase64(char* buf, unsigned int v, unsigned int count)
72 buf[--count] = convert2y[(unsigned char)(v & NUMNICKMASK)];
78 static char irc_tolower[256];
80 #define tolower(X) irc_tolower[(unsigned char)(X)]
83 irccasecmp(const char *stra, const char *strb) {
84 while (*stra && (tolower(*stra) == tolower(*strb)))
86 return tolower(*stra) - tolower(*strb);
90 ircncasecmp(const char *stra, const char *strb, unsigned int len) {
92 while (*stra && (tolower(*stra) == tolower(*strb)) && len)
93 stra++, strb++, len--;
94 return tolower(*stra) - tolower(*strb);
98 irccasestr(const char *haystack, const char *needle) {
99 unsigned int hay_len = strlen(haystack), needle_len = strlen(needle), pos;
100 if (hay_len < needle_len)
102 for (pos=0; pos<hay_len+1-needle_len; ++pos) {
103 if ((tolower(haystack[pos]) == tolower(*needle))
104 && !ircncasecmp(haystack+pos, needle, needle_len))
111 split_line(char *line, int irc_colon, int argv_size, char *argv[])
115 while (*line && (argc < argv_size)) {
116 while (*line == ' ') *line++ = 0;
117 if (*line == ':' && irc_colon && argc > 0) {
118 /* the rest is a single parameter */
119 argv[argc++] = line + 1;
125 if (argc >= argv_size)
127 while (*line != ' ' && *line) line++;
132 for (n=argc; n<argv_size; n++) {
133 argv[n] = (char*)0xFEEDBEEF;
139 /* This is ircu's mmatch() function, from match.c. */
140 int mmatch(const char *old_mask, const char *new_mask)
142 register const char *m = old_mask;
143 register const char *n = new_mask;
164 for (m--; (m > old_mask) && (*m == '?'); m--)
166 if ((*m == '*') && (m > old_mask) && (m[-1] != '\\'))
172 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
173 if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
184 if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?')))
192 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
193 if ((*n == '\\') && ((n[1] == '*') || (n[1] == '?')))
202 * This `if' has been changed compared to match() to do the following:
204 * old (m) new (n) boolean expression
205 * * any (*m == '*' && !mq) ||
206 * ? any except '*' (*m == '?' && !mq && (*n != '*' || nq)) ||
207 * any except * or ? same as m (!((*m == '*' || *m == '?') && !mq) &&
208 * toLower(*m) == toLower(*n) &&
209 * !((mq && !nq) || (!mq && nq)))
211 * Here `any' also includes \* and \? !
213 * After reworking the boolean expressions, we get:
214 * (Optimized to use boolean shortcircuits, with most frequently occuring
215 * cases upfront (which took 2 hours!)).
217 if ((*m == '*' && !mq) ||
218 ((!mq || nq) && tolower(*m) == tolower(*n)) ||
219 (*m == '?' && !mq && (*n != '*' || nq)))
232 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
233 if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
242 match_ircglob(const char *text, const char *glob)
244 unsigned int star_p, q_cnt;
251 /* intentionally not tolower(...) so people can force
252 * capitalization, or we can overload \ in the future */
253 if (*text++ != *glob++) return 0;
259 if (*glob == '*') star_p = 1;
260 else if (*glob == '?') q_cnt++;
264 while (q_cnt) { if (!*text++) return 0; q_cnt--; }
266 /* if this is the last glob character, it will match any text */
267 if (!*glob) return 1;
268 /* Thanks to the loop above, we know that the next
269 * character is a normal character. So just look for
270 * the right character.
272 for (; *text; text++) {
273 if ((tolower(*text) == tolower(*glob))
274 && match_ircglob(text+1, glob+1)) {
280 /* if !star_p, fall through to normal character case,
281 * first checking to see if ?s carried us to the end */
282 if (!*glob && !*text) return 1;
284 if (!*text) return 0;
285 while (*text && *glob && *glob != '*' && *glob != '?' && *glob != '\\') {
286 if (tolower(*text++) != tolower(*glob++)) return 0;
292 extern const char *hidden_host_suffix;
295 user_matches_glob(struct userNode *user, const char *orig_glob, int include_nick)
299 /* Make a writable copy of the glob */
300 glob = alloca(strlen(orig_glob)+1);
301 strcpy(glob, orig_glob);
302 /* Check the nick, if it's present */
304 if (!(marker = strchr(glob, '!'))) {
305 log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include a '!'", user->nick, orig_glob, include_nick);
309 if (!match_ircglob(user->nick, glob)) return 0;
312 /* Check the ident */
313 if (!(marker = strchr(glob, '@'))) {
314 log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include an '@'", user->nick, orig_glob, include_nick);
318 if (!match_ircglob(user->ident, glob))
321 /* Now check the host part */
322 if (isdigit(*glob) && !glob[strspn(glob, "0123456789./*?")]) {
323 /* Looks like an IP-based mask */
324 return match_ircglob(inet_ntoa(user->ip), glob);
326 /* The host part of the mask isn't IP-based */
327 if (hidden_host_suffix && user->handle_info) {
328 char hidden_host[HOSTLEN+1];
329 snprintf(hidden_host, sizeof(hidden_host), "%s.%s", user->handle_info->handle, hidden_host_suffix);
330 if (match_ircglob(hidden_host, glob))
333 return match_ircglob(user->hostname, glob);
338 is_ircmask(const char *text)
340 while (*text && (isalnum((char)*text) || strchr("-_[]|\\`^{}?*", *text))) text++;
341 if (*text++ != '!') return 0;
342 while (*text && *text != '@' && !isspace((char)*text)) text++;
343 if (*text++ != '@') return 0;
344 while (*text && !isspace((char)*text)) text++;
349 is_gline(const char *text)
351 if (*text == '@') return 0;
352 text += strcspn(text, "@!% \t\r\n");
353 if (*text++ != '@') return 0;
354 if (!*text) return 0;
355 while (*text && (isalnum((char)*text) || strchr(".-?*", *text))) text++;
360 split_ircmask(char *text, char **nick, char **ident, char **host)
365 while (isalnum((char)*text) || strchr("=[]\\`^{}?*", *text)) text++;
366 if (*text != '!' || ((text - start) > NICKLEN)) return 0;
368 if (nick) *nick = start;
371 while (*text && *text != '@' && !isspace((char)*text)) text++;
372 if (*text != '@' || ((text - start) > USERLEN)) return 0;
374 if (ident) *ident = start;
377 while (*text && (isalnum((char)*text) || strchr(".-?*", *text))) text++;
378 if (host) *host = start;
379 return !*text && ((text - start) <= HOSTLEN) && nick && ident && host;
383 sanitize_ircmask(char *input)
385 unsigned int length, flag;
386 char *mask, *start, *output;
388 /* Sanitize everything in place; input *must* be a valid
393 /* The nick is truncated at the end. */
396 while(*input++ != '!')
405 /* This flag is used to indicate following parts should
414 /* The ident and host must be truncated at the beginning and
415 replaced with a '*' to be compatible with ircu. */
418 while(*input++ != '@')
422 if(length > USERLEN || flag)
426 start = input - USERLEN;
448 if(length > HOSTLEN || flag)
452 start = input - HOSTLEN;
466 TypeLength(char type)
469 case 'y': return 365*24*60*60;
470 case 'M': return 31*24*60*60;
471 case 'w': return 7*24*60*60;
472 case 'd': return 24*60*60;
473 case 'h': return 60*60;
481 ParseInterval(const char *interval)
483 unsigned long seconds = 0;
487 /* process the string, resetting the count if we find a unit character */
488 while ((c = *interval++)) {
489 if (isdigit((int)c)) {
490 partial = partial*10 + c - '0';
492 seconds += TypeLength(c) * partial;
496 /* assume the last chunk is seconds (the normal case) */
497 return seconds + partial;
501 GetSizeMultiplier(char type)
504 case 'G': case 'g': return 1024*1024*1024;
505 case 'M': case 'm': return 1024*1024;
506 case 'K': case 'k': return 1024;
507 case 'B': case 'b': return 1;
513 ParseVolume(const char *volume)
515 unsigned long accum = 0, partial = 0;
517 while ((c = *volume++)) {
518 if (isdigit((int)c)) {
519 partial = partial*10 + c - '0';
521 accum += GetSizeMultiplier(c) * partial;
525 return accum + partial;
529 parse_ipmask(const char *str, struct in_addr *addr, unsigned long *mask)
532 unsigned long t_a, t_m;
535 if (addr) addr->s_addr = htonl(t_a);
536 if (mask) *mask = t_m;
538 if (!isdigit(*str)) return 0;
541 accum = (accum * 10) + *str++ - '0';
542 } while (isdigit(*str));
543 if (accum > 255) return 0;
544 t_a = (t_a << 8) | accum;
545 t_m = (t_m << 8) | 255;
549 while (*str == '*') {
556 } else if (*str == 0) {
565 } else if (*str == '/') {
569 accum = (accum * 10) + *str++ - '0';
570 } while (isdigit(*str));
571 while (pos < start+accum && pos < 32) {
572 t_a = (t_a << 1) | 0;
573 t_m = (t_m << 1) | 1;
576 if (pos != start+accum) return 0;
577 } else if (*str == 0) {
584 if (pos != 32) return 0;
585 if (addr) addr->s_addr = htonl(t_a);
586 if (mask) *mask = t_m;
591 unsplit_string(char *set[], unsigned int max, char *dest)
593 static char unsplit_buffer[MAXLEN*2];
594 unsigned int ii, jj, pos;
596 if (!dest) dest = unsplit_buffer;
597 for (ii=pos=0; ii<max; ii++) {
598 for (jj=0; set[ii][jj]; jj++) {
599 dest[pos++] = set[ii][jj];
608 intervalString2(char *output, time_t interval, int brief)
610 static const struct {
614 { "year", 365 * 24 * 60 * 60 },
615 { "week", 7 * 24 * 60 * 60 },
616 { "day", 24 * 60 * 60 },
621 unsigned int type, words, pos, count;
625 strcpy(output, brief ? "0s" : "0 seconds");
629 for (type = 0, words = pos = 0;
630 interval && (words < 2) && (type < ArrayLength(unit));
632 if (interval < unit[type].length)
634 count = interval / unit[type].length;
635 interval = interval % unit[type].length;
638 pos += sprintf(output + pos, "%d%c", count, unit[type].name[0]);
640 pos += sprintf(output + pos, " and %d %s", count, unit[type].name);
642 pos += sprintf(output + pos, "%d %s", count, unit[type].name);
653 getipbyname(const char *name, unsigned long *ip)
655 struct hostent *he = gethostbyname(name);
657 if (he->h_addrtype != AF_INET)
659 memcpy(ip, he->h_addr_list[0], sizeof(*ip));
666 DEFINE_LIST(string_buffer, char)
669 string_buffer_append_substring(struct string_buffer *buf, const char *tail, unsigned int len)
671 while (buf->used + len >= buf->size) {
676 buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
678 memcpy(buf->list + buf->used, tail, len+1);
683 string_buffer_append_string(struct string_buffer *buf, const char *tail)
685 string_buffer_append_substring(buf, tail, strlen(tail));
689 string_buffer_append_vprintf(struct string_buffer *buf, const char *fmt, va_list args)
695 VA_COPY(working, args);
697 if (!buf->list || ((buf->used + buf->size) < len)) {
698 buf->size = buf->used + len;
699 buf->list = realloc(buf->list, buf->size);
701 ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working);
703 /* pre-C99 behavior; double buffer size until it is big enough */
705 VA_COPY(working, args);
706 while ((ret = vsnprintf(buf->list + buf->used, buf->size, fmt, working)) == -1) {
708 buf->list = realloc(buf->list, buf->size);
710 VA_COPY(working, args);
713 } else if (buf->used + ret < buf->size) {
714 /* no need to increase allocation size */
717 /* now we know exactly how much space we need */
718 if (buf->size <= buf->used + ret) {
719 buf->size = buf->used + ret + 1;
720 buf->list = realloc(buf->list, buf->size);
723 VA_COPY(working, args);
724 buf->used += vsnprintf(buf->list + buf->used, buf->size, fmt, working);
730 void string_buffer_append_printf(struct string_buffer *buf, const char *fmt, ...)
734 string_buffer_append_vprintf(buf, fmt, args);
738 string_buffer_replace(struct string_buffer *buf, unsigned int from, unsigned int len, const char *repl)
740 unsigned int repl_len = strlen(repl);
741 if (from > buf->used) return;
742 if (len + from > buf->used) len = buf->used - from;
743 buf->used = buf->used + repl_len - len;
744 if (buf->size <= buf->used) {
745 while (buf->used >= buf->size) {
748 buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
750 memmove(buf->list+from+repl_len, buf->list+from+len, strlen(buf->list+from+len));
751 strcpy(buf->list+from, repl);
754 struct string_list str_tab;
757 strtab(unsigned int ii) {
758 if (ii > 65536) return NULL;
759 if (ii > str_tab.size) {
760 unsigned int old_size = str_tab.size;
761 while (ii >= str_tab.size) str_tab.size <<= 1;
762 str_tab.list = realloc(str_tab.list, str_tab.size*sizeof(str_tab.list[0]));
763 memset(str_tab.list+old_size, 0, (str_tab.size-old_size)*sizeof(str_tab.list[0]));
765 if (!str_tab.list[ii]) {
766 str_tab.list[ii] = malloc(12);
767 sprintf(str_tab.list[ii], "%u", ii);
769 return str_tab.list[ii];
775 unsigned int upr, lwr;
776 for (lwr=0; lwr<256; ++lwr) tolower(lwr) = lwr;
777 for (upr='A', lwr='a'; lwr <= 'z'; ++upr, ++lwr) tolower(upr) = lwr;
778 #ifdef WITH_PROTOCOL_P10
779 for (upr='[', lwr='{'; lwr <= '~'; ++upr, ++lwr) tolower(upr) = lwr;
780 for (upr=0xc0, lwr=0xe0; lwr <= 0xf6; ++upr, ++lwr) tolower(upr) = lwr;
781 for (upr=0xd8, lwr=0xf8; lwr <= 0xfe; ++upr, ++lwr) tolower(upr) = lwr;
784 str_tab.list = calloc(str_tab.size, sizeof(str_tab.list[0]));
791 for (ii=0; ii<str_tab.size; ++ii) {
792 if (str_tab.list[ii]) free(str_tab.list[ii]);