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