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