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