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