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