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