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