Fix input and output bugs in P10 IPv6 addresses with zero elements.
[srvx.git] / src / proto-p10.c
1 /* proto-p10.c - IRC protocol output
2  * Copyright 2000-2008 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 "proto-common.c"
22
23 /* Full commands. */
24 #define CMD_ACCOUNT             "ACCOUNT"
25 #define CMD_ADMIN               "ADMIN"
26 #define CMD_ASLL                "ASLL"
27 #define CMD_AWAY                "AWAY"
28 #define CMD_BURST               "BURST"
29 #define CMD_CLEARMODE           "CLEARMODE"
30 #define CMD_CLOSE               "CLOSE"
31 #define CMD_CNOTICE             "CNOTICE"
32 #define CMD_CONNECT             "CONNECT"
33 #define CMD_CPRIVMSG            "CPRIVMSG"
34 #define CMD_CREATE              "CREATE"
35 #define CMD_DESTRUCT            "DESTRUCT"
36 #define CMD_DESYNCH             "DESYNCH"
37 #define CMD_DIE                 "DIE"
38 #define CMD_DNS                 "DNS"
39 #define CMD_EOB                 "END_OF_BURST"
40 #define CMD_EOB_ACK             "EOB_ACK"
41 #define CMD_ERROR               "ERROR"
42 #define CMD_FAKEHOST            "FAKE"
43 #define CMD_GET                 "GET"
44 #define CMD_GLINE               "GLINE"
45 #define CMD_HASH                "HASH"
46 #define CMD_HELP                "HELP"
47 #define CMD_INFO                "INFO"
48 #define CMD_INVITE              "INVITE"
49 #define CMD_ISON                "ISON"
50 #define CMD_JOIN                "JOIN"
51 #define CMD_JUPE                "JUPE"
52 #define CMD_KICK                "KICK"
53 #define CMD_KILL                "KILL"
54 #define CMD_LINKS               "LINKS"
55 #define CMD_LIST                "LIST"
56 #define CMD_LUSERS              "LUSERS"
57 #define CMD_MAP                 "MAP"
58 #define CMD_MODE                "MODE"
59 #define CMD_MOTD                "MOTD"
60 #define CMD_NAMES               "NAMES"
61 #define CMD_NICK                "NICK"
62 #define CMD_NOTICE              "NOTICE"
63 #define CMD_OPER                "OPER"
64 #define CMD_OPMODE              "OPMODE"
65 #define CMD_PART                "PART"
66 #define CMD_PASS                "PASS"
67 #define CMD_PING                "PING"
68 #define CMD_PONG                "PONG"
69 #define CMD_POST                "POST"
70 #define CMD_PRIVMSG             "PRIVMSG"
71 #define CMD_PRIVS               "PRIVS"
72 #define CMD_PROTO               "PROTO"
73 #define CMD_QUIT                "QUIT"
74 #define CMD_REHASH              "REHASH"
75 #define CMD_RESET               "RESET"
76 #define CMD_RESTART             "RESTART"
77 #define CMD_RPING               "RPING"
78 #define CMD_RPONG               "RPONG"
79 #define CMD_SERVER              "SERVER"
80 #define CMD_SERVLIST            "SERVLIST"
81 #define CMD_SERVSET             "SERVSET"
82 #define CMD_SET                 "SET"
83 #define CMD_SETTIME             "SETTIME"
84 #define CMD_SILENCE             "SILENCE"
85 #define CMD_SQUERY              "SQUERY"
86 #define CMD_SQUIT               "SQUIT"
87 #define CMD_STATS               "STATS"
88 #define CMD_SVSNICK             "SVSNICK"
89 #define CMD_TIME                "TIME"
90 #define CMD_TOPIC               "TOPIC"
91 #define CMD_TRACE               "TRACE"
92 #define CMD_UPING               "UPING"
93 #define CMD_USER                "USER"
94 #define CMD_USERHOST            "USERHOST"
95 #define CMD_USERIP              "USERIP"
96 #define CMD_VERSION             "VERSION"
97 #define CMD_WALLCHOPS           "WALLCHOPS"
98 #define CMD_WALLOPS             "WALLOPS"
99 #define CMD_WALLUSERS           "WALLUSERS"
100 #define CMD_WALLVOICES          "WALLVOICES"
101 #define CMD_WHO                 "WHO"
102 #define CMD_WHOIS               "WHOIS"
103 #define CMD_WHOWAS              "WHOWAS"
104
105 /* Tokenized commands. */
106 #define TOK_ACCOUNT             "AC"
107 #define TOK_ADMIN               "AD"
108 #define TOK_ASLL                "LL"
109 #define TOK_AWAY                "A"
110 #define TOK_BURST               "B"
111 #define TOK_CLEARMODE           "CM"
112 #define TOK_CLOSE               "CLOSE"
113 #define TOK_CNOTICE             "CN"
114 #define TOK_CONNECT             "CO"
115 #define TOK_CPRIVMSG            "CP"
116 #define TOK_CREATE              "C"
117 #define TOK_DESTRUCT            "DE"
118 #define TOK_DESYNCH             "DS"
119 #define TOK_DIE                 "DIE"
120 #define TOK_DNS                 "DNS"
121 #define TOK_EOB                 "EB"
122 #define TOK_EOB_ACK             "EA"
123 #define TOK_ERROR               "Y"
124 #define TOK_FAKEHOST            "FA"
125 #define TOK_GET                 "GET"
126 #define TOK_GLINE               "GL"
127 #define TOK_HASH                "HASH"
128 #define TOK_HELP                "HELP"
129 #define TOK_INFO                "F"
130 #define TOK_INVITE              "I"
131 #define TOK_ISON                "ISON"
132 #define TOK_JOIN                "J"
133 #define TOK_JUPE                "JU"
134 #define TOK_KICK                "K"
135 #define TOK_KILL                "D"
136 #define TOK_LINKS               "LI"
137 #define TOK_LIST                "LIST"
138 #define TOK_LUSERS              "LU"
139 #define TOK_MAP                 "MAP"
140 #define TOK_MODE                "M"
141 #define TOK_MOTD                "MO"
142 #define TOK_NAMES               "E"
143 #define TOK_NICK                "N"
144 #define TOK_NOTICE              "O"
145 #define TOK_OPER                "OPER"
146 #define TOK_OPMODE              "OM"
147 #define TOK_PART                "L"
148 #define TOK_PASS                "PA"
149 #define TOK_PING                "G"
150 #define TOK_PONG                "Z"
151 #define TOK_POST                "POST"
152 #define TOK_PRIVMSG             "P"
153 #define TOK_PRIVS               "PRIVS"
154 #define TOK_PROTO               "PROTO"
155 #define TOK_QUIT                "Q"
156 #define TOK_REHASH              "REHASH"
157 #define TOK_RESET               "RESET"
158 #define TOK_RESTART             "RESTART"
159 #define TOK_RPING               "RI"
160 #define TOK_RPONG               "RO"
161 #define TOK_SERVER              "S"
162 #define TOK_SERVLIST            "SERVSET"
163 #define TOK_SERVSET             "SERVSET"
164 #define TOK_SET                 "SET"
165 #define TOK_SETTIME             "SE"
166 #define TOK_SILENCE             "U"
167 #define TOK_SQUERY              "SQUERY"
168 #define TOK_SQUIT               "SQ"
169 #define TOK_STATS               "R"
170 #define TOK_SVSNICK             "SN"
171 #define TOK_TIME                "TI"
172 #define TOK_TOPIC               "T"
173 #define TOK_TRACE               "TR"
174 #define TOK_UPING               "UP"
175 #define TOK_USER                "USER"
176 #define TOK_USERHOST            "USERHOST"
177 #define TOK_USERIP              "USERIP"
178 #define TOK_VERSION             "V"
179 #define TOK_WALLCHOPS           "WC"
180 #define TOK_WALLOPS             "WA"
181 #define TOK_WALLUSERS           "WU"
182 #define TOK_WALLVOICES          "WV"
183 #define TOK_WHO                 "H"
184 #define TOK_WHOIS               "W"
185 #define TOK_WHOWAS              "X"
186
187 /* Protocol messages; aliased to full commands or tokens depending
188    on compile-time configuration. ircu prefers tokens WITH THE
189    EXCEPTION OF THE SERVER AND PASS COMMANDS, which cannot be
190    tokenized, because clients' (ie. a linking server) commands are
191    only checked against the full command list.
192 */
193 #if defined(ENABLE_TOKENS)
194 #define TYPE(NAME)              TOK_ ## NAME
195 #else /* !ENABLE_TOKENS */
196 #define TYPE(NAME)              CMD_ ## NAME
197 #endif /* ENABLE_TOKENS */
198
199 #define P10_ACCOUNT             TYPE(ACCOUNT)
200 #define P10_ADMIN               TYPE(ADMIN)
201 #define P10_ASLL                TYPE(ASLL)
202 #define P10_AWAY                TYPE(AWAY)
203 #define P10_BURST               TYPE(BURST)
204 #define P10_CLEARMODE           TYPE(CLEARMODE)
205 #define P10_CLOSE               TYPE(CLOSE)
206 #define P10_CNOTICE             TYPE(CNOTICE)
207 #define P10_CONNECT             TYPE(CONNECT)
208 #define P10_CPRIVMSG            TYPE(CPRIVMSG)
209 #define P10_CREATE              TYPE(CREATE)
210 #define P10_DESTRUCT            TYPE(DESTRUCT)
211 #define P10_DESYNCH             TYPE(DESYNCH)
212 #define P10_DIE                 TYPE(DIE)
213 #define P10_DNS                 TYPE(DNS)
214 #define P10_EOB                 TYPE(EOB)
215 #define P10_EOB_ACK             TYPE(EOB_ACK)
216 #define P10_ERROR               TYPE(ERROR)
217 #define P10_FAKEHOST            TYPE(FAKEHOST)
218 #define P10_GET                 TYPE(GET)
219 #define P10_GLINE               TYPE(GLINE)
220 #define P10_HASH                TYPE(HASH)
221 #define P10_HELP                TYPE(HELP)
222 #define P10_INFO                TYPE(INFO)
223 #define P10_INVITE              TYPE(INVITE)
224 #define P10_ISON                TYPE(ISON)
225 #define P10_JOIN                TYPE(JOIN)
226 #define P10_JUPE                TYPE(JUPE)
227 #define P10_KICK                TYPE(KICK)
228 #define P10_KILL                TYPE(KILL)
229 #define P10_LINKS               TYPE(LINKS)
230 #define P10_LIST                TYPE(LIST)
231 #define P10_LUSERS              TYPE(LUSERS)
232 #define P10_MAP                 TYPE(MAP)
233 #define P10_MODE                TYPE(MODE)
234 #define P10_MOTD                TYPE(MOTD)
235 #define P10_NAMES               TYPE(NAMES)
236 #define P10_NICK                TYPE(NICK)
237 #define P10_NOTICE              TYPE(NOTICE)
238 #define P10_OPER                TYPE(OPER)
239 #define P10_OPMODE              TYPE(OPMODE)
240 #define P10_PART                TYPE(PART)
241 #define P10_PASS                CMD_PASS
242 #define P10_PING                TYPE(PING)
243 #define P10_PONG                TYPE(PONG)
244 #define P10_POST                TYPE(POST)
245 #define P10_PRIVMSG             TYPE(PRIVMSG)
246 #define P10_PRIVS               TYPE(PRIVS)
247 #define P10_PROTO               TYPE(PROTO)
248 #define P10_QUIT                TYPE(QUIT)
249 #define P10_REHASH              TYPE(REHASH)
250 #define P10_RESET               TYPE(RESET)
251 #define P10_RESTART             TYPE(RESTART)
252 #define P10_RPING               TYPE(RPING)
253 #define P10_RPONG               TYPE(RPONG)
254 #define P10_SERVER              CMD_SERVER
255 #define P10_SERVLIST            TYPE(SERVLIST)
256 #define P10_SERVSET             TYPE(SERVSET)
257 #define P10_SET                 TYPE(SET)
258 #define P10_SETTIME             TYPE(SETTIME)
259 #define P10_SILENCE             TYPE(SILENCE)
260 #define P10_SQUERY              TYPE(SQUERY)
261 #define P10_SQUIT               TYPE(SQUIT)
262 #define P10_STATS               TYPE(STATS)
263 #define P10_SVSNICK             TYPE(SVSNICK)
264 #define P10_TIME                TYPE(TIME)
265 #define P10_TOPIC               TYPE(TOPIC)
266 #define P10_TRACE               TYPE(TRACE)
267 #define P10_UPING               TYPE(UPING)
268 #define P10_USER                TYPE(USER)
269 #define P10_USERHOST            TYPE(USERHOST)
270 #define P10_USERIP              TYPE(USERIP)
271 #define P10_VERSION             TYPE(VERSION)
272 #define P10_WALLCHOPS           TYPE(WALLCHOPS)
273 #define P10_WALLOPS             TYPE(WALLOPS)
274 #define P10_WALLUSERS           TYPE(WALLUSERS)
275 #define P10_WALLVOICES          TYPE(WALLVOICES)
276 #define P10_WHO                 TYPE(WHO)
277 #define P10_WHOIS               TYPE(WHOIS)
278 #define P10_WHOWAS              TYPE(WHOWAS)
279
280 /* Servers claiming to have a boot or link time before PREHISTORY
281  * trigger errors to the log.  We hope no server has been running
282  * constantly since September 1994.  :)
283  */
284 #define PREHISTORY 780000000
285
286 static struct server *servers_num[64*64];
287 static privmsg_func_t *privmsg_funcs;
288 static unsigned int num_privmsg_funcs;
289 static privmsg_func_t *notice_funcs;
290 static unsigned int num_notice_funcs;
291 static struct dict *unbursted_channels;
292 static const char *his_servername;
293 static const char *his_servercomment;
294
295 /* These correspond to 1 << X:      012345678901234567 */
296 const char irc_user_mode_chars[] = "o iw dkgn        I";
297
298 static struct userNode *AddUser(struct server* uplink, const char *nick, const char *ident, const char *hostname, const char *modes, const char *numeric, const char *userinfo, unsigned long timestamp, const char *realip);
299
300 extern int off_channel;
301
302 static int parse_oplevel(char *str);
303
304 /* Numerics can be XYY, XYYY, or XXYYY; with X's identifying the
305  * server and Y's indentifying the client on that server. */
306 struct server*
307 GetServerN(const char *numeric)
308 {
309     switch (strlen(numeric)) {
310     default:
311         return servers_num[base64toint(numeric, 2)];
312     case 4:
313     case 3:
314     case 1:
315         return servers_num[base64toint(numeric, 1)];
316     case 0:
317         return NULL;
318     }
319 }
320
321 struct userNode*
322 GetUserN(const char *numeric) /* using numeric */
323 {
324     struct userNode *un;
325     struct server *s;
326     int n, slen, ulen;
327
328     switch (strlen(numeric)) {
329     default:
330         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s): numeric too long!", numeric);
331         return NULL;
332     case 5: slen = 2; ulen = 3; break;
333     case 4: slen = 1; ulen = 3; break;
334     case 3: slen = 1; ulen = 2; break;
335     case 2: case 1: case 0:
336         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s): numeric too short!", numeric);
337         return NULL;
338     }
339     if (!(s = servers_num[base64toint(numeric, slen)])) {
340         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s): couldn't find server (len=%d)!", numeric, slen);
341         return NULL;
342     }
343     n = base64toint(numeric+slen, ulen) & s->num_mask;
344     if (!(un = s->users[n])) {
345         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s) couldn't find user!", numeric);
346     }
347     return un;
348 }
349
350 static void
351 privmsg_user_helper(struct userNode *un, void *data)
352 {
353     struct privmsg_desc *pd = data;
354     unsigned int num = un->num_local;
355     if (!pd->is_notice) {
356         if ((num < num_privmsg_funcs) && privmsg_funcs[num]) {
357             privmsg_funcs[num](pd->user, un, pd->text, pd->is_qualified);
358         }
359     } else {
360         if ((num < num_notice_funcs) && notice_funcs[num]) {
361             notice_funcs[num](pd->user, un, pd->text, pd->is_qualified);
362         }
363     }
364 }
365
366 void
367 irc_server(struct server *srv)
368 {
369     char extranum[COMBO_NUMERIC_LEN+1];
370
371     inttobase64(extranum, srv->num_mask, (srv->numeric[1] || (srv->num_mask >= 64*64)) ? 3 : 2);
372     if (srv == self) {
373         /* The +s, ignored by Run's ircu, means "service" to Undernet's ircu */
374         putsock(P10_SERVER " %s %d %lu %lu J10 %s%s +s6 :%s",
375                 srv->name, srv->hops+1, srv->boot, srv->link_time, srv->numeric, extranum, srv->description);
376     } else {
377         putsock("%s " P10_SERVER " %s %d %lu %lu %c10 %s%s +s6 :%s",
378                 self->numeric, srv->name, srv->hops+1, srv->boot, srv->link_time, (srv->self_burst ? 'J' : 'P'), srv->numeric, extranum, srv->description);
379     }
380 }
381
382 static void
383 irc_p10_pton(irc_in_addr_t *ip, const char *input)
384 {
385     if (strlen(input) == 6) {
386         unsigned int value;
387         memset(ip, 0, 6 * sizeof(ip->in6[0]));
388         value = base64toint(input, 6);
389         if (value)
390             ip->in6[5] = htons(65535);
391         ip->in6[6] = htons(value >> 16);
392         ip->in6[7] = htons(value & 65535);
393     } else {
394         unsigned int pos = 0;
395         do {
396             if (*input == '_') {
397                 unsigned int left;
398                 for (left = (25 - strlen(input)) / 3 - pos; left; left--)
399                     ip->in6[pos++] = 0;
400                 input++;
401             } else {
402                 ip->in6[pos++] = ntohs(base64toint(input, 3));
403                 input += 3;
404             }
405         } while (pos < 8);
406     }
407 }
408
409 static void
410 irc_p10_ntop(char *output, const irc_in_addr_t *ip)
411 {
412     if (!irc_in_addr_is_valid(*ip)) {
413         strcpy(output, "AAAAAA");
414     } else if (irc_in_addr_is_ipv4(*ip)) {
415         unsigned int in4;
416         in4 = (ntohs(ip->in6[6]) << 16) | ntohs(ip->in6[7]);
417         inttobase64(output, in4, 6);
418         output[6] = '\0';
419     } else if (irc_in_addr_is_ipv6(*ip)) {
420         unsigned int max_start, max_zeros, curr_zeros, zero, ii;
421         /* Can start by printing out the leading non-zero parts. */
422         for (ii = 0; (ip->in6[ii]) && (ii < 8); ++ii) {
423             inttobase64(output, ntohs(ip->in6[ii]), 3);
424             output += 3;
425         }
426         /* Find the longest run of zeros. */
427         for (max_start = zero = ii, max_zeros = curr_zeros = 0; ii < 8; ++ii) {
428             if (!ip->in6[ii])
429                 curr_zeros++;
430             else if (curr_zeros > max_zeros) {
431                 max_start = ii - curr_zeros;
432                 max_zeros = curr_zeros;
433                 curr_zeros = 0;
434             }
435         }
436         if (curr_zeros > max_zeros) {
437             max_start = ii - curr_zeros;
438             max_zeros = curr_zeros;
439             curr_zeros = 0;
440         }
441         /* Print the rest of the address */
442         for (ii = zero; ii < 8; ) {
443             if ((ii == max_start) && max_zeros) {
444                 *output++ = '_';
445                 ii += max_zeros;
446             } else {
447                 inttobase64(output, ntohs(ip->in6[ii]), 3);
448                 output += 3;
449                 ii += 1;
450             }
451         }
452         *output = '\0';
453     } else {
454         strcpy(output, "???");
455     }
456 }
457
458 void
459 irc_user(struct userNode *user)
460 {
461     char b64ip[25];
462     if (!user || IsDummy(user))
463         return;
464     irc_p10_ntop(b64ip, &user->ip);
465     if (user->modes) {
466         char modes[32];
467         irc_user_modes(user, modes, sizeof(modes));
468         putsock("%s " P10_NICK " %s %d %lu %s %s +%s %s %s :%s",
469                 user->uplink->numeric, user->nick, user->uplink->hops+1, (unsigned long)user->timestamp, user->ident, user->hostname, modes, b64ip, user->numeric, user->info);
470     } else {
471         putsock("%s " P10_NICK " %s %d %lu %s %s %s %s :%s",
472                 user->uplink->numeric, user->nick, user->uplink->hops+1, (unsigned long)user->timestamp, user->ident, user->hostname, b64ip, user->numeric, user->info);
473     }
474 }
475
476 void
477 irc_account(struct userNode *user, const char *stamp, unsigned long timestamp, unsigned long serial)
478 {
479     putsock("%s " P10_ACCOUNT " %s %s %lu %lu", self->numeric, user->numeric, stamp, timestamp, serial);
480 }
481
482 void
483 irc_fakehost(struct userNode *user, const char *host)
484 {
485     putsock("%s " P10_FAKEHOST " %s %s", self->numeric, user->numeric, host);
486 }
487
488 void
489 irc_regnick(UNUSED_ARG(struct userNode *user))
490 {
491     /* no operation here */
492 }
493
494 void
495 irc_nick(struct userNode *user, UNUSED_ARG(const char *old_nick))
496 {
497     putsock("%s " P10_NICK " %s %lu", user->numeric, user->nick, (unsigned long)now);
498 }
499
500 void
501 irc_fetchtopic(struct userNode *from, const char *to)
502 {
503     if (!from || !to)
504         return;
505     putsock("%s " P10_TOPIC " %s", from->numeric, to);
506 }
507
508 void
509 irc_squit(struct server *srv, const char *message, const char *service_message)
510 {
511     if (!service_message)
512         service_message = message;
513
514     /* Are we leaving the network? */
515     if (srv == self && cManager.uplink->state == CONNECTED) {
516         unsigned int i;
517
518         /* Quit all clients linked to me. */
519         for (i = 0; i <= self->num_mask; i++) {
520             if (!self->users[i])
521                 continue;
522             irc_quit(self->users[i], service_message);
523         }
524     }
525
526     putsock("%s " P10_SQUIT " %s %d :%s", self->numeric, srv->name, 0, message);
527
528     if (srv == self) {
529         /* Force a reconnect to the currently selected server. */
530         cManager.uplink->tries = 0;
531         log_module(MAIN_LOG, LOG_INFO, "Squitting from uplink: %s", message);
532         close_socket();
533     }
534 }
535
536 void
537 irc_wallchops(struct userNode *from, const char *to, const char *message)
538 {
539     putsock("%s " P10_WALLCHOPS " %s :%s", from->numeric, to, message);
540 }
541
542 static int
543 deliver_to_dummy(struct userNode *source, struct userNode *dest, const char *message, int type)
544 {
545     unsigned int num;
546
547     if (!dest || !IsDummy(dest) || !IsLocal(dest))
548         return 0;
549     num = dest->num_local;
550     switch (type) {
551     default:
552         if ((num < num_notice_funcs) && notice_funcs[num])
553             notice_funcs[num](source, dest, message, 0);
554         break;
555     case 1:
556         if ((num < num_privmsg_funcs) && privmsg_funcs[num])
557             privmsg_funcs[num](source, dest, message, 0);
558         break;
559     }
560     return 1;
561 }
562
563 void
564 irc_notice(struct userNode *from, const char *to, const char *message)
565 {
566     if (to[0] == '#' || to[0] == '$'
567         || !deliver_to_dummy(from, GetUserN(to), message, 0))
568         putsock("%s " P10_NOTICE " %s :%s", from->numeric, to, message);
569 }
570
571 void
572 irc_notice_user(struct userNode *from, struct userNode *to, const char *message)
573 {
574     if (!deliver_to_dummy(from, to, message, 0))
575         putsock("%s " P10_NOTICE " %s :%s", from->numeric, to->numeric, message);
576 }
577
578 void
579 irc_privmsg(struct userNode *from, const char *to, const char *message)
580 {
581     if (to[0] == '#' || to[0] == '$'
582         || !deliver_to_dummy(from, GetUserN(to), message, 1))
583         putsock("%s " P10_PRIVMSG " %s :%s", from->numeric, to, message);
584 }
585
586 void
587 irc_eob(void)
588 {
589     putsock("%s " P10_EOB, self->numeric);
590 }
591
592 void
593 irc_eob_ack(void)
594 {
595     putsock("%s " P10_EOB_ACK, self->numeric);
596 }
597
598 void
599 irc_ping(const char *payload)
600 {
601     putsock("%s " P10_PING " :%s", self->numeric, payload);
602 }
603
604 void
605 irc_pong(const char *who, const char *data)
606 {
607     putsock("%s " P10_PONG " %s :%s", self->numeric, who, data);
608 }
609
610 void
611 irc_pong_asll(const char *who, const char *orig_ts)
612 {
613     char *delim;
614     struct timeval orig;
615     struct timeval sys_now;
616     int diff;
617
618     orig.tv_sec = strtoul(orig_ts, &delim, 10);
619     orig.tv_usec = (*delim == '.') ? strtoul(delim + 1, NULL, 10) : 0;
620     gettimeofday(&sys_now, NULL);
621     diff = (sys_now.tv_sec - orig.tv_sec) * 1000 + (sys_now.tv_usec - orig.tv_usec) / 1000;
622     putsock("%s " P10_PONG " %s %s %d %lu.%06lu", self->numeric, who, orig_ts, diff, (unsigned long)sys_now.tv_sec, (unsigned long)sys_now.tv_usec);
623 }
624
625 void
626 irc_pass(const char *passwd)
627 {
628     putsock(P10_PASS " :%s", passwd);
629 }
630
631 void
632 irc_introduce(const char *passwd)
633 {
634     void timed_send_ping(void *data);
635
636     self->self_burst = self->burst = 1;
637     irc_pass(passwd);
638     irc_server(self);
639     burst_length = 0;
640     timeq_add(now + ping_freq, timed_send_ping, 0);
641 }
642
643 void
644 irc_gline(struct server *srv, struct gline *gline)
645 {
646     if (gline->lastmod)
647         putsock("%s " P10_GLINE " %s +%s %lu %lu :%s",
648                 self->numeric, (srv ? srv->numeric : "*"), gline->target, (unsigned long)(gline->expires-now), (unsigned long)gline->lastmod, gline->reason);
649     else
650         putsock("%s " P10_GLINE " %s +%s %lu :%s",
651                 self->numeric, (srv ? srv->numeric : "*"), gline->target, (unsigned long)(gline->expires-now), gline->reason);
652 }
653
654 void
655 irc_settime(const char *srv_name_mask, unsigned long new_time)
656 {
657     ioset_set_time(new_time);
658     if (!strcmp(srv_name_mask, "*"))
659         srv_name_mask = "";
660     putsock("%s " P10_SETTIME " %lu %s", self->numeric, new_time, srv_name_mask);
661 }
662
663 void
664 irc_ungline(const char *mask)
665 {
666     putsock("%s " P10_GLINE " * -%s", self->numeric, mask);
667 }
668
669 static void
670 irc_burst(struct chanNode *chan)
671 {
672     char burst_line[512];
673     int pos, base_len, len;
674     struct modeNode *mn;
675     struct banNode *bn;
676     long last_mode=-1;
677     unsigned int first_ban;
678     unsigned int n;
679
680     base_len = sprintf(burst_line, "%s " P10_BURST " %s %lu ",
681                        self->numeric, chan->name,
682                        (unsigned long)chan->timestamp);
683     len = irc_make_chanmode(chan, burst_line+base_len);
684     pos = base_len + len;
685     if (len > 0 && chan->members.used > 0)
686         burst_line[pos++] = ' ';
687
688     /* dump the users */
689     for (n=0; n<chan->members.used; n++) {
690         mn = chan->members.list[n];
691         if (pos > 500) {
692             burst_line[pos-1] = 0; /* -1 to back up over the space or comma */
693             putsock("%s", burst_line);
694             pos = base_len;
695             last_mode = -1;
696         }
697         memcpy(burst_line+pos, mn->user->numeric, strlen(mn->user->numeric));
698         pos += strlen(mn->user->numeric);
699         if (mn->modes && (mn->modes != last_mode)) {
700             last_mode = mn->modes;
701             burst_line[pos++] = ':';
702             if (last_mode & MODE_CHANOP)
703                 burst_line[pos++] = 'o';
704             if (last_mode & MODE_VOICE)
705                 burst_line[pos++] = 'v';
706         }
707         if ((n+1)<chan->members.used)
708             burst_line[pos++] = ',';
709     }
710
711     /* dump the bans */
712     if (chan->banlist.used) {
713         first_ban = 1;
714
715         if (chan->members.used > 0)
716             burst_line[pos++] = ' ';
717
718         for (n=0; n<chan->banlist.used; ) {
719             if (first_ban && (pos < 500)) {
720                 burst_line[pos++] = ':';
721                 burst_line[pos++] = '%';
722             }
723             bn = chan->banlist.list[n];
724             len = strlen(bn->ban);
725             if (pos + 2 + len < 505) {
726                 memcpy(burst_line + pos, bn->ban, len);
727                 pos += len;
728                 burst_line[pos++] = ' ';
729                 first_ban = 0;
730                 n++;
731             } else {
732                 burst_line[pos-1] = 0;
733                 putsock("%s", burst_line);
734                 pos = base_len;
735                 first_ban = 1;
736             }
737         }
738     }
739
740     /* print the last line */
741     burst_line[pos] = 0;
742     putsock("%s", burst_line);
743 }
744
745 void
746 irc_quit(struct userNode *user, const char *message)
747 {
748     putsock("%s " P10_QUIT " :%s", user->numeric, message);
749 }
750
751 void
752 irc_error(const char *to, const char *message)
753 {
754     if (to) {
755         putsock("%s " P10_ERROR " :%s", to, message);
756     } else {
757         putsock(":%s " P10_ERROR " :%s", self->name, message);
758     }
759 }
760
761 void
762 irc_kill(struct userNode *from, struct userNode *target, const char *message)
763 {
764     if (from) {
765         putsock("%s " P10_KILL " %s :%s!%s (%s)",
766                 from->numeric, target->numeric, self->name, from->nick, message);
767     } else {
768         putsock("%s " P10_KILL " %s :%s (%s)",
769                 self->numeric, target->numeric, self->name, message);
770     }
771 }
772
773 void
774 irc_mode(struct userNode *from, struct chanNode *target, const char *modes)
775 {
776     putsock("%s " P10_MODE " %s %s %lu",
777             (from ? from->numeric : self->numeric),
778             target->name, modes, (unsigned long)target->timestamp);
779 }
780
781 void
782 irc_invite(struct userNode *from, struct userNode *who, struct chanNode *to)
783 {
784     putsock("%s " P10_INVITE " %s %s", from->numeric, who->nick, to->name);
785 }
786
787 void
788 irc_join(struct userNode *who, struct chanNode *what)
789 {
790     if (what->members.used == 1) {
791         putsock("%s " P10_CREATE " %s %lu",
792                 who->numeric, what->name, (unsigned long)what->timestamp);
793     } else {
794         putsock("%s " P10_JOIN " %s %lu", who->numeric, what->name,
795                 (unsigned long)what->timestamp);
796     }
797 }
798
799 void
800 irc_kick(struct userNode *who, struct userNode *target, struct chanNode *channel, const char *msg)
801 {
802     const char *numeric;
803     struct modeNode *mn = GetUserMode(channel, who);
804     numeric = ((mn && (mn->modes & MODE_CHANOP)) || off_channel) ? who->numeric : self->numeric;
805     putsock("%s " P10_KICK " %s %s :%s",
806             numeric, channel->name, target->numeric, msg);
807 }
808
809 void
810 irc_stats(struct userNode *from, struct server *target, char type)
811 {
812     putsock("%s " P10_STATS " %c :%s", from->numeric, type, target->numeric);
813 }
814
815 void
816 irc_svsnick(struct userNode *from, struct userNode *target, const char *newnick)
817 {
818     putsock("%s " P10_SVSNICK " %s %s %lu", from->uplink->numeric, target->numeric, newnick, (unsigned long)now);
819 }
820
821 void
822 irc_part(struct userNode *who, struct chanNode *what, const char *reason)
823 {
824     if (reason) {
825         putsock("%s " P10_PART " %s :%s", who->numeric, what->name, reason);
826     } else {
827         putsock("%s " P10_PART " %s", who->numeric, what->name);
828     }
829 }
830
831 void
832 irc_topic(struct userNode *who, struct chanNode *what, const char *topic)
833 {
834     putsock("%s " P10_TOPIC " %s :%s", who->numeric, what->name, topic);
835 }
836
837 void
838 irc_raw(const char *what)
839 {
840     putsock("%s", what);
841 }
842
843 void
844 irc_numeric(struct userNode *user, unsigned int num, const char *format, ...)
845 {
846     va_list arg_list;
847     char buffer[MAXLEN];
848     va_start(arg_list, format);
849     vsnprintf(buffer, MAXLEN-2, format, arg_list);
850     buffer[MAXLEN-1] = 0;
851     putsock(":%s %03d %s %s", self->name, num, user->nick, buffer);
852 }
853
854 static void send_burst(void);
855
856 static void
857 change_nicklen(int new_nicklen)
858 {
859     unsigned int nn;
860     char new_nick[NICKLEN+1];
861     struct userNode *user;
862
863     nicklen = new_nicklen;
864     /* fix up any users we have here */
865     for (nn=0; nn<=self->num_mask; nn++) {
866         if (!(user = self->users[nn]))
867             continue;
868         safestrncpy(new_nick, user->nick, sizeof(new_nick));
869         new_nick[nicklen] = 0;
870         NickChange(user, new_nick, 1);
871     }
872 }
873
874 static CMD_FUNC(cmd_whois)
875 {
876     struct userNode *from;
877     struct userNode *who;
878     char buf[MAXLEN];
879     unsigned int i, mlen, len;
880
881     if (argc < 3)
882         return 0;
883     if (!(from = GetUserH(origin))) {
884         log_module(MAIN_LOG, LOG_ERROR, "Could not find WHOIS origin user %s", origin);
885         return 0;
886     }
887     if (!(who = GetUserH(argv[2]))) {
888         irc_numeric(from, ERR_NOSUCHNICK, "%s@%s :No such nick", argv[2], self->name);
889         return 1;
890     }
891
892     if (IsFakeHost(who) && IsHiddenHost(who))
893         irc_numeric(from, RPL_WHOISUSER, "%s %s %s * :%s", who->nick, who->ident, who->fakehost, who->info);
894     else if (IsHiddenHost(who) && who->handle_info && hidden_host_suffix)
895         irc_numeric(from, RPL_WHOISUSER, "%s %s %s.%s * :%s", who->nick, who->ident, who->handle_info->handle, hidden_host_suffix, who->info);
896     else
897         irc_numeric(from, RPL_WHOISUSER, "%s %s %s * :%s", who->nick, who->ident, who->hostname, who->info);
898
899     if ((!IsService(who) && !IsNoChan(who)) || (from == who)) {
900         struct modeNode *mn;
901         mlen = strlen(self->name) + strlen(from->nick) + 12 + strlen(who->nick);
902         len = 0;
903         *buf = '\0';
904         for (i = who->channels.used; i > 0; )
905         {
906             mn = who->channels.list[--i];
907
908             if (!IsOper(from) && (mn->channel->modes & (MODE_PRIVATE | MODE_SECRET)) && !GetUserMode(mn->channel, from))
909                 continue;
910
911             if (len + strlen(mn->channel->name) + mlen > MAXLEN - 5)
912             {
913                 irc_numeric(from, RPL_WHOISCHANNELS, "%s :%s", who->nick, buf);
914                 *buf = '\0';
915                 len = 0;
916             }
917
918             if (IsDeaf(who))
919                 *(buf + len++) = '-';
920             if ((mn->channel->modes & (MODE_PRIVATE | MODE_SECRET)) && !GetUserMode(mn->channel, from))
921                 *(buf + len++) = '*';
922             if (mn->modes & MODE_CHANOP)
923                 *(buf + len++) = '@';
924             else if (mn->modes & MODE_VOICE)
925                 *(buf + len++) = '+';
926
927             if (len)
928                 *(buf + len) = '\0';
929             strcpy(buf + len, mn->channel->name);
930             len += strlen(mn->channel->name);
931             strcat(buf + len, " ");
932             len++;
933         }
934         if (buf[0] != '\0')
935             irc_numeric(from, RPL_WHOISCHANNELS, "%s :%s", who->nick, buf);
936     }
937
938     if (his_servername && his_servercomment && !IsOper(from) && from != who)
939         irc_numeric(from, RPL_WHOISSERVER, "%s %s :%s", who->nick, his_servername, his_servercomment);
940     else
941         irc_numeric(from, RPL_WHOISSERVER, "%s %s :%s", who->nick, who->uplink->name, who->uplink->description);
942
943     if (IsAway(who))
944         irc_numeric(from, RPL_AWAY, "%s :Away", who->nick);
945     if (IsOper(who))
946         irc_numeric(from, RPL_WHOISOPERATOR, "%s :%s", who->nick, IsLocal(who) ? "is a megalomaniacal power hungry tyrant" : "is an IRC Operator");
947     if (who->handle_info)
948         irc_numeric(from, RPL_WHOISACCOUNT, "%s %s :is logged in as", who->nick, who->handle_info->handle);
949     if (IsHiddenHost(who) && who->handle_info && (IsOper(from) || from == who))
950         irc_numeric(from, RPL_WHOISACTUALLY, "%s %s@%s %s :Actual user@host, Actual IP", who->nick, who->ident, who->hostname, irc_ntoa(&who->ip));
951     if (IsLocal(who) && !IsService(who) && (!IsNoIdle(who) || IsOper(from) || from == who))
952         irc_numeric(from, RPL_WHOISIDLE, "%s %ld %ld :seconds idle, signon time", who->nick, now - who->idle_since, who->timestamp);
953
954     irc_numeric(from, RPL_ENDOFWHOIS, "%s :End of /WHOIS list", who->nick);
955     return 1;
956 }
957
958 static CMD_FUNC(cmd_server)
959 {
960     struct server *srv;
961     const char *str;
962
963     if (argc < 8)
964         return 0;
965     if (self->uplink) {
966         /* another server introduced us */
967         srv = AddServer(GetServerH(origin), argv[1], atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), argv[6], argv[argc-1]);
968         if (!srv)
969             return 0;
970         srv->self_burst = argv[5][0] == 'J';
971         srv->burst = 1;
972     } else {
973         /* this must be our uplink */
974         srv = self->uplink = AddServer(self, argv[1], atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), argv[6], argv[argc-1]);
975         if (!srv)
976             return 0;
977         srv->self_burst = argv[5][0] == 'J';
978         srv->burst = 1;
979         if ((argv[7][0] == '+') && !force_n2k) {
980             log_module(MAIN_LOG, LOG_WARNING, "Got Undernet-style SERVER message but \"force_n2k\" not on.");
981         }
982         send_burst();
983     }
984
985     /* Fix up our timestamps if necessary. */
986     if (srv->boot <= PREHISTORY) {
987         /* Server from the mists of time.. */
988         if (srv->hops == 1) {
989             log_module(MAIN_LOG, LOG_ERROR, "Server %s claims to have booted at time %lu.  This is absurd.", srv->name, (unsigned long)srv->boot);
990         }
991     } else if ((str = conf_get_data("server/reliable_clock", RECDB_QSTRING))
992                && enabled_string(str)) {
993         /* If we have a reliable clock, we just keep our current time. */
994     } else {
995         if (srv->boot <= self->boot) {
996             /* The other server is older than us.  Accept their timestamp.
997              * Alternately, we are same age, but we accept their time
998              * since we are linking to them. */
999             self->boot = srv->boot;
1000             ioset_set_time(srv->link_time);
1001         }
1002     }
1003     if (srv == self->uplink) {
1004         extern unsigned long burst_begin;
1005         burst_begin = now;
1006     }
1007     return 1;
1008 }
1009
1010 static CMD_FUNC(cmd_eob)
1011 {
1012     struct server *sender;
1013     dict_iterator_t it;
1014     unsigned int ii;
1015
1016     if (!(sender = GetServerH(origin)))
1017         return 0;
1018     if (sender == self->uplink) {
1019         cManager.uplink->state = CONNECTED;
1020         for (it = dict_first(unbursted_channels); it; it = iter_next(it))
1021             irc_burst(iter_data(it));
1022         dict_delete(unbursted_channels);
1023         unbursted_channels = NULL;
1024         irc_eob();
1025         irc_eob_ack();
1026     }
1027     sender->self_burst = 0;
1028     recalc_bursts(sender);
1029     for (ii=0; ii<slf_used; ii++)
1030         slf_list[ii](sender);
1031     return 1;
1032 }
1033
1034 static CMD_FUNC(cmd_eob_ack)
1035 {
1036     extern unsigned long burst_begin;
1037
1038     if (GetServerH(origin) == self->uplink) {
1039         burst_length = now - burst_begin;
1040         self->self_burst = self->burst = 0;
1041     }
1042     cManager.uplink->state = CONNECTED;
1043     return 1;
1044 }
1045
1046 static CMD_FUNC(cmd_ping)
1047 {
1048     struct server *srv;
1049     struct userNode *un;
1050
1051     if (argc > 3)
1052         irc_pong_asll(argv[2], argv[3]);
1053     else if ((srv = GetServerH(origin)))
1054         irc_pong(self->name, srv->numeric);
1055     else if ((un = GetUserH(origin)))
1056         irc_pong(self->name, un->numeric);
1057     else
1058         irc_pong(self->name, origin);
1059
1060     timeq_del(0, timed_send_ping, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
1061     timeq_del(0, timed_ping_timeout, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
1062     timeq_add(now + ping_freq, timed_send_ping, 0);
1063     received_ping();
1064     return 1;
1065 }
1066
1067 static CMD_FUNC(cmd_error_nick)
1068 {
1069     /* Go back to original IRC length .. and try to reconnect :/ */
1070     change_nicklen(9);
1071     irc_squit(self, "Got erroneous nickname, truncating nicks.", NULL);
1072     return 1;
1073 }
1074
1075 struct create_desc {
1076     struct userNode *user;
1077     unsigned long when;
1078 };
1079
1080 static void
1081 join_helper(struct chanNode *chan, void *data)
1082 {
1083     struct create_desc *cd = data;
1084     AddChannelUser(cd->user, chan);
1085 }
1086
1087 static void
1088 create_helper(char *name, void *data)
1089 {
1090     struct create_desc *cd = data;
1091
1092     if (!strcmp(name, "0")) {
1093         while (cd->user->channels.used > 0)
1094             DelChannelUser(cd->user, cd->user->channels.list[0]->channel, 0, 0);
1095         return;
1096     }
1097
1098     AddChannelUser(cd->user, AddChannel(name, cd->when, NULL, NULL));
1099 }
1100
1101 static CMD_FUNC(cmd_create)
1102 {
1103     struct create_desc cd;
1104     struct userNode *user;
1105
1106     if ((argc < 3) || !(user = GetUserH(origin)))
1107         return 0;
1108     cd.user = user;
1109     cd.when = atoi(argv[2]);
1110     parse_foreach(argv[1], join_helper, create_helper, NULL, NULL, &cd);
1111     return 1;
1112 }
1113
1114 static CMD_FUNC(cmd_join)
1115 {
1116     struct create_desc cd;
1117
1118     if (!(cd.user = GetUserH(origin)))
1119         return 0;
1120     if (argc < 2)
1121         return 0;
1122     else if (argc < 3)
1123         cd.when = now;
1124     else
1125         cd.when = atoi(argv[2]);
1126     parse_foreach(argv[1], join_helper, create_helper, NULL, NULL, &cd);
1127     return 1;
1128 }
1129
1130 static CMD_FUNC(cmd_pong)
1131 {
1132     if (argc < 3)
1133         return 0;
1134     if (!strcmp(argv[2], self->name)) {
1135         timeq_del(0, timed_send_ping, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
1136         timeq_del(0, timed_ping_timeout, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
1137         timeq_add(now + ping_freq, timed_send_ping, 0);
1138         received_ping();
1139     }
1140     return 1;
1141 }
1142
1143 static CMD_FUNC(cmd_nick)
1144 {
1145     struct userNode *user;
1146     if ((user = GetUserH(origin))) {
1147         /* nick change (since the source is a user numeric) */
1148         if (argc < 2)
1149             return 0;
1150         NickChange(user, argv[1], 1);
1151     } else {
1152         struct server *serv;
1153         char modes[MAXLEN];
1154         /* new nick */
1155         if (argc < 9)
1156             return 0;
1157         serv = GetServerH(origin);
1158         if (argc > 9)
1159             unsplit_string(argv+6, argc-9, modes);
1160         else
1161             strcpy(modes, "+");
1162         AddUser(serv, argv[1], argv[4], argv[5], modes, argv[argc-2], argv[argc-1], atoi(argv[3]), argv[argc-3]);
1163     }
1164     return 1;
1165 }
1166
1167 static CMD_FUNC(cmd_account)
1168 {
1169     struct userNode *user;
1170     unsigned long timestamp = 0;
1171     unsigned long serial = 0;
1172
1173     if ((argc < 3) || !origin || !GetServerH(origin))
1174         return 0; /* Origin must be server. */
1175     user = GetUserN(argv[1]);
1176     if (!user)
1177         return 1; /* A QUIT probably passed the ACCOUNT. */
1178     if (argc > 3)
1179         timestamp = strtoul(argv[3], NULL, 10);
1180     if (argc > 4)
1181         serial = strtoul(argv[4], NULL, 10);
1182     call_account_func(user, argv[2], timestamp, serial);
1183     return 1;
1184 }
1185
1186 static CMD_FUNC(cmd_fakehost)
1187 {
1188     struct userNode *user;
1189
1190     if ((argc < 3) || !origin || !GetServerH(origin))
1191         return 0;
1192     if (!(user = GetUserN(argv[1])))
1193         return 1;
1194     assign_fakehost(user, argv[2], 0);
1195     return 1;
1196 }
1197
1198 static CMD_FUNC(cmd_burst)
1199 {
1200     extern int rel_age;
1201     char modes[MAXLEN], *members = "", *banlist = NULL;
1202     unsigned int next = 3, res = 1;
1203     struct chanNode *cNode;
1204     struct userNode *un;
1205     struct modeNode *mNode;
1206     long mode;
1207     int oplevel = -1;
1208     char *user, *end, sep;
1209     unsigned long in_timestamp;
1210
1211     if (argc < 3)
1212         return 0;
1213     modes[0] = 0;
1214     while (next < argc) {
1215         switch (argv[next][0]) {
1216         case '+': {
1217             const char *pos;
1218             int n_modes;
1219             for (pos=argv[next], n_modes = 1; *pos; pos++)
1220                 if ((*pos == 'k') || (*pos == 'l') || (*pos == 'A')
1221                     || (*pos == 'U'))
1222                     n_modes++;
1223             if (next + n_modes > argc)
1224                 n_modes = argc - next;
1225             unsplit_string(argv+next, n_modes, modes);
1226             next += n_modes;
1227             break;
1228         }
1229         case '%': banlist = argv[next++]+1; break;
1230         default: members = argv[next++]; break;
1231         }
1232     }
1233
1234     in_timestamp = atoi(argv[2]);
1235     if ((cNode = dict_find(unbursted_channels, argv[1], NULL))) {
1236         cNode->timestamp = in_timestamp;
1237         dict_remove(unbursted_channels, cNode->name);
1238         irc_burst(cNode);
1239     }
1240     cNode = AddChannel(argv[1], in_timestamp, modes, banlist);
1241
1242     /* Burst channel members in now. */
1243     for (user = members, sep = *members, mode = 0; sep; user = end) {
1244         for (end = user + 3; isalnum(*end) || *end == '[' || *end == ']'; end++) ;
1245         sep = *end++; end[-1] = 0;
1246         if (sep == ':') {
1247             mode = 0;
1248             while ((sep = *end++)) {
1249                 if (sep == 'o') {
1250                     mode |= MODE_CHANOP;
1251                     oplevel = -1;
1252                 } else if (sep == 'v') {
1253                     mode |= MODE_VOICE;
1254                     oplevel = -1;
1255                 } else if (isdigit(sep)) {
1256                     mode |= MODE_CHANOP;
1257                     if (oplevel >= 0)
1258                         oplevel += parse_oplevel(end);
1259                     else
1260                         oplevel = parse_oplevel(end);
1261                     while (isdigit(*end)) end++;
1262                 } else
1263                     break;
1264             }
1265             if (rel_age < 0)
1266                 mode = 0;
1267         }
1268         if (!(un = GetUserN(user))) {
1269             res = 0;
1270             continue;
1271         }
1272         if ((mNode = AddChannelUser(un, cNode))) {
1273             mNode->modes = mode;
1274             mNode->oplevel = oplevel;
1275         }
1276     }
1277
1278     return res;
1279 }
1280
1281 static CMD_FUNC(cmd_mode)
1282 {
1283     struct chanNode *cn;
1284     struct userNode *un;
1285
1286     if (argc < 3)
1287         return 0;
1288     if (!IsChannelName(argv[1])) {
1289         un = GetUserH(argv[1]);
1290         if (!un) {
1291             log_module(MAIN_LOG, LOG_ERROR, "Unable to find user %s whose mode is changing.", argv[1]);
1292             return 0;
1293         }
1294         mod_usermode(un, argv[2]);
1295         return 1;
1296     }
1297
1298     if (!(cn = GetChannel(argv[1]))) {
1299         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose mode is changing.", argv[1]);
1300         return 0;
1301     }
1302     if ((un = GetUserH(origin))) {
1303         struct modeNode *mn;
1304         /* Update idle time for person setting the mode */
1305         if ((mn = GetUserMode(cn, un)))
1306             mn->idle_since = now;
1307     } else {
1308         /* If it came from a server, reset timestamp to re-sync. */
1309         cn->timestamp = atoi(argv[argc-1]);
1310     }
1311
1312     return mod_chanmode(un, cn, argv+2, argc-2, MCP_ALLOW_OVB|MCP_FROM_SERVER|(un ? MC_NOTIFY : 0));
1313 }
1314
1315 static CMD_FUNC(cmd_opmode)
1316 {
1317     struct chanNode *cn;
1318     struct userNode *un;
1319
1320     if (argc < 3)
1321         return 0;
1322
1323     if (!(cn = GetChannel(argv[1]))) {
1324         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose mode is changing.", argv[1]);
1325         return 0;
1326     }
1327     if (!(un = GetUserH(origin))) {
1328         log_module(MAIN_LOG, LOG_ERROR, "Unable to find user %s requesting OPMODE.", origin);
1329         return 0;
1330     }
1331     if (!IsOper(un)) {
1332         log_module(MAIN_LOG, LOG_ERROR, "Non-privileged user %s using OPMODE.", un->nick);
1333         return 0;
1334     }
1335
1336     return mod_chanmode(un, cn, argv+2, argc-2, MCP_ALLOW_OVB|MCP_FROM_SERVER); /* do NOT announce opmode locally */
1337 }
1338
1339 static int clear_chanmode(struct chanNode *channel, const char *modes);
1340
1341 static CMD_FUNC(cmd_clearmode)
1342 {
1343     struct chanNode *cn;
1344     struct userNode *un;
1345
1346     if (argc < 3)
1347         return 0;
1348
1349     if (!(cn = GetChannel(argv[1]))) {
1350         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose mode is changing.", argv[1]);
1351         return 0;
1352     }
1353     if (!(un = GetUserH(origin))) {
1354         log_module(MAIN_LOG, LOG_ERROR, "Unable to find user %s requesting CLEARMODE.", origin);
1355         return 0;
1356     }
1357     if (!IsOper(un)) {
1358         log_module(MAIN_LOG, LOG_ERROR, "Non-privileged user %s using CLEARMODE.", un->nick);
1359         return 0;
1360     }
1361
1362     return clear_chanmode(cn, argv[2]);
1363 }
1364
1365 static CMD_FUNC(cmd_topic)
1366 {
1367     struct chanNode *cn;
1368     unsigned long chan_ts, topic_ts;
1369
1370     if (argc < 3)
1371         return 0;
1372     if (!(cn = GetChannel(argv[1]))) {
1373         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose topic is being set", argv[1]);
1374         return 0;
1375     }
1376     if (argc >= 5) {
1377         /* Looks like an Asuka style topic burst. */
1378         chan_ts = atoi(argv[2]);
1379         topic_ts = atoi(argv[3]);
1380     } else {
1381         chan_ts = cn->timestamp;
1382         topic_ts = now;
1383     }
1384     SetChannelTopic(cn, GetUserH(origin), argv[argc-1], 0);
1385     cn->topic_time = topic_ts;
1386     return 1;
1387 }
1388
1389 static CMD_FUNC(cmd_num_topic)
1390 {
1391     struct chanNode *cn;
1392
1393     if (!argv[0])
1394         return 0; /* huh? */
1395     if (argv[2]) {
1396         cn = GetChannel(argv[2]);
1397         if (!cn) {
1398             log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s in topic reply", argv[2]);
1399             return 0;
1400         }
1401     } else
1402         return 0;
1403
1404     switch (atoi(argv[0])) {
1405     case 331:
1406         cn->topic_time = 0;
1407         break;  /* no topic */
1408     case 332:
1409         if (argc < 4)
1410             return 0;
1411         safestrncpy(cn->topic, unsplit_string(argv+3, argc-3, NULL), sizeof(cn->topic));
1412         break;
1413     case 333:
1414         if (argc < 5)
1415             return 0;
1416         safestrncpy(cn->topic_nick, argv[3], sizeof(cn->topic_nick));
1417         cn->topic_time = atoi(argv[4]);
1418         break;
1419     default:
1420         return 0; /* should never happen */
1421     }
1422     return 1;
1423 }
1424
1425 static CMD_FUNC(cmd_num_gline)
1426 {
1427     unsigned long lastmod;
1428     if (argc < 6)
1429         return 0;
1430     lastmod = (argc > 5) ? strtoul(argv[5], NULL, 0) : 0;
1431     gline_add(origin, argv[3], atoi(argv[4])-now, argv[argc - 1], now, lastmod, 0);
1432     return 1;
1433 }
1434
1435 static CMD_FUNC(cmd_quit)
1436 {
1437     struct userNode *user;
1438     if (argc < 2)
1439         return 0;
1440     /* Sometimes we get a KILL then a QUIT or the like, so we don't want to
1441      * call DelUser unless we have the user in our grasp. */
1442     if ((user = GetUserH(origin)))
1443         DelUser(user, NULL, false, argv[1]);
1444     return 1;
1445 }
1446
1447 static CMD_FUNC(cmd_kill)
1448 {
1449     struct userNode *user;
1450     if (argc < 2)
1451         return 0;
1452     user = GetUserN(argv[1]);
1453     if (!user) {
1454         /* If we get a KILL for a non-existent user, it could be a
1455          * Ghost response to a KILL we sent out earlier.  So we only
1456          * whine if the target is local.
1457          */
1458         if (!strncmp(argv[1], self->numeric, strlen(self->numeric)))
1459             log_module(MAIN_LOG, LOG_ERROR, "Unable to find kill victim %s", argv[1]);
1460         return 0;
1461     }
1462
1463     if (IsLocal(user) && IsService(user)) {
1464         /* TODO: rate limit this so silly things don't happen. */
1465         ReintroduceUser(user);
1466         return 1;
1467     }
1468
1469     DelUser(user, NULL, false, argv[2]);
1470     return 1;
1471 }
1472
1473 static CMD_FUNC(cmd_kick)
1474 {
1475     if (argc < 3)
1476         return 0;
1477     ChannelUserKicked(GetUserH(origin), GetUserN(argv[2]), GetChannel(argv[1]));
1478     return 1;
1479 }
1480
1481 static CMD_FUNC(cmd_squit)
1482 {
1483     struct server *server;
1484
1485     if (argc < 4)
1486         return 0;
1487     if (!(server = GetServerH(argv[1])))
1488         return 0;
1489
1490     if (server == self->uplink) {
1491         /* Force a reconnect to the currently selected server. */
1492         cManager.uplink->tries = 0;
1493         log_module(MAIN_LOG, LOG_INFO, "Squitting from uplink: %s", argv[3]);
1494         close_socket();
1495         return 1;
1496     }
1497
1498     DelServer(server, 0, argv[3]);
1499     return 1;
1500 }
1501
1502 static CMD_FUNC(cmd_privmsg)
1503 {
1504     struct privmsg_desc pd;
1505     if (argc < 3)
1506         return 0;
1507     pd.user = GetUserH(origin);
1508     if (!pd.user || (IsGagged(pd.user) && !IsOper(pd.user)))
1509         return 1;
1510     pd.is_notice = 0;
1511     pd.text = argv[argc - 1];
1512     parse_foreach(argv[1], privmsg_chan_helper, NULL, privmsg_user_helper, privmsg_invalid, &pd);
1513     return 1;
1514 }
1515
1516 static CMD_FUNC(cmd_notice)
1517 {
1518     struct privmsg_desc pd;
1519     if (argc < 3)
1520         return 0;
1521     pd.user = GetUserH(origin);
1522     if (!pd.user || (IsGagged(pd.user) && !IsOper(pd.user)))
1523         return 1;
1524     pd.is_notice = 1;
1525     pd.text = argv[argc - 1];
1526     parse_foreach(argv[1], privmsg_chan_helper, NULL, privmsg_user_helper, privmsg_invalid, &pd);
1527     return 1;
1528 }
1529
1530 static CMD_FUNC(cmd_away)
1531 {
1532     struct userNode *uNode;
1533
1534     uNode = GetUserH(origin);
1535     if (!uNode)
1536         return 1;
1537     if (argc < 2)
1538         uNode->modes &= ~FLAGS_AWAY;
1539     else
1540         uNode->modes |= FLAGS_AWAY;
1541     return 1;
1542 }
1543
1544 static CMD_FUNC(cmd_gline)
1545 {
1546     unsigned long lastmod;
1547
1548     if (argc < 3)
1549         return 0;
1550     if (argv[2][0] == '+') {
1551         if (argc < 5)
1552             return 0;
1553         lastmod = (argc > 5) ? strtoul(argv[5], NULL, 0) : 0;
1554         gline_add(origin, argv[2]+1, strtoul(argv[3], NULL, 0), argv[argc-1], now, lastmod, 0);
1555         return 1;
1556     } else if (argv[2][0] == '-') {
1557         gline_remove(argv[2]+1, 0);
1558         return 1;
1559     } else
1560         return 0;
1561 }
1562
1563 static CMD_FUNC(cmd_svsnick)
1564 {
1565     struct userNode *target, *dest;
1566     if ((argc < 4)
1567         || !(target = GetUserN(argv[1]))
1568         || !IsLocal(target)
1569         || (dest = GetUserH(argv[2])))
1570         return 0;
1571     NickChange(target, argv[2], 0);
1572     return 1;
1573 }
1574
1575 void
1576 free_user(struct userNode *user)
1577 {
1578     free(user->nick);
1579     free(user);
1580 }
1581
1582 static void
1583 parse_cleanup(void)
1584 {
1585     unsigned int nn;
1586     free(of_list);
1587     free(privmsg_funcs);
1588     num_privmsg_funcs = 0;
1589     free(notice_funcs);
1590     num_notice_funcs = 0;
1591     free(mcf_list);
1592     dict_delete(irc_func_dict);
1593     for (nn=0; nn<dead_users.used; nn++)
1594         free_user(dead_users.list[nn]);
1595     userList_clean(&dead_users);
1596 }
1597
1598 static void
1599 p10_conf_reload(void) {
1600     hidden_host_suffix = conf_get_data("server/hidden_host", RECDB_QSTRING);
1601     his_servername = conf_get_data("server/his_servername", RECDB_QSTRING);
1602     his_servercomment = conf_get_data("server/his_servercomment", RECDB_QSTRING);
1603 }
1604
1605 static void
1606 remove_unbursted_channel(struct chanNode *cNode) {
1607     if (unbursted_channels)
1608         dict_remove(unbursted_channels, cNode->name);
1609 }
1610
1611 void
1612 init_parse(void)
1613 {
1614     const char *str, *desc;
1615     int numnick, usermask, max_users;
1616     char numer[COMBO_NUMERIC_LEN+1];
1617
1618     /* read config items */
1619     str = conf_get_data("server/ping_freq", RECDB_QSTRING);
1620     ping_freq = str ? ParseInterval(str) : 120;
1621     str = conf_get_data("server/ping_timeout", RECDB_QSTRING);
1622     ping_timeout = str ? ParseInterval(str) : 30;
1623     str = conf_get_data("server/force_n2k", RECDB_QSTRING);
1624     force_n2k = str ? enabled_string(str) : 1;
1625     str = conf_get_data("server/numeric", RECDB_QSTRING);
1626     if (!str) {
1627         log_module(MAIN_LOG, LOG_ERROR, "No server/numeric entry in config file.");
1628         exit(1);
1629     }
1630     numnick = atoi(str);
1631     str = conf_get_data("server/max_users", RECDB_QSTRING);
1632     max_users = str ? atoi(str) : 4096;
1633     for (usermask = 4; usermask < max_users; usermask <<= 1) ;
1634     usermask--;
1635     if ((numnick < 64) && (usermask < 4096) && !force_n2k)
1636         inttobase64(numer, (numnick << 12) + (usermask & 0x00fff), 3);
1637     else
1638         inttobase64(numer, (numnick << 18) + (usermask & 0x3ffff), 5);
1639
1640     str = conf_get_data("server/hostname", RECDB_QSTRING);
1641     desc = conf_get_data("server/description", RECDB_QSTRING);
1642     if (!str || !desc) {
1643         log_module(MAIN_LOG, LOG_ERROR, "No server/hostname entry in config file.");
1644         exit(1);
1645     }
1646     self = AddServer(NULL, str, 0, boot_time, now, numer, desc);
1647     conf_register_reload(p10_conf_reload);
1648
1649     irc_func_dict = dict_new();
1650     dict_insert(irc_func_dict, CMD_BURST, cmd_burst);
1651     dict_insert(irc_func_dict, TOK_BURST, cmd_burst);
1652     dict_insert(irc_func_dict, CMD_CREATE, cmd_create);
1653     dict_insert(irc_func_dict, TOK_CREATE, cmd_create);
1654     dict_insert(irc_func_dict, CMD_EOB, cmd_eob);
1655     dict_insert(irc_func_dict, TOK_EOB, cmd_eob);
1656     dict_insert(irc_func_dict, CMD_EOB_ACK, cmd_eob_ack);
1657     dict_insert(irc_func_dict, TOK_EOB_ACK, cmd_eob_ack);
1658     dict_insert(irc_func_dict, CMD_MODE, cmd_mode);
1659     dict_insert(irc_func_dict, TOK_MODE, cmd_mode);
1660     dict_insert(irc_func_dict, CMD_NICK, cmd_nick);
1661     dict_insert(irc_func_dict, TOK_NICK, cmd_nick);
1662     dict_insert(irc_func_dict, CMD_ACCOUNT, cmd_account);
1663     dict_insert(irc_func_dict, TOK_ACCOUNT, cmd_account);
1664     dict_insert(irc_func_dict, CMD_FAKEHOST, cmd_fakehost);
1665     dict_insert(irc_func_dict, TOK_FAKEHOST, cmd_fakehost);
1666     dict_insert(irc_func_dict, CMD_PASS, cmd_pass);
1667     dict_insert(irc_func_dict, TOK_PASS, cmd_pass);
1668     dict_insert(irc_func_dict, CMD_PING, cmd_ping);
1669     dict_insert(irc_func_dict, TOK_PING, cmd_ping);
1670     dict_insert(irc_func_dict, CMD_PRIVMSG, cmd_privmsg);
1671     dict_insert(irc_func_dict, TOK_PRIVMSG, cmd_privmsg);
1672     dict_insert(irc_func_dict, CMD_PONG, cmd_pong);
1673     dict_insert(irc_func_dict, TOK_PONG, cmd_pong);
1674     dict_insert(irc_func_dict, CMD_QUIT, cmd_quit);
1675     dict_insert(irc_func_dict, TOK_QUIT, cmd_quit);
1676     dict_insert(irc_func_dict, CMD_SERVER, cmd_server);
1677     dict_insert(irc_func_dict, TOK_SERVER, cmd_server);
1678     dict_insert(irc_func_dict, CMD_JOIN, cmd_join);
1679     dict_insert(irc_func_dict, TOK_JOIN, cmd_join);
1680     dict_insert(irc_func_dict, CMD_PART, cmd_part);
1681     dict_insert(irc_func_dict, TOK_PART, cmd_part);
1682     dict_insert(irc_func_dict, CMD_ERROR, cmd_error);
1683     dict_insert(irc_func_dict, TOK_ERROR, cmd_error);
1684     dict_insert(irc_func_dict, CMD_TOPIC, cmd_topic);
1685     dict_insert(irc_func_dict, TOK_TOPIC, cmd_topic);
1686     dict_insert(irc_func_dict, CMD_AWAY, cmd_away);
1687     dict_insert(irc_func_dict, TOK_AWAY, cmd_away);
1688     dict_insert(irc_func_dict, CMD_SILENCE, cmd_dummy);
1689     dict_insert(irc_func_dict, TOK_SILENCE, cmd_dummy);
1690     dict_insert(irc_func_dict, CMD_KICK, cmd_kick);
1691     dict_insert(irc_func_dict, TOK_KICK, cmd_kick);
1692     dict_insert(irc_func_dict, CMD_SQUIT, cmd_squit);
1693     dict_insert(irc_func_dict, TOK_SQUIT, cmd_squit);
1694     dict_insert(irc_func_dict, CMD_KILL, cmd_kill);
1695     dict_insert(irc_func_dict, TOK_KILL, cmd_kill);
1696     dict_insert(irc_func_dict, CMD_NOTICE, cmd_notice);
1697     dict_insert(irc_func_dict, TOK_NOTICE, cmd_notice);
1698     dict_insert(irc_func_dict, CMD_STATS, cmd_stats);
1699     dict_insert(irc_func_dict, TOK_STATS, cmd_stats);
1700     dict_insert(irc_func_dict, CMD_SVSNICK, cmd_svsnick);
1701     dict_insert(irc_func_dict, TOK_SVSNICK, cmd_svsnick);
1702     dict_insert(irc_func_dict, CMD_WHOIS, cmd_whois);
1703     dict_insert(irc_func_dict, TOK_WHOIS, cmd_whois);
1704     dict_insert(irc_func_dict, CMD_GLINE, cmd_gline);
1705     dict_insert(irc_func_dict, TOK_GLINE, cmd_gline);
1706     dict_insert(irc_func_dict, CMD_OPMODE, cmd_opmode);
1707     dict_insert(irc_func_dict, TOK_OPMODE, cmd_opmode);
1708     dict_insert(irc_func_dict, CMD_CLEARMODE, cmd_clearmode);
1709     dict_insert(irc_func_dict, TOK_CLEARMODE, cmd_clearmode);
1710     dict_insert(irc_func_dict, CMD_VERSION, cmd_version);
1711     dict_insert(irc_func_dict, TOK_VERSION, cmd_version);
1712     dict_insert(irc_func_dict, CMD_ADMIN, cmd_admin);
1713     dict_insert(irc_func_dict, TOK_ADMIN, cmd_admin);
1714
1715     /* In P10, DESTRUCT doesn't do anything except be broadcast to servers.
1716      * Apparently to obliterate channels from any servers that think they
1717      * exist?
1718      */
1719     dict_insert(irc_func_dict, CMD_DESTRUCT, cmd_dummy);
1720     dict_insert(irc_func_dict, TOK_DESTRUCT, cmd_dummy);
1721     /* Ignore invites */
1722     dict_insert(irc_func_dict, CMD_INVITE, cmd_dummy);
1723     dict_insert(irc_func_dict, TOK_INVITE, cmd_dummy);
1724     /* DESYNCH is just informational, so ignore it */
1725     dict_insert(irc_func_dict, CMD_DESYNCH, cmd_dummy);
1726     dict_insert(irc_func_dict, TOK_DESYNCH, cmd_dummy);
1727     /* Ignore channel operator notices. */
1728     dict_insert(irc_func_dict, CMD_WALLCHOPS, cmd_dummy);
1729     dict_insert(irc_func_dict, TOK_WALLCHOPS, cmd_dummy);
1730     dict_insert(irc_func_dict, CMD_WALLVOICES, cmd_dummy);
1731     dict_insert(irc_func_dict, TOK_WALLVOICES, cmd_dummy);
1732     /* Ignore opers being silly. */
1733     dict_insert(irc_func_dict, CMD_WALLOPS, cmd_dummy);
1734     dict_insert(irc_func_dict, TOK_WALLOPS, cmd_dummy);
1735     /* We have reliable clock!  Always!  Wraaa! */
1736     dict_insert(irc_func_dict, CMD_SETTIME, cmd_dummy);
1737     dict_insert(irc_func_dict, TOK_SETTIME, cmd_dummy);
1738     /* handle topics */
1739     dict_insert(irc_func_dict, "331", cmd_num_topic);
1740     dict_insert(irc_func_dict, "332", cmd_num_topic);
1741     dict_insert(irc_func_dict, "333", cmd_num_topic);
1742     dict_insert(irc_func_dict, "345", cmd_dummy); /* blah has been invited to blah */
1743     dict_insert(irc_func_dict, "432", cmd_error_nick); /* Erroneus [sic] nickname */
1744     /* ban list resetting */
1745     /* "stats g" responses */
1746     dict_insert(irc_func_dict, "247", cmd_num_gline);
1747     dict_insert(irc_func_dict, "219", cmd_dummy); /* "End of /STATS report" */
1748     /* other numeric responses we might get */
1749     dict_insert(irc_func_dict, "401", cmd_dummy); /* target left network */
1750     dict_insert(irc_func_dict, "403", cmd_dummy); /* no such channel */
1751     dict_insert(irc_func_dict, "404", cmd_dummy); /* cannot send to channel */
1752     dict_insert(irc_func_dict, "439", cmd_dummy); /* target change too fast */
1753     dict_insert(irc_func_dict, "441", cmd_dummy); /* target isn't on that channel */
1754     dict_insert(irc_func_dict, "442", cmd_dummy); /* you aren't on that channel */
1755     dict_insert(irc_func_dict, "443", cmd_dummy); /* is already on channel (after invite?) */
1756     dict_insert(irc_func_dict, "461", cmd_dummy); /* Not enough parameters (after TOPIC w/ 0 args) */
1757     dict_insert(irc_func_dict, "467", cmd_dummy); /* Channel key already set */
1758
1759     num_privmsg_funcs = 16;
1760     privmsg_funcs = malloc(sizeof(privmsg_func_t)*num_privmsg_funcs);
1761     memset(privmsg_funcs, 0, sizeof(privmsg_func_t)*num_privmsg_funcs);
1762
1763     num_notice_funcs = 16;
1764     notice_funcs = malloc(sizeof(privmsg_func_t)*num_notice_funcs);
1765     memset(notice_funcs, 0, sizeof(privmsg_func_t)*num_notice_funcs);
1766
1767     userList_init(&dead_users);
1768     reg_del_channel_func(remove_unbursted_channel);
1769     reg_exit_func(parse_cleanup);
1770 }
1771
1772 int
1773 parse_line(char *line, int recursive)
1774 {
1775     char *argv[MAXNUMPARAMS], *origin;
1776     int argc, cmd, res=0;
1777     cmd_func_t *func;
1778
1779     argc = split_line(line, true, MAXNUMPARAMS, argv);
1780     cmd = self->uplink || !argv[0][1] || !argv[0][2];
1781     if (argc > cmd) {
1782         if (cmd) {
1783             if (argv[0][0] == ':') {
1784                 origin = argv[0]+1;
1785             } else if (!argv[0][1] || !argv[0][2]) {
1786                 struct server *sNode = GetServerN(argv[0]);
1787                 origin = sNode ? sNode->name : 0;
1788             } else {
1789                 struct userNode *uNode = GetUserN(argv[0]);
1790                 origin = uNode ? uNode->nick : 0;
1791             }
1792         } else
1793             origin = 0;
1794         if ((func = dict_find(irc_func_dict, argv[cmd], NULL)))
1795             res = func(origin, argc-cmd, argv+cmd);
1796     }
1797     if (!res) {
1798         log_module(MAIN_LOG, LOG_ERROR, "PARSE ERROR on line: %s", unsplit_string(argv, argc, NULL));
1799     } else if (!recursive) {
1800         unsigned int i;
1801         for (i=0; i<dead_users.used; i++)
1802             free_user(dead_users.list[i]);
1803         dead_users.used = 0;
1804     }
1805     return res;
1806 }
1807
1808 static void
1809 parse_foreach(char *target_list, foreach_chanfunc cf, foreach_nonchan nc, foreach_userfunc uf, foreach_nonuser nu, void *data)
1810 {
1811     char *j, old;
1812
1813     do {
1814         j = target_list;
1815         while (*j != 0 && *j != ',')
1816             j++;
1817         old = *j;
1818         *j = 0;
1819
1820         if (IsChannelName(target_list)
1821             || (target_list[0] == '0' && target_list[1] == '\0')) {
1822             struct chanNode *chan = GetChannel(target_list);
1823
1824             if (chan) {
1825                 if (cf)
1826                     cf(chan, data);
1827             } else {
1828                 if (nc)
1829                     nc(target_list, data);
1830             }
1831         } else {
1832             struct userNode *user;
1833             struct privmsg_desc *pd = data;
1834
1835             pd->is_qualified = 0;
1836             if (*target_list == '@') {
1837                 user = NULL;
1838             } else if (strchr(target_list, '@')) {
1839                 struct server *server;
1840
1841                 pd->is_qualified = 1;
1842                 user = GetUserH(strtok(target_list, "@"));
1843                 server = GetServerH(strtok(NULL, "@"));
1844
1845                 if (user && (user->uplink != server)) {
1846                     /* Don't attempt to index into any arrays
1847                        using a user's numeric on another server. */
1848                     user = NULL;
1849                 }
1850             } else {
1851                 user = GetUserN(target_list);
1852             }
1853
1854             if (user) {
1855                 if (uf)
1856                     uf(user, data);
1857             } else {
1858                 if (nu)
1859                     nu(target_list, data);
1860             }
1861         }
1862         target_list = j+1;
1863     } while (old == ',');
1864 }
1865
1866 static int
1867 get_local_numeric(void)
1868 {
1869     static unsigned int next_numeric = 0;
1870     if (self->clients > self->num_mask)
1871         return -1;
1872     while (self->users[next_numeric])
1873         if (++next_numeric > self->num_mask)
1874             next_numeric = 0;
1875     return next_numeric;
1876 }
1877
1878 static void
1879 make_numeric(struct server *svr, int local_num, char *outbuf)
1880 {
1881     int slen, llen;
1882
1883     if (force_n2k || svr->numeric[1]) {
1884         slen = 2;
1885         llen = 3;
1886     } else {
1887         slen = 1;
1888         llen = (local_num < 64*64) ? 2 : 3;
1889     }
1890     strncpy(outbuf, svr->numeric, slen);
1891     inttobase64(outbuf+slen, local_num, llen);
1892     outbuf[slen+llen] = 0;
1893 }
1894
1895 struct server *
1896 AddServer(struct server *uplink, const char *name, int hops, unsigned long boot, unsigned long link_time, const char *numeric, const char *description)
1897 {
1898     struct server* sNode;
1899     int slen, mlen;
1900
1901     if ((sNode = GetServerN(numeric))) {
1902         /* This means we're trying to re-add an existant server.
1903          * To be safe, we should forget the previous incarnation.
1904          * (And all its linked servers.)
1905          *
1906          * It usually only happens in replays when the original
1907          * had a ping timeout and the replay didn't (because
1908          * replaying a ping timeout invariably gets things wrong).
1909          */
1910         DelServer(sNode, 0, NULL);
1911     }
1912
1913     switch (strlen(numeric)) {
1914     case 5: slen = 2; mlen = 3; break;
1915     case 4: slen = 1; mlen = 3; break;
1916     case 3: slen = 1; mlen = 2; break;
1917     default:
1918         log_module(MAIN_LOG, LOG_ERROR, "AddServer(\"%s\", \"%s\", ...): Numeric %s has invalid length.", uplink->name, name, numeric);
1919         return NULL;
1920     }
1921
1922     sNode = calloc(1, sizeof(*sNode));
1923     sNode->uplink = uplink;
1924     safestrncpy(sNode->name, name, sizeof(sNode->name));
1925     sNode->num_mask = base64toint(numeric+slen, mlen);
1926     sNode->hops = hops;
1927     sNode->boot = boot;
1928     sNode->link_time = link_time;
1929     strncpy(sNode->numeric, numeric, slen);
1930     safestrncpy(sNode->description, description, sizeof(sNode->description));
1931     sNode->users = calloc(sNode->num_mask+1, sizeof(*sNode->users));
1932     serverList_init(&sNode->children);
1933     if (sNode->uplink) {
1934         /* uplink may be NULL if we're just building ourself */
1935         serverList_append(&sNode->uplink->children, sNode);
1936     }
1937     servers_num[base64toint(numeric, slen)] = sNode;
1938     dict_insert(servers, sNode->name, sNode);
1939     return sNode;
1940 }
1941
1942 void DelServer(struct server* serv, int announce, const char *message)
1943 {
1944     unsigned int i;
1945
1946     /* If we receive an ERROR command before the SERVER
1947      * command a NULL server can be passed */
1948     if (!serv)
1949         return;
1950
1951     /* Hrm, what's the right way to SQUIT some other server?
1952      * (This code is only to handle killing juped servers.) */
1953     if (announce && (serv->uplink == self) && (serv != self->uplink))
1954         irc_squit(serv, message, NULL);
1955
1956     /* must recursively remove servers linked to this one first */
1957     for (i=serv->children.used;i>0;)
1958         if (serv->children.list[--i] != self)
1959             DelServer(serv->children.list[i], false, NULL);
1960
1961     /* clean up server's user hash tables */
1962     for (i=0;i<=serv->num_mask;i++)
1963         if (serv->users[i])
1964             DelUser(serv->users[i], NULL, false, "server delinked");
1965
1966     /* delete server */
1967     if (serv->uplink)
1968         serverList_remove(&serv->uplink->children, serv);
1969     if (serv == self->uplink)
1970         self->uplink = NULL;
1971     servers_num[base64toint(serv->numeric, strlen(serv->numeric))] = NULL;
1972     dict_remove(servers, serv->name);
1973     serverList_clean(&serv->children);
1974     free(serv->users);
1975     free(serv);
1976 }
1977
1978 struct userNode *
1979 AddLocalUser(const char *nick, const char *ident, const char *hostname, const char *desc, const char *modes)
1980 {
1981     char numeric[COMBO_NUMERIC_LEN+1];
1982     int local_num = get_local_numeric();
1983     unsigned long timestamp = now;
1984     struct userNode *old_user = GetUserH(nick);
1985
1986     if (!modes)
1987         modes = "+oik";
1988     if (old_user) {
1989         if (IsLocal(old_user))
1990             return old_user;
1991         timestamp = old_user->timestamp - 1;
1992     }
1993     if (local_num == -1) {
1994         log_module(MAIN_LOG, LOG_ERROR, "Unable to allocate numnick for service %s", nick);
1995         return 0;
1996     }
1997     if (!hostname)
1998         hostname = self->name;
1999     make_numeric(self, local_num, numeric);
2000     return AddUser(self, nick, ident, hostname, modes, numeric, desc, now, "AAAAAA");
2001 }
2002
2003 struct userNode *
2004 AddClone(const char *nick, const char *ident, const char *hostname, const char *desc)
2005 {
2006     char numeric[COMBO_NUMERIC_LEN+1];
2007     int local_num = get_local_numeric();
2008     unsigned long timestamp = now;
2009     struct userNode *old_user = GetUserH(nick);
2010
2011     if (old_user) {
2012         if (IsLocal(old_user))
2013             return old_user;
2014         timestamp = old_user->timestamp - 1;
2015     }
2016     if (local_num == -1) {
2017         log_module(MAIN_LOG, LOG_ERROR, "Unable to allocate numnick for clone %s", nick);
2018         return 0;
2019     }
2020     make_numeric(self, local_num, numeric);
2021     return AddUser(self, nick, ident, hostname, "+i", numeric, desc, timestamp, "AAAAAA");
2022 }
2023
2024 int
2025 is_valid_nick(const char *nick) {
2026     unsigned int ii;
2027     /* IRC has some of The Most Fucked-Up ideas about character sets
2028      * in the world.. */
2029     if (!isalpha(*nick) && !strchr("{|}~[\\]^_`", *nick))
2030         return 0;
2031     for (ii = 0; nick[ii]; ++ii)
2032         if (!isalnum(nick[ii]) && !strchr("{|}~[\\]^-_`", nick[ii]))
2033             return 0;
2034     if (strlen(nick) > nicklen)
2035         return 0;
2036     return 1;
2037 }
2038
2039 static struct userNode*
2040 AddUser(struct server* uplink, const char *nick, const char *ident, const char *hostname, const char *modes, const char *numeric, const char *userinfo, unsigned long timestamp, const char *realip)
2041 {
2042     struct userNode *oldUser, *uNode;
2043     unsigned int n, ignore_user, dummy;
2044
2045     if ((strlen(numeric) < 3) || (strlen(numeric) > 5)) {
2046         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): numeric %s wrong length!", (void*)uplink, nick, numeric);
2047         return NULL;
2048     }
2049
2050     if (!uplink) {
2051         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): server for numeric %s doesn't exist!", (void*)uplink, nick, numeric);
2052         return NULL;
2053     }
2054
2055     if (uplink != GetServerN(numeric)) {
2056         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): server for numeric %s differs from nominal uplink %s.", (void*)uplink, nick, numeric, uplink->name);
2057         return NULL;
2058     }
2059
2060     dummy = modes && modes[0] == '*';
2061     if (dummy) {
2062         ++modes;
2063     } else if (!is_valid_nick(nick)) {
2064         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): invalid nickname detected.", (void*)uplink, nick);
2065         return NULL;
2066     }
2067
2068     ignore_user = 0;
2069     if ((oldUser = GetUserH(nick))) {
2070         if (IsLocal(oldUser)
2071             && (IsService(oldUser) || IsPersistent(oldUser))) {
2072             /* The service should collide the new user off - but not
2073              * if the new user is coming in during a burst.  (During a
2074              * burst, the bursting server will kill either our user --
2075              * triggering a ReintroduceUser() -- or its own.)
2076              */
2077             oldUser->timestamp = timestamp - 1;
2078             ignore_user = 1;
2079             if (!uplink->burst)
2080                 irc_user(oldUser);
2081         } else if (oldUser->timestamp > timestamp) {
2082             /* "Old" user is really newer; remove them. */
2083             DelUser(oldUser, 0, 1, "Overruled by older nick");
2084         } else {
2085             /* User being added is too new; do not add them to
2086              * clients, but do add them to the server's list, since it
2087              * will send a KILL and QUIT soon. */
2088             ignore_user = 1;
2089         }
2090     }
2091
2092     /* create new usernode and set all values */
2093     uNode = calloc(1, sizeof(*uNode));
2094     uNode->nick = strdup(nick);
2095     safestrncpy(uNode->ident, ident, sizeof(uNode->ident));
2096     safestrncpy(uNode->info, userinfo, sizeof(uNode->info));
2097     safestrncpy(uNode->hostname, hostname, sizeof(uNode->hostname));
2098     safestrncpy(uNode->numeric, numeric, sizeof(uNode->numeric));
2099     irc_p10_pton(&uNode->ip, realip);
2100     uNode->timestamp = timestamp;
2101     uNode->idle_since = timestamp;
2102     modeList_init(&uNode->channels);
2103     uNode->uplink = uplink;
2104     if (++uNode->uplink->clients > uNode->uplink->max_clients) {
2105         uNode->uplink->max_clients = uNode->uplink->clients;
2106     }
2107     uNode->num_local = base64toint(numeric+strlen(uNode->uplink->numeric), 3) & uNode->uplink->num_mask;
2108     uNode->uplink->users[uNode->num_local] = uNode;
2109     mod_usermode(uNode, modes);
2110     if (dummy)
2111         uNode->modes |= FLAGS_DUMMY;
2112     if (ignore_user)
2113         return uNode;
2114
2115     dict_insert(clients, uNode->nick, uNode);
2116     if (dict_size(clients) > max_clients) {
2117         max_clients = dict_size(clients);
2118         max_clients_time = now;
2119     }
2120     if (IsLocal(uNode))
2121         irc_user(uNode);
2122     for (n=0; (n<nuf_used) && !uNode->dead; n++)
2123         nuf_list[n](uNode);
2124     return uNode;
2125 }
2126
2127 /* removes user from it's server's hash table and nick hash table */
2128 void
2129 DelUser(struct userNode* user, struct userNode *killer, int announce, const char *why)
2130 {
2131     unsigned int n;
2132
2133     verify(user);
2134
2135     /* mark them as dead, in case anybody cares */
2136     user->dead = 1;
2137
2138     /* remove user from all channels */
2139     while (user->channels.used > 0)
2140         DelChannelUser(user, user->channels.list[user->channels.used-1]->channel, NULL, false);
2141
2142     /* Call these in reverse order so ChanServ can update presence
2143        information before NickServ nukes the handle_info. */
2144     for (n = duf_used; n > 0; )
2145         duf_list[--n](user, killer, why);
2146
2147     user->uplink->clients--;
2148     user->uplink->users[user->num_local] = NULL;
2149     if (IsOper(user))
2150         userList_remove(&curr_opers, user);
2151     /* remove from global dictionary, but not if after a collide */
2152     if (user == dict_find(clients, user->nick, NULL))
2153         dict_remove(clients, user->nick);
2154
2155     if (IsInvisible(user))
2156         invis_clients--;
2157
2158     if (announce) {
2159         if (IsLocal(user))
2160             irc_quit(user, why);
2161         else
2162             irc_kill(killer, user, why);
2163     }
2164
2165     if (IsLocal(user)) {
2166         unsigned int num = user->num_local;
2167         if (num < num_privmsg_funcs)
2168             privmsg_funcs[num] = NULL;
2169         if (num < num_notice_funcs)
2170             notice_funcs[num] = NULL;
2171     }
2172
2173     modeList_clean(&user->channels);
2174     /* We don't free them, in case we try to privmsg them or something
2175      * (like when a stupid oper kills themself).  We just put them onto
2176      * a list of clients that get freed after processing each line.
2177      */
2178     if (dead_users.size)
2179         userList_append(&dead_users, user);
2180     else
2181         free_user(user);
2182 }
2183
2184 static void call_oper_funcs(struct userNode *user);
2185
2186 void mod_usermode(struct userNode *user, const char *mode_change) {
2187     int add = 1;
2188     const char *word = mode_change;
2189
2190     if (!user || !mode_change)
2191         return;
2192     while (*word != ' ' && *word) word++;
2193     while (*word == ' ') word++;
2194     while (1) {
2195 #define do_user_mode(FLAG) do { if (add) user->modes |= FLAG; else user->modes &= ~FLAG; } while (0)
2196         switch (*mode_change++) {
2197         case 0: case ' ': return;
2198         case '+': add = 1; break;
2199         case '-': add = 0; break;
2200         case 'o':
2201             do_user_mode(FLAGS_OPER);
2202             if (!add) {
2203                 userList_remove(&curr_opers, user);
2204             } else if (!userList_contains(&curr_opers, user)) {
2205                 userList_append(&curr_opers, user);
2206                 call_oper_funcs(user);
2207             }
2208             break;
2209         case 'i': do_user_mode(FLAGS_INVISIBLE);
2210             if (add)
2211                 invis_clients++;
2212             else
2213                 invis_clients--;
2214             break;
2215         case 'w': do_user_mode(FLAGS_WALLOP); break;
2216         case 'd': do_user_mode(FLAGS_DEAF); break;
2217         case 'k': do_user_mode(FLAGS_SERVICE); break;
2218         case 'g': do_user_mode(FLAGS_GLOBAL); break;
2219         case 'n': do_user_mode(FLAGS_NOCHAN); break;
2220         case 'I': do_user_mode(FLAGS_NOIDLE); break;
2221         case 'x': do_user_mode(FLAGS_HIDDEN_HOST); break;
2222         case 'r':
2223             if (*word) {
2224                 char tag[MAXLEN];
2225                 char *sep;
2226                 unsigned int ii;
2227                 unsigned long ts = 0;
2228                 unsigned long id = 0;
2229
2230                 for (ii=0; (*word != ' ') && (*word != '\0') && (*word != ':'); )
2231                     tag[ii++] = *word++;
2232                 if (*word == ':') {
2233                     ts = strtoul(word + 1, &sep, 10);
2234                     if (*sep == ':') {
2235                         id = strtoul(sep + 1, &sep, 10);
2236                     } else if (*sep != ' ' && *sep != '\0') {
2237                         ts = 0;
2238                     }
2239                     word = sep;
2240                 }
2241                 tag[ii] = '\0';
2242                 while (*word == ' ')
2243                     word++;
2244                 call_account_func(user, tag, ts, id);
2245             }
2246             break;
2247         case 'f':
2248             if (*word) {
2249                 char host[MAXLEN];
2250                 unsigned int ii;
2251                 for (ii=0; (*word != ' ') && (*word != '\0'); )
2252                     host[ii++] = *word++;
2253                 host[ii] = 0;
2254                 while (*word == ' ')
2255                     word++;
2256                 assign_fakehost(user, host, 0);
2257             }
2258             break;
2259         }
2260 #undef do_user_mode
2261     }
2262 }
2263
2264 static int
2265 keyncpy(char output[], char input[], size_t output_size)
2266 {
2267     size_t ii;
2268
2269     if (input[0] == ':')
2270     {
2271         output[0] = '\0';
2272         return 1;
2273     }
2274
2275     for (ii = 0; (ii + 1 < output_size) && (input[ii] != '\0'); ++ii)
2276     {
2277         output[ii] = input[ii];
2278     }
2279
2280     output[ii] = '\0';
2281     return 0;
2282 }
2283
2284 struct mod_chanmode *
2285 mod_chanmode_parse(struct chanNode *channel, char **modes, unsigned int argc, unsigned int flags, short base_oplevel)
2286 {
2287     struct mod_chanmode *change;
2288     unsigned int ii, in_arg, ch_arg, add;
2289
2290     if (argc == 0)
2291         return NULL;
2292     if (!(change = mod_chanmode_alloc(argc - 1)))
2293         return NULL;
2294
2295     for (ii = ch_arg = 0, in_arg = add = 1;
2296          (modes[0][ii] != '\0') && (modes[0][ii] != ' ');
2297          ++ii) {
2298         switch (modes[0][ii]) {
2299         case '+':
2300             add = 1;
2301             break;
2302         case '-':
2303             add = 0;
2304             break;
2305 #define do_chan_mode(FLAG) do { if (add) change->modes_set |= (FLAG), change->modes_clear &= ~(FLAG); else change->modes_clear |= (FLAG), change->modes_set &= ~(FLAG); } while(0)
2306         case 'C': do_chan_mode(MODE_NOCTCPS); break;
2307         case 'D': do_chan_mode(MODE_DELAYJOINS); break;
2308         case 'c': do_chan_mode(MODE_NOCOLORS); break;
2309         case 'i': do_chan_mode(MODE_INVITEONLY); break;
2310         case 'm': do_chan_mode(MODE_MODERATED); break;
2311         case 'n': do_chan_mode(MODE_NOPRIVMSGS); break;
2312         case 'p': do_chan_mode(MODE_PRIVATE); break;
2313         case 'r': do_chan_mode(MODE_REGONLY); break;
2314         case 's': do_chan_mode(MODE_SECRET); break;
2315         case 't': do_chan_mode(MODE_TOPICLIMIT); break;
2316         case 'z':
2317           if (!(flags & MCP_REGISTERED)) {
2318               do_chan_mode(MODE_REGISTERED);
2319           } else {
2320               mod_chanmode_free(change);
2321               return NULL;
2322           }
2323           break;
2324 #undef do_chan_mode
2325         case 'l':
2326             if (add) {
2327                 if (in_arg >= argc)
2328                     goto error;
2329                 change->modes_set |= MODE_LIMIT;
2330                 change->new_limit = atoi(modes[in_arg++]);
2331             } else {
2332                 change->modes_set &= ~MODE_LIMIT;
2333                 change->modes_clear |= MODE_LIMIT;
2334             }
2335             break;
2336         case 'k':
2337             if (add) {
2338                 if ((in_arg >= argc)
2339                     || keyncpy(change->new_key, modes[in_arg++], sizeof(change->new_key)))
2340                     goto error;
2341                 change->modes_set |= MODE_KEY;
2342             } else {
2343                 change->modes_clear |= MODE_KEY;
2344                 if (!(flags & MCP_KEY_FREE)) {
2345                     if (in_arg >= argc)
2346                         goto error;
2347                     in_arg++;
2348                 }
2349             }
2350             break;
2351         case 'U':
2352             if (add)
2353             {
2354                 if ((in_arg >= argc)
2355                     || keyncpy(change->new_upass, modes[in_arg++], sizeof(change->new_upass)))
2356                     goto error;
2357                 change->modes_set |= MODE_UPASS;
2358             } else {
2359                 change->modes_clear |= MODE_UPASS;
2360                 if (!(flags & MCP_UPASS_FREE)) {
2361                     if (in_arg >= argc)
2362                         goto error;
2363                     in_arg++;
2364                 }
2365             }
2366             break;
2367         case 'A':
2368             if (add) {
2369                 if ((in_arg >= argc)
2370                     || keyncpy(change->new_apass, modes[in_arg++], sizeof(change->new_apass)))
2371                     goto error;
2372                 change->modes_set |= MODE_APASS;
2373             } else {
2374                 change->modes_clear |= MODE_APASS;
2375                 if (!(flags & MCP_APASS_FREE)) {
2376                     if (in_arg >= argc)
2377                       goto error;
2378                     in_arg++;
2379                 }
2380             }
2381             break;
2382         case 'b':
2383             if (!(flags & MCP_ALLOW_OVB))
2384                 goto error;
2385             if (in_arg >= argc)
2386                 goto error;
2387             change->args[ch_arg].mode = MODE_BAN;
2388             if (!add)
2389                 change->args[ch_arg].mode |= MODE_REMOVE;
2390             change->args[ch_arg++].u.hostmask = modes[in_arg++];
2391             break;
2392         case 'o': case 'v':
2393         {
2394             struct userNode *victim;
2395             char *oplevel_str;
2396             int oplevel;
2397
2398             if (in_arg >= argc)
2399                 goto error;
2400             oplevel_str = strchr(modes[in_arg], ':');
2401             if (oplevel_str)
2402             {
2403                 /* XXYYY M #channel +o XXYYY:<oplevel> */
2404                 *oplevel_str++ = '\0';
2405                 oplevel = parse_oplevel(oplevel_str);
2406                 if (oplevel <= base_oplevel && !(flags & MCP_FROM_SERVER))
2407                     oplevel = base_oplevel + 1;
2408             }
2409             else if (channel->modes & MODE_UPASS)
2410                 oplevel = base_oplevel + 1;
2411             else
2412                 oplevel = -1;
2413
2414             /* Check that oplevel is within bounds. */
2415             if (oplevel > MAXOPLEVEL)
2416                 oplevel = MAXOPLEVEL;
2417
2418             if (!(flags & MCP_ALLOW_OVB))
2419                 goto error;
2420             if (in_arg >= argc)
2421                 goto error;
2422             change->args[ch_arg].mode = (modes[0][ii] == 'o') ? MODE_CHANOP : MODE_VOICE;
2423             if (!add)
2424                 change->args[ch_arg].mode |= MODE_REMOVE;
2425             if (flags & MCP_FROM_SERVER)
2426                 victim = GetUserN(modes[in_arg++]);
2427             else
2428                 victim = GetUserH(modes[in_arg++]);
2429             if (!victim)
2430                 continue;
2431             if ((change->args[ch_arg].u.member = GetUserMode(channel, victim)))
2432             {
2433                 /* Apply the oplevel change */
2434                 change->args[ch_arg].u.member->oplevel = oplevel;
2435                 ch_arg++;
2436             }
2437             break;
2438         }
2439         default:
2440             if (!(flags & MCP_FROM_SERVER))
2441                 goto error;
2442             break;
2443         }
2444     }
2445     change->argc = ch_arg; /* in case any turned out to be ignored */
2446     if (change->modes_set & MODE_SECRET) {
2447         change->modes_set &= ~(MODE_PRIVATE);
2448         change->modes_clear |= MODE_PRIVATE;
2449     } else if (change->modes_set & MODE_PRIVATE) {
2450         change->modes_set &= ~(MODE_SECRET);
2451         change->modes_clear |= MODE_SECRET;
2452     }
2453     return change;
2454   error:
2455     mod_chanmode_free(change);
2456     return NULL;
2457 }
2458
2459 struct chanmode_buffer {
2460     char modes[MAXLEN];
2461     char args[MAXLEN];
2462     struct chanNode *channel;
2463     struct userNode *actor;
2464     unsigned int modes_used;
2465     unsigned int args_used;
2466     size_t chname_len;
2467     unsigned int is_add : 1;
2468     unsigned int is_chanop : 1;
2469 };
2470
2471 static void
2472 mod_chanmode_append(struct chanmode_buffer *buf, char ch, const char *arg)
2473 {
2474     size_t arg_len = strlen(arg);
2475     if (buf->modes_used > (MAXMODEPARAMS) ||
2476         buf->modes_used + buf->args_used + buf->chname_len + arg_len > 450) {
2477         memcpy(buf->modes + buf->modes_used, buf->args, buf->args_used);
2478         buf->modes[buf->modes_used + buf->args_used] = '\0';
2479         irc_mode((buf->is_chanop ? buf->actor : NULL), buf->channel, buf->modes);
2480         buf->modes[0] = buf->is_add ? '+' : '-';
2481         buf->modes_used = 1;
2482         buf->args_used = 0;
2483     }
2484     buf->modes[buf->modes_used++] = ch;
2485     buf->args[buf->args_used++] = ' ';
2486     memcpy(buf->args + buf->args_used, arg, arg_len);
2487     buf->args_used += arg_len;
2488 }
2489
2490 void
2491 mod_chanmode_announce(struct userNode *who, struct chanNode *channel, struct mod_chanmode *change)
2492 {
2493     struct chanmode_buffer chbuf;
2494     unsigned int arg;
2495     struct modeNode *mn;
2496     char int_buff[32], mode = '\0';
2497
2498     assert(change->argc <= change->alloc_argc);
2499     memset(&chbuf, 0, sizeof(chbuf));
2500     chbuf.channel = channel;
2501     chbuf.actor = who;
2502     chbuf.chname_len = strlen(channel->name);
2503
2504     mn = GetUserMode(channel, who);
2505     if ((mn && (mn->modes & MODE_CHANOP)) || off_channel)
2506         chbuf.is_chanop = 1;
2507
2508     /* First remove modes */
2509     chbuf.is_add = 0;
2510     if (change->modes_clear) {
2511         if (mode != '-')
2512             chbuf.modes[chbuf.modes_used++] = mode = '-';
2513 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_clear & MODE_##BIT) chbuf.modes[chbuf.modes_used++] = CHAR
2514         DO_MODE_CHAR(PRIVATE, 'p');
2515         DO_MODE_CHAR(SECRET, 's');
2516         DO_MODE_CHAR(MODERATED, 'm');
2517         DO_MODE_CHAR(TOPICLIMIT, 't');
2518         DO_MODE_CHAR(INVITEONLY, 'i');
2519         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2520         DO_MODE_CHAR(LIMIT, 'l');
2521         DO_MODE_CHAR(DELAYJOINS, 'D');
2522         DO_MODE_CHAR(REGONLY, 'r');
2523         DO_MODE_CHAR(NOCOLORS, 'c');
2524         DO_MODE_CHAR(NOCTCPS, 'C');
2525         DO_MODE_CHAR(REGISTERED, 'z');
2526 #undef DO_MODE_CHAR
2527         if (change->modes_clear & channel->modes & MODE_KEY)
2528             mod_chanmode_append(&chbuf, 'k', channel->key);
2529         if (change->modes_clear & channel->modes & MODE_UPASS)
2530             mod_chanmode_append(&chbuf, 'U', channel->upass);
2531         if (change->modes_clear & channel->modes & MODE_APASS)
2532             mod_chanmode_append(&chbuf, 'A', channel->apass);
2533     }
2534     for (arg = 0; arg < change->argc; ++arg) {
2535         if (!(change->args[arg].mode & MODE_REMOVE))
2536             continue;
2537         if (mode != '-')
2538             chbuf.modes[chbuf.modes_used++] = mode = '-';
2539         switch (change->args[arg].mode & ~MODE_REMOVE) {
2540         case MODE_BAN:
2541             mod_chanmode_append(&chbuf, 'b', change->args[arg].u.hostmask);
2542             break;
2543         default:
2544             if (change->args[arg].mode & MODE_CHANOP)
2545                 mod_chanmode_append(&chbuf, 'o', change->args[arg].u.member->user->numeric);
2546             if (change->args[arg].mode & MODE_VOICE)
2547                 mod_chanmode_append(&chbuf, 'v', change->args[arg].u.member->user->numeric);
2548             break;
2549         }
2550     }
2551
2552     /* Then set them */
2553     chbuf.is_add = 1;
2554     if (change->modes_set) {
2555         if (mode != '+')
2556             chbuf.modes[chbuf.modes_used++] = mode = '+';
2557 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_set & MODE_##BIT) chbuf.modes[chbuf.modes_used++] = CHAR
2558         DO_MODE_CHAR(PRIVATE, 'p');
2559         DO_MODE_CHAR(SECRET, 's');
2560         DO_MODE_CHAR(MODERATED, 'm');
2561         DO_MODE_CHAR(TOPICLIMIT, 't');
2562         DO_MODE_CHAR(INVITEONLY, 'i');
2563         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2564         DO_MODE_CHAR(DELAYJOINS, 'D');
2565         DO_MODE_CHAR(REGONLY, 'r');
2566         DO_MODE_CHAR(NOCOLORS, 'c');
2567         DO_MODE_CHAR(NOCTCPS, 'C');
2568         DO_MODE_CHAR(REGISTERED, 'z');
2569 #undef DO_MODE_CHAR
2570         if(change->modes_set & MODE_KEY)
2571             mod_chanmode_append(&chbuf, 'k', change->new_key);
2572         if (change->modes_set & MODE_UPASS)
2573             mod_chanmode_append(&chbuf, 'U', change->new_upass);
2574         if (change->modes_set & MODE_APASS)
2575             mod_chanmode_append(&chbuf, 'A', change->new_apass);
2576         if(change->modes_set & MODE_LIMIT) {
2577             sprintf(int_buff, "%d", change->new_limit);
2578             mod_chanmode_append(&chbuf, 'l', int_buff);
2579         }
2580     }
2581     for (arg = 0; arg < change->argc; ++arg) {
2582         if (change->args[arg].mode & MODE_REMOVE)
2583             continue;
2584         if (mode != '+')
2585             chbuf.modes[chbuf.modes_used++] = mode = '+';
2586         switch (change->args[arg].mode) {
2587         case MODE_BAN:
2588             mod_chanmode_append(&chbuf, 'b', change->args[arg].u.hostmask);
2589             break;
2590         default:
2591             if (change->args[arg].mode & MODE_CHANOP)
2592                 mod_chanmode_append(&chbuf, 'o', change->args[arg].u.member->user->numeric);
2593             if (change->args[arg].mode & MODE_VOICE)
2594                 mod_chanmode_append(&chbuf, 'v', change->args[arg].u.member->user->numeric);
2595             break;
2596         }
2597     }
2598
2599     /* Flush the buffer and apply changes locally */
2600     if (chbuf.modes_used > 0) {
2601         memcpy(chbuf.modes + chbuf.modes_used, chbuf.args, chbuf.args_used);
2602         chbuf.modes[chbuf.modes_used + chbuf.args_used] = '\0';
2603         irc_mode((chbuf.is_chanop ? chbuf.actor : NULL), chbuf.channel, chbuf.modes);
2604     }
2605     mod_chanmode_apply(who, channel, change);
2606 }
2607
2608 char *
2609 mod_chanmode_format(struct mod_chanmode *change, char *outbuff)
2610 {
2611     unsigned int used = 0;
2612     assert(change->argc <= change->alloc_argc);
2613     if (change->modes_clear) {
2614         outbuff[used++] = '-';
2615 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_clear & MODE_##BIT) outbuff[used++] = CHAR
2616         DO_MODE_CHAR(PRIVATE, 'p');
2617         DO_MODE_CHAR(SECRET, 's');
2618         DO_MODE_CHAR(MODERATED, 'm');
2619         DO_MODE_CHAR(TOPICLIMIT, 't');
2620         DO_MODE_CHAR(INVITEONLY, 'i');
2621         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2622         DO_MODE_CHAR(LIMIT, 'l');
2623         DO_MODE_CHAR(KEY, 'k');
2624         DO_MODE_CHAR(UPASS, 'U');
2625         DO_MODE_CHAR(APASS, 'A');
2626         DO_MODE_CHAR(DELAYJOINS, 'D');
2627         DO_MODE_CHAR(REGONLY, 'r');
2628         DO_MODE_CHAR(NOCOLORS, 'c');
2629         DO_MODE_CHAR(NOCTCPS, 'C');
2630         DO_MODE_CHAR(REGISTERED, 'z');
2631 #undef DO_MODE_CHAR
2632     }
2633     if (change->modes_set) {
2634         outbuff[used++] = '+';
2635 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_set & MODE_##BIT) outbuff[used++] = CHAR
2636         DO_MODE_CHAR(PRIVATE, 'p');
2637         DO_MODE_CHAR(SECRET, 's');
2638         DO_MODE_CHAR(MODERATED, 'm');
2639         DO_MODE_CHAR(TOPICLIMIT, 't');
2640         DO_MODE_CHAR(INVITEONLY, 'i');
2641         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2642         DO_MODE_CHAR(DELAYJOINS, 'D');
2643         DO_MODE_CHAR(REGONLY, 'r');
2644         DO_MODE_CHAR(NOCOLORS, 'c');
2645         DO_MODE_CHAR(NOCTCPS, 'C');
2646         DO_MODE_CHAR(REGISTERED, 'z');
2647 #undef DO_MODE_CHAR
2648         switch (change->modes_set & (MODE_KEY|MODE_LIMIT|MODE_APASS|MODE_UPASS)) {
2649         /* Doing this implementation has been a pain in the arse, I hope I didn't forget a possible combination */
2650         case MODE_KEY|MODE_LIMIT|MODE_APASS|MODE_UPASS:
2651             used += sprintf(outbuff+used, "lkAU %d %s %s %s", change->new_limit, change->new_key, change->new_apass, change->new_upass);
2652             break;
2653
2654         case MODE_KEY|MODE_LIMIT|MODE_APASS:
2655             used += sprintf(outbuff+used, "lkA %d %s %s", change->new_limit, change->new_key, change->new_apass);
2656             break;
2657         case MODE_KEY|MODE_LIMIT|MODE_UPASS:
2658             used += sprintf(outbuff+used, "lkU %d %s %s", change->new_limit, change->new_key, change->new_upass);
2659             break;
2660         case MODE_KEY|MODE_APASS|MODE_UPASS:
2661             used += sprintf(outbuff+used, "kAU %s %s %s", change->new_key, change->new_apass, change->new_upass);
2662             break;
2663
2664         case MODE_KEY|MODE_APASS:
2665             used += sprintf(outbuff+used, "kA %s %s", change->new_key, change->new_apass);
2666             break;
2667         case MODE_KEY|MODE_UPASS:
2668             used += sprintf(outbuff+used, "kU %s %s", change->new_key, change->new_upass);
2669             break;
2670         case MODE_KEY|MODE_LIMIT:
2671             used += sprintf(outbuff+used, "lk %d %s", change->new_limit, change->new_key);
2672             break;
2673         case MODE_LIMIT|MODE_UPASS:
2674             used += sprintf(outbuff+used, "lU %d %s", change->new_limit, change->new_upass);
2675             break;
2676         case MODE_LIMIT|MODE_APASS:
2677             used += sprintf(outbuff+used, "lA %d %s", change->new_limit, change->new_apass);
2678             break;
2679         case MODE_APASS|MODE_UPASS:
2680             used += sprintf(outbuff+used, "AU %s %s", change->new_apass, change->new_upass);
2681             break;
2682
2683         case MODE_LIMIT|MODE_APASS|MODE_UPASS:
2684             used += sprintf(outbuff+used, "lAU %d %s %s", change->new_limit, change->new_apass, change->new_upass);
2685             break;
2686
2687         case MODE_APASS:
2688             used += sprintf(outbuff+used, "A %s", change->new_apass);
2689             break;
2690         case MODE_UPASS:
2691             used += sprintf(outbuff+used, "U %s", change->new_upass);
2692             break;
2693         case MODE_KEY:
2694             used += sprintf(outbuff+used, "k %s", change->new_key);
2695             break;
2696         case MODE_LIMIT:
2697             used += sprintf(outbuff+used, "l %d", change->new_limit);
2698             break;
2699         }
2700     }
2701     outbuff[used] = 0;
2702     return outbuff;
2703 }
2704
2705 static int
2706 clear_chanmode(struct chanNode *channel, const char *modes)
2707 {
2708     unsigned int cleared;
2709
2710     for (cleared = 0; *modes; modes++) {
2711         switch (*modes) {
2712         case 'o': cleared |= MODE_CHANOP; break;
2713         case 'v': cleared |= MODE_VOICE; break;
2714         case 'p': cleared |= MODE_PRIVATE; break;
2715         case 's': cleared |= MODE_SECRET; break;
2716         case 'm': cleared |= MODE_MODERATED; break;
2717         case 't': cleared |= MODE_TOPICLIMIT; break;
2718         case 'i': cleared |= MODE_INVITEONLY; break;
2719         case 'n': cleared |= MODE_NOPRIVMSGS; break;
2720         case 'k':
2721             cleared |= MODE_KEY;
2722             channel->key[0] = '\0';
2723             break;
2724         case 'A':
2725             cleared |= MODE_APASS;
2726             channel->apass[0] = '\0';
2727             break;
2728         case 'U':
2729             cleared |= MODE_UPASS;
2730             channel->upass[0] = '\0';
2731             break;
2732         case 'l':
2733             cleared |= MODE_LIMIT;
2734             channel->limit = 0;
2735             break;
2736         case 'b': cleared |= MODE_BAN; break;
2737         case 'D': cleared |= MODE_DELAYJOINS; break;
2738         case 'r': cleared |= MODE_REGONLY; break;
2739         case 'c': cleared |= MODE_NOCOLORS; break;
2740         case 'C': cleared |= MODE_NOCTCPS; break;
2741         case 'z': cleared |= MODE_REGISTERED; break;
2742         }
2743     }
2744
2745     if (!cleared)
2746         return 1;
2747
2748     /* Remove simple modes. */
2749     channel->modes &= ~cleared;
2750
2751     /* If removing bans, kill 'em all. */
2752     if ((cleared & MODE_BAN) && channel->banlist.used) {
2753         unsigned int i;
2754         for (i=0; i<channel->banlist.used; i++)
2755             free(channel->banlist.list[i]);
2756         channel->banlist.used = 0;
2757     }
2758
2759     /* Remove member modes. */
2760     if ((cleared & (MODE_CHANOP | MODE_VOICE)) && channel->members.used) {
2761         int mask = ~(cleared & (MODE_CHANOP | MODE_VOICE));
2762         unsigned int i;
2763
2764         for (i = 0; i < channel->members.used; i++)
2765             channel->members.list[i]->modes &= mask;
2766     }
2767
2768     return 1;
2769 }
2770
2771 void
2772 reg_privmsg_func(struct userNode *user, privmsg_func_t handler)
2773 {
2774     unsigned int numeric = user->num_local;
2775     if (numeric >= num_privmsg_funcs) {
2776         int newnum = numeric + 8, ii;
2777         privmsg_funcs = realloc(privmsg_funcs, newnum*sizeof(privmsg_func_t));
2778         for (ii = num_privmsg_funcs; ii < newnum; ++ii)
2779             privmsg_funcs[ii] = NULL;
2780         num_privmsg_funcs = newnum;
2781     }
2782     if (privmsg_funcs[numeric])
2783         log_module(MAIN_LOG, LOG_WARNING, "re-registering new privmsg handler for numeric %d", numeric);
2784     privmsg_funcs[numeric] = handler;
2785 }
2786
2787 void
2788 unreg_privmsg_func(struct userNode *user)
2789 {
2790     if (!IsLocal(user) || user->num_local >= num_privmsg_funcs)
2791         return; /* this really only works with users */
2792
2793     privmsg_funcs[user->num_local] = NULL;
2794 }
2795
2796
2797 void
2798 reg_notice_func(struct userNode *user, privmsg_func_t handler)
2799 {
2800     unsigned int numeric = user->num_local;
2801     if (numeric >= num_notice_funcs) {
2802         int newnum = numeric + 8, ii;
2803         notice_funcs = realloc(notice_funcs, newnum*sizeof(privmsg_func_t));
2804         for (ii = num_privmsg_funcs; ii < newnum; ++ii)
2805             privmsg_funcs[ii] = NULL;
2806         num_notice_funcs = newnum;
2807     }
2808     if (notice_funcs[numeric])
2809         log_module(MAIN_LOG, LOG_WARNING, "re-registering new notice handler for numeric %d", numeric);
2810     notice_funcs[numeric] = handler;
2811 }
2812
2813 void
2814 unreg_notice_func(struct userNode *user)
2815 {
2816     if (!IsLocal(user) || user->num_local >= num_privmsg_funcs)
2817         return; /* this really only works with users */
2818
2819     notice_funcs[user->num_local] = NULL;
2820 }
2821
2822 static void
2823 send_burst(void)
2824 {
2825     unsigned int i, hop, max_hop=1;
2826     dict_iterator_t it;
2827
2828     /* burst (juped) servers, closest first (except self, which is sent already) */
2829     for (i=0; i<ArrayLength(servers_num); i++)
2830         if (servers_num[i] && servers_num[i]->hops > max_hop)
2831             max_hop = servers_num[i]->hops;
2832     for (hop=1; hop<=max_hop; hop++) {
2833         for (i=0;i<ArrayLength(servers_num);i++) {
2834             if (servers_num[i]
2835                 && (servers_num[i]->hops == hop)
2836                 && (servers_num[i] != self->uplink))
2837                 irc_server(servers_num[i]);
2838         }
2839     }
2840
2841     /* burst local nicks */
2842     for (i=0; i<=self->num_mask; i++)
2843         if (self->users[i])
2844             irc_user(self->users[i]);
2845
2846     /* build dict of unbursted channel names (just copy existing channels) */
2847     unbursted_channels = dict_new();
2848     for (it = dict_first(channels); it; it = iter_next(it))
2849         dict_insert(unbursted_channels, iter_key(it), iter_data(it));
2850 }
2851
2852 /*
2853  * Oplevel parsing
2854  */
2855 static int
2856 parse_oplevel(char *str)
2857 {
2858     int oplevel = 0;
2859     while (isdigit(*str))
2860         oplevel = oplevel * 10 + *str++ - '0';
2861     return oplevel;
2862 }