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