Fix bugs; better handle oplevels from ircu2.10.12
[srvx.git] / src / proto-p10.c
1 /* proto-p10.c - IRC protocol output
2  * Copyright 2000-2004 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 char *his_servername;
293 static char *his_servercomment;
294
295 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);
296
297 extern int off_channel;
298
299 /* Numerics can be XYY, XYYY, or XXYYY; with X's identifying the
300  * server and Y's indentifying the client on that server. */
301 struct server*
302 GetServerN(const char *numeric)
303 {
304     switch (strlen(numeric)) {
305     default:
306         return servers_num[base64toint(numeric, 2)];
307     case 4:
308     case 3:
309     case 1:
310         return servers_num[base64toint(numeric, 1)];
311     case 0:
312         return NULL;
313     }
314 }
315
316 struct userNode*
317 GetUserN(const char *numeric) /* using numeric */
318 {
319     struct userNode *un;
320     struct server *s;
321     int n, slen, ulen;
322
323     switch (strlen(numeric)) {
324     default:
325         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s): numeric too long!", numeric);
326         return NULL;
327     case 5: slen = 2; ulen = 3; break;
328     case 4: slen = 1; ulen = 3; break;
329     case 3: slen = 1; ulen = 2; break;
330     case 2: case 1: case 0:
331         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s): numeric too short!", numeric);
332         return NULL;
333     }
334     if (!(s = servers_num[base64toint(numeric, slen)])) {
335         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s): couldn't find server (len=%d)!", numeric, slen);
336         return NULL;
337     }
338     n = base64toint(numeric+slen, ulen) & s->num_mask;
339     if (!(un = s->users[n])) {
340         log_module(MAIN_LOG, LOG_WARNING, "GetUserN(%s) couldn't find user!", numeric);
341     }
342     return un;
343 }
344
345 static void
346 privmsg_user_helper(struct userNode *un, void *data)
347 {
348     struct privmsg_desc *pd = data;
349     unsigned int num = un->num_local;
350     if (!pd->is_notice) {
351         if ((num < num_privmsg_funcs) && privmsg_funcs[num]) {
352             privmsg_funcs[num](pd->user, un, pd->text, pd->is_qualified);
353         }
354     } else {
355         if ((num < num_notice_funcs) && notice_funcs[num]) {
356             notice_funcs[num](pd->user, un, pd->text, pd->is_qualified);
357         }
358     }
359 }
360
361 void
362 irc_server(struct server *srv)
363 {
364     char extranum[COMBO_NUMERIC_LEN+1];
365
366     inttobase64(extranum, srv->num_mask, (srv->numeric[1] || (srv->num_mask >= 64*64)) ? 3 : 2);
367     if (srv == self) {
368         /* The +s, ignored by Run's ircu, means "service" to Undernet's ircu */
369         putsock(P10_SERVER " %s %d %li %li J10 %s%s +s :%s",
370                 srv->name, srv->hops+1, srv->boot, srv->link, srv->numeric, extranum, srv->description);
371     } else {
372         putsock("%s " P10_SERVER " %s %d %li %li %c10 %s%s +s :%s",
373                 self->numeric, srv->name, srv->hops+1, srv->boot, srv->link, (srv->self_burst ? 'J' : 'P'), srv->numeric, extranum, srv->description);
374     }
375 }
376
377 void
378 irc_user(struct userNode *user)
379 {
380     char b64ip[7];
381     if (!user)
382         return;
383     inttobase64(b64ip, ntohl(user->ip.s_addr), 6);
384     if (user->modes) {
385         int modelen;
386         char modes[32];
387
388         modelen = 0;
389         if (IsOper(user))
390             modes[modelen++] = 'o';
391         if (IsInvisible(user))
392             modes[modelen++] = 'i';
393         if (IsWallOp(user))
394             modes[modelen++] = 'w';
395         if (IsService(user))
396             modes[modelen++] = 'k';
397         if (IsServNotice(user))
398             modes[modelen++] = 's';
399         if (IsDeaf(user))
400             modes[modelen++] = 'd';
401         if (IsGlobal(user))
402             modes[modelen++] = 'g';
403         if (IsHelperIrcu(user))
404             modes[modelen++] = 'h';
405         if (IsHiddenHost(user))
406             modes[modelen++] = 'x';
407         modes[modelen] = 0;
408
409         /* we don't need to put the + in modes because it's in the format string. */
410         putsock("%s " P10_NICK " %s %d %li %s %s +%s %s %s :%s",
411                 user->uplink->numeric, user->nick, user->uplink->hops+1, user->timestamp, user->ident, user->hostname, modes, b64ip, user->numeric, user->info);
412     } else {
413         putsock("%s " P10_NICK " %s %d %li %s %s %s %s :%s",
414                 user->uplink->numeric, user->nick, user->uplink->hops+1, user->timestamp, user->ident, user->hostname, b64ip, user->numeric, user->info);
415     }
416 }
417
418 void
419 irc_account(struct userNode *user, const char *stamp)
420 {
421     putsock("%s " P10_ACCOUNT " %s %s", self->numeric, user->numeric, stamp);
422 }
423
424 void
425 irc_fakehost(struct userNode *user, const char *host)
426 {
427     putsock("%s " P10_FAKEHOST " %s %s", self->numeric, user->numeric, host);
428 }
429
430 void
431 irc_regnick(UNUSED_ARG(struct userNode *user))
432 {
433     /* no operation here */
434 }
435
436 void
437 irc_nick(struct userNode *user, UNUSED_ARG(const char *old_nick))
438 {
439     putsock("%s " P10_NICK " %s "FMT_TIME_T, user->numeric, user->nick, now);
440 }
441
442 void
443 irc_fetchtopic(struct userNode *from, const char *to)
444 {
445     if (!from || !to)
446         return;
447     putsock("%s " P10_TOPIC " %s", from->numeric, to);
448 }
449
450 void
451 irc_squit(struct server *srv, const char *message, const char *service_message)
452 {
453     if (!service_message)
454         service_message = message;
455
456     /* Are we leaving the network? */
457     if (srv == self && cManager.uplink->state == CONNECTED) {
458         unsigned int i;
459
460         /* Quit all clients linked to me. */
461         for (i = 0; i <= self->num_mask; i++) {
462             if (!self->users[i])
463                 continue;
464             irc_quit(self->users[i], service_message);
465         }
466     }
467
468     putsock("%s " P10_SQUIT " %s %d :%s", self->numeric, srv->name, 0, message);
469
470     if (srv == self) {
471         /* Force a reconnect to the currently selected server. */
472         cManager.uplink->tries = 0;
473         log_module(MAIN_LOG, LOG_INFO, "Squitting from uplink: %s", message);
474         close_socket();
475     }
476 }
477
478 void
479 irc_wallchops(struct userNode *from, const char *to, const char *message)
480 {
481     putsock("%s " P10_WALLCHOPS " %s :%s", from->numeric, to, message);
482 }
483
484 void
485 irc_notice(struct userNode *from, const char *to, const char *message)
486 {
487     putsock("%s " P10_NOTICE " %s :%s", from->numeric, to, message);
488 }
489
490 void
491 irc_notice_user(struct userNode *from, struct userNode *to, const char *message)
492 {
493     putsock("%s " P10_NOTICE " %s :%s", from->numeric, to->numeric, message);
494 }
495
496 void
497 irc_privmsg(struct userNode *from, const char *to, const char *message)
498 {
499     putsock("%s " P10_PRIVMSG " %s :%s", from->numeric, to, message);
500 }
501
502 void
503 irc_eob(void)
504 {
505     putsock("%s " P10_EOB, self->numeric);
506 }
507
508 void
509 irc_eob_ack(void)
510 {
511     putsock("%s " P10_EOB_ACK, self->numeric);
512 }
513
514 void
515 irc_ping(const char *payload)
516 {
517     putsock("%s " P10_PING " :%s", self->numeric, payload);
518 }
519
520 void
521 irc_pong(const char *who, const char *data)
522 {
523     putsock("%s " P10_PONG " %s :%s", self->numeric, who, data);
524 }
525
526 void
527 irc_pass(const char *passwd)
528 {
529     putsock(P10_PASS " :%s", passwd);
530 }
531
532 void
533 irc_introduce(const char *passwd)
534 {
535     void timed_send_ping(void *data);
536
537     self->self_burst = self->burst = 1;
538     irc_pass(passwd);
539     irc_server(self);
540     burst_length = 0;
541     timeq_add(now + ping_freq, timed_send_ping, 0);
542 }
543
544 void
545 irc_gline(struct server *srv, struct gline *gline)
546 {
547     putsock("%s " P10_GLINE " %s +%s %ld :%s",
548             self->numeric, (srv ? srv->numeric : "*"), gline->target, gline->expires-now, gline->reason);
549 }
550
551 void
552 irc_settime(const char *srv_name_mask, time_t new_time)
553 {
554     ioset_set_time(new_time);
555     if (!strcmp(srv_name_mask, "*"))
556         srv_name_mask = "";
557     putsock("%s " P10_SETTIME " " FMT_TIME_T " %s", self->numeric, new_time, srv_name_mask);
558 }
559
560 void
561 irc_ungline(const char *mask)
562 {
563     putsock("%s " P10_GLINE " * -%s", self->numeric, mask);
564 }
565
566 static void
567 irc_burst(struct chanNode *chan)
568 {
569     char burst_line[512];
570     int pos, base_len, len;
571     struct modeNode *mn;
572     struct banNode *bn;
573     long last_mode=-1;
574     unsigned int n;
575
576     base_len = sprintf(burst_line, "%s " P10_BURST " %s " FMT_TIME_T " ",
577                        self->numeric, chan->name, chan->timestamp);
578     len = irc_make_chanmode(chan, burst_line+base_len);
579     pos = base_len + len;
580     if (len)
581         burst_line[pos++] = ' ';
582
583     /* dump the users */
584     for (n=0; n<chan->members.used; n++) {
585         mn = chan->members.list[n];
586         if (pos > 500) {
587             burst_line[pos-1] = 0; /* -1 to back up over the space or comma */
588             putsock("%s", burst_line);
589             pos = base_len;
590             last_mode = -1;
591         }
592         memcpy(burst_line+pos, mn->user->numeric, strlen(mn->user->numeric));
593         pos += strlen(mn->user->numeric);
594         if (mn->modes && (mn->modes != last_mode)) {
595             last_mode = mn->modes;
596             burst_line[pos++] = ':';
597             if (last_mode & MODE_CHANOP)
598                 burst_line[pos++] = 'o';
599             if (last_mode & MODE_VOICE)
600                 burst_line[pos++] = 'v';
601         }
602         if ((n+1)<chan->members.used)
603             burst_line[pos++] = ',';
604     }
605     if (chan->banlist.used) {
606         /* dump the bans */
607         if (pos+2+strlen(chan->banlist.list[0]->ban) > 505) {
608             burst_line[pos-1] = 0;
609             putsock("%s", burst_line);
610             pos = base_len;
611         } else {
612             burst_line[pos++] = ' ';
613         }
614
615         burst_line[pos++] = ':';
616         burst_line[pos++] = '%';
617         base_len = pos;
618         for (n=0; n<chan->banlist.used; n++) {
619             bn = chan->banlist.list[n];
620             len = strlen(bn->ban);
621             if (pos+len+1 > 510) {
622                 burst_line[pos-1] = 0; /* -1 to back up over the space or comma */
623                 putsock("%s", burst_line);
624                 pos = base_len;
625             }
626             memcpy(burst_line+pos, bn->ban, len);
627             pos += len;
628             burst_line[pos++] = ' ';
629         }
630     }
631     /* print the last line */
632     burst_line[pos] = 0;
633     putsock("%s", burst_line);
634 }
635
636 void
637 irc_quit(struct userNode *user, const char *message)
638 {
639     putsock("%s " P10_QUIT " :%s", user->numeric, message);
640 }
641
642 void
643 irc_error(const char *to, const char *message)
644 {
645     if (to) {
646         putsock("%s " P10_ERROR " :%s", to, message);
647     } else {
648         putsock(":%s " P10_ERROR " :%s", self->name, message);
649     }
650 }
651
652 void
653 irc_kill(struct userNode *from, struct userNode *target, const char *message)
654 {
655     if (from) {
656         putsock("%s " P10_KILL " %s :%s!%s (%s)",
657                 from->numeric, target->numeric, self->name, from->nick, message);
658     } else {
659         putsock("%s " P10_KILL " %s :%s (%s)",
660                 self->numeric, target->numeric, self->name, message);
661     }
662 }
663
664 void
665 irc_mode(struct userNode *from, struct chanNode *target, const char *modes)
666 {
667     putsock("%s " P10_MODE " %s %s "FMT_TIME_T,
668             (from ? from->numeric : self->numeric),
669             target->name, modes, target->timestamp);
670 }
671
672 void
673 irc_invite(struct userNode *from, struct userNode *who, struct chanNode *to)
674 {
675     putsock("%s " P10_INVITE " %s %s", from->numeric, who->nick, to->name);
676 }
677
678 void
679 irc_join(struct userNode *who, struct chanNode *what)
680 {
681     if (what->members.used == 1) {
682         putsock("%s " P10_CREATE " %s %lu",
683                 who->numeric, what->name, what->timestamp);
684     } else {
685         putsock("%s " P10_JOIN " %s %lu", who->numeric, what->name, what->timestamp);
686     }
687 }
688
689 void
690 irc_kick(struct userNode *who, struct userNode *target, struct chanNode *channel, const char *msg)
691 {
692     const char *numeric;
693     struct modeNode *mn = GetUserMode(channel, who);
694     numeric = ((mn && (mn->modes & MODE_CHANOP)) || off_channel) ? who->numeric : self->numeric;
695     putsock("%s " P10_KICK " %s %s :%s",
696             numeric, channel->name, target->numeric, msg);
697 }
698
699 void
700 irc_stats(struct userNode *from, struct server *target, char type)
701 {
702     putsock("%s " P10_STATS " %c :%s", from->numeric, type, target->numeric);
703 }
704
705 void
706 irc_svsnick(struct userNode *from, struct userNode *target, const char *newnick)
707 {
708     putsock("%s " P10_SVSNICK " %s %s "FMT_TIME_T, from->uplink->numeric, target->numeric, newnick, now);
709 }
710
711 void
712 irc_part(struct userNode *who, struct chanNode *what, const char *reason)
713 {
714     if (reason) {
715         putsock("%s " P10_PART " %s :%s", who->numeric, what->name, reason);
716     } else {
717         putsock("%s " P10_PART " %s", who->numeric, what->name);
718     }
719 }
720
721 void
722 irc_topic(struct userNode *who, struct chanNode *what, const char *topic)
723 {
724     putsock("%s " P10_TOPIC " %s :%s", who->numeric, what->name, topic);
725 }
726
727 void
728 irc_raw(const char *what)
729 {
730     putsock("%s", what);
731 }
732
733 void
734 irc_numeric(struct userNode *user, unsigned int num, const char *format, ...)
735 {
736     va_list arg_list;
737     char buffer[MAXLEN];
738     va_start(arg_list, format);
739     vsnprintf(buffer, MAXLEN-2, format, arg_list);
740     buffer[MAXLEN-1] = 0;
741     putsock(":%s %03d %s %s", self->name, num, user->nick, buffer);
742 }
743
744 static void send_burst(void);
745
746 static void
747 change_nicklen(int new_nicklen)
748 {
749     unsigned int nn;
750     char new_nick[NICKLEN+1];
751     struct userNode *user;
752
753     nicklen = new_nicklen;
754     /* fix up any users we have here */
755     for (nn=0; nn<=self->num_mask; nn++) {
756         if (!(user = self->users[nn]))
757             continue;
758         safestrncpy(new_nick, user->nick, sizeof(new_nick));
759         new_nick[nicklen] = 0;
760         NickChange(user, new_nick, 1);
761     }
762 }
763
764 static CMD_FUNC(cmd_whois)
765 {
766     struct userNode *from;
767     struct userNode *who;
768
769     if (argc < 3)
770         return 0;
771     if (!(from = GetUserH(origin))) {
772         log_module(MAIN_LOG, LOG_ERROR, "Could not find WHOIS origin user %s", origin);
773         return 0;
774     }
775     if(!(who = GetUserH(argv[2]))) {
776         irc_numeric(from, ERR_NOSUCHNICK, "%s@%s :No such nick", argv[2], self->name);
777         return 1;
778     }
779     if (IsHiddenHost(who) && !IsOper(from)) {
780         /* Just stay quiet. */
781         return 1;
782     }
783     irc_numeric(from, RPL_WHOISUSER, "%s %s %s * :%s", who->nick, who->ident, who->hostname, who->info);
784     if (his_servername && his_servercomment)
785         irc_numeric(from, RPL_WHOISSERVER, "%s %s :%s", who->nick, his_servername, his_servercomment);
786     else
787         irc_numeric(from, RPL_WHOISSERVER, "%s %s :%s", who->nick, who->uplink->name, who->uplink->description);
788     if (IsOper(who))
789         irc_numeric(from, RPL_WHOISOPERATOR, "%s :is a megalomaniacal power hungry tyrant", who->nick);
790     irc_numeric(from, RPL_ENDOFWHOIS, "%s :End of /WHOIS list", who->nick);
791     return 1;
792 }
793
794 static CMD_FUNC(cmd_server)
795 {
796     struct server *srv;
797     const char *str;
798
799     if (argc < 8)
800         return 0;
801     if (self->uplink) {
802         /* another server introduced us */
803         srv = AddServer(GetServerH(origin), argv[1], atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), argv[6], argv[argc-1]);
804         if (!srv)
805             return 0;
806         srv->self_burst = argv[5][0] == 'J';
807         srv->burst = 1;
808     } else {
809         /* this must be our uplink */
810         srv = self->uplink = AddServer(self, argv[1], atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), argv[6], argv[argc-1]);
811         if (!srv)
812             return 0;
813         srv->self_burst = argv[5][0] == 'J';
814         srv->burst = 1;
815         if ((argv[7][0] == '+') && !force_n2k) {
816             log_module(MAIN_LOG, LOG_WARNING, "Got Undernet-style SERVER message but \"force_n2k\" not on.");
817         }
818         send_burst();
819     }
820
821     /* Fix up our timestamps if necessary. */
822     if (srv->boot <= PREHISTORY) {
823         /* Server from the mists of time.. */
824         if (srv->hops == 1) {
825             log_module(MAIN_LOG, LOG_ERROR, "Server %s claims to have booted at time "FMT_TIME_T".  This is absurd.", srv->name, srv->boot);
826         }
827     } else if ((str = conf_get_data("server/reliable_clock", RECDB_QSTRING))
828                && enabled_string(str)) {
829         /* If we have a reliable clock, we just keep our current time. */
830     } else {
831         if (srv->boot <= self->boot) {
832             /* The other server is older than us.  Accept their timestamp.
833              * Alternately, we are same age, but we accept their time
834              * since we are linking to them. */
835             self->boot = srv->boot;
836             ioset_set_time(srv->link);
837         }
838     }
839     if (srv == self->uplink) {
840         extern time_t burst_begin;
841         burst_begin = now;
842     }
843     return 1;
844 }
845
846 static CMD_FUNC(cmd_eob)
847 {
848     struct server *sender;
849     dict_iterator_t it;
850     unsigned int ii;
851
852     if (!(sender = GetServerH(origin)))
853         return 0;
854     if (sender == self->uplink) {
855         cManager.uplink->state = CONNECTED;
856         for (it = dict_first(unbursted_channels); it; it = iter_next(it))
857             irc_burst(iter_data(it));
858         dict_delete(unbursted_channels);
859         unbursted_channels = NULL;
860         irc_eob();
861         irc_eob_ack();
862     }
863     sender->self_burst = 0;
864     recalc_bursts(sender);
865     for (ii=0; ii<slf_used; ii++)
866         slf_list[ii](sender);
867     return 1;
868 }
869
870 static CMD_FUNC(cmd_eob_ack)
871 {
872     extern time_t burst_begin;
873
874     if (GetServerH(origin) == self->uplink) {
875         burst_length = now - burst_begin;
876         self->self_burst = self->burst = 0;
877     }
878     cManager.uplink->state = CONNECTED;
879     return 1;
880 }
881
882 static CMD_FUNC(cmd_ping)
883 {
884     struct server *srv;
885     struct userNode *un;
886
887     if(argc > 3)
888         irc_pong(argv[2], argv[1]);
889     else if ((srv = GetServerH(origin)))
890         irc_pong(self->name, srv->numeric);
891     else if ((un = GetUserH(origin)))
892         irc_pong(self->name, un->numeric);
893     else
894         irc_pong(self->name, origin);
895
896     timeq_del(0, timed_send_ping, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
897     timeq_del(0, timed_ping_timeout, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
898     timeq_add(now + ping_freq, timed_send_ping, 0);
899     received_ping();
900     return 1;
901 }
902
903 static CMD_FUNC(cmd_error_nick)
904 {
905     /* Go back to original IRC length .. and try to reconnect :/ */
906     change_nicklen(9);
907     irc_squit(self, "Got erroneous nickname, truncating nicks.", NULL);
908     return 1;
909 }
910
911 struct create_desc {
912     struct userNode *user;
913     time_t when;
914 };
915
916 static void
917 join_helper(struct chanNode *chan, void *data)
918 {
919     struct create_desc *cd = data;
920     AddChannelUser(cd->user, chan);
921 }
922
923 static void
924 create_helper(char *name, void *data)
925 {
926     struct create_desc *cd = data;
927
928     if (!strcmp(name, "0")) {
929         while (cd->user->channels.used > 0)
930             DelChannelUser(cd->user, cd->user->channels.list[0]->channel, 0, 0);
931         return;
932     }
933
934     AddChannelUser(cd->user, AddChannel(name, cd->when, NULL, NULL));
935 }
936
937 static CMD_FUNC(cmd_create)
938 {
939     struct create_desc cd;
940     struct userNode *user;
941
942     if ((argc < 3) || !(user = GetUserH(origin)))
943         return 0;
944     cd.user = user;
945     cd.when = atoi(argv[2]);
946     parse_foreach(argv[1], join_helper, create_helper, NULL, NULL, &cd);
947     return 1;
948 }
949
950 static CMD_FUNC(cmd_join)
951 {
952     struct create_desc cd;
953
954     if (!(cd.user = GetUserH(origin)))
955         return 0;
956     if (argc < 2)
957         return 0;
958     else if (argc < 3)
959         cd.when = now;
960     else
961         cd.when = atoi(argv[2]);
962     parse_foreach(argv[1], join_helper, create_helper, NULL, NULL, &cd);
963     return 1;
964 }
965
966 static CMD_FUNC(cmd_pong)
967 {
968     if (argc < 3)
969         return 0;
970     if (!strcmp(argv[2], self->name)) {
971         timeq_del(0, timed_send_ping, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
972         timeq_del(0, timed_ping_timeout, 0, TIMEQ_IGNORE_WHEN|TIMEQ_IGNORE_DATA);
973         timeq_add(now + ping_freq, timed_send_ping, 0);
974         received_ping();
975     }
976     return 1;
977 }
978
979 static CMD_FUNC(cmd_nick)
980 {
981     struct userNode *user;
982     if ((user = GetUserH(origin))) {
983         /* nick change (since the source is a user numeric) */
984         if (argc < 2)
985             return 0;
986         NickChange(user, argv[1], 1);
987     } else {
988         struct server *serv;
989         char modes[MAXLEN];
990         /* new nick */
991         if (argc < 9)
992             return 0;
993         serv = GetServerH(origin);
994         if (argc > 9)
995             unsplit_string(argv+6, argc-9, modes);
996         else
997             strcpy(modes, "+");
998         AddUser(serv, argv[1], argv[4], argv[5], modes, argv[argc-2], argv[argc-1], atoi(argv[3]), argv[argc-3]);
999     }
1000     return 1;
1001 }
1002
1003 static CMD_FUNC(cmd_account)
1004 {
1005     struct userNode *user;
1006
1007     if ((argc < 3) || !origin || !GetServerH(origin))
1008         return 0; /* Origin must be server. */
1009     user = GetUserN(argv[1]);
1010     if (!user)
1011         return 1; /* A QUIT probably passed the ACCOUNT. */
1012     call_account_func(user, argv[2]);
1013     return 1;
1014 }
1015
1016 static CMD_FUNC(cmd_fakehost)
1017 {
1018     struct userNode *user;
1019
1020     if ((argc < 3) || !origin || !GetServerH(origin))
1021         return 0;
1022     if (!(user = GetUserN(argv[1])))
1023         return 1;
1024     assign_fakehost(user, argv[2], 0);
1025     return 1;
1026 }
1027
1028 static CMD_FUNC(cmd_burst)
1029 {
1030     extern int rel_age;
1031     char modes[MAXLEN], *members = "", *banlist = NULL;
1032     unsigned int next = 3, res = 1;
1033     struct chanNode *cNode;
1034     struct userNode *un;
1035     struct modeNode *mNode;
1036     long mode;
1037     char *user, *end, sep;
1038     time_t in_timestamp;
1039
1040     if (argc < 3)
1041         return 0;
1042     modes[0] = 0;
1043     while (next < argc) {
1044         switch (argv[next][0]) {
1045         case '+': {
1046             const char *pos;
1047             int n_modes;
1048             for (pos=argv[next], n_modes = 1; *pos; pos++)
1049                 if ((*pos == 'k') || (*pos == 'l'))
1050                     n_modes++;
1051             unsplit_string(argv+next, n_modes, modes);
1052             next += n_modes;
1053             break;
1054         }
1055         case '%': banlist = argv[next++]+1; break;
1056         default: members = argv[next++]; break;
1057         }
1058     }
1059
1060     in_timestamp = atoi(argv[2]);
1061     if ((cNode = dict_find(unbursted_channels, argv[1], NULL))) {
1062         cNode->timestamp = in_timestamp;
1063         dict_remove(unbursted_channels, cNode->name);
1064         irc_burst(cNode);
1065     }
1066     cNode = AddChannel(argv[1], in_timestamp, modes, banlist);
1067
1068     /* Burst channel members in now. */
1069     for (user = members, sep = *members, mode = 0; sep; user = end) {
1070         for (end = user + 3; isalnum(*end) || *end == '[' || *end == ']'; end++) ;
1071         sep = *end++; end[-1] = 0;
1072         if (sep == ':') {
1073             mode = 0;
1074             while ((sep = *end++)) {
1075                 if (sep == 'o')
1076                     mode |= MODE_CHANOP;
1077                 else if (sep == 'v')
1078                     mode |= MODE_VOICE;
1079                 else if (isdigit(sep)) {
1080                     mode |= MODE_CHANOP;
1081                     while (isdigit(*end)) end++;
1082                 } else
1083                     break;
1084             }
1085             if (rel_age < 0)
1086                 mode = 0;
1087         }
1088         if (!(un = GetUserN(user))) {
1089             res = 0;
1090             continue;
1091         }
1092         if ((mNode = AddChannelUser(un, cNode)))
1093             mNode->modes = mode;
1094     }
1095
1096     return res;
1097 }
1098
1099 static CMD_FUNC(cmd_mode)
1100 {
1101     struct chanNode *cn;
1102     struct userNode *un;
1103
1104     if (argc < 3)
1105         return 0;
1106     if (!IsChannelName(argv[1])) {
1107         un = GetUserH(argv[1]);
1108         if (!un) {
1109             log_module(MAIN_LOG, LOG_ERROR, "Unable to find user %s whose mode is changing.", argv[1]);
1110             return 0;
1111         }
1112         mod_usermode(un, argv[2]);
1113         return 1;
1114     }
1115
1116     if (!(cn = GetChannel(argv[1]))) {
1117         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose mode is changing.", argv[1]);
1118         return 0;
1119     }
1120     if ((un = GetUserH(origin))) {
1121         struct modeNode *mn;
1122         /* Update idle time for person setting the mode */
1123         if ((mn = GetUserMode(cn, un)))
1124             mn->idle_since = now;
1125     } else {
1126         /* If it came from a server, reset timestamp to re-sync. */
1127         cn->timestamp = atoi(argv[argc-1]);
1128     }
1129
1130     return mod_chanmode(un, cn, argv+2, argc-2, MCP_ALLOW_OVB|MCP_FROM_SERVER|(un ? MC_NOTIFY : 0));
1131 }
1132
1133 static CMD_FUNC(cmd_opmode)
1134 {
1135     struct chanNode *cn;
1136     struct userNode *un;
1137
1138     if (argc < 3)
1139         return 0;
1140
1141     if (!(cn = GetChannel(argv[1]))) {
1142         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose mode is changing.", argv[1]);
1143         return 0;
1144     }
1145     if (!(un = GetUserH(origin))) {
1146         log_module(MAIN_LOG, LOG_ERROR, "Unable to find user %s requesting OPMODE.", origin);
1147         return 0;
1148     }
1149     if (!IsOper(un)) {
1150         log_module(MAIN_LOG, LOG_ERROR, "Non-privileged user %s using OPMODE.", un->nick);
1151         return 0;
1152     }
1153
1154     return mod_chanmode(un, cn, argv+2, argc-2, MCP_ALLOW_OVB|MCP_FROM_SERVER); /* do NOT announce opmode locally */
1155 }
1156
1157 static int clear_chanmode(struct chanNode *channel, const char *modes);
1158
1159 static CMD_FUNC(cmd_clearmode)
1160 {
1161     struct chanNode *cn;
1162     struct userNode *un;
1163
1164     if (argc < 3)
1165         return 0;
1166
1167     if (!(cn = GetChannel(argv[1]))) {
1168         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose mode is changing.", argv[1]);
1169         return 0;
1170     }
1171     if (!(un = GetUserH(origin))) {
1172         log_module(MAIN_LOG, LOG_ERROR, "Unable to find user %s requesting CLEARMODE.", origin);
1173         return 0;
1174     }
1175     if (!IsOper(un)) {
1176         log_module(MAIN_LOG, LOG_ERROR, "Non-privileged user %s using CLEARMODE.", un->nick);
1177         return 0;
1178     }
1179
1180     return clear_chanmode(cn, argv[2]);
1181 }
1182
1183 static CMD_FUNC(cmd_topic)
1184 {
1185     struct chanNode *cn;
1186     time_t chan_ts, topic_ts;
1187
1188     if (argc < 3)
1189         return 0;
1190     if (!(cn = GetChannel(argv[1]))) {
1191         log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s whose topic is being set", argv[1]);
1192         return 0;
1193     }
1194     if (argc >= 5) {
1195         /* Looks like an Asuka style topic burst. */
1196         chan_ts = atoi(argv[2]);
1197         topic_ts = atoi(argv[3]);
1198     } else {
1199         chan_ts = cn->timestamp;
1200         topic_ts = now;
1201     }
1202     SetChannelTopic(cn, GetUserH(origin), argv[argc-1], 0);
1203     cn->topic_time = topic_ts;
1204     return 1;
1205 }
1206
1207 static CMD_FUNC(cmd_num_topic)
1208 {
1209     struct chanNode *cn;
1210
1211     if (!argv[0])
1212         return 0; /* huh? */
1213     if (argv[2]) {
1214         cn = GetChannel(argv[2]);
1215         if (!cn) {
1216             log_module(MAIN_LOG, LOG_ERROR, "Unable to find channel %s in topic reply", argv[2]);
1217             return 0;
1218         }
1219     } else
1220         return 0;
1221
1222     switch (atoi(argv[0])) {
1223     case 331:
1224         cn->topic_time = 0;
1225         break;  /* no topic */
1226     case 332:
1227         if (argc < 4)
1228             return 0;
1229         safestrncpy(cn->topic, unsplit_string(argv+3, argc-3, NULL), sizeof(cn->topic));
1230         break;
1231     case 333:
1232         if (argc < 5)
1233             return 0;
1234         safestrncpy(cn->topic_nick, argv[3], sizeof(cn->topic_nick));
1235         cn->topic_time = atoi(argv[4]);
1236         break;
1237     default:
1238         return 0; /* should never happen */
1239     }
1240     return 1;
1241 }
1242
1243 static CMD_FUNC(cmd_num_gline)
1244 {
1245     if (argc < 6)
1246         return 0;
1247     gline_add(origin, argv[3], atoi(argv[4])-now, argv[5], now, 0);
1248     return 1;
1249 }
1250
1251 static CMD_FUNC(cmd_quit)
1252 {
1253     struct userNode *user;
1254     if (argc < 2)
1255         return 0;
1256     /* Sometimes we get a KILL then a QUIT or the like, so we don't want to
1257      * call DelUser unless we have the user in our grasp. */
1258     if ((user = GetUserH(origin)))
1259         DelUser(user, NULL, false, argv[1]);
1260     return 1;
1261 }
1262
1263 static CMD_FUNC(cmd_kill)
1264 {
1265     struct userNode *user;
1266     if (argc < 2)
1267         return 0;
1268     user = GetUserN(argv[1]);
1269     if (!user) {
1270         /* If we get a KILL for a non-existent user, it could be a
1271          * Ghost response to a KILL we sent out earlier.  So we only
1272          * whine if the target is local.
1273          */
1274         if (!strncmp(argv[1], self->numeric, strlen(self->numeric)))
1275             log_module(MAIN_LOG, LOG_ERROR, "Unable to find kill victim %s", argv[1]);
1276         return 0;
1277     }
1278
1279     if (IsLocal(user) && IsService(user)) {
1280         /* TODO: rate limit this so silly things don't happen. */
1281         ReintroduceUser(user);
1282         return 1;
1283     }
1284
1285     DelUser(user, NULL, false, argv[2]);
1286     return 1;
1287 }
1288
1289 static CMD_FUNC(cmd_part)
1290 {
1291     struct userNode *user;
1292
1293     if (argc < 2)
1294         return 0;
1295     user = GetUserH(origin);
1296     if (!user)
1297         return 0;
1298     parse_foreach(argv[1], part_helper, NULL, NULL, NULL, user);
1299     return 1;
1300 }
1301
1302 static CMD_FUNC(cmd_kick)
1303 {
1304     if (argc < 3)
1305         return 0;
1306     ChannelUserKicked(GetUserH(origin), GetUserN(argv[2]), GetChannel(argv[1]));
1307     return 1;
1308 }
1309
1310 static CMD_FUNC(cmd_squit)
1311 {
1312     struct server *server;
1313
1314     if (argc < 4)
1315         return 0;
1316     if (!(server = GetServerH(argv[1])))
1317         return 0;
1318
1319     if (server == self->uplink) {
1320         /* Force a reconnect to the currently selected server. */
1321         cManager.uplink->tries = 0;
1322         log_module(MAIN_LOG, LOG_INFO, "Squitting from uplink: %s", argv[3]);
1323         close_socket();
1324         return 1;
1325     }
1326
1327     DelServer(server, 0, argv[3]);
1328     return 1;
1329 }
1330
1331 static CMD_FUNC(cmd_privmsg)
1332 {
1333     struct privmsg_desc pd;
1334     if (argc != 3)
1335         return 0;
1336     pd.user = GetUserH(origin);
1337     if (!pd.user || (IsGagged(pd.user) && !IsOper(pd.user)))
1338         return 1;
1339     pd.is_notice = 0;
1340     pd.text = argv[2];
1341     parse_foreach(argv[1], privmsg_chan_helper, NULL, privmsg_user_helper, privmsg_invalid, &pd);
1342     return 1;
1343 }
1344
1345 static CMD_FUNC(cmd_notice)
1346 {
1347     struct privmsg_desc pd;
1348     if (argc != 3)
1349         return 0;
1350     pd.user = GetUserH(origin);
1351     if (!pd.user || (IsGagged(pd.user) && !IsOper(pd.user)))
1352         return 1;
1353     pd.is_notice = 1;
1354     pd.text = argv[2];
1355     parse_foreach(argv[1], privmsg_chan_helper, NULL, privmsg_user_helper, privmsg_invalid, &pd);
1356     return 1;
1357 }
1358
1359 static CMD_FUNC(cmd_away)
1360 {
1361     struct userNode *uNode;
1362
1363     uNode = GetUserH(origin);
1364     if (!uNode)
1365         return 1;
1366     if (argc < 2)
1367         uNode->modes &= ~FLAGS_AWAY;
1368     else
1369         uNode->modes |= FLAGS_AWAY;
1370     return 1;
1371 }
1372
1373 static CMD_FUNC(cmd_gline)
1374 {
1375     if (argc < 3)
1376         return 0;
1377     if (argv[2][0] == '+') {
1378         if (argc < 5)
1379             return 0;
1380         gline_add(origin, argv[2]+1, strtoul(argv[3], NULL, 0), argv[argc-1], now, 0);
1381         return 1;
1382     } else if (argv[2][0] == '-') {
1383         gline_remove(argv[2]+1, 0);
1384         return 1;
1385     } else
1386         return 0;
1387 }
1388
1389 static CMD_FUNC(cmd_svsnick)
1390 {
1391     struct userNode *target, *dest;
1392     if ((argc < 4)
1393         || !(target = GetUserN(argv[1]))
1394         || !IsLocal(target)
1395         || (dest = GetUserH(argv[2])))
1396         return 0;
1397     NickChange(target, argv[2], 0);
1398     return 1;
1399 }
1400
1401 static oper_func_t *of_list;
1402 static unsigned int of_size = 0, of_used = 0;
1403
1404 void
1405 free_user(struct userNode *user)
1406 {
1407     free(user->nick);
1408     free(user);
1409 }
1410
1411 static void
1412 parse_cleanup(void)
1413 {
1414     unsigned int nn;
1415     free(of_list);
1416     free(privmsg_funcs);
1417     free(notice_funcs);
1418     free(mcf_list);
1419     dict_delete(irc_func_dict);
1420     for (nn=0; nn<dead_users.used; nn++)
1421         free_user(dead_users.list[nn]);
1422     userList_clean(&dead_users);
1423 }
1424
1425 static void
1426 p10_conf_reload(void) {
1427     hidden_host_suffix = conf_get_data("server/hidden_host", RECDB_QSTRING);
1428 }
1429
1430 static void
1431 remove_unbursted_channel(struct chanNode *cNode) {
1432     if (unbursted_channels)
1433         dict_remove(unbursted_channels, cNode->name);
1434 }
1435
1436 void
1437 init_parse(void)
1438 {
1439     const char *str, *desc;
1440     int numnick, usermask, max_users;
1441     char numer[COMBO_NUMERIC_LEN+1];
1442
1443     /* read config items */
1444     str = conf_get_data("server/ping_freq", RECDB_QSTRING);
1445     ping_freq = str ? ParseInterval(str) : 120;
1446     str = conf_get_data("server/ping_timeout", RECDB_QSTRING);
1447     ping_timeout = str ? ParseInterval(str) : 30;
1448     str = conf_get_data("server/force_n2k", RECDB_QSTRING);
1449     force_n2k = str ? enabled_string(str) : 1;
1450     str = conf_get_data("server/numeric", RECDB_QSTRING);
1451     if (!str) {
1452         log_module(MAIN_LOG, LOG_ERROR, "No server/numeric entry in config file.");
1453         exit(1);
1454     }
1455     numnick = atoi(str);
1456     str = conf_get_data("server/max_users", RECDB_QSTRING);
1457     max_users = str ? atoi(str) : 4096;
1458     for (usermask = 4; usermask < max_users; usermask <<= 1) ;
1459     usermask--;
1460     if ((numnick < 64) && (usermask < 4096) && !force_n2k)
1461         inttobase64(numer, (numnick << 12) + (usermask & 0x00fff), 3);
1462     else
1463         inttobase64(numer, (numnick << 18) + (usermask & 0x3ffff), 5);
1464
1465     str = conf_get_data("server/his_servername", RECDB_QSTRING);
1466     his_servername = str ? strdup(str) : NULL;
1467     str = conf_get_data("server/his_servercomment", RECDB_QSTRING);
1468     his_servercomment = str ? strdup(str) : NULL;
1469
1470     str = conf_get_data("server/hostname", RECDB_QSTRING);
1471     desc = conf_get_data("server/description", RECDB_QSTRING);
1472     if (!str || !desc) {
1473         log_module(MAIN_LOG, LOG_ERROR, "No server/hostname entry in config file.");
1474         exit(1);
1475     }
1476     self = AddServer(NULL, str, 0, boot_time, now, numer, desc);
1477     conf_register_reload(p10_conf_reload);
1478
1479     irc_func_dict = dict_new();
1480     dict_insert(irc_func_dict, CMD_BURST, cmd_burst);
1481     dict_insert(irc_func_dict, TOK_BURST, cmd_burst);
1482     dict_insert(irc_func_dict, CMD_CREATE, cmd_create);
1483     dict_insert(irc_func_dict, TOK_CREATE, cmd_create);
1484     dict_insert(irc_func_dict, CMD_EOB, cmd_eob);
1485     dict_insert(irc_func_dict, TOK_EOB, cmd_eob);
1486     dict_insert(irc_func_dict, CMD_EOB_ACK, cmd_eob_ack);
1487     dict_insert(irc_func_dict, TOK_EOB_ACK, cmd_eob_ack);
1488     dict_insert(irc_func_dict, CMD_MODE, cmd_mode);
1489     dict_insert(irc_func_dict, TOK_MODE, cmd_mode);
1490     dict_insert(irc_func_dict, CMD_NICK, cmd_nick);
1491     dict_insert(irc_func_dict, TOK_NICK, cmd_nick);
1492     dict_insert(irc_func_dict, CMD_ACCOUNT, cmd_account);
1493     dict_insert(irc_func_dict, TOK_ACCOUNT, cmd_account);
1494     dict_insert(irc_func_dict, CMD_FAKEHOST, cmd_fakehost);
1495     dict_insert(irc_func_dict, TOK_FAKEHOST, cmd_fakehost);
1496     dict_insert(irc_func_dict, CMD_PASS, cmd_pass);
1497     dict_insert(irc_func_dict, TOK_PASS, cmd_pass);
1498     dict_insert(irc_func_dict, CMD_PING, cmd_ping);
1499     dict_insert(irc_func_dict, TOK_PING, cmd_ping);
1500     dict_insert(irc_func_dict, CMD_PRIVMSG, cmd_privmsg);
1501     dict_insert(irc_func_dict, TOK_PRIVMSG, cmd_privmsg);
1502     dict_insert(irc_func_dict, CMD_PONG, cmd_pong);
1503     dict_insert(irc_func_dict, TOK_PONG, cmd_pong);
1504     dict_insert(irc_func_dict, CMD_QUIT, cmd_quit);
1505     dict_insert(irc_func_dict, TOK_QUIT, cmd_quit);
1506     dict_insert(irc_func_dict, CMD_SERVER, cmd_server);
1507     dict_insert(irc_func_dict, TOK_SERVER, cmd_server);
1508     dict_insert(irc_func_dict, CMD_JOIN, cmd_join);
1509     dict_insert(irc_func_dict, TOK_JOIN, cmd_join);
1510     dict_insert(irc_func_dict, CMD_PART, cmd_part);
1511     dict_insert(irc_func_dict, TOK_PART, cmd_part);
1512     dict_insert(irc_func_dict, CMD_ERROR, cmd_error);
1513     dict_insert(irc_func_dict, TOK_ERROR, cmd_error);
1514     dict_insert(irc_func_dict, CMD_TOPIC, cmd_topic);
1515     dict_insert(irc_func_dict, TOK_TOPIC, cmd_topic);
1516     dict_insert(irc_func_dict, CMD_AWAY, cmd_away);
1517     dict_insert(irc_func_dict, TOK_AWAY, cmd_away);
1518     dict_insert(irc_func_dict, CMD_SILENCE, cmd_dummy);
1519     dict_insert(irc_func_dict, TOK_SILENCE, cmd_dummy);
1520     dict_insert(irc_func_dict, CMD_KICK, cmd_kick);
1521     dict_insert(irc_func_dict, TOK_KICK, cmd_kick);
1522     dict_insert(irc_func_dict, CMD_SQUIT, cmd_squit);
1523     dict_insert(irc_func_dict, TOK_SQUIT, cmd_squit);
1524     dict_insert(irc_func_dict, CMD_KILL, cmd_kill);
1525     dict_insert(irc_func_dict, TOK_KILL, cmd_kill);
1526     dict_insert(irc_func_dict, CMD_NOTICE, cmd_notice);
1527     dict_insert(irc_func_dict, TOK_NOTICE, cmd_notice);
1528     dict_insert(irc_func_dict, CMD_STATS, cmd_stats);
1529     dict_insert(irc_func_dict, TOK_STATS, cmd_stats);
1530     dict_insert(irc_func_dict, CMD_SVSNICK, cmd_svsnick);
1531     dict_insert(irc_func_dict, TOK_SVSNICK, cmd_svsnick);
1532     dict_insert(irc_func_dict, CMD_WHOIS, cmd_whois);
1533     dict_insert(irc_func_dict, TOK_WHOIS, cmd_whois);
1534     dict_insert(irc_func_dict, CMD_GLINE, cmd_gline);
1535     dict_insert(irc_func_dict, TOK_GLINE, cmd_gline);
1536     dict_insert(irc_func_dict, CMD_OPMODE, cmd_opmode);
1537     dict_insert(irc_func_dict, TOK_OPMODE, cmd_opmode);
1538     dict_insert(irc_func_dict, CMD_CLEARMODE, cmd_clearmode);
1539     dict_insert(irc_func_dict, TOK_CLEARMODE, cmd_clearmode);
1540     dict_insert(irc_func_dict, CMD_VERSION, cmd_version);
1541     dict_insert(irc_func_dict, TOK_VERSION, cmd_version);
1542     dict_insert(irc_func_dict, CMD_ADMIN, cmd_admin);
1543     dict_insert(irc_func_dict, TOK_ADMIN, cmd_admin);
1544
1545     /* In P10, DESTRUCT doesn't do anything except be broadcast to servers.
1546      * Apparently to obliterate channels from any servers that think they
1547      * exist?
1548      */
1549     dict_insert(irc_func_dict, CMD_DESTRUCT, cmd_dummy);
1550     dict_insert(irc_func_dict, TOK_DESTRUCT, cmd_dummy);
1551     /* Ignore invites */
1552     dict_insert(irc_func_dict, CMD_INVITE, cmd_dummy);
1553     dict_insert(irc_func_dict, TOK_INVITE, cmd_dummy);
1554     /* DESYNCH is just informational, so ignore it */
1555     dict_insert(irc_func_dict, CMD_DESYNCH, cmd_dummy);
1556     dict_insert(irc_func_dict, TOK_DESYNCH, cmd_dummy);
1557     /* Ignore channel operator notices. */
1558     dict_insert(irc_func_dict, CMD_WALLCHOPS, cmd_dummy);
1559     dict_insert(irc_func_dict, TOK_WALLCHOPS, cmd_dummy);
1560     dict_insert(irc_func_dict, CMD_WALLVOICES, cmd_dummy);
1561     dict_insert(irc_func_dict, TOK_WALLVOICES, cmd_dummy);
1562     /* Ignore opers being silly. */
1563     dict_insert(irc_func_dict, CMD_WALLOPS, cmd_dummy);
1564     dict_insert(irc_func_dict, TOK_WALLOPS, cmd_dummy);
1565     /* We have reliable clock!  Always!  Wraaa! */
1566     dict_insert(irc_func_dict, CMD_SETTIME, cmd_dummy);
1567     dict_insert(irc_func_dict, TOK_SETTIME, cmd_dummy);
1568     /* handle topics */
1569     dict_insert(irc_func_dict, "331", cmd_num_topic);
1570     dict_insert(irc_func_dict, "332", cmd_num_topic);
1571     dict_insert(irc_func_dict, "333", cmd_num_topic);
1572     dict_insert(irc_func_dict, "345", cmd_dummy); /* blah has been invited to blah */
1573     dict_insert(irc_func_dict, "432", cmd_error_nick); /* Erroneus [sic] nickname */
1574     /* ban list resetting */
1575     /* "stats g" responses */
1576     dict_insert(irc_func_dict, "247", cmd_num_gline);
1577     dict_insert(irc_func_dict, "219", cmd_dummy); /* "End of /STATS report" */
1578     /* other numeric responses we might get */
1579     dict_insert(irc_func_dict, "401", cmd_dummy); /* target left network */
1580     dict_insert(irc_func_dict, "403", cmd_dummy); /* no such channel */
1581     dict_insert(irc_func_dict, "404", cmd_dummy); /* cannot send to channel */
1582     dict_insert(irc_func_dict, "441", cmd_dummy); /* target isn't on that channel */
1583     dict_insert(irc_func_dict, "442", cmd_dummy); /* you aren't on that channel */
1584     dict_insert(irc_func_dict, "443", cmd_dummy); /* is already on channel (after invite?) */
1585     dict_insert(irc_func_dict, "461", cmd_dummy); /* Not enough parameters (after TOPIC w/ 0 args) */
1586     dict_insert(irc_func_dict, "467", cmd_dummy); /* Channel key already set */
1587
1588     num_privmsg_funcs = 16;
1589     privmsg_funcs = malloc(sizeof(privmsg_func_t)*num_privmsg_funcs);
1590     memset(privmsg_funcs, 0, sizeof(privmsg_func_t)*num_privmsg_funcs);
1591
1592     num_notice_funcs = 16;
1593     notice_funcs = malloc(sizeof(privmsg_func_t)*num_notice_funcs);
1594     memset(notice_funcs, 0, sizeof(privmsg_func_t)*num_notice_funcs);
1595
1596     userList_init(&dead_users);
1597     reg_del_channel_func(remove_unbursted_channel);
1598     reg_exit_func(parse_cleanup);
1599 }
1600
1601 int
1602 parse_line(char *line, int recursive)
1603 {
1604     char *argv[MAXNUMPARAMS], *origin;
1605     int argc, cmd, res=0;
1606     cmd_func_t *func;
1607
1608     argc = split_line(line, true, MAXNUMPARAMS, argv);
1609     cmd = self->uplink || !argv[0][1] || !argv[0][2];
1610     if (argc > cmd) {
1611         if (cmd) {
1612             if (argv[0][0] == ':') {
1613                 origin = argv[0]+1;
1614             } else if (!argv[0][1] || !argv[0][2]) {
1615                 struct server *sNode = GetServerN(argv[0]);
1616                 origin = sNode ? sNode->name : 0;
1617             } else {
1618                 struct userNode *uNode = GetUserN(argv[0]);
1619                 origin = uNode ? uNode->nick : 0;
1620             }
1621         } else
1622             origin = 0;
1623         if ((func = dict_find(irc_func_dict, argv[cmd], NULL)))
1624             res = func(origin, argc-cmd, argv+cmd);
1625     }
1626     if (!res) {
1627         log_module(MAIN_LOG, LOG_ERROR, "PARSE ERROR on line: %s", unsplit_string(argv, argc, NULL));
1628     } else if (!recursive) {
1629         unsigned int i;
1630         for (i=0; i<dead_users.used; i++)
1631             free_user(dead_users.list[i]);
1632         dead_users.used = 0;
1633     }
1634     return res;
1635 }
1636
1637 static void
1638 parse_foreach(char *target_list, foreach_chanfunc cf, foreach_nonchan nc, foreach_userfunc uf, foreach_nonuser nu, void *data)
1639 {
1640     char *j, old;
1641     do {
1642         j = target_list;
1643         while (*j != 0 && *j != ',')
1644             j++;
1645         old = *j;
1646         *j = 0;
1647         if (IsChannelName(target_list)
1648             || (target_list[0] == '0' && target_list[1] == '\0')) {
1649             struct chanNode *chan = GetChannel(target_list);
1650             if (chan) {
1651                 if (cf)
1652                     cf(chan, data);
1653             } else {
1654                 if (nc)
1655                     nc(target_list, data);
1656             }
1657         } else {
1658             struct userNode *user;
1659             struct privmsg_desc *pd = data;
1660
1661             pd->is_qualified = 0;
1662             if (*target_list == '@') {
1663                 user = NULL;
1664             } else if (strchr(target_list, '@')) {
1665                 struct server *server;
1666
1667                 pd->is_qualified = 1;
1668                 user = GetUserH(strtok(target_list, "@"));
1669                 server = GetServerH(strtok(NULL, "@"));
1670
1671                 if (user && (user->uplink != server)) {
1672                     /* Don't attempt to index into any arrays
1673                        using a user's numeric on another server. */
1674                     user = NULL;
1675                 }
1676             } else {
1677                 user = GetUserN(target_list);
1678             }
1679
1680             if (user) {
1681                 if (uf)
1682                     uf(user, data);
1683             } else {
1684                 if (nu)
1685                     nu(target_list, data);
1686             }
1687         }
1688         target_list = j+1;
1689     } while (old == ',');
1690 }
1691
1692 static int
1693 get_local_numeric(void)
1694 {
1695     static unsigned int next_numeric = 0;
1696     if (self->clients > self->num_mask)
1697         return -1;
1698     while (self->users[next_numeric])
1699         if (++next_numeric > self->num_mask)
1700             next_numeric = 0;
1701     return next_numeric;
1702 }
1703
1704 static void
1705 make_numeric(struct server *svr, int local_num, char *outbuf)
1706 {
1707     int slen, llen;
1708
1709     if (force_n2k || svr->numeric[1]) {
1710         slen = 2;
1711         llen = 3;
1712     } else {
1713         slen = 1;
1714         llen = (local_num < 64*64) ? 2 : 3;
1715     }
1716     strncpy(outbuf, svr->numeric, slen);
1717     inttobase64(outbuf+slen, local_num, llen);
1718     outbuf[slen+llen] = 0;
1719 }
1720
1721 struct server *
1722 AddServer(struct server *uplink, const char *name, int hops, time_t boot, time_t link, const char *numeric, const char *description)
1723 {
1724     struct server* sNode;
1725     int slen, mlen;
1726
1727     if ((sNode = GetServerN(numeric))) {
1728         /* This means we're trying to re-add an existant server.
1729          * To be safe, we should forget the previous incarnation.
1730          * (And all its linked servers.)
1731          *
1732          * It usually only happens in replays when the original
1733          * had a ping timeout and the replay didn't (because
1734          * replaying a ping timeout invariably gets things wrong).
1735          */
1736         DelServer(sNode, 0, NULL);
1737     }
1738
1739     switch (strlen(numeric)) {
1740     case 5: slen = 2; mlen = 3; break;
1741     case 4: slen = 1; mlen = 3; break;
1742     case 3: slen = 1; mlen = 2; break;
1743     default:
1744         log_module(MAIN_LOG, LOG_ERROR, "AddServer(\"%s\", \"%s\", ...): Numeric %s has invalid length.", uplink->name, name, numeric);
1745         return NULL;
1746     }
1747
1748     sNode = calloc(1, sizeof(*sNode));
1749     sNode->uplink = uplink;
1750     safestrncpy(sNode->name, name, sizeof(sNode->name));
1751     sNode->num_mask = base64toint(numeric+slen, mlen);
1752     sNode->hops = hops;
1753     sNode->boot = boot;
1754     sNode->link = link;
1755     strncpy(sNode->numeric, numeric, slen);
1756     safestrncpy(sNode->description, description, sizeof(sNode->description));
1757     sNode->users = calloc(sNode->num_mask+1, sizeof(*sNode->users));
1758     serverList_init(&sNode->children);
1759     if (sNode->uplink) {
1760         /* uplink may be NULL if we're just building ourself */
1761         serverList_append(&sNode->uplink->children, sNode);
1762     }
1763     servers_num[base64toint(numeric, slen)] = sNode;
1764     dict_insert(servers, sNode->name, sNode);
1765     return sNode;
1766 }
1767
1768 void DelServer(struct server* serv, int announce, const char *message)
1769 {
1770     unsigned int i;
1771
1772     /* If we receive an ERROR command before the SERVER
1773      * command a NULL server can be passed */
1774     if (!serv)
1775         return;
1776
1777     /* Hrm, what's the right way to SQUIT some other server?
1778      * (This code is only to handle killing juped servers.) */
1779     if (announce && (serv->uplink == self) && (serv != self->uplink))
1780         irc_squit(serv, message, NULL);
1781
1782     /* must recursively remove servers linked to this one first */
1783     for (i=serv->children.used;i>0;)
1784         if (serv->children.list[--i] != self)
1785             DelServer(serv->children.list[i], false, NULL);
1786
1787     /* clean up server's user hash tables */
1788     for (i=0;i<=serv->num_mask;i++)
1789         if (serv->users[i])
1790             DelUser(serv->users[i], NULL, false, "server delinked");
1791
1792     /* delete server */
1793     if (serv->uplink)
1794         serverList_remove(&serv->uplink->children, serv);
1795     if (serv == self->uplink)
1796         self->uplink = NULL;
1797     servers_num[base64toint(serv->numeric, strlen(serv->numeric))] = NULL;
1798     dict_remove(servers, serv->name);
1799     serverList_clean(&serv->children);
1800     free(serv->users);
1801     free(serv);
1802 }
1803
1804 struct userNode *
1805 AddService(const char *nick, const char *modes, const char *desc, const char *hostname)
1806 {
1807     char numeric[COMBO_NUMERIC_LEN+1];
1808     int local_num = get_local_numeric();
1809     time_t timestamp = now;
1810     struct userNode *old_user = GetUserH(nick);
1811
1812     if (old_user) {
1813         if (IsLocal(old_user))
1814             return old_user;
1815         timestamp = old_user->timestamp - 1;
1816     }
1817     if (local_num == -1) {
1818         log_module(MAIN_LOG, LOG_ERROR, "Unable to allocate numnick for service %s", nick);
1819         return 0;
1820     }
1821     if (!hostname)
1822         hostname = self->name;
1823     make_numeric(self, local_num, numeric);
1824     return AddUser(self, nick, nick, hostname, modes ? modes : "+oik", numeric, desc, now, "AAAAAA");
1825 }
1826
1827 struct userNode *
1828 AddClone(const char *nick, const char *ident, const char *hostname, const char *desc)
1829 {
1830     char numeric[COMBO_NUMERIC_LEN+1];
1831     int local_num = get_local_numeric();
1832     time_t timestamp = now;
1833     struct userNode *old_user = GetUserH(nick);
1834
1835     if (old_user) {
1836         if (IsLocal(old_user))
1837             return old_user;
1838         timestamp = old_user->timestamp - 1;
1839     }
1840     if (local_num == -1) {
1841         log_module(MAIN_LOG, LOG_ERROR, "Unable to allocate numnick for clone %s", nick);
1842         return 0;
1843     }
1844     make_numeric(self, local_num, numeric);
1845     return AddUser(self, nick, ident, hostname, "+i", numeric, desc, timestamp, "AAAAAA");
1846 }
1847
1848 int
1849 is_valid_nick(const char *nick) {
1850     /* IRC has some of The Most Fucked-Up ideas about character sets
1851      * in the world.. */
1852     if (!isalpha(*nick) && !strchr("{|}~[\\]^_`", *nick))
1853         return 0;
1854     for (++nick; *nick; ++nick)
1855         if (!isalnum(*nick) && !strchr("{|}~[\\]^-_`", *nick))
1856             return 0;
1857     if (strlen(nick) > nicklen)
1858         return 0;
1859     return 1;
1860 }
1861
1862 static struct userNode*
1863 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)
1864 {
1865     struct userNode *oldUser, *uNode;
1866     unsigned int n, ignore_user;
1867
1868     if ((strlen(numeric) < 3) || (strlen(numeric) > 5)) {
1869         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): numeric %s wrong length!", uplink, nick, numeric);
1870         return NULL;
1871     }
1872
1873     if (!uplink) {
1874         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): server for numeric %s doesn't exist!", uplink, nick, numeric);
1875         return NULL;
1876     }
1877
1878     if (uplink != GetServerN(numeric)) {
1879         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): server for numeric %s differs from nominal uplink %s.", uplink, nick, numeric, uplink->name);
1880         return NULL;
1881     }
1882
1883     if (!is_valid_nick(nick)) {
1884         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): invalid nickname detected.", uplink, nick);
1885         return NULL;
1886     }
1887
1888     ignore_user = 0;
1889     if ((oldUser = GetUserH(nick))) {
1890         if (IsLocal(oldUser) && (IsService(oldUser) || IsPersistent(oldUser))) {
1891             /* The service should collide the new user off. */
1892             oldUser->timestamp = timestamp - 1;
1893             irc_user(oldUser);
1894         }
1895         if (oldUser->timestamp > timestamp) {
1896             /* "Old" user is really newer; remove them */
1897             DelUser(oldUser, 0, 1, "Overruled by older nick");
1898         } else {
1899             /* User being added is too new; do not add them to
1900              * clients, but do add them to the server's list, since it
1901              * will send a KILL and QUIT soon. */
1902             ignore_user = 1;
1903         }
1904     }
1905
1906     /* create new usernode and set all values */
1907     uNode = calloc(1, sizeof(*uNode));
1908     uNode->nick = strdup(nick);
1909     safestrncpy(uNode->ident, ident, sizeof(uNode->ident));
1910     safestrncpy(uNode->info, userinfo, sizeof(uNode->info));
1911     safestrncpy(uNode->hostname, hostname, sizeof(uNode->hostname));
1912     safestrncpy(uNode->numeric, numeric, sizeof(uNode->numeric));
1913     uNode->ip.s_addr = htonl(base64toint(realip, 6));
1914     uNode->timestamp = timestamp;
1915     modeList_init(&uNode->channels);
1916     uNode->uplink = uplink;
1917     if (++uNode->uplink->clients > uNode->uplink->max_clients) {
1918         uNode->uplink->max_clients = uNode->uplink->clients;
1919     }
1920     uNode->num_local = base64toint(numeric+strlen(uNode->uplink->numeric), 3) & uNode->uplink->num_mask;
1921     uNode->uplink->users[uNode->num_local] = uNode;
1922     mod_usermode(uNode, modes);
1923     if (ignore_user)
1924         return uNode;
1925
1926     dict_insert(clients, uNode->nick, uNode);
1927     if (dict_size(clients) > max_clients) {
1928         max_clients = dict_size(clients);
1929         max_clients_time = now;
1930     }
1931     if (IsLocal(uNode))
1932         irc_user(uNode);
1933     for (n=0; n<nuf_used; n++)
1934         if (nuf_list[n](uNode))
1935             break;
1936     return uNode;
1937 }
1938
1939 /* removes user from it's server's hash table and nick hash table */
1940 void
1941 DelUser(struct userNode* user, struct userNode *killer, int announce, const char *why)
1942 {
1943     unsigned int n;
1944
1945     /* mark them as dead, in case anybody cares */
1946     user->dead = 1;
1947
1948     /* remove user from all channels */
1949     while (user->channels.used > 0)
1950         DelChannelUser(user, user->channels.list[user->channels.used-1]->channel, false, 0);
1951
1952     /* Call these in reverse order so ChanServ can update presence
1953        information before NickServ nukes the handle_info. */
1954     for (n = duf_used; n > 0; )
1955         duf_list[--n](user, killer, why);
1956
1957     user->uplink->clients--;
1958     user->uplink->users[user->num_local] = NULL;
1959     if (IsOper(user))
1960         userList_remove(&curr_opers, user);
1961     /* remove from global dictionary, but not if after a collide */
1962     if (user == dict_find(clients, user->nick, NULL))
1963         dict_remove(clients, user->nick);
1964
1965     if (IsInvisible(user))
1966         invis_clients--;
1967
1968     if (announce) {
1969         if (IsLocal(user))
1970             irc_quit(user, why);
1971         else
1972             irc_kill(killer, user, why);
1973     }
1974
1975     modeList_clean(&user->channels);
1976     /* We don't free them, in case we try to privmsg them or something
1977      * (like when a stupid oper kills themself).  We just put them onto
1978      * a list of clients that get freed after processing each line.
1979      */
1980     if (dead_users.size)
1981         userList_append(&dead_users, user);
1982     else
1983         free_user(user);
1984 }
1985
1986 void mod_usermode(struct userNode *user, const char *mode_change) {
1987     static void call_oper_funcs(struct userNode *user);
1988     int add = 1;
1989     const char *word = mode_change;
1990
1991     if (!user || !mode_change)
1992         return;
1993     while (*word != ' ' && *word) word++;
1994     while (*word == ' ') word++;
1995     while (1) {
1996 #define do_user_mode(FLAG) do { if (add) user->modes |= FLAG; else user->modes &= ~FLAG; } while (0)
1997         switch (*mode_change++) {
1998         case 0: case ' ': return;
1999         case '+': add = 1; break;
2000         case '-': add = 0; break;
2001         case 'o':
2002             do_user_mode(FLAGS_OPER);
2003             if (add) {
2004                 userList_append(&curr_opers, user);
2005                 call_oper_funcs(user);
2006             } else {
2007                 userList_remove(&curr_opers, user);
2008             }
2009             break;
2010         case 'O': do_user_mode(FLAGS_LOCOP); break;
2011         case 'i': do_user_mode(FLAGS_INVISIBLE);
2012             if (add)
2013                 invis_clients++;
2014             else
2015                 invis_clients--;
2016             break;
2017         case 'w': do_user_mode(FLAGS_WALLOP); break;
2018         case 's': do_user_mode(FLAGS_SERVNOTICE); break;
2019         case 'd': do_user_mode(FLAGS_DEAF); break;
2020         case 'k': do_user_mode(FLAGS_SERVICE); break;
2021         case 'g': do_user_mode(FLAGS_GLOBAL); break;
2022         case 'h': do_user_mode(FLAGS_HELPER); break;
2023         case 'x': do_user_mode(FLAGS_HIDDEN_HOST); break;
2024         case 'r':
2025             if (*word) {
2026                 char tag[MAXLEN];
2027                 unsigned int ii;
2028                 for (ii=0; (*word != ' ') && (*word != '\0'); )
2029                     tag[ii++] = *word++;
2030                 tag[ii] = 0;
2031                 while (*word == ' ')
2032                     word++;
2033                 call_account_func(user, tag);
2034             }
2035             break;
2036         case 'f':
2037             if (*word) {
2038                 char host[MAXLEN];
2039                 unsigned int ii;
2040                 for (ii=0; (*word != ' ') && (*word != '\0'); )
2041                     host[ii++] = *word++;
2042                 host[ii] = 0;
2043                 while (*word == ' ')
2044                     word++;
2045                 assign_fakehost(user, host, 0);
2046             }
2047             break;
2048         }
2049 #undef do_user_mode
2050     }
2051 }
2052
2053 struct mod_chanmode *
2054 mod_chanmode_parse(struct chanNode *channel, char **modes, unsigned int argc, unsigned int flags)
2055 {
2056     struct mod_chanmode *change;
2057     unsigned int ii, in_arg, ch_arg, add;
2058
2059     if (argc == 0)
2060         return NULL;
2061     if (!(change = mod_chanmode_alloc(argc - 1)))
2062         return NULL;
2063
2064     for (ii = ch_arg = 0, in_arg = add = 1;
2065          (modes[0][ii] != '\0') && (modes[0][ii] != ' ');
2066          ++ii) {
2067         switch (modes[0][ii]) {
2068         case '+':
2069             add = 1;
2070             break;
2071         case '-':
2072             add = 0;
2073             break;
2074 #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)
2075         case 'C': do_chan_mode(MODE_NOCTCPS); break;
2076         case 'D': do_chan_mode(MODE_DELAYJOINS); break;
2077         case 'c': do_chan_mode(MODE_NOCOLORS); break;
2078         case 'i': do_chan_mode(MODE_INVITEONLY); break;
2079         case 'm': do_chan_mode(MODE_MODERATED); break;
2080         case 'n': do_chan_mode(MODE_NOPRIVMSGS); break;
2081         case 'p': do_chan_mode(MODE_PRIVATE); break;
2082         case 'r': do_chan_mode(MODE_REGONLY); break;
2083         case 's': do_chan_mode(MODE_SECRET); break;
2084         case 't': do_chan_mode(MODE_TOPICLIMIT); break;
2085 #undef do_chan_mode
2086         case 'l':
2087             if (add) {
2088                 if (in_arg >= argc)
2089                     goto error;
2090                 change->modes_set |= MODE_LIMIT;
2091                 change->new_limit = atoi(modes[in_arg++]);
2092             } else {
2093                 change->modes_set &= ~MODE_LIMIT;
2094                 change->modes_clear |= MODE_LIMIT;
2095             }
2096             break;
2097         case 'k':
2098             if (add) {
2099                 if (in_arg >= argc)
2100                     goto error;
2101                 change->modes_set |= MODE_KEY;
2102                 safestrncpy(change->new_key, modes[in_arg++], sizeof(change->new_key));
2103             } else {
2104                 change->modes_clear |= MODE_KEY;
2105                 if (!(flags & MCP_KEY_FREE)) {
2106                     if (in_arg >= argc)
2107                         goto error;
2108                     in_arg++;
2109                 }
2110             }
2111             break;
2112         case 'b':
2113             if (!(flags & MCP_ALLOW_OVB))
2114                 goto error;
2115             if (in_arg >= argc)
2116                 goto error;
2117             change->args[ch_arg].mode = MODE_BAN;
2118             if (!add)
2119                 change->args[ch_arg].mode |= MODE_REMOVE;
2120             change->args[ch_arg++].u.hostmask = modes[in_arg++];
2121             break;
2122         case 'o': case 'v':
2123         {
2124             struct userNode *victim;
2125             if (!(flags & MCP_ALLOW_OVB))
2126                 goto error;
2127             if (in_arg >= argc)
2128                 goto error;
2129             change->args[ch_arg].mode = (modes[0][ii] == 'o') ? MODE_CHANOP : MODE_VOICE;
2130             if (!add)
2131                 change->args[ch_arg].mode |= MODE_REMOVE;
2132             if (flags & MCP_FROM_SERVER)
2133                 victim = GetUserN(modes[in_arg++]);
2134             else
2135                 victim = GetUserH(modes[in_arg++]);
2136             if (!victim)
2137                 continue;
2138             if ((change->args[ch_arg].u.member = GetUserMode(channel, victim)))
2139                 ch_arg++;
2140             break;
2141         }
2142         default:
2143             if (!(flags & MCP_FROM_SERVER))
2144                 goto error;
2145             break;
2146         }
2147     }
2148     change->argc = ch_arg; /* in case any turned out to be ignored */
2149     if (change->modes_set & MODE_SECRET) {
2150         change->modes_set &= ~(MODE_PRIVATE);
2151         change->modes_clear |= MODE_PRIVATE;
2152     } else if (change->modes_set & MODE_PRIVATE) {
2153         change->modes_set &= ~(MODE_SECRET);
2154         change->modes_clear |= MODE_SECRET;
2155     }
2156     return change;
2157   error:
2158     mod_chanmode_free(change);
2159     return NULL;
2160 }
2161
2162 struct chanmode_buffer {
2163     char modes[MAXLEN];
2164     char args[MAXLEN];
2165     struct chanNode *channel;
2166     struct userNode *actor;
2167     unsigned int modes_used;
2168     unsigned int args_used;
2169     size_t chname_len;
2170     unsigned int is_add : 1;
2171     unsigned int is_chanop : 1;
2172 };
2173
2174 static void
2175 mod_chanmode_append(struct chanmode_buffer *buf, char ch, const char *arg)
2176 {
2177     size_t arg_len = strlen(arg);
2178     if (buf->modes_used > (MAXMODEPARAMS) ||
2179         buf->modes_used + buf->args_used + buf->chname_len + arg_len > 450) {
2180         memcpy(buf->modes + buf->modes_used, buf->args, buf->args_used);
2181         buf->modes[buf->modes_used + buf->args_used] = '\0';
2182         irc_mode((buf->is_chanop ? buf->actor : NULL), buf->channel, buf->modes);
2183         buf->modes[0] = buf->is_add ? '+' : '-';
2184         buf->modes_used = 1;
2185         buf->args_used = 0;
2186     }
2187     buf->modes[buf->modes_used++] = ch;
2188     buf->args[buf->args_used++] = ' ';
2189     memcpy(buf->args + buf->args_used, arg, arg_len);
2190     buf->args_used += arg_len;
2191 }
2192
2193 void
2194 mod_chanmode_announce(struct userNode *who, struct chanNode *channel, struct mod_chanmode *change)
2195 {
2196     struct chanmode_buffer chbuf;
2197     unsigned int arg;
2198     struct modeNode *mn;
2199     char int_buff[32], mode = '\0';
2200
2201     assert(change->argc <= change->alloc_argc);
2202     memset(&chbuf, 0, sizeof(chbuf));
2203     chbuf.channel = channel;
2204     chbuf.actor = who;
2205     chbuf.chname_len = strlen(channel->name);
2206
2207     mn = GetUserMode(channel, who);
2208     if ((mn && (mn->modes & MODE_CHANOP)) || off_channel)
2209         chbuf.is_chanop = 1;
2210
2211     /* First remove modes */
2212     chbuf.is_add = 0;
2213     if (change->modes_clear) {
2214         if (mode != '-')
2215             chbuf.modes[chbuf.modes_used++] = mode = '-';
2216 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_clear & MODE_##BIT) chbuf.modes[chbuf.modes_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(DELAYJOINS, 'D');
2225         DO_MODE_CHAR(REGONLY, 'r');
2226         DO_MODE_CHAR(NOCOLORS, 'c');
2227         DO_MODE_CHAR(NOCTCPS, 'C');
2228 #undef DO_MODE_CHAR
2229         if (change->modes_clear & channel->modes & MODE_KEY)
2230             mod_chanmode_append(&chbuf, 'k', channel->key);
2231     }
2232     for (arg = 0; arg < change->argc; ++arg) {
2233         if (!(change->args[arg].mode & MODE_REMOVE))
2234             continue;
2235         if (mode != '-')
2236             chbuf.modes[chbuf.modes_used++] = mode = '-';
2237         switch (change->args[arg].mode & ~MODE_REMOVE) {
2238         case MODE_BAN:
2239             mod_chanmode_append(&chbuf, 'b', change->args[arg].u.hostmask);
2240             break;
2241         default:
2242             if (change->args[arg].mode & MODE_CHANOP)
2243                 mod_chanmode_append(&chbuf, 'o', change->args[arg].u.member->user->numeric);
2244             if (change->args[arg].mode & MODE_VOICE)
2245                 mod_chanmode_append(&chbuf, 'v', change->args[arg].u.member->user->numeric);
2246             break;
2247         }
2248     }
2249
2250     /* Then set them */
2251     chbuf.is_add = 1;
2252     if (change->modes_set) {
2253         if (mode != '+')
2254             chbuf.modes[chbuf.modes_used++] = mode = '+';
2255 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_set & MODE_##BIT) chbuf.modes[chbuf.modes_used++] = CHAR
2256         DO_MODE_CHAR(PRIVATE, 'p');
2257         DO_MODE_CHAR(SECRET, 's');
2258         DO_MODE_CHAR(MODERATED, 'm');
2259         DO_MODE_CHAR(TOPICLIMIT, 't');
2260         DO_MODE_CHAR(INVITEONLY, 'i');
2261         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2262         DO_MODE_CHAR(DELAYJOINS, 'D');
2263         DO_MODE_CHAR(REGONLY, 'r');
2264         DO_MODE_CHAR(NOCOLORS, 'c');
2265         DO_MODE_CHAR(NOCTCPS, 'C');
2266 #undef DO_MODE_CHAR
2267         if(change->modes_set & MODE_KEY)
2268             mod_chanmode_append(&chbuf, 'k', change->new_key);
2269         if(change->modes_set & MODE_LIMIT) {
2270             sprintf(int_buff, "%d", change->new_limit);
2271             mod_chanmode_append(&chbuf, 'l', int_buff);
2272         }
2273     }
2274     for (arg = 0; arg < change->argc; ++arg) {
2275         if (change->args[arg].mode & MODE_REMOVE)
2276             continue;
2277         if (mode != '+')
2278             chbuf.modes[chbuf.modes_used++] = mode = '+';
2279         switch (change->args[arg].mode) {
2280         case MODE_BAN:
2281             mod_chanmode_append(&chbuf, 'b', change->args[arg].u.hostmask);
2282             break;
2283         default:
2284             if (change->args[arg].mode & MODE_CHANOP)
2285                 mod_chanmode_append(&chbuf, 'o', change->args[arg].u.member->user->numeric);
2286             if (change->args[arg].mode & MODE_VOICE)
2287                 mod_chanmode_append(&chbuf, 'v', change->args[arg].u.member->user->numeric);
2288             break;
2289         }
2290     }
2291
2292     /* Flush the buffer and apply changes locally */
2293     if (chbuf.modes_used > 0) {
2294         memcpy(chbuf.modes + chbuf.modes_used, chbuf.args, chbuf.args_used);
2295         chbuf.modes[chbuf.modes_used + chbuf.args_used] = '\0';
2296         irc_mode((chbuf.is_chanop ? chbuf.actor : NULL), chbuf.channel, chbuf.modes);
2297     }
2298     mod_chanmode_apply(who, channel, change);
2299 }
2300
2301 char *
2302 mod_chanmode_format(struct mod_chanmode *change, char *outbuff)
2303 {
2304     unsigned int used = 0;
2305     assert(change->argc <= change->alloc_argc);
2306     if (change->modes_clear) {
2307         outbuff[used++] = '-';
2308 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_clear & MODE_##BIT) outbuff[used++] = CHAR
2309         DO_MODE_CHAR(PRIVATE, 'p');
2310         DO_MODE_CHAR(SECRET, 's');
2311         DO_MODE_CHAR(MODERATED, 'm');
2312         DO_MODE_CHAR(TOPICLIMIT, 't');
2313         DO_MODE_CHAR(INVITEONLY, 'i');
2314         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2315         DO_MODE_CHAR(LIMIT, 'l');
2316         DO_MODE_CHAR(KEY, 'k');
2317         DO_MODE_CHAR(DELAYJOINS, 'D');
2318         DO_MODE_CHAR(REGONLY, 'r');
2319         DO_MODE_CHAR(NOCOLORS, 'c');
2320         DO_MODE_CHAR(NOCTCPS, 'C');
2321 #undef DO_MODE_CHAR
2322     }
2323     if (change->modes_set) {
2324         outbuff[used++] = '+';
2325 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_set & MODE_##BIT) outbuff[used++] = CHAR
2326         DO_MODE_CHAR(PRIVATE, 'p');
2327         DO_MODE_CHAR(SECRET, 's');
2328         DO_MODE_CHAR(MODERATED, 'm');
2329         DO_MODE_CHAR(TOPICLIMIT, 't');
2330         DO_MODE_CHAR(INVITEONLY, 'i');
2331         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2332         DO_MODE_CHAR(DELAYJOINS, 'D');
2333         DO_MODE_CHAR(REGONLY, 'r');
2334         DO_MODE_CHAR(NOCOLORS, 'c');
2335         DO_MODE_CHAR(NOCTCPS, 'C');
2336 #undef DO_MODE_CHAR
2337         switch (change->modes_set & (MODE_KEY|MODE_LIMIT)) {
2338         case MODE_KEY|MODE_LIMIT:
2339             used += sprintf(outbuff+used, "lk %d %s", change->new_limit, change->new_key);
2340             break;
2341         case MODE_KEY:
2342             used += sprintf(outbuff+used, "k %s", change->new_key);
2343             break;
2344         case MODE_LIMIT:
2345             used += sprintf(outbuff+used, "l %d", change->new_limit);
2346             break;
2347         }
2348     }
2349     outbuff[used] = 0;
2350     return outbuff;
2351 }
2352
2353 static int
2354 clear_chanmode(struct chanNode *channel, const char *modes)
2355 {
2356     unsigned int remove;
2357
2358     for (remove = 0; *modes; modes++) {
2359         switch (*modes) {
2360         case 'o': remove |= MODE_CHANOP; break;
2361         case 'v': remove |= MODE_VOICE; break;
2362         case 'p': remove |= MODE_PRIVATE; break;
2363         case 's': remove |= MODE_SECRET; break;
2364         case 'm': remove |= MODE_MODERATED; break;
2365         case 't': remove |= MODE_TOPICLIMIT; break;
2366         case 'i': remove |= MODE_INVITEONLY; break;
2367         case 'n': remove |= MODE_NOPRIVMSGS; break;
2368         case 'k':
2369             remove |= MODE_KEY;
2370             channel->key[0] = '\0';
2371             break;
2372         case 'l':
2373             remove |= MODE_LIMIT;
2374             channel->limit = 0;
2375             break;
2376         case 'b': remove |= MODE_BAN; break;
2377         case 'D': remove |= MODE_DELAYJOINS; break;
2378         case 'r': remove |= MODE_REGONLY; break;
2379         case 'c': remove |= MODE_NOCOLORS; break;
2380         case 'C': remove |= MODE_NOCTCPS; break;
2381         }
2382     }
2383
2384     if (!remove)
2385         return 1;
2386
2387     /* Remove simple modes. */
2388     channel->modes &= ~remove;
2389
2390     /* If removing bans, kill 'em all. */
2391     if ((remove & MODE_BAN) && channel->banlist.used) {
2392         unsigned int i;
2393         for (i=0; i<channel->banlist.used; i++)
2394             free(channel->banlist.list[i]);
2395         channel->banlist.used = 0;
2396     }
2397
2398     /* Remove member modes. */
2399     if ((remove & (MODE_CHANOP | MODE_VOICE)) && channel->members.used) {
2400         int mask = ~(remove & (MODE_CHANOP | MODE_VOICE));
2401         unsigned int i;
2402
2403         for (i = 0; i < channel->members.used; i++)
2404             channel->members.list[i]->modes &= mask;
2405     }
2406
2407     return 1;
2408 }
2409
2410 void
2411 reg_privmsg_func(struct userNode *user, privmsg_func_t handler)
2412 {
2413     unsigned int numeric = user->num_local;
2414     if (numeric >= num_privmsg_funcs) {
2415         int newnum = numeric + 8;
2416         privmsg_funcs = realloc(privmsg_funcs, newnum*sizeof(privmsg_func_t));
2417         memset(privmsg_funcs+num_privmsg_funcs, 0, (newnum-num_privmsg_funcs)*sizeof(privmsg_func_t));
2418         num_privmsg_funcs = newnum;
2419     }
2420     if (privmsg_funcs[numeric])
2421         log_module(MAIN_LOG, LOG_WARNING, "re-registering new privmsg handler for numeric %d", numeric);
2422     privmsg_funcs[numeric] = handler;
2423 }
2424
2425 void
2426 unreg_privmsg_func(struct userNode *user, privmsg_func_t handler)
2427 {
2428     unsigned int x;
2429
2430     if (!user || handler)
2431       return; /* this really only works with users */
2432
2433     memset(privmsg_funcs+user->num_local, 0, sizeof(privmsg_func_t));
2434
2435     for (x = user->num_local+1; x < num_privmsg_funcs; x++) 
2436        memmove(privmsg_funcs+x-1, privmsg_funcs+x, sizeof(privmsg_func_t));
2437     
2438     privmsg_funcs = realloc(privmsg_funcs, num_privmsg_funcs*sizeof(privmsg_func_t)); 
2439     num_privmsg_funcs--;
2440 }
2441
2442
2443 void
2444 reg_notice_func(struct userNode *user, privmsg_func_t handler)
2445 {
2446     unsigned int numeric = user->num_local;
2447     if (numeric >= num_notice_funcs) {
2448         int newnum = numeric + 8;
2449         notice_funcs = realloc(notice_funcs, newnum*sizeof(privmsg_func_t));
2450         memset(notice_funcs+num_notice_funcs, 0, (newnum-num_notice_funcs)*sizeof(privmsg_func_t));
2451         num_notice_funcs = newnum;
2452     }
2453     if (notice_funcs[numeric])
2454         log_module(MAIN_LOG, LOG_WARNING, "re-registering new notice handler for numeric %d", numeric);
2455     notice_funcs[numeric] = handler;
2456 }
2457
2458 void
2459 unreg_notice_func(struct userNode *user, privmsg_func_t handler)
2460 {
2461     unsigned int x;
2462
2463     if (!user || handler)
2464           return; /* this really only works with users */
2465
2466     memset(notice_funcs+user->num_local, 0, sizeof(privmsg_func_t));
2467
2468     for (x = user->num_local+1; x < num_notice_funcs; x++)
2469        memmove(notice_funcs+x-1, notice_funcs+x, sizeof(privmsg_func_t));
2470
2471     memset(notice_funcs+user->num_local, 0, sizeof(privmsg_func_t));
2472     notice_funcs = realloc(notice_funcs, num_notice_funcs*sizeof(privmsg_func_t));
2473     num_notice_funcs--;
2474 }
2475
2476 void
2477 reg_oper_func(oper_func_t handler)
2478 {
2479     if (of_used == of_size) {
2480         if (of_size) {
2481             of_size <<= 1;
2482             of_list = realloc(of_list, of_size*sizeof(oper_func_t));
2483         } else {
2484             of_size = 8;
2485             of_list = malloc(of_size*sizeof(oper_func_t));
2486         }
2487     }
2488     of_list[of_used++] = handler;
2489 }
2490
2491 static void
2492 call_oper_funcs(struct userNode *user)
2493 {
2494     unsigned int n;
2495     if (IsLocal(user))
2496         return;
2497     for (n=0; n<of_used; n++)
2498         of_list[n](user);
2499 }
2500
2501 static void
2502 send_burst(void)
2503 {
2504     unsigned int i, hop, max_hop=1;
2505     dict_iterator_t it;
2506
2507     /* burst (juped) servers, closest first (except self, which is sent already) */
2508     for (i=0; i<ArrayLength(servers_num); i++)
2509         if (servers_num[i] && servers_num[i]->hops > max_hop)
2510             max_hop = servers_num[i]->hops;
2511     for (hop=1; hop<=max_hop; hop++) {
2512         for (i=0;i<ArrayLength(servers_num);i++) {
2513             if (servers_num[i]
2514                 && (servers_num[i]->hops == hop)
2515                 && (servers_num[i] != self->uplink))
2516                 irc_server(servers_num[i]);
2517         }
2518     }
2519
2520     /* burst local nicks */
2521     for (i=0; i<=self->num_mask; i++)
2522         if (self->users[i])
2523             irc_user(self->users[i]);
2524
2525     /* build dict of unbursted channel names (just copy existing channels) */
2526     unbursted_channels = dict_new();
2527     for (it = dict_first(channels); it; it = iter_next(it))
2528         dict_insert(unbursted_channels, iter_key(it), iter_data(it));
2529 }