]> jfr.im git - irc/evilnet/x3.git/blob - src/tools.c
Extended channel ban support. As well as text and nick change bans, however these...
[irc/evilnet/x3.git] / src / tools.c
1 /* tools.c - miscellaneous utility functions
2 * Copyright 2000-2004 srvx Development Team
3 *
4 * This file is part of x3.
5 *
6 * x3 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 3 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 void
361 irc_strtolower(char *str) {
362 char *p;
363 for(p = str;*p;p++) {
364 *p = tolower(*p);
365 }
366 }
367
368 int
369 irccasecmp(const char *stra, const char *strb) {
370 while (*stra && (tolower(*stra) == tolower(*strb)))
371 stra++, strb++;
372 return tolower(*stra) - tolower(*strb);
373 }
374
375 int
376 ircncasecmp(const char *stra, const char *strb, unsigned int len) {
377 len--;
378 while (*stra && (tolower(*stra) == tolower(*strb)) && len)
379 stra++, strb++, len--;
380 return tolower(*stra) - tolower(*strb);
381 }
382
383 const char *
384 irccasestr(const char *haystack, const char *needle) {
385 unsigned int hay_len = strlen(haystack), needle_len = strlen(needle), pos;
386 if (hay_len < needle_len)
387 return NULL;
388 for (pos=0; pos<hay_len+1-needle_len; ++pos) {
389 if ((tolower(haystack[pos]) == tolower(*needle))
390 && !ircncasecmp(haystack+pos, needle, needle_len))
391 return haystack+pos;
392 }
393 return NULL;
394 }
395
396 char *
397 ircstrlower(char *str) {
398 size_t ii;
399 for (ii = 0; str[ii] != '\0'; ++ii)
400 str[ii] = tolower(str[ii]);
401 return str;
402 }
403
404 int
405 split_line(char *line, int irc_colon, int argv_size, char *argv[])
406 {
407 int argc = 0;
408 int n;
409 while (*line && (argc < argv_size)) {
410 while (*line == ' ')
411 *line++ = 0;
412 if (*line == ':' && irc_colon && argc > 0) {
413 /* the rest is a single parameter */
414 argv[argc++] = line + 1;
415 break;
416 }
417 if (!*line)
418 break;
419 argv[argc++] = line;
420 if (argc >= argv_size)
421 break;
422 while (*line != ' ' && *line)
423 line++;
424 }
425 #ifdef NDEBUG
426 n = 0;
427 #else
428 for (n=argc; n<argv_size; n++)
429 argv[n] = (char*)0xFEEDBEEF;
430 #endif
431 return argc;
432 }
433
434 /* This is ircu's mmatch() function, from match.c. */
435 int mmatch(const char *old_mask, const char *new_mask)
436 {
437 register const char *m = old_mask;
438 register const char *n = new_mask;
439 const char *ma = m;
440 const char *na = n;
441 int wild = 0;
442 int mq = 0, nq = 0;
443
444 while (1)
445 {
446 if (*m == '*')
447 {
448 while (*m == '*')
449 m++;
450 wild = 1;
451 ma = m;
452 na = n;
453 }
454
455 if (!*m)
456 {
457 if (!*n)
458 return 0;
459 for (m--; (m > old_mask) && (*m == '?'); m--)
460 ;
461 if ((*m == '*') && (m > old_mask) && (m[-1] != '\\'))
462 return 0;
463 if (!wild)
464 return 1;
465 m = ma;
466
467 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
468 if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
469 ++na;
470
471 n = ++na;
472 }
473 else if (!*n)
474 {
475 while (*m == '*')
476 m++;
477 return (*m != 0);
478 }
479 if ((*m == '\\') && ((m[1] == '*') || (m[1] == '?')))
480 {
481 m++;
482 mq = 1;
483 }
484 else
485 mq = 0;
486
487 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
488 if ((*n == '\\') && ((n[1] == '*') || (n[1] == '?')))
489 {
490 n++;
491 nq = 1;
492 }
493 else
494 nq = 0;
495
496 /*
497 * This `if' has been changed compared to match() to do the following:
498 * Match when:
499 * old (m) new (n) boolean expression
500 * * any (*m == '*' && !mq) ||
501 * ? any except '*' (*m == '?' && !mq && (*n != '*' || nq)) ||
502 * any except * or ? same as m (!((*m == '*' || *m == '?') && !mq) &&
503 * toLower(*m) == toLower(*n) &&
504 * !((mq && !nq) || (!mq && nq)))
505 *
506 * Here `any' also includes \* and \? !
507 *
508 * After reworking the boolean expressions, we get:
509 * (Optimized to use boolean shortcircuits, with most frequently occuring
510 * cases upfront (which took 2 hours!)).
511 */
512 if ((*m == '*' && !mq) ||
513 ((!mq || nq) && tolower(*m) == tolower(*n)) ||
514 (*m == '?' && !mq && (*n != '*' || nq)))
515 {
516 if (*m)
517 m++;
518 if (*n)
519 n++;
520 }
521 else
522 {
523 if (!wild)
524 return 1;
525 m = ma;
526
527 /* Added to `mmatch' : Because '\?' and '\*' now is one character: */
528 if ((*na == '\\') && ((na[1] == '*') || (na[1] == '?')))
529 ++na;
530
531 n = ++na;
532 }
533 }
534 }
535
536 int
537 match_ircglob(const char *text, const char *glob)
538 {
539 const char *m = glob, *n = text;
540 const char *m_tmp = glob, *n_tmp = text;
541 int star_p;
542
543 for (;;) switch (*m) {
544 case '\0':
545 if (!*n)
546 return 1;
547 backtrack:
548 if (m_tmp == glob)
549 return 0;
550 m = m_tmp;
551 n = ++n_tmp;
552 if (!*n)
553 return 0;
554 break;
555 case '\\':
556 m++;
557 /* allow escaping to force capitalization */
558 if (*m++ != *n++)
559 goto backtrack;
560 break;
561 case '*': case '?':
562 for (star_p = 0; ; m++) {
563 if (*m == '*')
564 star_p = 1;
565 else if (*m == '?') {
566 if (!*n++)
567 goto backtrack;
568 } else break;
569 }
570 if (star_p) {
571 if (!*m)
572 return 1;
573 else if (*m == '\\') {
574 m_tmp = ++m;
575 if (!*m)
576 return 0;
577 for (n_tmp = n; *n && *n != *m; n++) ;
578 } else {
579 m_tmp = m;
580 for (n_tmp = n; *n && tolower(*n) != tolower(*m); n++) ;
581 }
582 }
583 /* and fall through */
584 default:
585 if (!*n)
586 return *m == '\0';
587 if (tolower(*m) != tolower(*n))
588 goto backtrack;
589 m++;
590 n++;
591 break;
592 }
593 }
594
595 extern const char *hidden_host_suffix;
596
597 /* Prevent *@* *@** *@*a* type masks, while allowing anything else. This is the best way iv found to detect
598 * a global matching mask; if it matches this string, it'll match almost anything :) */
599 int is_overmask(char *mask)
600 {
601 return(match_ircglob("abcdefghijklmnopqrstuv!frcmbghilnrtoasde@apdic.yfa.dsfsdaffsdasfdasfd.abcdefghijklmnopqrstuvwxyz.asdfasfdfsdsfdasfda.ydfbe", mask));
602 }
603
604 int
605 user_matches_glob(struct userNode *user, const char *orig_glob, int flags)
606 {
607 char *tmpglob, *glob, *marker, *echannel, *emodes;
608 char exttype = 0;
609 int extreverse = 0, is_extended = 0, match = 0, banned = 0;
610 unsigned int count, n;
611 struct modeNode *mn;
612
613 /* Make a writable copy of the glob */
614 glob = alloca(strlen(orig_glob)+1);
615 strcpy(glob, orig_glob);
616
617 /* Extended bans */
618 tmpglob = alloca(strlen(orig_glob)+1);
619 tmpglob = strdup(orig_glob);
620
621 if (*tmpglob == '~') {
622 tmpglob++; /* get rid of the ~ */
623
624 if (*tmpglob == '!') {
625 extreverse = 1;
626 tmpglob++; /* get rid of the ! */
627 }
628
629 exttype = *tmpglob;
630 tmpglob++; /* get rid of the type */
631
632 if (*tmpglob == ':') {
633 is_extended = 1;
634 tmpglob++; /* get rid of the : */
635 glob = strdup(tmpglob);
636 }
637 }
638
639 if (is_extended) {
640 log_module(MAIN_LOG, LOG_DEBUG, "Extended ban. T (%c) R (%d) M (%s)", exttype, extreverse, glob);
641 switch (exttype) {
642 case 'a':
643 if (user->handle_info) {
644 if (extreverse) {
645 if (0 != strcasecmp(glob, user->handle_info->handle))
646 return 1;
647 } else {
648 if (0 == strcasecmp(glob, user->handle_info->handle))
649 return 1;
650 }
651 } else {
652 if (extreverse)
653 return 1;
654 }
655 return match_ircglob(user->hostname, glob);
656 case 'c':
657 if (!strstr(glob, "#"))
658 return 0;
659
660 tmpglob = strdup(glob);
661 if (*glob != '#') {
662 echannel = strstr(glob, "#");
663 emodes = strtok(tmpglob, "#");
664 } else {
665 echannel = strdup(glob);
666 emodes = "";
667 }
668
669 if (extreverse) {
670 for (n=count=0; n<user->channels.used; n++) {
671 mn = user->channels.list[n];
672 match = 0;
673
674 if (0 == strcasecmp(echannel, mn->channel->name)) {
675 if (strlen(emodes) > 0) {
676 if (mn->modes & MODE_CHANOP) {
677 if (strstr(emodes, "@"))
678 match = 1;
679 }
680 if (mn->modes & MODE_HALFOP) {
681 if (strstr(emodes, "%"))
682 match = 1;
683 }
684 if (mn->modes & MODE_VOICE) {
685 if (strstr(emodes, "+"))
686 match = 1;
687 }
688 } else
689 match = 1;
690 }
691
692 if (match == 0)
693 banned = 1;
694 else {
695 banned = 0;
696 break;
697 }
698 }
699 } else {
700 for (n=count=0; n<user->channels.used; n++) {
701 mn = user->channels.list[n];
702 match = 0;
703
704 if (0 == strcasecmp(echannel, mn->channel->name)) {
705 if (strlen(emodes) > 0) {
706 if (mn->modes & MODE_CHANOP) {
707 if (strstr(emodes, "@"))
708 match = 1;
709 }
710 if (mn->modes & MODE_HALFOP) {
711 if (strstr(emodes, "%"))
712 match = 1;
713 }
714 if (mn->modes & MODE_VOICE) {
715 if (strstr(emodes, "+"))
716 match = 1;
717 }
718 } else
719 match = 1;
720 }
721 if (match == 1)
722 banned = 1;
723 }
724 }
725
726 if (banned)
727 return 1;
728 else
729 return match_ircglob(user->hostname, glob);
730 case 'n': /* this is handled ircd side */
731 return match_ircglob(user->hostname, glob);
732 case 't': /* this is handled ircd side */
733 return match_ircglob(user->hostname, glob);
734 default:
735 return 0;
736 }
737 }
738
739 /* Check the nick, if it's present */
740 if (flags & MATCH_USENICK) {
741 if (!(marker = strchr(glob, '!'))) {
742 log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include a '!'", user->nick, orig_glob, flags);
743 return 0;
744 }
745 *marker = 0;
746 if (!match_ircglob(user->nick, glob)) return 0;
747 glob = marker + 1;
748 }
749 /* Check the ident */
750 if (!(marker = strchr(glob, '@'))) {
751 log_module(MAIN_LOG, LOG_ERROR, "user_matches_glob(\"%s\", \"%s\", %d) called, and glob doesn't include an '@'", user->nick, orig_glob, flags);
752 return 0;
753 }
754 *marker = 0;
755 if (!match_ircglob(user->ident, glob))
756 return 0;
757 glob = marker + 1;
758 /* Check for a fakehost match. */
759 if (IsFakeHost(user) && match_ircglob(user->fakehost, glob))
760 return 1;
761
762 /* Check for a sethost (S:lines) */
763 if (IsSetHost(user) && match_ircglob(user->sethost, glob))
764 return 1;
765
766 /* Check for an account match. */
767 if (hidden_host_suffix && user->handle_info) {
768 char hidden_host[HOSTLEN+1];
769 snprintf(hidden_host, sizeof(hidden_host), "%s.%s", user->handle_info->handle, hidden_host_suffix);
770 if (match_ircglob(hidden_host, glob))
771 return 1;
772 }
773
774 /* Match crypt hostname */
775 if (match_ircglob(user->crypthost, glob))
776 return 1;
777
778 /* Match crypt IP */
779 if (match_ircglob(user->cryptip, glob))
780 return 1;
781
782 /* If only matching the visible hostnames, bail early. */
783 if ((flags & MATCH_VISIBLE) && IsHiddenHost(user)
784 && (IsFakeHost(user) || (hidden_host_suffix && user->handle_info)))
785 return 0;
786 /* If it might be an IP glob, test that. */
787 if (!glob[strspn(glob, "0123456789./*?")]
788 && match_ircglob(irc_ntoa(&user->ip), glob))
789 return 1;
790 /* None of the above; could only be a hostname match. */
791 return match_ircglob(user->hostname, glob);
792 }
793
794 int
795 is_ircmask(const char *text)
796 {
797 char *tmptext;
798
799 if (*text == '~') {
800 tmptext = alloca(strlen(text)+1);
801 tmptext = strdup(text);
802
803 tmptext++; /* get rid of the ~ */
804
805 if (*tmptext == '!')
806 tmptext++; /* get rid of the ! if it exists */
807
808 tmptext++; /* get rid of the ext ban type */
809
810 if (*tmptext == ':') {
811 tmptext++; /* get rid of the : */
812 while (*tmptext && !isspace((char)*tmptext))
813 tmptext++; /* get rid of the rest */
814 return !*tmptext;
815 }
816 }
817
818 while (*text && (isalnum((char)*text) || strchr("-_[]|\\`^{}?*", *text)))
819 text++;
820 if (*text++ != '!')
821 return 0;
822 while (*text && *text != '@' && !isspace((char)*text))
823 text++;
824 if (*text++ != '@')
825 return 0;
826 while (*text && !isspace((char)*text))
827 text++;
828 return !*text;
829 }
830
831 int
832 is_gline(const char *text)
833 {
834 if (*text == '@')
835 return 0;
836 text += strcspn(text, "@!% \t\r\n");
837 if (*text++ != '@')
838 return 0;
839 if (!*text)
840 return 0;
841 while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
842 text++;
843 return !*text;
844 }
845
846 int
847 is_shun(const char *text)
848 {
849 if (*text == '@')
850 return 0;
851 text += strcspn(text, "@!% \t\r\n");
852 if (*text++ != '@')
853 return 0;
854 if (!*text)
855 return 0;
856 while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
857 text++;
858 return !*text;
859 }
860
861 int
862 split_ircmask(char *text, char **nick, char **ident, char **host)
863 {
864 char *start;
865
866 start = text;
867 while (isalnum((char)*text) || strchr("=[]\\`^{}?*", *text))
868 text++;
869 if (*text != '!' || ((text - start) > NICKLEN))
870 return 0;
871 *text = 0;
872 if (nick)
873 *nick = start;
874
875 start = ++text;
876 while (*text && *text != '@' && !isspace((char)*text))
877 text++;
878 if (*text != '@' || ((text - start) > USERLEN))
879 return 0;
880 *text = 0;
881 if (ident)
882 *ident = start;
883
884 start = ++text;
885 while (*text && (isalnum((char)*text) || strchr(".-?*:", *text)))
886 text++;
887 if (host)
888 *host = start;
889 return !*text && ((text - start) <= HOSTLEN) && nick && ident && host;
890 }
891
892 char *
893 sanitize_ircmask(char *input)
894 {
895 unsigned int length, flag;
896 char *mask, *start, *output;
897
898 /* Sanitize everything in place; input *must* be a valid
899 hostmask. */
900 output = input;
901 flag = 0;
902
903 /* The nick is truncated at the end. */
904 length = 0;
905 mask = input;
906 while(*input++ != '!')
907 {
908 length++;
909 }
910 if(length > NICKLEN)
911 {
912 mask += NICKLEN;
913 *mask++ = '!';
914
915 /* This flag is used to indicate following parts should
916 be shifted. */
917 flag = 1;
918 }
919 else
920 {
921 mask = input;
922 }
923
924 /* The ident and host must be truncated at the beginning and
925 replaced with a '*' to be compatible with ircu. */
926 length = 0;
927 start = input;
928 while(*input++ != '@')
929 {
930 length++;
931 }
932 if(length > USERLEN || flag)
933 {
934 if(length > USERLEN)
935 {
936 start = input - USERLEN;
937 *mask++ = '*';
938 }
939 while(*start != '@')
940 {
941 *mask++ = *start++;
942 }
943 *mask++ = '@';
944
945 flag = 1;
946 }
947 else
948 {
949 mask = input;
950 }
951
952 length = 0;
953 start = input;
954 while(*input++)
955 {
956 length++;
957 }
958 if(length > HOSTLEN || flag)
959 {
960 if(length > HOSTLEN)
961 {
962 start = input - HOSTLEN;
963 *mask++ = '*';
964 }
965 while(*start)
966 {
967 *mask++ = *start++;
968 }
969 *mask = '\0';
970 }
971
972 return output;
973 }
974
975 static long
976 TypeLength(char type)
977 {
978 switch (type) {
979 case 'y': return 365*24*60*60;
980 case 'M': return 30*24*60*60;
981 case 'w': return 7*24*60*60;
982 case 'd': return 24*60*60;
983 case 'h': return 60*60;
984 case 'm': return 60;
985 case 's': return 1;
986 default: return 0;
987 }
988 }
989
990 /* This function is not entirely accurate as it does not take into account leap units
991 * or varying months. TODO: use proper dateadd functions to calculate real seconds
992 * from now for the units (eg 1M should be give us seconds till todays date next month)
993 */
994 unsigned long
995 ParseInterval(const char *interval)
996 {
997 unsigned long seconds = 0;
998 int partial = 0;
999 char c;
1000
1001 /* process the string, resetting the count if we find a unit character */
1002 while ((c = *interval++)) {
1003 if (isdigit((int)c)) {
1004 partial = partial*10 + c - '0';
1005 } else if (strchr("yMwdhms", c)) {
1006 seconds += TypeLength(c) * partial;
1007 partial = 0;
1008 } else {
1009 return 0;
1010 }
1011 }
1012 /* assume the last chunk is seconds (the normal case) */
1013 return seconds + partial;
1014 }
1015
1016 static long
1017 GetSizeMultiplier(char type)
1018 {
1019 switch (type) {
1020 case 'G': case 'g': return 1024*1024*1024;
1021 case 'M': case 'm': return 1024*1024;
1022 case 'K': case 'k': return 1024;
1023 case 'B': case 'b': return 1;
1024 default: return 0;
1025 }
1026 }
1027
1028 unsigned long
1029 ParseVolume(const char *volume)
1030 {
1031 unsigned long accum = 0, partial = 0;
1032 char c;
1033 while ((c = *volume++)) {
1034 if (isdigit((int)c)) {
1035 partial = partial*10 + c - '0';
1036 } else {
1037 accum += GetSizeMultiplier(c) * partial;
1038 partial = 0;
1039 }
1040 }
1041 return accum + partial;
1042 }
1043
1044 char *
1045 unsplit_string(char *set[], unsigned int max, char *dest)
1046 {
1047 static char unsplit_buffer[MAXLEN*2];
1048 unsigned int ii, jj, pos;
1049
1050 if (!dest)
1051 dest = unsplit_buffer;
1052 for (ii=pos=0; ii<max; ii++) {
1053 for (jj=0; set[ii][jj]; jj++)
1054 dest[pos++] = set[ii][jj];
1055 dest[pos++] = ' ';
1056 }
1057 dest[--pos] = 0;
1058 return dest;
1059 }
1060
1061 char *
1062 intervalString(char *output, time_t interval, struct handle_info *hi)
1063 {
1064 static const struct {
1065 const char *msg_single;
1066 const char *msg_plural;
1067 long length;
1068 } unit[] = {
1069 { "MSG_YEAR", "MSG_YEARS", 365 * 24 * 60 * 60 },
1070 { "MSG_WEEK", "MSG_WEEKS", 7 * 24 * 60 * 60 },
1071 { "MSG_DAY", "MSG_DAYS", 24 * 60 * 60 },
1072 { "MSG_HOUR", "MSG_HOURS", 60 * 60 },
1073 { "MSG_MINUTE", "MSG_MINUTES", 60 },
1074 { "MSG_SECOND", "MSG_SECONDS", 1 }
1075 };
1076 struct language *lang;
1077 const char *msg;
1078 unsigned int type, words, pos, count;
1079
1080 lang = hi ? hi->language : lang_C;
1081 if(!interval)
1082 {
1083 msg = language_find_message(lang, "MSG_0_SECONDS");
1084 return strcpy(output, msg);
1085 }
1086
1087 for (type = 0, words = pos = 0;
1088 interval && (words < 2) && (type < ArrayLength(unit));
1089 type++) {
1090 if (interval < unit[type].length)
1091 continue;
1092 count = interval / unit[type].length;
1093 interval = interval % unit[type].length;
1094
1095 if (words++ == 1) {
1096 msg = language_find_message(lang, "MSG_AND");
1097 pos += sprintf(output + pos, "%s ", msg);
1098 }
1099 if (count == 1)
1100 msg = language_find_message(lang, unit[type].msg_single);
1101 else
1102 msg = language_find_message(lang, unit[type].msg_plural);
1103 pos += sprintf(output + pos, "%d%s", count, msg);
1104 }
1105
1106 output[pos] = 0;
1107 return output;
1108 }
1109
1110 int
1111 getipbyname(const char *name, unsigned long *ip)
1112 {
1113 struct hostent *he = gethostbyname(name);
1114 if (!he)
1115 return 0;
1116 if (he->h_addrtype != AF_INET)
1117 return 0;
1118 memcpy(ip, he->h_addr_list[0], sizeof(*ip));
1119 return 1;
1120 }
1121
1122 DEFINE_LIST(string_buffer, char)
1123
1124 void
1125 string_buffer_append_substring(struct string_buffer *buf, const char *tail, unsigned int len)
1126 {
1127 while (buf->used + len >= buf->size) {
1128 if (!buf->size)
1129 buf->size = 16;
1130 else
1131 buf->size <<= 1;
1132 buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
1133 }
1134 memcpy(buf->list + buf->used, tail, len+1);
1135 buf->used += len;
1136 }
1137
1138 void
1139 string_buffer_append_string(struct string_buffer *buf, const char *tail)
1140 {
1141 string_buffer_append_substring(buf, tail, strlen(tail));
1142 }
1143
1144 void
1145 string_buffer_append_vprintf(struct string_buffer *buf, const char *fmt, va_list args)
1146 {
1147 va_list working;
1148 unsigned int len;
1149 int ret;
1150
1151 VA_COPY(working, args);
1152 len = strlen(fmt);
1153 if (!buf->list || ((buf->used + buf->size) < len)) {
1154 buf->size = buf->used + len;
1155 buf->list = realloc(buf->list, buf->size);
1156 }
1157 ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working);
1158 if (ret <= 0) {
1159 /* pre-C99 behavior; double buffer size until it is big enough */
1160 va_end(working);
1161 VA_COPY(working, args);
1162 while ((ret = vsnprintf(buf->list + buf->used, buf->size - buf->used, fmt, working)) <= 0) {
1163 buf->size += len;
1164 buf->list = realloc(buf->list, buf->size);
1165 va_end(working);
1166 VA_COPY(working, args);
1167 }
1168 buf->used += ret;
1169 } else if (buf->used + ret < buf->size) {
1170 /* no need to increase allocation size */
1171 buf->used += ret;
1172 } else {
1173 /* now we know exactly how much space we need */
1174 if (buf->size <= buf->used + ret) {
1175 buf->size = buf->used + ret + 1;
1176 buf->list = realloc(buf->list, buf->size);
1177 }
1178 va_end(working);
1179 VA_COPY(working, args);
1180 buf->used += vsnprintf(buf->list + buf->used, buf->size, fmt, working);
1181 }
1182 va_end(working);
1183 va_end(args);
1184 }
1185
1186 void string_buffer_append_printf(struct string_buffer *buf, const char *fmt, ...)
1187 {
1188 va_list args;
1189 va_start(args, fmt);
1190 string_buffer_append_vprintf(buf, fmt, args);
1191 }
1192
1193 void
1194 string_buffer_replace(struct string_buffer *buf, unsigned int from, unsigned int len, const char *repl)
1195 {
1196 unsigned int repl_len = strlen(repl);
1197 if (from > buf->used)
1198 return;
1199 if (len + from > buf->used)
1200 len = buf->used - from;
1201 buf->used = buf->used + repl_len - len;
1202 if (buf->size <= buf->used) {
1203 while (buf->used >= buf->size)
1204 buf->size <<= 1;
1205 buf->list = realloc(buf->list, buf->size*sizeof(buf->list[0]));
1206 }
1207 memmove(buf->list+from+repl_len, buf->list+from+len, strlen(buf->list+from+len));
1208 strcpy(buf->list+from, repl);
1209 }
1210
1211 struct string_list str_tab;
1212
1213 const char *
1214 strtab(unsigned int ii) {
1215 if (ii > 65536)
1216 return NULL;
1217 if (ii > str_tab.size) {
1218 unsigned int old_size = str_tab.size;
1219 while (ii >= str_tab.size)
1220 str_tab.size <<= 1;
1221 str_tab.list = realloc(str_tab.list, str_tab.size*sizeof(str_tab.list[0]));
1222 memset(str_tab.list+old_size, 0, (str_tab.size-old_size)*sizeof(str_tab.list[0]));
1223 }
1224 if (!str_tab.list[ii]) {
1225 str_tab.list[ii] = malloc(12);
1226 sprintf(str_tab.list[ii], "%u", ii);
1227 }
1228 return str_tab.list[ii];
1229 }
1230
1231 void
1232 tools_init(void)
1233 {
1234 unsigned int upr, lwr;
1235 for (lwr=0; lwr<256; ++lwr)
1236 tolower(lwr) = lwr;
1237 for (upr='A', lwr='a'; lwr <= 'z'; ++upr, ++lwr)
1238 tolower(upr) = lwr;
1239 #ifdef WITH_PROTOCOL_P10
1240 for (upr='[', lwr='{'; lwr <= '~'; ++upr, ++lwr)
1241 tolower(upr) = lwr;
1242 for (upr=0xc0, lwr=0xe0; lwr <= 0xf6; ++upr, ++lwr)
1243 tolower(upr) = lwr;
1244 for (upr=0xd8, lwr=0xf8; lwr <= 0xfe; ++upr, ++lwr)
1245 tolower(upr) = lwr;
1246 #endif
1247 str_tab.size = 1001;
1248 str_tab.list = calloc(str_tab.size, sizeof(str_tab.list[0]));
1249 }
1250
1251 void
1252 tools_cleanup(void)
1253 {
1254 unsigned int ii;
1255 for (ii=0; ii<str_tab.size; ++ii)
1256 free(str_tab.list[ii]);
1257 free(str_tab.list);
1258 }
1259
1260 /* mysep() is my answer to the strtok/strsep
1261 * issue. strsep is nice but doesn't skip
1262 * multiple dilimiters, which can really
1263 * offset tokens and cause huge corruption
1264 * so this function will use strsep but
1265 * act like strtok in that sense.
1266 */
1267 char *mysep(char **sepstr, char *delim)
1268 {
1269 static char *retstr;
1270
1271 if(!*sepstr || !**sepstr)
1272 return(NULL);
1273
1274 do
1275 {
1276 retstr = strsep(sepstr, delim);
1277 }while (retstr && !(*retstr));
1278
1279 return(retstr);
1280 }
1281
1282 /* Mallocing snprintf *
1283 *
1284 * If it overruns size, it will simply be safely truncated.
1285 */
1286 char *
1287 x3_msnprintf(const int size, const char *format, ...)
1288 {
1289 va_list ap;
1290 char* buff = calloc(sizeof(char *), size+1);
1291
1292 va_start(ap, format);
1293 vsnprintf(buff, size, format, ap);
1294 va_end(ap);
1295 buff = realloc(buff, strlen(buff) + 1);
1296 return buff;
1297 }
1298
1299 char *time2str(time_t thetime)
1300 {
1301 char *buf, *tmp;
1302
1303 buf = ctime(&thetime);
1304 tmp = (char *)strchr(buf, '\n');
1305 *tmp = '\0';
1306 return(buf);
1307 }
1308
1309 char* x3_strtok(char **save, char *str, char *fs)
1310 {
1311 char *pos = *save; /* keep last position across calls */
1312 char *tmp;
1313
1314 if (str)
1315 pos = str; /* new string scan */
1316
1317 while (pos && *pos && strchr(fs, *pos) != NULL)
1318 pos++; /* skip leading separators */
1319
1320 if (!pos || !*pos)
1321 return (pos = *save = NULL); /* string contains only sep's */
1322
1323 tmp = pos; /* now, keep position of the token */
1324
1325 while (*pos && strchr(fs, *pos) == NULL)
1326 pos++; /* skip content of the token */
1327
1328 if (*pos)
1329 *pos++ = '\0'; /* remove first sep after the token */
1330 else
1331 pos = NULL; /* end of string */
1332
1333 *save = pos;
1334 return (tmp);
1335 }
1336
1337 int valid_email(const char *email)
1338 {
1339 unsigned int i;
1340 for (i=0;i<strlen(email);i++)
1341 {
1342 if(!isalnum(email[i]) &&
1343 email[i] != '.' &&
1344 email[i] != '@' &&
1345 email[i] != '-' &&
1346 email[i] != '+' &&
1347 email[i] != '_' )
1348 return false;
1349 }
1350 if(strchr(email, '@') == NULL)
1351 return false;
1352 return true;
1353 }
1354
1355 /*
1356 * Create a string of form "foo!bar@fubar" given foo, bar and fubar
1357 * as the parameters. If NULL, they become "*".
1358 */
1359 #define NUH_BUFSIZE (NICKLEN + USERLEN + HOSTLEN + 10)
1360 static char *make_nick_user_host(char *namebuf, const char *nick,
1361 const char *name, const char *host)
1362 {
1363 snprintf(namebuf, NUH_BUFSIZE, "%s!%s@%s", nick, name, host);
1364 return namebuf;
1365 }
1366
1367 /*
1368 * pretty_mask
1369 *
1370 * by Carlo Wood (Run), 05 Oct 1998.
1371 *
1372 * Canonify a mask.
1373 *
1374 * When the nick is longer then NICKLEN, it is cut off (its an error of course).
1375 * When the user name or host name are too long (USERLEN and HOSTLEN
1376 * respectively) then they are cut off at the start with a '*'.
1377 *
1378 * The following transformations are made:
1379 *
1380 * 1) xxx -> nick!*@*
1381 * 2) xxx.xxx -> *!*@host
1382 * 3) xxx!yyy -> nick!user@*
1383 * 4) xxx@yyy -> *!user@host
1384 * 5) xxx!yyy@zzz -> nick!user@host
1385 */
1386 char *pretty_mask(char *mask)
1387 {
1388 static char star[2] = { '*', 0 };
1389 static char retmask[NUH_BUFSIZE] = "";
1390 char *last_dot = NULL;
1391 char *ptr = NULL;
1392
1393 /* Case 1: default */
1394 char *nick = mask;
1395 char *user = star;
1396 char *host = star;
1397
1398 /* Do a _single_ pass through the characters of the mask: */
1399 for (ptr = mask; *ptr; ++ptr)
1400 {
1401 if (*ptr == '!')
1402 {
1403 /* Case 3 or 5: Found first '!' (without finding a '@' yet) */
1404 user = ++ptr;
1405 host = star;
1406 }
1407 else if (*ptr == '@')
1408 {
1409 /* Case 4: Found last '@' (without finding a '!' yet) */
1410 nick = star;
1411 user = mask;
1412 host = ++ptr;
1413 }
1414 else if (*ptr == '.')
1415 {
1416 /* Case 2: Found last '.' (without finding a '!' or '@' yet) */
1417 last_dot = ptr;
1418 continue;
1419 }
1420 else
1421 continue;
1422 for (; *ptr; ++ptr)
1423 {
1424 if (*ptr == '@')
1425 {
1426 /* Case 4 or 5: Found last '@' */
1427 host = ptr + 1;
1428 }
1429 }
1430 break;
1431 }
1432 if (user == star && last_dot)
1433 {
1434 /* Case 2: */
1435 nick = star;
1436 user = star;
1437 host = mask;
1438 }
1439 /* Check lengths */
1440 if (nick != star)
1441 {
1442 char *nick_end = (user != star) ? user - 1 : ptr;
1443 if (nick_end - nick > NICKLEN)
1444 nick[NICKLEN] = 0;
1445 *nick_end = 0;
1446 }
1447 if (user != star)
1448 {
1449 char *user_end = (host != star) ? host - 1 : ptr;
1450 if (user_end - user > USERLEN)
1451 {
1452 user = user_end - USERLEN;
1453 *user = '*';
1454 }
1455 *user_end = 0;
1456 }
1457 if (host != star && ptr - host > HOSTLEN)
1458 {
1459 host = ptr - HOSTLEN;
1460 *host = '*';
1461 }
1462 return make_nick_user_host(retmask, nick, user, host);
1463 }
1464
1465 int str_is_number(const char *str)
1466 {
1467 char *ptr;
1468 int ret = false;
1469 for(ptr = (char *)str;*ptr;ptr++) {
1470 if((*ptr >= '0' && *ptr <= '9') || *ptr == '-')
1471 ret = true;
1472 else
1473 return false;
1474 }
1475 return ret;
1476 }