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