1 /* tools.c - miscellaneous utility functions
2 * Copyright 2000-2004 srvx Development Team
4 * This file is part of srvx.
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.
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.
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.
29 #ifdef HAVE_SYS_SOCKET_H
30 #include <sys/socket.h>
32 #ifdef HAVE_ARPA_INET_H
33 #include <arpa/inet.h>
37 #define NUMNICKBASE (1 << NUMNICKLOG)
38 #define NUMNICKMASK (NUMNICKBASE - 1)
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','[',']'
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
61 base64toint(const char* s, int count)
65 i = (i << NUMNICKLOG) + convert2n[(unsigned char)*s++];
71 const char* inttobase64(char* buf, unsigned int v, unsigned int count)
75 buf[--count] = convert2y[(unsigned char)(v & NUMNICKMASK)];
81 static char irc_tolower[256];
83 #define tolower(X) irc_tolower[(unsigned char)(X)]
86 irccasecmp(const char *stra, const char *strb) {
87 while (*stra && (tolower(*stra) == tolower(*strb)))
89 return tolower(*stra) - tolower(*strb);
93 ircncasecmp(const char *stra, const char *strb, unsigned int len) {
95 while (*stra && (tolower(*stra) == tolower(*strb)) && len)
96 stra++, strb++, len--;
97 return tolower(*stra) - tolower(*strb);
101 irccasestr(const char *haystack, const char *needle) {
102 unsigned int hay_len = strlen(haystack), needle_len = strlen(needle), pos;
103 if (hay_len < needle_len)
105 for (pos=0; pos<hay_len+1-needle_len; ++pos) {
106 if ((tolower(haystack[pos]) == tolower(*needle))
107 && !ircncasecmp(haystack+pos, needle, needle_len))
114 split_line(char *line, int irc_colon, int argv_size, char *argv[])
118 while (*line && (argc < argv_size)) {
121 if (*line == ':' && irc_colon && argc > 0) {
122 /* the rest is a single parameter */
123 argv[argc++] = line + 1;
129 if (argc >= argv_size)
131 while (*line != ' ' && *line)
137 for (n=argc; n<argv_size; n++)
138 argv[n] = (char*)0xFEEDBEEF;
143 /* This is ircu's mmatch() function, from match.c. */
144 int mmatch(const char *old_mask, const char *new_mask)
146 register const char *m = old_mask;
147 register const char *n = new_mask;
168 for (m--; (m > old_mask) && (*m == '?'); m--)
170 if ((*m == '*') && (m > old_mask) && (m[-1] != '\\'))
176 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
177 if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
188 if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?')))
196 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
197 if ((*n == '\\') && ((n[1] == '*') || (n[1] == '?')))
206 * This `if' has been changed compared to match() to do the following:
208 * old (m) new (n) boolean expression
209 * * any (*m == '*' && !mq) ||
210 * ? any except '*' (*m == '?' && !mq && (*n != '*' || nq)) ||
211 * any except * or ? same as m (!((*m == '*' || *m == '?') && !mq) &&
212 * toLower(*m) == toLower(*n) &&
213 * !((mq && !nq) || (!mq && nq)))
215 * Here `any' also includes \* and \? !
217 * After reworking the boolean expressions, we get:
218 * (Optimized to use boolean shortcircuits, with most frequently occuring
219 * cases upfront (which took 2 hours!)).
221 if ((*m == '*' && !mq) ||
222 ((!mq || nq) && tolower(*m) == tolower(*n)) ||
223 (*m == '?' && !mq && (*n != '*' || nq)))
236 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
237 if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
246 match_ircglob(const char *text, const char *glob)
248 unsigned int star_p, q_cnt;
255 /* intentionally not tolower(...) so people can force
256 * capitalization, or we can overload \ in the future */
257 if (*text++ != *glob++)
266 else if (*glob == '?')
278 /* if this is the last glob character, it will match any text */
281 /* Thanks to the loop above, we know that the next
282 * character is a normal character. So just look for
283 * the right character.
285 for (; *text; text++) {
286 if ((tolower(*text) == tolower(*glob))
287 && match_ircglob(text+1, glob+1)) {
293 /* if !star_p, fall through to normal character case,
294 * first checking to see if ?s carried us to the end */
295 if (!*glob && !*text)
300 while (*text && *glob && *glob != '*' && *glob != '?' && *glob != '\\') {
301 if (tolower(*text++) != tolower(*glob++))
308 extern const char *hidden_host_suffix;
311 user_matches_glob(struct userNode *user, const char *orig_glob, int include_nick)
315 /* Make a writable copy of the glob */
316 glob = alloca(strlen(orig_glob)+1);
317 strcpy(glob, orig_glob);
318 /* Check the nick, if it's present */
320 if (!(marker = strchr(glob, '!'))) {
321 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);
325 if (!match_ircglob(user->nick, glob)) return 0;
328 /* Check the ident */
329 if (!(marker = strchr(glob, '@'))) {
330 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);
334 if (!match_ircglob(user->ident, glob))
337 /* Now check the host part */
338 if (isdigit(*glob) && !glob[strspn(glob, "0123456789./*?")]) {
339 /* Looks like an IP-based mask */
340 return match_ircglob(inet_ntoa(user->ip), glob);
342 /* The host part of the mask isn't IP-based */
343 if (IsFakeHost(user) && match_ircglob(user->fakehost, glob))
345 if (hidden_host_suffix && user->handle_info) {
346 char hidden_host[HOSTLEN+1];
347 snprintf(hidden_host, sizeof(hidden_host), "%s.%s", user->handle_info->handle, hidden_host_suffix);
348 if (match_ircglob(hidden_host, glob))
351 return match_ircglob(user->hostname, glob);
356 is_ircmask(const char *text)
358 while (*text && (isalnum((char)*text) || strchr("-_[]|\\`^{}?*", *text)))
362 while (*text && *text != '@' && !isspace((char)*text))
366 while (*text && !isspace((char)*text))
372 is_gline(const char *text)
376 text += strcspn(text, "@!% \t\r\n");
381 while (*text && (isalnum((char)*text) || strchr(".-?*", *text)))
387 split_ircmask(char *text, char **nick, char **ident, char **host)
392 while (isalnum((char)*text) || strchr("=[]\\`^{}?*", *text))
394 if (*text != '!' || ((text - start) > NICKLEN))
401 while (*text && *text != '@' && !isspace((char)*text))
403 if (*text != '@' || ((text - start) > USERLEN))
410 while (*text && (isalnum((char)*text) || strchr(".-?*", *text)))
414 return !*text && ((text - start) <= HOSTLEN) && nick && ident && host;
418 sanitize_ircmask(char *input)
420 unsigned int length, flag;
421 char *mask, *start, *output;
423 /* Sanitize everything in place; input *must* be a valid
428 /* The nick is truncated at the end. */
431 while(*input++ != '!')
440 /* This flag is used to indicate following parts should
449 /* The ident and host must be truncated at the beginning and
450 replaced with a '*' to be compatible with ircu. */
453 while(*input++ != '@')
457 if(length > USERLEN || flag)
461 start = input - USERLEN;
483 if(length > HOSTLEN || flag)
487 start = input - HOSTLEN;
501 TypeLength(char type)
504 case 'y': return 365*24*60*60;
505 case 'M': return 31*24*60*60;
506 case 'w': return 7*24*60*60;
507 case 'd': return 24*60*60;
508 case 'h': return 60*60;
516 ParseInterval(const char *interval)
518 unsigned long seconds = 0;
522 /* process the string, resetting the count if we find a unit character */
523 while ((c = *interval++)) {
524 if (isdigit((int)c)) {
525 partial = partial*10 + c - '0';
527 seconds += TypeLength(c) * partial;
531 /* assume the last chunk is seconds (the normal case) */
532 return seconds + partial;
536 GetSizeMultiplier(char type)
539 case 'G': case 'g': return 1024*1024*1024;
540 case 'M': case 'm': return 1024*1024;
541 case 'K': case 'k': return 1024;
542 case 'B': case 'b': return 1;
548 ParseVolume(const char *volume)
550 unsigned long accum = 0, partial = 0;
552 while ((c = *volume++)) {
553 if (isdigit((int)c)) {
554 partial = partial*10 + c - '0';
556 accum += GetSizeMultiplier(c) * partial;
560 return accum + partial;
564 parse_ipmask(const char *str, struct in_addr *addr, unsigned long *mask)
567 unsigned long t_a, t_m;
571 addr->s_addr = htonl(t_a);
579 accum = (accum * 10) + *str++ - '0';
580 } while (isdigit(*str));
583 t_a = (t_a << 8) | accum;
584 t_m = (t_m << 8) | 255;
588 while (*str == '*') {
595 } else if (*str == 0) {
603 } else if (*str == '/') {
607 accum = (accum * 10) + *str++ - '0';
608 } while (isdigit(*str));
609 while (pos < start+accum && pos < 32) {
610 t_a = (t_a << 1) | 0;
611 t_m = (t_m << 1) | 1;
614 if (pos != start+accum)
616 } else if (*str == 0)
625 addr->s_addr = htonl(t_a);
632 unsplit_string(char *set[], unsigned int max, char *dest)
634 static char unsplit_buffer[MAXLEN*2];
635 unsigned int ii, jj, pos;
638 dest = unsplit_buffer;
639 for (ii=pos=0; ii<max; ii++) {
640 for (jj=0; set[ii][jj]; jj++)
641 dest[pos++] = set[ii][jj];
649 intervalString(char *output, time_t interval, struct handle_info *hi)
651 static const struct {
652 const char *msg_single;
653 const char *msg_plural;
656 { "MSG_YEAR", "MSG_YEARS", 365 * 24 * 60 * 60 },
657 { "MSG_WEEK", "MSG_WEEKS", 7 * 24 * 60 * 60 },
658 { "MSG_DAY", "MSG_DAYS", 24 * 60 * 60 },
659 { "MSG_HOUR", "MSG_HOURS", 60 * 60 },
660 { "MSG_MINUTE", "MSG_MINUTES", 60 },
661 { "MSG_SECOND", "MSG_SECONDS", 1 }
663 struct language *lang;
665 unsigned int type, words, pos, count;
667 lang = hi ? hi->language : lang_C;
670 msg = language_find_message(lang, "MSG_0_SECONDS");
671 return strcpy(output, msg);
674 for (type = 0, words = pos = 0;
675 interval && (words < 2) && (type < ArrayLength(unit));
677 if (interval < unit[type].length)
679 count = interval / unit[type].length;
680 interval = interval % unit[type].length;
683 msg = language_find_message(lang, "MSG_AND");
684 pos += sprintf(output + pos, " %s ", msg);
687 msg = language_find_message(lang, unit[type].msg_single);
689 msg = language_find_message(lang, unit[type].msg_plural);
690 pos += sprintf(output + pos, "%d %s", count, msg);
698 getipbyname(const char *name, unsigned long *ip)
700 struct hostent *he = gethostbyname(name);
703 if (he->h_addrtype != AF_INET)
705 memcpy(ip, he->h_addr_list[0], sizeof(*ip));
709 DEFINE_LIST(string_buffer, char)
712 string_buffer_append_substring(struct string_buffer *buf, const char *tail, unsigned int len)
714 while (buf->used + len >= buf->size) {
719 buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
721 memcpy(buf->list + buf->used, tail, len+1);
726 string_buffer_append_string(struct string_buffer *buf, const char *tail)
728 string_buffer_append_substring(buf, tail, strlen(tail));
732 string_buffer_append_vprintf(struct string_buffer *buf, const char *fmt, va_list args)
738 VA_COPY(working, args);
740 if (!buf->list || ((buf->used + buf->size) < len)) {
741 buf->size = buf->used + len;
742 buf->list = realloc(buf->list, buf->size);
744 ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working);
746 /* pre-C99 behavior; double buffer size until it is big enough */
748 VA_COPY(working, args);
749 while ((ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working)) <= 0) {
751 buf->list = realloc(buf->list, buf->size);
753 VA_COPY(working, args);
756 } else if (buf->used + ret < buf->size) {
757 /* no need to increase allocation size */
760 /* now we know exactly how much space we need */
761 if (buf->size <= buf->used + ret) {
762 buf->size = buf->used + ret + 1;
763 buf->list = realloc(buf->list, buf->size);
766 VA_COPY(working, args);
767 buf->used += vsnprintf(buf->list + buf->used, buf->size, fmt, working);
773 void string_buffer_append_printf(struct string_buffer *buf, const char *fmt, ...)
777 string_buffer_append_vprintf(buf, fmt, args);
781 string_buffer_replace(struct string_buffer *buf, unsigned int from, unsigned int len, const char *repl)
783 unsigned int repl_len = strlen(repl);
784 if (from > buf->used)
786 if (len + from > buf->used)
787 len = buf->used - from;
788 buf->used = buf->used + repl_len - len;
789 if (buf->size <= buf->used) {
790 while (buf->used >= buf->size)
792 buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
794 memmove(buf->list+from+repl_len, buf->list+from+len, strlen(buf->list+from+len));
795 strcpy(buf->list+from, repl);
798 struct string_list str_tab;
801 strtab(unsigned int ii) {
804 if (ii > str_tab.size) {
805 unsigned int old_size = str_tab.size;
806 while (ii >= str_tab.size)
808 str_tab.list = realloc(str_tab.list, str_tab.size*sizeof(str_tab.list[0]));
809 memset(str_tab.list+old_size, 0, (str_tab.size-old_size)*sizeof(str_tab.list[0]));
811 if (!str_tab.list[ii]) {
812 str_tab.list[ii] = malloc(12);
813 sprintf(str_tab.list[ii], "%u", ii);
815 return str_tab.list[ii];
821 unsigned int upr, lwr;
822 for (lwr=0; lwr<256; ++lwr)
824 for (upr='A', lwr='a'; lwr <= 'z'; ++upr, ++lwr)
826 #ifdef WITH_PROTOCOL_P10
827 for (upr='[', lwr='{'; lwr <= '~'; ++upr, ++lwr)
829 for (upr=0xc0, lwr=0xe0; lwr <= 0xf6; ++upr, ++lwr)
831 for (upr=0xd8, lwr=0xf8; lwr <= 0xfe; ++upr, ++lwr)
835 str_tab.list = calloc(str_tab.size, sizeof(str_tab.list[0]));
842 for (ii=0; ii<str_tab.size; ++ii)
843 free(str_tab.list[ii]);