Add "dummy client" support.
[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     free(notice_funcs);
1538     free(mcf_list);
1539     dict_delete(irc_func_dict);
1540     for (nn=0; nn<dead_users.used; nn++)
1541         free_user(dead_users.list[nn]);
1542     userList_clean(&dead_users);
1543 }
1544
1545 static void
1546 p10_conf_reload(void) {
1547     hidden_host_suffix = conf_get_data("server/hidden_host", RECDB_QSTRING);
1548 }
1549
1550 static void
1551 remove_unbursted_channel(struct chanNode *cNode) {
1552     if (unbursted_channels)
1553         dict_remove(unbursted_channels, cNode->name);
1554 }
1555
1556 void
1557 init_parse(void)
1558 {
1559     const char *str, *desc;
1560     int numnick, usermask, max_users;
1561     char numer[COMBO_NUMERIC_LEN+1];
1562
1563     /* read config items */
1564     str = conf_get_data("server/ping_freq", RECDB_QSTRING);
1565     ping_freq = str ? ParseInterval(str) : 120;
1566     str = conf_get_data("server/ping_timeout", RECDB_QSTRING);
1567     ping_timeout = str ? ParseInterval(str) : 30;
1568     str = conf_get_data("server/force_n2k", RECDB_QSTRING);
1569     force_n2k = str ? enabled_string(str) : 1;
1570     str = conf_get_data("server/numeric", RECDB_QSTRING);
1571     if (!str) {
1572         log_module(MAIN_LOG, LOG_ERROR, "No server/numeric entry in config file.");
1573         exit(1);
1574     }
1575     numnick = atoi(str);
1576     str = conf_get_data("server/max_users", RECDB_QSTRING);
1577     max_users = str ? atoi(str) : 4096;
1578     for (usermask = 4; usermask < max_users; usermask <<= 1) ;
1579     usermask--;
1580     if ((numnick < 64) && (usermask < 4096) && !force_n2k)
1581         inttobase64(numer, (numnick << 12) + (usermask & 0x00fff), 3);
1582     else
1583         inttobase64(numer, (numnick << 18) + (usermask & 0x3ffff), 5);
1584
1585     str = conf_get_data("server/his_servername", RECDB_QSTRING);
1586     his_servername = str ? strdup(str) : NULL;
1587     str = conf_get_data("server/his_servercomment", RECDB_QSTRING);
1588     his_servercomment = str ? strdup(str) : NULL;
1589
1590     str = conf_get_data("server/hostname", RECDB_QSTRING);
1591     desc = conf_get_data("server/description", RECDB_QSTRING);
1592     if (!str || !desc) {
1593         log_module(MAIN_LOG, LOG_ERROR, "No server/hostname entry in config file.");
1594         exit(1);
1595     }
1596     self = AddServer(NULL, str, 0, boot_time, now, numer, desc);
1597     conf_register_reload(p10_conf_reload);
1598
1599     irc_func_dict = dict_new();
1600     dict_insert(irc_func_dict, CMD_BURST, cmd_burst);
1601     dict_insert(irc_func_dict, TOK_BURST, cmd_burst);
1602     dict_insert(irc_func_dict, CMD_CREATE, cmd_create);
1603     dict_insert(irc_func_dict, TOK_CREATE, cmd_create);
1604     dict_insert(irc_func_dict, CMD_EOB, cmd_eob);
1605     dict_insert(irc_func_dict, TOK_EOB, cmd_eob);
1606     dict_insert(irc_func_dict, CMD_EOB_ACK, cmd_eob_ack);
1607     dict_insert(irc_func_dict, TOK_EOB_ACK, cmd_eob_ack);
1608     dict_insert(irc_func_dict, CMD_MODE, cmd_mode);
1609     dict_insert(irc_func_dict, TOK_MODE, cmd_mode);
1610     dict_insert(irc_func_dict, CMD_NICK, cmd_nick);
1611     dict_insert(irc_func_dict, TOK_NICK, cmd_nick);
1612     dict_insert(irc_func_dict, CMD_ACCOUNT, cmd_account);
1613     dict_insert(irc_func_dict, TOK_ACCOUNT, cmd_account);
1614     dict_insert(irc_func_dict, CMD_FAKEHOST, cmd_fakehost);
1615     dict_insert(irc_func_dict, TOK_FAKEHOST, cmd_fakehost);
1616     dict_insert(irc_func_dict, CMD_PASS, cmd_pass);
1617     dict_insert(irc_func_dict, TOK_PASS, cmd_pass);
1618     dict_insert(irc_func_dict, CMD_PING, cmd_ping);
1619     dict_insert(irc_func_dict, TOK_PING, cmd_ping);
1620     dict_insert(irc_func_dict, CMD_PRIVMSG, cmd_privmsg);
1621     dict_insert(irc_func_dict, TOK_PRIVMSG, cmd_privmsg);
1622     dict_insert(irc_func_dict, CMD_PONG, cmd_pong);
1623     dict_insert(irc_func_dict, TOK_PONG, cmd_pong);
1624     dict_insert(irc_func_dict, CMD_QUIT, cmd_quit);
1625     dict_insert(irc_func_dict, TOK_QUIT, cmd_quit);
1626     dict_insert(irc_func_dict, CMD_SERVER, cmd_server);
1627     dict_insert(irc_func_dict, TOK_SERVER, cmd_server);
1628     dict_insert(irc_func_dict, CMD_JOIN, cmd_join);
1629     dict_insert(irc_func_dict, TOK_JOIN, cmd_join);
1630     dict_insert(irc_func_dict, CMD_PART, cmd_part);
1631     dict_insert(irc_func_dict, TOK_PART, cmd_part);
1632     dict_insert(irc_func_dict, CMD_ERROR, cmd_error);
1633     dict_insert(irc_func_dict, TOK_ERROR, cmd_error);
1634     dict_insert(irc_func_dict, CMD_TOPIC, cmd_topic);
1635     dict_insert(irc_func_dict, TOK_TOPIC, cmd_topic);
1636     dict_insert(irc_func_dict, CMD_AWAY, cmd_away);
1637     dict_insert(irc_func_dict, TOK_AWAY, cmd_away);
1638     dict_insert(irc_func_dict, CMD_SILENCE, cmd_dummy);
1639     dict_insert(irc_func_dict, TOK_SILENCE, cmd_dummy);
1640     dict_insert(irc_func_dict, CMD_KICK, cmd_kick);
1641     dict_insert(irc_func_dict, TOK_KICK, cmd_kick);
1642     dict_insert(irc_func_dict, CMD_SQUIT, cmd_squit);
1643     dict_insert(irc_func_dict, TOK_SQUIT, cmd_squit);
1644     dict_insert(irc_func_dict, CMD_KILL, cmd_kill);
1645     dict_insert(irc_func_dict, TOK_KILL, cmd_kill);
1646     dict_insert(irc_func_dict, CMD_NOTICE, cmd_notice);
1647     dict_insert(irc_func_dict, TOK_NOTICE, cmd_notice);
1648     dict_insert(irc_func_dict, CMD_STATS, cmd_stats);
1649     dict_insert(irc_func_dict, TOK_STATS, cmd_stats);
1650     dict_insert(irc_func_dict, CMD_SVSNICK, cmd_svsnick);
1651     dict_insert(irc_func_dict, TOK_SVSNICK, cmd_svsnick);
1652     dict_insert(irc_func_dict, CMD_WHOIS, cmd_whois);
1653     dict_insert(irc_func_dict, TOK_WHOIS, cmd_whois);
1654     dict_insert(irc_func_dict, CMD_GLINE, cmd_gline);
1655     dict_insert(irc_func_dict, TOK_GLINE, cmd_gline);
1656     dict_insert(irc_func_dict, CMD_OPMODE, cmd_opmode);
1657     dict_insert(irc_func_dict, TOK_OPMODE, cmd_opmode);
1658     dict_insert(irc_func_dict, CMD_CLEARMODE, cmd_clearmode);
1659     dict_insert(irc_func_dict, TOK_CLEARMODE, cmd_clearmode);
1660     dict_insert(irc_func_dict, CMD_VERSION, cmd_version);
1661     dict_insert(irc_func_dict, TOK_VERSION, cmd_version);
1662     dict_insert(irc_func_dict, CMD_ADMIN, cmd_admin);
1663     dict_insert(irc_func_dict, TOK_ADMIN, cmd_admin);
1664
1665     /* In P10, DESTRUCT doesn't do anything except be broadcast to servers.
1666      * Apparently to obliterate channels from any servers that think they
1667      * exist?
1668      */
1669     dict_insert(irc_func_dict, CMD_DESTRUCT, cmd_dummy);
1670     dict_insert(irc_func_dict, TOK_DESTRUCT, cmd_dummy);
1671     /* Ignore invites */
1672     dict_insert(irc_func_dict, CMD_INVITE, cmd_dummy);
1673     dict_insert(irc_func_dict, TOK_INVITE, cmd_dummy);
1674     /* DESYNCH is just informational, so ignore it */
1675     dict_insert(irc_func_dict, CMD_DESYNCH, cmd_dummy);
1676     dict_insert(irc_func_dict, TOK_DESYNCH, cmd_dummy);
1677     /* Ignore channel operator notices. */
1678     dict_insert(irc_func_dict, CMD_WALLCHOPS, cmd_dummy);
1679     dict_insert(irc_func_dict, TOK_WALLCHOPS, cmd_dummy);
1680     dict_insert(irc_func_dict, CMD_WALLVOICES, cmd_dummy);
1681     dict_insert(irc_func_dict, TOK_WALLVOICES, cmd_dummy);
1682     /* Ignore opers being silly. */
1683     dict_insert(irc_func_dict, CMD_WALLOPS, cmd_dummy);
1684     dict_insert(irc_func_dict, TOK_WALLOPS, cmd_dummy);
1685     /* We have reliable clock!  Always!  Wraaa! */
1686     dict_insert(irc_func_dict, CMD_SETTIME, cmd_dummy);
1687     dict_insert(irc_func_dict, TOK_SETTIME, cmd_dummy);
1688     /* handle topics */
1689     dict_insert(irc_func_dict, "331", cmd_num_topic);
1690     dict_insert(irc_func_dict, "332", cmd_num_topic);
1691     dict_insert(irc_func_dict, "333", cmd_num_topic);
1692     dict_insert(irc_func_dict, "345", cmd_dummy); /* blah has been invited to blah */
1693     dict_insert(irc_func_dict, "432", cmd_error_nick); /* Erroneus [sic] nickname */
1694     /* ban list resetting */
1695     /* "stats g" responses */
1696     dict_insert(irc_func_dict, "247", cmd_num_gline);
1697     dict_insert(irc_func_dict, "219", cmd_dummy); /* "End of /STATS report" */
1698     /* other numeric responses we might get */
1699     dict_insert(irc_func_dict, "401", cmd_dummy); /* target left network */
1700     dict_insert(irc_func_dict, "403", cmd_dummy); /* no such channel */
1701     dict_insert(irc_func_dict, "404", cmd_dummy); /* cannot send to channel */
1702     dict_insert(irc_func_dict, "439", cmd_dummy); /* target change too fast */
1703     dict_insert(irc_func_dict, "441", cmd_dummy); /* target isn't on that channel */
1704     dict_insert(irc_func_dict, "442", cmd_dummy); /* you aren't on that channel */
1705     dict_insert(irc_func_dict, "443", cmd_dummy); /* is already on channel (after invite?) */
1706     dict_insert(irc_func_dict, "461", cmd_dummy); /* Not enough parameters (after TOPIC w/ 0 args) */
1707     dict_insert(irc_func_dict, "467", cmd_dummy); /* Channel key already set */
1708
1709     num_privmsg_funcs = 16;
1710     privmsg_funcs = malloc(sizeof(privmsg_func_t)*num_privmsg_funcs);
1711     memset(privmsg_funcs, 0, sizeof(privmsg_func_t)*num_privmsg_funcs);
1712
1713     num_notice_funcs = 16;
1714     notice_funcs = malloc(sizeof(privmsg_func_t)*num_notice_funcs);
1715     memset(notice_funcs, 0, sizeof(privmsg_func_t)*num_notice_funcs);
1716
1717     userList_init(&dead_users);
1718     reg_del_channel_func(remove_unbursted_channel);
1719     reg_exit_func(parse_cleanup);
1720 }
1721
1722 int
1723 parse_line(char *line, int recursive)
1724 {
1725     char *argv[MAXNUMPARAMS], *origin;
1726     int argc, cmd, res=0;
1727     cmd_func_t *func;
1728
1729     argc = split_line(line, true, MAXNUMPARAMS, argv);
1730     cmd = self->uplink || !argv[0][1] || !argv[0][2];
1731     if (argc > cmd) {
1732         if (cmd) {
1733             if (argv[0][0] == ':') {
1734                 origin = argv[0]+1;
1735             } else if (!argv[0][1] || !argv[0][2]) {
1736                 struct server *sNode = GetServerN(argv[0]);
1737                 origin = sNode ? sNode->name : 0;
1738             } else {
1739                 struct userNode *uNode = GetUserN(argv[0]);
1740                 origin = uNode ? uNode->nick : 0;
1741             }
1742         } else
1743             origin = 0;
1744         if ((func = dict_find(irc_func_dict, argv[cmd], NULL)))
1745             res = func(origin, argc-cmd, argv+cmd);
1746     }
1747     if (!res) {
1748         log_module(MAIN_LOG, LOG_ERROR, "PARSE ERROR on line: %s", unsplit_string(argv, argc, NULL));
1749     } else if (!recursive) {
1750         unsigned int i;
1751         for (i=0; i<dead_users.used; i++)
1752             free_user(dead_users.list[i]);
1753         dead_users.used = 0;
1754     }
1755     return res;
1756 }
1757
1758 static void
1759 parse_foreach(char *target_list, foreach_chanfunc cf, foreach_nonchan nc, foreach_userfunc uf, foreach_nonuser nu, void *data)
1760 {
1761     char *j, old;
1762
1763     do {
1764         j = target_list;
1765         while (*j != 0 && *j != ',')
1766             j++;
1767         old = *j;
1768         *j = 0;
1769
1770         if (IsChannelName(target_list)
1771             || (target_list[0] == '0' && target_list[1] == '\0')) {
1772             struct chanNode *chan = GetChannel(target_list);
1773
1774             if (chan) {
1775                 if (cf)
1776                     cf(chan, data);
1777             } else {
1778                 if (nc)
1779                     nc(target_list, data);
1780             }
1781         } else {
1782             struct userNode *user;
1783             struct privmsg_desc *pd = data;
1784
1785             pd->is_qualified = 0;
1786             if (*target_list == '@') {
1787                 user = NULL;
1788             } else if (strchr(target_list, '@')) {
1789                 struct server *server;
1790
1791                 pd->is_qualified = 1;
1792                 user = GetUserH(strtok(target_list, "@"));
1793                 server = GetServerH(strtok(NULL, "@"));
1794
1795                 if (user && (user->uplink != server)) {
1796                     /* Don't attempt to index into any arrays
1797                        using a user's numeric on another server. */
1798                     user = NULL;
1799                 }
1800             } else {
1801                 user = GetUserN(target_list);
1802             }
1803
1804             if (user) {
1805                 if (uf)
1806                     uf(user, data);
1807             } else {
1808                 if (nu)
1809                     nu(target_list, data);
1810             }
1811         }
1812         target_list = j+1;
1813     } while (old == ',');
1814 }
1815
1816 static int
1817 get_local_numeric(void)
1818 {
1819     static unsigned int next_numeric = 0;
1820     if (self->clients > self->num_mask)
1821         return -1;
1822     while (self->users[next_numeric])
1823         if (++next_numeric > self->num_mask)
1824             next_numeric = 0;
1825     return next_numeric;
1826 }
1827
1828 static void
1829 make_numeric(struct server *svr, int local_num, char *outbuf)
1830 {
1831     int slen, llen;
1832
1833     if (force_n2k || svr->numeric[1]) {
1834         slen = 2;
1835         llen = 3;
1836     } else {
1837         slen = 1;
1838         llen = (local_num < 64*64) ? 2 : 3;
1839     }
1840     strncpy(outbuf, svr->numeric, slen);
1841     inttobase64(outbuf+slen, local_num, llen);
1842     outbuf[slen+llen] = 0;
1843 }
1844
1845 struct server *
1846 AddServer(struct server *uplink, const char *name, int hops, time_t boot, time_t link, const char *numeric, const char *description)
1847 {
1848     struct server* sNode;
1849     int slen, mlen;
1850
1851     if ((sNode = GetServerN(numeric))) {
1852         /* This means we're trying to re-add an existant server.
1853          * To be safe, we should forget the previous incarnation.
1854          * (And all its linked servers.)
1855          *
1856          * It usually only happens in replays when the original
1857          * had a ping timeout and the replay didn't (because
1858          * replaying a ping timeout invariably gets things wrong).
1859          */
1860         DelServer(sNode, 0, NULL);
1861     }
1862
1863     switch (strlen(numeric)) {
1864     case 5: slen = 2; mlen = 3; break;
1865     case 4: slen = 1; mlen = 3; break;
1866     case 3: slen = 1; mlen = 2; break;
1867     default:
1868         log_module(MAIN_LOG, LOG_ERROR, "AddServer(\"%s\", \"%s\", ...): Numeric %s has invalid length.", uplink->name, name, numeric);
1869         return NULL;
1870     }
1871
1872     sNode = calloc(1, sizeof(*sNode));
1873     sNode->uplink = uplink;
1874     safestrncpy(sNode->name, name, sizeof(sNode->name));
1875     sNode->num_mask = base64toint(numeric+slen, mlen);
1876     sNode->hops = hops;
1877     sNode->boot = boot;
1878     sNode->link = link;
1879     strncpy(sNode->numeric, numeric, slen);
1880     safestrncpy(sNode->description, description, sizeof(sNode->description));
1881     sNode->users = calloc(sNode->num_mask+1, sizeof(*sNode->users));
1882     serverList_init(&sNode->children);
1883     if (sNode->uplink) {
1884         /* uplink may be NULL if we're just building ourself */
1885         serverList_append(&sNode->uplink->children, sNode);
1886     }
1887     servers_num[base64toint(numeric, slen)] = sNode;
1888     dict_insert(servers, sNode->name, sNode);
1889     return sNode;
1890 }
1891
1892 void DelServer(struct server* serv, int announce, const char *message)
1893 {
1894     unsigned int i;
1895
1896     /* If we receive an ERROR command before the SERVER
1897      * command a NULL server can be passed */
1898     if (!serv)
1899         return;
1900
1901     /* Hrm, what's the right way to SQUIT some other server?
1902      * (This code is only to handle killing juped servers.) */
1903     if (announce && (serv->uplink == self) && (serv != self->uplink))
1904         irc_squit(serv, message, NULL);
1905
1906     /* must recursively remove servers linked to this one first */
1907     for (i=serv->children.used;i>0;)
1908         if (serv->children.list[--i] != self)
1909             DelServer(serv->children.list[i], false, NULL);
1910
1911     /* clean up server's user hash tables */
1912     for (i=0;i<=serv->num_mask;i++)
1913         if (serv->users[i])
1914             DelUser(serv->users[i], NULL, false, "server delinked");
1915
1916     /* delete server */
1917     if (serv->uplink)
1918         serverList_remove(&serv->uplink->children, serv);
1919     if (serv == self->uplink)
1920         self->uplink = NULL;
1921     servers_num[base64toint(serv->numeric, strlen(serv->numeric))] = NULL;
1922     dict_remove(servers, serv->name);
1923     serverList_clean(&serv->children);
1924     free(serv->users);
1925     free(serv);
1926 }
1927
1928 struct userNode *
1929 AddLocalUser(const char *nick, const char *ident, const char *hostname, const char *desc, const char *modes)
1930 {
1931     char numeric[COMBO_NUMERIC_LEN+1];
1932     int local_num = get_local_numeric();
1933     time_t timestamp = now;
1934     struct userNode *old_user = GetUserH(nick);
1935
1936     if (!modes)
1937         modes = "+oik";
1938     if (old_user) {
1939         if (IsLocal(old_user))
1940             return old_user;
1941         timestamp = old_user->timestamp - 1;
1942     }
1943     if (local_num == -1) {
1944         log_module(MAIN_LOG, LOG_ERROR, "Unable to allocate numnick for service %s", nick);
1945         return 0;
1946     }
1947     if (!hostname)
1948         hostname = self->name;
1949     make_numeric(self, local_num, numeric);
1950     return AddUser(self, nick, ident, hostname, modes, numeric, desc, now, "AAAAAA");
1951 }
1952
1953 struct userNode *
1954 AddClone(const char *nick, const char *ident, const char *hostname, const char *desc)
1955 {
1956     char numeric[COMBO_NUMERIC_LEN+1];
1957     int local_num = get_local_numeric();
1958     time_t timestamp = now;
1959     struct userNode *old_user = GetUserH(nick);
1960
1961     if (old_user) {
1962         if (IsLocal(old_user))
1963             return old_user;
1964         timestamp = old_user->timestamp - 1;
1965     }
1966     if (local_num == -1) {
1967         log_module(MAIN_LOG, LOG_ERROR, "Unable to allocate numnick for clone %s", nick);
1968         return 0;
1969     }
1970     make_numeric(self, local_num, numeric);
1971     return AddUser(self, nick, ident, hostname, "+i", numeric, desc, timestamp, "AAAAAA");
1972 }
1973
1974 int
1975 is_valid_nick(const char *nick) {
1976     unsigned int ii;
1977     /* IRC has some of The Most Fucked-Up ideas about character sets
1978      * in the world.. */
1979     if (!isalpha(*nick) && !strchr("{|}~[\\]^_`", *nick))
1980         return 0;
1981     for (ii = 0; nick[ii]; ++ii)
1982         if (!isalnum(nick[ii]) && !strchr("{|}~[\\]^-_`", nick[ii]))
1983             return 0;
1984     if (strlen(nick) > nicklen)
1985         return 0;
1986     return 1;
1987 }
1988
1989 static struct userNode*
1990 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)
1991 {
1992     struct userNode *oldUser, *uNode;
1993     unsigned int n, ignore_user, dummy;
1994
1995     if ((strlen(numeric) < 3) || (strlen(numeric) > 5)) {
1996         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): numeric %s wrong length!", uplink, nick, numeric);
1997         return NULL;
1998     }
1999
2000     if (!uplink) {
2001         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): server for numeric %s doesn't exist!", uplink, nick, numeric);
2002         return NULL;
2003     }
2004
2005     if (uplink != GetServerN(numeric)) {
2006         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): server for numeric %s differs from nominal uplink %s.", uplink, nick, numeric, uplink->name);
2007         return NULL;
2008     }
2009
2010     dummy = modes && modes[0] == '*';
2011     if (dummy) {
2012         ++modes;
2013     } else if (!is_valid_nick(nick)) {
2014         log_module(MAIN_LOG, LOG_WARNING, "AddUser(%p, %s, ...): invalid nickname detected.", uplink, nick);
2015         return NULL;
2016     }
2017
2018     ignore_user = 0;
2019     if ((oldUser = GetUserH(nick))) {
2020         if (IsLocal(oldUser) && (IsService(oldUser) || IsPersistent(oldUser))) {
2021             /* The service should collide the new user off. */
2022             oldUser->timestamp = timestamp - 1;
2023             irc_user(oldUser);
2024         }
2025         if (oldUser->timestamp > timestamp) {
2026             /* "Old" user is really newer; remove them */
2027             DelUser(oldUser, 0, 1, "Overruled by older nick");
2028         } else {
2029             /* User being added is too new; do not add them to
2030              * clients, but do add them to the server's list, since it
2031              * will send a KILL and QUIT soon. */
2032             ignore_user = 1;
2033         }
2034     }
2035
2036     /* create new usernode and set all values */
2037     uNode = calloc(1, sizeof(*uNode));
2038     uNode->nick = strdup(nick);
2039     safestrncpy(uNode->ident, ident, sizeof(uNode->ident));
2040     safestrncpy(uNode->info, userinfo, sizeof(uNode->info));
2041     safestrncpy(uNode->hostname, hostname, sizeof(uNode->hostname));
2042     safestrncpy(uNode->numeric, numeric, sizeof(uNode->numeric));
2043     irc_p10_pton(&uNode->ip, realip);
2044     uNode->timestamp = timestamp;
2045     modeList_init(&uNode->channels);
2046     uNode->uplink = uplink;
2047     if (++uNode->uplink->clients > uNode->uplink->max_clients) {
2048         uNode->uplink->max_clients = uNode->uplink->clients;
2049     }
2050     uNode->num_local = base64toint(numeric+strlen(uNode->uplink->numeric), 3) & uNode->uplink->num_mask;
2051     uNode->uplink->users[uNode->num_local] = uNode;
2052     mod_usermode(uNode, modes);
2053     if (dummy)
2054         uNode->modes |= FLAGS_DUMMY;
2055     if (ignore_user)
2056         return uNode;
2057
2058     dict_insert(clients, uNode->nick, uNode);
2059     if (dict_size(clients) > max_clients) {
2060         max_clients = dict_size(clients);
2061         max_clients_time = now;
2062     }
2063     if (IsLocal(uNode))
2064         irc_user(uNode);
2065     for (n=0; n<nuf_used; n++)
2066         if (nuf_list[n](uNode))
2067             break;
2068     return uNode;
2069 }
2070
2071 /* removes user from it's server's hash table and nick hash table */
2072 void
2073 DelUser(struct userNode* user, struct userNode *killer, int announce, const char *why)
2074 {
2075     unsigned int n;
2076
2077     verify(user);
2078
2079     /* mark them as dead, in case anybody cares */
2080     user->dead = 1;
2081
2082     /* remove user from all channels */
2083     while (user->channels.used > 0)
2084         DelChannelUser(user, user->channels.list[user->channels.used-1]->channel, NULL, false);
2085
2086     /* Call these in reverse order so ChanServ can update presence
2087        information before NickServ nukes the handle_info. */
2088     for (n = duf_used; n > 0; )
2089         duf_list[--n](user, killer, why);
2090
2091     user->uplink->clients--;
2092     user->uplink->users[user->num_local] = NULL;
2093     if (IsOper(user))
2094         userList_remove(&curr_opers, user);
2095     /* remove from global dictionary, but not if after a collide */
2096     if (user == dict_find(clients, user->nick, NULL))
2097         dict_remove(clients, user->nick);
2098
2099     if (IsInvisible(user))
2100         invis_clients--;
2101
2102     if (announce) {
2103         if (IsLocal(user))
2104             irc_quit(user, why);
2105         else
2106             irc_kill(killer, user, why);
2107     }
2108
2109     if (IsLocal(user)) {
2110         unsigned int num = user->num_local;
2111         if (num < num_privmsg_funcs)
2112             privmsg_funcs[num] = NULL;
2113         if (num < num_notice_funcs)
2114             notice_funcs[num] = NULL;
2115     }
2116
2117     modeList_clean(&user->channels);
2118     /* We don't free them, in case we try to privmsg them or something
2119      * (like when a stupid oper kills themself).  We just put them onto
2120      * a list of clients that get freed after processing each line.
2121      */
2122     if (dead_users.size)
2123         userList_append(&dead_users, user);
2124     else
2125         free_user(user);
2126 }
2127
2128 static void call_oper_funcs(struct userNode *user);
2129
2130 void mod_usermode(struct userNode *user, const char *mode_change) {
2131     int add = 1;
2132     const char *word = mode_change;
2133
2134     if (!user || !mode_change)
2135         return;
2136     while (*word != ' ' && *word) word++;
2137     while (*word == ' ') word++;
2138     while (1) {
2139 #define do_user_mode(FLAG) do { if (add) user->modes |= FLAG; else user->modes &= ~FLAG; } while (0)
2140         switch (*mode_change++) {
2141         case 0: case ' ': return;
2142         case '+': add = 1; break;
2143         case '-': add = 0; break;
2144         case 'o':
2145             do_user_mode(FLAGS_OPER);
2146             if (add) {
2147                 userList_append(&curr_opers, user);
2148                 call_oper_funcs(user);
2149             } else {
2150                 userList_remove(&curr_opers, user);
2151             }
2152             break;
2153         case 'i': do_user_mode(FLAGS_INVISIBLE);
2154             if (add)
2155                 invis_clients++;
2156             else
2157                 invis_clients--;
2158             break;
2159         case 'w': do_user_mode(FLAGS_WALLOP); break;
2160         case 'd': do_user_mode(FLAGS_DEAF); break;
2161         case 'k': do_user_mode(FLAGS_SERVICE); break;
2162         case 'g': do_user_mode(FLAGS_GLOBAL); break;
2163         case 'x': do_user_mode(FLAGS_HIDDEN_HOST); break;
2164         case 'r':
2165             if (*word) {
2166                 char tag[MAXLEN];
2167                 unsigned int ii;
2168                 for (ii=0; (*word != ' ') && (*word != '\0'); )
2169                     tag[ii++] = *word++;
2170                 tag[ii] = 0;
2171                 while (*word == ' ')
2172                     word++;
2173                 call_account_func(user, tag);
2174             }
2175             break;
2176         case 'f':
2177             if (*word) {
2178                 char host[MAXLEN];
2179                 unsigned int ii;
2180                 for (ii=0; (*word != ' ') && (*word != '\0'); )
2181                     host[ii++] = *word++;
2182                 host[ii] = 0;
2183                 while (*word == ' ')
2184                     word++;
2185                 assign_fakehost(user, host, 0);
2186             }
2187             break;
2188         }
2189 #undef do_user_mode
2190     }
2191 }
2192
2193 struct mod_chanmode *
2194 mod_chanmode_parse(struct chanNode *channel, char **modes, unsigned int argc, unsigned int flags, short base_oplevel)
2195 {
2196     struct mod_chanmode *change;
2197     unsigned int ii, in_arg, ch_arg, add;
2198
2199     if (argc == 0)
2200         return NULL;
2201     if (!(change = mod_chanmode_alloc(argc - 1)))
2202         return NULL;
2203
2204     for (ii = ch_arg = 0, in_arg = add = 1;
2205          (modes[0][ii] != '\0') && (modes[0][ii] != ' ');
2206          ++ii) {
2207         switch (modes[0][ii]) {
2208         case '+':
2209             add = 1;
2210             break;
2211         case '-':
2212             add = 0;
2213             break;
2214 #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)
2215         case 'C': do_chan_mode(MODE_NOCTCPS); break;
2216         case 'D': do_chan_mode(MODE_DELAYJOINS); break;
2217         case 'c': do_chan_mode(MODE_NOCOLORS); break;
2218         case 'i': do_chan_mode(MODE_INVITEONLY); break;
2219         case 'm': do_chan_mode(MODE_MODERATED); break;
2220         case 'n': do_chan_mode(MODE_NOPRIVMSGS); break;
2221         case 'p': do_chan_mode(MODE_PRIVATE); break;
2222         case 'r': do_chan_mode(MODE_REGONLY); break;
2223         case 's': do_chan_mode(MODE_SECRET); break;
2224         case 't': do_chan_mode(MODE_TOPICLIMIT); break;
2225         case 'z':
2226           if (!(flags & MCP_REGISTERED)) {
2227            do_chan_mode(MODE_REGISTERED);
2228           } else {
2229            mod_chanmode_free(change);
2230            return NULL;
2231           }
2232           break;
2233 #undef do_chan_mode
2234         case 'l':
2235             if (add) {
2236                 if (in_arg >= argc)
2237                     goto error;
2238                 change->modes_set |= MODE_LIMIT;
2239                 change->new_limit = atoi(modes[in_arg++]);
2240             } else {
2241                 change->modes_set &= ~MODE_LIMIT;
2242                 change->modes_clear |= MODE_LIMIT;
2243             }
2244             break;
2245         case 'k':
2246             if (add) {
2247                 if (in_arg >= argc)
2248                     goto error;
2249                 change->modes_set |= MODE_KEY;
2250                 safestrncpy(change->new_key, modes[in_arg++], sizeof(change->new_key));
2251             } else {
2252                 change->modes_clear |= MODE_KEY;
2253                 if (!(flags & MCP_KEY_FREE)) {
2254                     if (in_arg >= argc)
2255                         goto error;
2256                     in_arg++;
2257                 }
2258             }
2259             break;
2260         case 'U':
2261             if (add)
2262             {
2263               if (in_arg >= argc)
2264                   goto error;
2265               change->modes_set |= MODE_UPASS;
2266               safestrncpy(change->new_upass, modes[in_arg++], sizeof(change->new_upass));
2267             } else {
2268                 change->modes_clear |= MODE_UPASS;
2269                 if (!(flags & MCP_UPASS_FREE)) {
2270                     if (in_arg >= argc)
2271                         goto error;
2272                     in_arg++;
2273                 }
2274             }
2275             break;
2276         case 'A':
2277             if (add) {
2278                 if (in_arg >= argc)
2279                     goto error;
2280                 change->modes_set |= MODE_APASS;
2281                 safestrncpy(change->new_apass, modes[in_arg++], sizeof(change->new_apass));
2282             } else {
2283                 change->modes_clear |= MODE_APASS;
2284                 if (!(flags & MCP_APASS_FREE)) {
2285                     if (in_arg >= argc)
2286                       goto error;
2287                     in_arg++;
2288                 }
2289             }
2290             break;
2291         case 'b':
2292             if (!(flags & MCP_ALLOW_OVB))
2293                 goto error;
2294             if (in_arg >= argc)
2295                 goto error;
2296             change->args[ch_arg].mode = MODE_BAN;
2297             if (!add)
2298                 change->args[ch_arg].mode |= MODE_REMOVE;
2299             change->args[ch_arg++].u.hostmask = modes[in_arg++];
2300             break;
2301         case 'o': case 'v':
2302         {
2303             struct userNode *victim;
2304             char *oplevel_str;
2305             int oplevel;
2306
2307             if (in_arg >= argc)
2308                 goto error;
2309             oplevel_str = strchr(modes[in_arg], ':');
2310             if (oplevel_str)
2311             {
2312                 /* XXYYY M #channel +o XXYYY:<oplevel> */
2313                 *oplevel_str++ = '\0';
2314                 oplevel = parse_oplevel(oplevel_str);
2315                 if (oplevel <= base_oplevel && !(flags & MCP_FROM_SERVER))
2316                     oplevel = base_oplevel + 1;
2317             }
2318             else if (channel->modes & MODE_UPASS)
2319                 oplevel = base_oplevel + 1;
2320             else
2321                 oplevel = -1;
2322
2323             /* Check that oplevel is within bounds. */
2324             if (oplevel > MAXOPLEVEL)
2325                 oplevel = MAXOPLEVEL;
2326
2327             if (!(flags & MCP_ALLOW_OVB))
2328                 goto error;
2329             if (in_arg >= argc)
2330                 goto error;
2331             change->args[ch_arg].mode = (modes[0][ii] == 'o') ? MODE_CHANOP : MODE_VOICE;
2332             if (!add)
2333                 change->args[ch_arg].mode |= MODE_REMOVE;
2334             if (flags & MCP_FROM_SERVER)
2335                 victim = GetUserN(modes[in_arg++]);
2336             else
2337                 victim = GetUserH(modes[in_arg++]);
2338             if (!victim)
2339                 continue;
2340             if ((change->args[ch_arg].u.member = GetUserMode(channel, victim)))
2341             {
2342                 /* Apply the oplevel change */
2343                 change->args[ch_arg].u.member->oplevel = oplevel;
2344                 ch_arg++;
2345             }
2346             break;
2347         }
2348         default:
2349             if (!(flags & MCP_FROM_SERVER))
2350                 goto error;
2351             break;
2352         }
2353     }
2354     change->argc = ch_arg; /* in case any turned out to be ignored */
2355     if (change->modes_set & MODE_SECRET) {
2356         change->modes_set &= ~(MODE_PRIVATE);
2357         change->modes_clear |= MODE_PRIVATE;
2358     } else if (change->modes_set & MODE_PRIVATE) {
2359         change->modes_set &= ~(MODE_SECRET);
2360         change->modes_clear |= MODE_SECRET;
2361     }
2362     return change;
2363   error:
2364     mod_chanmode_free(change);
2365     return NULL;
2366 }
2367
2368 struct chanmode_buffer {
2369     char modes[MAXLEN];
2370     char args[MAXLEN];
2371     struct chanNode *channel;
2372     struct userNode *actor;
2373     unsigned int modes_used;
2374     unsigned int args_used;
2375     size_t chname_len;
2376     unsigned int is_add : 1;
2377     unsigned int is_chanop : 1;
2378 };
2379
2380 static void
2381 mod_chanmode_append(struct chanmode_buffer *buf, char ch, const char *arg)
2382 {
2383     size_t arg_len = strlen(arg);
2384     if (buf->modes_used > (MAXMODEPARAMS) ||
2385         buf->modes_used + buf->args_used + buf->chname_len + arg_len > 450) {
2386         memcpy(buf->modes + buf->modes_used, buf->args, buf->args_used);
2387         buf->modes[buf->modes_used + buf->args_used] = '\0';
2388         irc_mode((buf->is_chanop ? buf->actor : NULL), buf->channel, buf->modes);
2389         buf->modes[0] = buf->is_add ? '+' : '-';
2390         buf->modes_used = 1;
2391         buf->args_used = 0;
2392     }
2393     buf->modes[buf->modes_used++] = ch;
2394     buf->args[buf->args_used++] = ' ';
2395     memcpy(buf->args + buf->args_used, arg, arg_len);
2396     buf->args_used += arg_len;
2397 }
2398
2399 void
2400 mod_chanmode_announce(struct userNode *who, struct chanNode *channel, struct mod_chanmode *change)
2401 {
2402     struct chanmode_buffer chbuf;
2403     unsigned int arg;
2404     struct modeNode *mn;
2405     char int_buff[32], mode = '\0';
2406
2407     assert(change->argc <= change->alloc_argc);
2408     memset(&chbuf, 0, sizeof(chbuf));
2409     chbuf.channel = channel;
2410     chbuf.actor = who;
2411     chbuf.chname_len = strlen(channel->name);
2412
2413     mn = GetUserMode(channel, who);
2414     if ((mn && (mn->modes & MODE_CHANOP)) || off_channel)
2415         chbuf.is_chanop = 1;
2416
2417     /* First remove modes */
2418     chbuf.is_add = 0;
2419     if (change->modes_clear) {
2420         if (mode != '-')
2421             chbuf.modes[chbuf.modes_used++] = mode = '-';
2422 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_clear & MODE_##BIT) chbuf.modes[chbuf.modes_used++] = CHAR
2423         DO_MODE_CHAR(PRIVATE, 'p');
2424         DO_MODE_CHAR(SECRET, 's');
2425         DO_MODE_CHAR(MODERATED, 'm');
2426         DO_MODE_CHAR(TOPICLIMIT, 't');
2427         DO_MODE_CHAR(INVITEONLY, 'i');
2428         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2429         DO_MODE_CHAR(LIMIT, 'l');
2430         DO_MODE_CHAR(DELAYJOINS, 'D');
2431         DO_MODE_CHAR(REGONLY, 'r');
2432         DO_MODE_CHAR(NOCOLORS, 'c');
2433         DO_MODE_CHAR(NOCTCPS, 'C');
2434         DO_MODE_CHAR(REGISTERED, 'z');
2435 #undef DO_MODE_CHAR
2436         if (change->modes_clear & channel->modes & MODE_KEY)
2437             mod_chanmode_append(&chbuf, 'k', channel->key);
2438         if (change->modes_clear & channel->modes & MODE_UPASS)
2439             mod_chanmode_append(&chbuf, 'U', channel->upass);
2440         if (change->modes_clear * channel->modes & MODE_APASS)
2441             mod_chanmode_append(&chbuf, 'A', channel->apass);
2442     }
2443     for (arg = 0; arg < change->argc; ++arg) {
2444         if (!(change->args[arg].mode & MODE_REMOVE))
2445             continue;
2446         if (mode != '-')
2447             chbuf.modes[chbuf.modes_used++] = mode = '-';
2448         switch (change->args[arg].mode & ~MODE_REMOVE) {
2449         case MODE_BAN:
2450             mod_chanmode_append(&chbuf, 'b', change->args[arg].u.hostmask);
2451             break;
2452         default:
2453             if (change->args[arg].mode & MODE_CHANOP)
2454                 mod_chanmode_append(&chbuf, 'o', change->args[arg].u.member->user->numeric);
2455             if (change->args[arg].mode & MODE_VOICE)
2456                 mod_chanmode_append(&chbuf, 'v', change->args[arg].u.member->user->numeric);
2457             break;
2458         }
2459     }
2460
2461     /* Then set them */
2462     chbuf.is_add = 1;
2463     if (change->modes_set) {
2464         if (mode != '+')
2465             chbuf.modes[chbuf.modes_used++] = mode = '+';
2466 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_set & MODE_##BIT) chbuf.modes[chbuf.modes_used++] = CHAR
2467         DO_MODE_CHAR(PRIVATE, 'p');
2468         DO_MODE_CHAR(SECRET, 's');
2469         DO_MODE_CHAR(MODERATED, 'm');
2470         DO_MODE_CHAR(TOPICLIMIT, 't');
2471         DO_MODE_CHAR(INVITEONLY, 'i');
2472         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2473         DO_MODE_CHAR(DELAYJOINS, 'D');
2474         DO_MODE_CHAR(REGONLY, 'r');
2475         DO_MODE_CHAR(NOCOLORS, 'c');
2476         DO_MODE_CHAR(NOCTCPS, 'C');
2477         DO_MODE_CHAR(REGISTERED, 'z');
2478 #undef DO_MODE_CHAR
2479         if(change->modes_set & MODE_KEY)
2480             mod_chanmode_append(&chbuf, 'k', change->new_key);
2481         if (change->modes_set & MODE_UPASS)
2482             mod_chanmode_append(&chbuf, 'U', change->new_upass);
2483         if (change->modes_set & MODE_APASS)
2484             mod_chanmode_append(&chbuf, 'A', change->new_apass);
2485         if(change->modes_set & MODE_LIMIT) {
2486             sprintf(int_buff, "%d", change->new_limit);
2487             mod_chanmode_append(&chbuf, 'l', int_buff);
2488         }
2489     }
2490     for (arg = 0; arg < change->argc; ++arg) {
2491         if (change->args[arg].mode & MODE_REMOVE)
2492             continue;
2493         if (mode != '+')
2494             chbuf.modes[chbuf.modes_used++] = mode = '+';
2495         switch (change->args[arg].mode) {
2496         case MODE_BAN:
2497             mod_chanmode_append(&chbuf, 'b', change->args[arg].u.hostmask);
2498             break;
2499         default:
2500             if (change->args[arg].mode & MODE_CHANOP)
2501                 mod_chanmode_append(&chbuf, 'o', change->args[arg].u.member->user->numeric);
2502             if (change->args[arg].mode & MODE_VOICE)
2503                 mod_chanmode_append(&chbuf, 'v', change->args[arg].u.member->user->numeric);
2504             break;
2505         }
2506     }
2507
2508     /* Flush the buffer and apply changes locally */
2509     if (chbuf.modes_used > 0) {
2510         memcpy(chbuf.modes + chbuf.modes_used, chbuf.args, chbuf.args_used);
2511         chbuf.modes[chbuf.modes_used + chbuf.args_used] = '\0';
2512         irc_mode((chbuf.is_chanop ? chbuf.actor : NULL), chbuf.channel, chbuf.modes);
2513     }
2514     mod_chanmode_apply(who, channel, change);
2515 }
2516
2517 char *
2518 mod_chanmode_format(struct mod_chanmode *change, char *outbuff)
2519 {
2520     unsigned int used = 0;
2521     assert(change->argc <= change->alloc_argc);
2522     if (change->modes_clear) {
2523         outbuff[used++] = '-';
2524 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_clear & MODE_##BIT) outbuff[used++] = CHAR
2525         DO_MODE_CHAR(PRIVATE, 'p');
2526         DO_MODE_CHAR(SECRET, 's');
2527         DO_MODE_CHAR(MODERATED, 'm');
2528         DO_MODE_CHAR(TOPICLIMIT, 't');
2529         DO_MODE_CHAR(INVITEONLY, 'i');
2530         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2531         DO_MODE_CHAR(LIMIT, 'l');
2532         DO_MODE_CHAR(KEY, 'k');
2533         DO_MODE_CHAR(UPASS, 'U');
2534         DO_MODE_CHAR(APASS, 'A');
2535         DO_MODE_CHAR(DELAYJOINS, 'D');
2536         DO_MODE_CHAR(REGONLY, 'r');
2537         DO_MODE_CHAR(NOCOLORS, 'c');
2538         DO_MODE_CHAR(NOCTCPS, 'C');
2539         DO_MODE_CHAR(REGISTERED, 'z');
2540 #undef DO_MODE_CHAR
2541     }
2542     if (change->modes_set) {
2543         outbuff[used++] = '+';
2544 #define DO_MODE_CHAR(BIT, CHAR) if (change->modes_set & MODE_##BIT) outbuff[used++] = CHAR
2545         DO_MODE_CHAR(PRIVATE, 'p');
2546         DO_MODE_CHAR(SECRET, 's');
2547         DO_MODE_CHAR(MODERATED, 'm');
2548         DO_MODE_CHAR(TOPICLIMIT, 't');
2549         DO_MODE_CHAR(INVITEONLY, 'i');
2550         DO_MODE_CHAR(NOPRIVMSGS, 'n');
2551         DO_MODE_CHAR(DELAYJOINS, 'D');
2552         DO_MODE_CHAR(REGONLY, 'r');
2553         DO_MODE_CHAR(NOCOLORS, 'c');
2554         DO_MODE_CHAR(NOCTCPS, 'C');
2555         DO_MODE_CHAR(REGISTERED, 'z');
2556 #undef DO_MODE_CHAR
2557         switch (change->modes_set & (MODE_KEY|MODE_LIMIT|MODE_APASS|MODE_UPASS)) {
2558         /* Doing this implementation has been a pain in the arse, I hope I didn't forget a possible combination */
2559         case MODE_KEY|MODE_LIMIT|MODE_APASS|MODE_UPASS:
2560             used += sprintf(outbuff+used, "lkAU %d %s %s %s", change->new_limit, change->new_key, change->new_apass, change->new_upass);
2561             break;
2562
2563         case MODE_KEY|MODE_LIMIT|MODE_APASS:
2564             used += sprintf(outbuff+used, "lkA %d %s %s", change->new_limit, change->new_key, change->new_apass);
2565             break;
2566         case MODE_KEY|MODE_LIMIT|MODE_UPASS:
2567             used += sprintf(outbuff+used, "lkU %d %s %s", change->new_limit, change->new_key, change->new_upass);
2568             break;
2569         case MODE_KEY|MODE_APASS|MODE_UPASS:
2570             used += sprintf(outbuff+used, "kAU %s %s %s", change->new_key, change->new_apass, change->new_upass);
2571             break;
2572
2573         case MODE_KEY|MODE_APASS:
2574             used += sprintf(outbuff+used, "kA %s %s", change->new_key, change->new_apass);
2575             break;
2576         case MODE_KEY|MODE_UPASS:
2577             used += sprintf(outbuff+used, "kU %s %s", change->new_key, change->new_upass);
2578             break;
2579         case MODE_KEY|MODE_LIMIT:
2580             used += sprintf(outbuff+used, "lk %d %s", change->new_limit, change->new_key);
2581             break;
2582         case MODE_LIMIT|MODE_UPASS:
2583             used += sprintf(outbuff+used, "lU %d %s", change->new_limit, change->new_upass);
2584             break;
2585         case MODE_LIMIT|MODE_APASS:
2586             used += sprintf(outbuff+used, "lA %d %s", change->new_limit, change->new_apass);
2587             break;
2588         case MODE_APASS|MODE_UPASS:
2589             used += sprintf(outbuff+used, "AU %s %s", change->new_apass, change->new_upass);
2590             break;
2591
2592         case MODE_LIMIT|MODE_APASS|MODE_UPASS:
2593             used += sprintf(outbuff+used, "lAU %d %s %s", change->new_limit, change->new_apass, change->new_upass);
2594             break;
2595
2596         case MODE_APASS:
2597             used += sprintf(outbuff+used, "A %s", change->new_apass);
2598             break;
2599         case MODE_UPASS:
2600             used += sprintf(outbuff+used, "U %s", change->new_upass);
2601             break;
2602         case MODE_KEY:
2603             used += sprintf(outbuff+used, "k %s", change->new_key);
2604             break;
2605         case MODE_LIMIT:
2606             used += sprintf(outbuff+used, "l %d", change->new_limit);
2607             break;
2608         }
2609     }
2610     outbuff[used] = 0;
2611     return outbuff;
2612 }
2613
2614 static int
2615 clear_chanmode(struct chanNode *channel, const char *modes)
2616 {
2617     unsigned int remove;
2618
2619     for (remove = 0; *modes; modes++) {
2620         switch (*modes) {
2621         case 'o': remove |= MODE_CHANOP; break;
2622         case 'v': remove |= MODE_VOICE; break;
2623         case 'p': remove |= MODE_PRIVATE; break;
2624         case 's': remove |= MODE_SECRET; break;
2625         case 'm': remove |= MODE_MODERATED; break;
2626         case 't': remove |= MODE_TOPICLIMIT; break;
2627         case 'i': remove |= MODE_INVITEONLY; break;
2628         case 'n': remove |= MODE_NOPRIVMSGS; break;
2629         case 'k':
2630             remove |= MODE_KEY;
2631             channel->key[0] = '\0';
2632             break;
2633         case 'A':
2634             remove |= MODE_APASS;
2635             channel->apass[0] = '\0';
2636             break;
2637         case 'U':
2638             remove |= MODE_UPASS;
2639             channel->upass[0] = '\0';
2640             break;
2641         case 'l':
2642             remove |= MODE_LIMIT;
2643             channel->limit = 0;
2644             break;
2645         case 'b': remove |= MODE_BAN; break;
2646         case 'D': remove |= MODE_DELAYJOINS; break;
2647         case 'r': remove |= MODE_REGONLY; break;
2648         case 'c': remove |= MODE_NOCOLORS; break;
2649         case 'C': remove |= MODE_NOCTCPS; break;
2650         case 'z': remove |= MODE_REGISTERED; break;
2651         }
2652     }
2653
2654     if (!remove)
2655         return 1;
2656
2657     /* Remove simple modes. */
2658     channel->modes &= ~remove;
2659
2660     /* If removing bans, kill 'em all. */
2661     if ((remove & MODE_BAN) && channel->banlist.used) {
2662         unsigned int i;
2663         for (i=0; i<channel->banlist.used; i++)
2664             free(channel->banlist.list[i]);
2665         channel->banlist.used = 0;
2666     }
2667
2668     /* Remove member modes. */
2669     if ((remove & (MODE_CHANOP | MODE_VOICE)) && channel->members.used) {
2670         int mask = ~(remove & (MODE_CHANOP | MODE_VOICE));
2671         unsigned int i;
2672
2673         for (i = 0; i < channel->members.used; i++)
2674             channel->members.list[i]->modes &= mask;
2675     }
2676
2677     return 1;
2678 }
2679
2680 void
2681 reg_privmsg_func(struct userNode *user, privmsg_func_t handler)
2682 {
2683     unsigned int numeric = user->num_local;
2684     if (numeric >= num_privmsg_funcs) {
2685         int newnum = numeric + 8;
2686         privmsg_funcs = realloc(privmsg_funcs, newnum*sizeof(privmsg_func_t));
2687         memset(privmsg_funcs+num_privmsg_funcs, 0, (newnum-num_privmsg_funcs)*sizeof(privmsg_func_t));
2688         num_privmsg_funcs = newnum;
2689     }
2690     if (privmsg_funcs[numeric])
2691         log_module(MAIN_LOG, LOG_WARNING, "re-registering new privmsg handler for numeric %d", numeric);
2692     privmsg_funcs[numeric] = handler;
2693 }
2694
2695 void
2696 unreg_privmsg_func(struct userNode *user, privmsg_func_t handler)
2697 {
2698     unsigned int x;
2699
2700     if (!user || handler)
2701       return; /* this really only works with users */
2702
2703     memset(privmsg_funcs+user->num_local, 0, sizeof(privmsg_func_t));
2704
2705     for (x = user->num_local+1; x < num_privmsg_funcs; x++) 
2706        memmove(privmsg_funcs+x-1, privmsg_funcs+x, sizeof(privmsg_func_t));
2707     
2708     privmsg_funcs = realloc(privmsg_funcs, num_privmsg_funcs*sizeof(privmsg_func_t)); 
2709     num_privmsg_funcs--;
2710 }
2711
2712
2713 void
2714 reg_notice_func(struct userNode *user, privmsg_func_t handler)
2715 {
2716     unsigned int numeric = user->num_local;
2717     if (numeric >= num_notice_funcs) {
2718         int newnum = numeric + 8;
2719         notice_funcs = realloc(notice_funcs, newnum*sizeof(privmsg_func_t));
2720         memset(notice_funcs+num_notice_funcs, 0, (newnum-num_notice_funcs)*sizeof(privmsg_func_t));
2721         num_notice_funcs = newnum;
2722     }
2723     if (notice_funcs[numeric])
2724         log_module(MAIN_LOG, LOG_WARNING, "re-registering new notice handler for numeric %d", numeric);
2725     notice_funcs[numeric] = handler;
2726 }
2727
2728 void
2729 unreg_notice_func(struct userNode *user, privmsg_func_t handler)
2730 {
2731     unsigned int x;
2732
2733     if (!user || handler)
2734           return; /* this really only works with users */
2735
2736     memset(notice_funcs+user->num_local, 0, sizeof(privmsg_func_t));
2737
2738     for (x = user->num_local+1; x < num_notice_funcs; x++)
2739        memmove(notice_funcs+x-1, notice_funcs+x, sizeof(privmsg_func_t));
2740
2741     memset(notice_funcs+user->num_local, 0, sizeof(privmsg_func_t));
2742     notice_funcs = realloc(notice_funcs, num_notice_funcs*sizeof(privmsg_func_t));
2743     num_notice_funcs--;
2744 }
2745
2746 void
2747 reg_oper_func(oper_func_t handler)
2748 {
2749     if (of_used == of_size) {
2750         if (of_size) {
2751             of_size <<= 1;
2752             of_list = realloc(of_list, of_size*sizeof(oper_func_t));
2753         } else {
2754             of_size = 8;
2755             of_list = malloc(of_size*sizeof(oper_func_t));
2756         }
2757     }
2758     of_list[of_used++] = handler;
2759 }
2760
2761 static void
2762 call_oper_funcs(struct userNode *user)
2763 {
2764     unsigned int n;
2765     if (IsLocal(user))
2766         return;
2767     for (n=0; n<of_used; n++)
2768         of_list[n](user);
2769 }
2770
2771 static void
2772 send_burst(void)
2773 {
2774     unsigned int i, hop, max_hop=1;
2775     dict_iterator_t it;
2776
2777     /* burst (juped) servers, closest first (except self, which is sent already) */
2778     for (i=0; i<ArrayLength(servers_num); i++)
2779         if (servers_num[i] && servers_num[i]->hops > max_hop)
2780             max_hop = servers_num[i]->hops;
2781     for (hop=1; hop<=max_hop; hop++) {
2782         for (i=0;i<ArrayLength(servers_num);i++) {
2783             if (servers_num[i]
2784                 && (servers_num[i]->hops == hop)
2785                 && (servers_num[i] != self->uplink))
2786                 irc_server(servers_num[i]);
2787         }
2788     }
2789
2790     /* burst local nicks */
2791     for (i=0; i<=self->num_mask; i++)
2792         if (self->users[i])
2793             irc_user(self->users[i]);
2794
2795     /* build dict of unbursted channel names (just copy existing channels) */
2796     unbursted_channels = dict_new();
2797     for (it = dict_first(channels); it; it = iter_next(it))
2798         dict_insert(unbursted_channels, iter_key(it), iter_data(it));
2799 }
2800
2801 /*
2802  * Oplevel parsing
2803  */
2804 static int
2805 parse_oplevel(char *str)
2806 {
2807     int oplevel = 0;
2808     while (isdigit(*str))
2809         oplevel = oplevel * 10 + *str++ - '0';
2810     return oplevel;
2811 }