Author: Kev <klmitch@mit.edu>
[ircu2.10.12-pk.git] / ircd / channel.c
1 /*
2  * IRC - Internet Relay Chat, ircd/channel.c
3  * Copyright (C) 1990 Jarkko Oikarinen and
4  *                    University of Oulu, Co Center
5  *
6  * This program 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 1, or (at your option)
9  * 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 this program; if not, write to the Free Software
18  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  *
20  * $Id$
21  */
22 #include "config.h"
23
24 #include "channel.h"
25 #include "client.h"
26 #include "hash.h"
27 #include "ircd.h"
28 #include "ircd_alloc.h"
29 #include "ircd_chattr.h"
30 #include "ircd_defs.h"
31 #include "ircd_features.h"
32 #include "ircd_log.h"
33 #include "ircd_policy.h"
34 #include "ircd_reply.h"
35 #include "ircd_snprintf.h"
36 #include "ircd_string.h"
37 #include "list.h"
38 #include "match.h"
39 #include "msg.h"
40 #include "msgq.h"
41 #include "numeric.h"
42 #include "numnicks.h"
43 #include "querycmds.h"
44 #include "s_bsd.h"
45 #include "s_conf.h"
46 #include "s_debug.h"
47 #include "s_misc.h"
48 #include "s_user.h"
49 #include "send.h"
50 #include "struct.h"
51 #include "support.h"
52 #include "sys.h"
53 #include "whowas.h"
54
55 #include <assert.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59
60 struct Channel* GlobalChannelList = 0;
61
62 static unsigned int membershipAllocCount;
63 static struct Membership* membershipFreeList;
64
65 static struct SLink *next_overlapped_ban(void);
66 static int del_banid(struct Channel *, char *, int);
67 void del_invite(struct Client *, struct Channel *);
68
69 const char* const PartFmt1     = ":%s " MSG_PART " %s";
70 const char* const PartFmt2     = ":%s " MSG_PART " %s :%s";
71 const char* const PartFmt1serv = "%s%s " TOK_PART " %s";
72 const char* const PartFmt2serv = "%s%s " TOK_PART " %s :%s";
73
74
75 static struct SLink* next_ban;
76 static struct SLink* prev_ban;
77 static struct SLink* removed_bans_list;
78
79 /*
80  * Use a global variable to remember if an oper set a mode on a local channel. Ugly,
81  * but the only way to do it without changing set_mode intensively.
82  */
83 int LocalChanOperMode = 0;
84
85 #if !defined(NDEBUG)
86 /*
87  * return the length (>=0) of a chain of links.
88  */
89 static int list_length(struct SLink *lp)
90 {
91   int count = 0;
92
93   for (; lp; lp = lp->next)
94     ++count;
95   return count;
96 }
97 #endif
98
99 struct Membership* find_member_link(struct Channel* chptr, const struct Client* cptr)
100 {
101   struct Membership *m;
102   assert(0 != cptr);
103   assert(0 != chptr);
104   
105   /* Servers don't have member links */
106   if (IsServer(cptr)||IsMe(cptr))
107      return 0;
108   
109   /* +k users are typically on a LOT of channels.  So we iterate over who
110    * is in the channel.  X/W are +k and are in about 5800 channels each.
111    * however there are typically no more than 1000 people in a channel
112    * at a time.
113    */
114   if (IsChannelService(cptr)) {
115     m = chptr->members;
116     while (m) {
117       assert(m->channel == chptr);
118       if (m->user == cptr)
119         return m;
120       m = m->next_member;
121     }
122   }
123   /* Users on the other hand aren't allowed on more than 15 channels.  50%
124    * of users that are on channels are on 2 or less, 95% are on 7 or less,
125    * and 99% are on 10 or less.
126    */
127   else {
128    m = (cli_user(cptr))->channel;
129    while (m) {
130      assert(m->user == cptr);
131      if (m->channel == chptr)
132        return m;
133      m = m->next_channel;
134    }
135   }
136   return 0;
137 }
138
139 /*
140  * find_chasing - Find the client structure for a nick name (user)
141  * using history mechanism if necessary. If the client is not found, an error
142  * message (NO SUCH NICK) is generated. If the client was found
143  * through the history, chasing will be 1 and otherwise 0.
144  */
145 struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
146 {
147   struct Client* who = FindClient(user);
148
149   if (chasing)
150     *chasing = 0;
151   if (who)
152     return who;
153
154   if (!(who = get_history(user, feature_int(FEAT_KILLCHASETIMELIMIT)))) {
155     send_reply(sptr, ERR_NOSUCHNICK, user);
156     return 0;
157   }
158   if (chasing)
159     *chasing = 1;
160   return who;
161 }
162
163 /*
164  * Create a string of form "foo!bar@fubar" given foo, bar and fubar
165  * as the parameters.  If NULL, they become "*".
166  */
167 static char *make_nick_user_host(const char *nick, const char *name,
168                                  const char *host)
169 {
170   static char namebuf[NICKLEN + USERLEN + HOSTLEN + 3];
171   ircd_snprintf(0, namebuf, sizeof(namebuf), "%s!%s@%s", nick, name, host);
172   return namebuf;
173 }
174
175 /*
176  * Create a string of form "foo!bar@123.456.789.123" given foo, bar and the
177  * IP-number as the parameters.  If NULL, they become "*".
178  */
179 static char *make_nick_user_ip(char *nick, char *name, struct in_addr ip)
180 {
181   static char ipbuf[NICKLEN + USERLEN + 16 + 3];
182   ircd_snprintf(0, ipbuf, sizeof(ipbuf), "%s!%s@%s", nick, name,
183                 ircd_ntoa((const char*) &ip));
184   return ipbuf;
185 }
186
187 /*
188  * Subtract one user from channel i (and free channel
189  * block, if channel became empty).
190  * Returns: true  (1) if channel still exists
191  *          false (0) if the channel was destroyed
192  */
193 int sub1_from_channel(struct Channel* chptr)
194 {
195   struct SLink *tmp;
196   struct SLink *obtmp;
197
198   if (chptr->users > 1)         /* Can be 0, called for an empty channel too */
199   {
200     assert(0 != chptr->members);
201     --chptr->users;
202     return 1;
203   }
204
205   assert(0 == chptr->members);
206
207   /* Channel became (or was) empty: Remove channel */
208   if (is_listed(chptr))
209   {
210     int i;
211     for (i = 0; i <= HighestFd; i++)
212     {
213       struct Client *acptr = 0;
214       if ((acptr = LocalClientArray[i]) && cli_listing(acptr) &&
215           (cli_listing(acptr))->chptr == chptr)
216       {
217         list_next_channels(acptr, 1);
218         break;                  /* Only one client can list a channel */
219       }
220     }
221   }
222   /*
223    * Now, find all invite links from channel structure
224    */
225   while ((tmp = chptr->invites))
226     del_invite(tmp->value.cptr, chptr);
227
228   tmp = chptr->banlist;
229   while (tmp)
230   {
231     obtmp = tmp;
232     tmp = tmp->next;
233     MyFree(obtmp->value.ban.banstr);
234     MyFree(obtmp->value.ban.who);
235     free_link(obtmp);
236   }
237   if (chptr->prev)
238     chptr->prev->next = chptr->next;
239   else
240     GlobalChannelList = chptr->next;
241   if (chptr->next)
242     chptr->next->prev = chptr->prev;
243   hRemChannel(chptr);
244   --UserStats.channels;
245   /*
246    * make sure that channel actually got removed from hash table
247    */
248   assert(chptr->hnext == chptr);
249   MyFree(chptr);
250   return 0;
251 }
252
253 /*
254  * add_banid
255  *
256  * `cptr' must be the client adding the ban.
257  *
258  * If `change' is true then add `banid' to channel `chptr'.
259  * Returns 0 if the ban was added.
260  * Returns -2 if the ban already existed and was marked CHFL_BURST_BAN_WIPEOUT.
261  * Return -1 otherwise.
262  *
263  * Those bans that overlapped with `banid' are flagged with CHFL_BAN_OVERLAPPED
264  * when `change' is false, otherwise they will be removed from the banlist.
265  * Subsequently calls to next_overlapped_ban() or next_removed_overlapped_ban()
266  * respectively will return these bans until NULL is returned.
267  *
268  * If `firsttime' is true, the ban list as returned by next_overlapped_ban()
269  * is reset (unless a non-zero value is returned, in which case the
270  * CHFL_BAN_OVERLAPPED flag might not have been reset!).
271  *
272  * --Run
273  */
274 int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
275                      int change, int firsttime)
276 {
277   struct SLink*  ban;
278   struct SLink** banp;
279   int            cnt = 0;
280   int            removed_bans = 0;
281   int            len = strlen(banid);
282
283   if (firsttime)
284   {
285     next_ban = NULL;
286     assert(0 == prev_ban);
287     assert(0 == removed_bans_list);
288   }
289   if (MyUser(cptr))
290     collapse(banid);
291   for (banp = &chptr->banlist; *banp;)
292   {
293     len += strlen((*banp)->value.ban.banstr);
294     ++cnt;
295     if (((*banp)->flags & CHFL_BURST_BAN_WIPEOUT))
296     {
297       if (!strcmp((*banp)->value.ban.banstr, banid))
298       {
299         (*banp)->flags &= ~CHFL_BURST_BAN_WIPEOUT;
300         return -2;
301       }
302     }
303     else if (!mmatch((*banp)->value.ban.banstr, banid))
304       return -1;
305     if (!mmatch(banid, (*banp)->value.ban.banstr))
306     {
307       struct SLink *tmp = *banp;
308       if (change)
309       {
310         if (MyUser(cptr))
311         {
312           cnt--;
313           len -= strlen(tmp->value.ban.banstr);
314         }
315         *banp = tmp->next;
316         /* These will be sent to the user later as -b */
317         tmp->next = removed_bans_list;
318         removed_bans_list = tmp;
319         removed_bans = 1;
320       }
321       else if (!(tmp->flags & CHFL_BURST_BAN_WIPEOUT))
322       {
323         tmp->flags |= CHFL_BAN_OVERLAPPED;
324         if (!next_ban)
325           next_ban = tmp;
326         banp = &tmp->next;
327       }
328       else
329         banp = &tmp->next;
330     }
331     else
332     {
333       if (firsttime)
334         (*banp)->flags &= ~CHFL_BAN_OVERLAPPED;
335       banp = &(*banp)->next;
336     }
337   }
338   if (MyUser(cptr) && !removed_bans &&
339       (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
340        (cnt >= feature_int(FEAT_MAXBANS))))
341   {
342     send_reply(cptr, ERR_BANLISTFULL, chptr->chname, banid);
343     return -1;
344   }
345   if (change)
346   {
347     char*              ip_start;
348     struct Membership* member;
349     ban = make_link();
350     ban->next = chptr->banlist;
351
352     ban->value.ban.banstr = (char*) MyMalloc(strlen(banid) + 1);
353     assert(0 != ban->value.ban.banstr);
354     strcpy(ban->value.ban.banstr, banid);
355
356 #ifdef HEAD_IN_SAND_BANWHO
357     if (IsServer(cptr))
358       DupString(ban->value.ban.who, cli_name(&me));
359     else
360 #endif
361       DupString(ban->value.ban.who, cli_name(cptr));
362     assert(0 != ban->value.ban.who);
363
364     ban->value.ban.when = TStime();
365     ban->flags = CHFL_BAN;      /* This bit is never used I think... */
366     if ((ip_start = strrchr(banid, '@')) && check_if_ipmask(ip_start + 1))
367       ban->flags |= CHFL_BAN_IPMASK;
368     chptr->banlist = ban;
369
370     /*
371      * Erase ban-valid-bit
372      */
373     for (member = chptr->members; member; member = member->next_member)
374       ClearBanValid(member);     /* `ban' == channel member ! */
375   }
376   return 0;
377 }
378
379 static struct SLink *next_overlapped_ban(void)
380 {
381   struct SLink *tmp = next_ban;
382   if (tmp)
383   {
384     struct SLink *ban;
385     for (ban = tmp->next; ban; ban = ban->next)
386       if ((ban->flags & CHFL_BAN_OVERLAPPED))
387         break;
388     next_ban = ban;
389   }
390   return tmp;
391 }
392
393 struct SLink *next_removed_overlapped_ban(void)
394 {
395   struct SLink *tmp = removed_bans_list;
396   if (prev_ban)
397   {
398     if (prev_ban->value.ban.banstr)     /* Can be set to NULL in set_mode() */
399       MyFree(prev_ban->value.ban.banstr);
400     MyFree(prev_ban->value.ban.who);
401     free_link(prev_ban);
402     prev_ban = 0;
403   }
404   if (tmp)
405     removed_bans_list = removed_bans_list->next;
406   prev_ban = tmp;
407   return tmp;
408 }
409
410 /*
411  * del_banid
412  *
413  * If `change' is true, delete `banid' from channel `chptr'.
414  * Returns `false' if removal was (or would have been) successful.
415  */
416 static int del_banid(struct Channel *chptr, char *banid, int change)
417 {
418   struct SLink **ban;
419   struct SLink *tmp;
420
421   if (!banid)
422     return -1;
423   for (ban = &(chptr->banlist); *ban; ban = &((*ban)->next)) {
424     if (0 == ircd_strcmp(banid, (*ban)->value.ban.banstr))
425     {
426       tmp = *ban;
427       if (change)
428       {
429         struct Membership* member;
430         *ban = tmp->next;
431         MyFree(tmp->value.ban.banstr);
432         MyFree(tmp->value.ban.who);
433         free_link(tmp);
434         /*
435          * Erase ban-valid-bit, for channel members that are banned
436          */
437         for (member = chptr->members; member; member = member->next_member)
438           if (CHFL_BANVALIDMASK == (member->status & CHFL_BANVALIDMASK))
439             ClearBanValid(member);       /* `tmp' == channel member */
440       }
441       return 0;
442     }
443   }
444   return -1;
445 }
446
447 /*
448  * find_channel_member - returns Membership * if a person is joined and not a zombie
449  */
450 struct Membership* find_channel_member(struct Client* cptr, struct Channel* chptr)
451 {
452   struct Membership* member;
453   assert(0 != chptr);
454
455   member = find_member_link(chptr, cptr);
456   return (member && !IsZombie(member)) ? member : 0;
457 }
458
459 /*
460  * is_banned - a non-zero value if banned else 0.
461  */
462 static int is_banned(struct Client *cptr, struct Channel *chptr,
463                      struct Membership* member)
464 {
465   struct SLink* tmp;
466   char*         s;
467   char*         ip_s = NULL;
468
469   if (!IsUser(cptr))
470     return 0;
471
472   if (member && IsBanValid(member))
473     return IsBanned(member);
474
475   s = make_nick_user_host(cli_name(cptr), (cli_user(cptr))->username,
476                           (cli_user(cptr))->host);
477
478   for (tmp = chptr->banlist; tmp; tmp = tmp->next) {
479     if ((tmp->flags & CHFL_BAN_IPMASK)) {
480       if (!ip_s)
481         ip_s = make_nick_user_ip(cli_name(cptr), (cli_user(cptr))->username,
482                                  cli_ip(cptr));
483       if (match(tmp->value.ban.banstr, ip_s) == 0)
484         break;
485     }
486     else if (match(tmp->value.ban.banstr, s) == 0)
487       break;
488   }
489
490   if (member) {
491     SetBanValid(member);
492     if (tmp) {
493       SetBanned(member);
494       return 1;
495     }
496     else {
497       ClearBanned(member);
498       return 0;
499     }
500   }
501
502   return (tmp != NULL);
503 }
504
505 /*
506  * adds a user to a channel by adding another link to the channels member
507  * chain.
508  */
509 void add_user_to_channel(struct Channel* chptr, struct Client* who,
510                                 unsigned int flags)
511 {
512   assert(0 != chptr);
513   assert(0 != who);
514
515   if (cli_user(who)) {
516    
517     struct Membership* member = membershipFreeList;
518     if (member)
519       membershipFreeList = member->next_member;
520     else {
521       member = (struct Membership*) MyMalloc(sizeof(struct Membership));
522       ++membershipAllocCount;
523     }
524
525     assert(0 != member);
526     member->user         = who;
527     member->channel      = chptr;
528     member->status       = flags;
529
530     member->next_member  = chptr->members;
531     if (member->next_member)
532       member->next_member->prev_member = member;
533     member->prev_member  = 0; 
534     chptr->members       = member;
535
536     member->next_channel = (cli_user(who))->channel;
537     if (member->next_channel)
538       member->next_channel->prev_channel = member;
539     member->prev_channel = 0;
540     (cli_user(who))->channel = member;
541
542     ++chptr->users;
543     ++((cli_user(who))->joined);
544   }
545 }
546
547 static int remove_member_from_channel(struct Membership* member)
548 {
549   struct Channel* chptr;
550   assert(0 != member);
551   chptr = member->channel;
552   /*
553    * unlink channel member list
554    */
555   if (member->next_member)
556     member->next_member->prev_member = member->prev_member;
557   if (member->prev_member)
558     member->prev_member->next_member = member->next_member;
559   else
560     member->channel->members = member->next_member; 
561       
562   /*
563    * unlink client channel list
564    */
565   if (member->next_channel)
566     member->next_channel->prev_channel = member->prev_channel;
567   if (member->prev_channel)
568     member->prev_channel->next_channel = member->next_channel;
569   else
570     (cli_user(member->user))->channel = member->next_channel;
571
572   --(cli_user(member->user))->joined;
573
574   member->next_member = membershipFreeList;
575   membershipFreeList = member;
576
577   return sub1_from_channel(chptr);
578 }
579
580 static int channel_all_zombies(struct Channel* chptr)
581 {
582   struct Membership* member;
583
584   for (member = chptr->members; member; member = member->next_member) {
585     if (!IsZombie(member))
586       return 0;
587   }
588   return 1;
589 }
590       
591
592 void remove_user_from_channel(struct Client* cptr, struct Channel* chptr)
593 {
594   
595   struct Membership* member;
596   assert(0 != chptr);
597
598   if ((member = find_member_link(chptr, cptr))) {
599     if (remove_member_from_channel(member)) {
600       if (channel_all_zombies(chptr)) {
601         /*
602          * XXX - this looks dangerous but isn't if we got the referential
603          * integrity right for channels
604          */
605         while (remove_member_from_channel(chptr->members))
606           ;
607       }
608     }
609   }
610 }
611
612 void remove_user_from_all_channels(struct Client* cptr)
613 {
614   struct Membership* chan;
615   assert(0 != cptr);
616   assert(0 != cli_user(cptr));
617
618   while ((chan = (cli_user(cptr))->channel))
619     remove_user_from_channel(cptr, chan->channel);
620 }
621
622 int is_chan_op(struct Client *cptr, struct Channel *chptr)
623 {
624   struct Membership* member;
625   assert(chptr);
626   if ((member = find_member_link(chptr, cptr)))
627     return (!IsZombie(member) && IsChanOp(member));
628
629   return 0;
630 }
631
632 static int is_deopped(struct Client *cptr, struct Channel *chptr)
633 {
634   struct Membership* member;
635
636   assert(0 != chptr);
637   if ((member = find_member_link(chptr, cptr)))
638     return IsDeopped(member);
639
640   return (IsUser(cptr) ? 1 : 0);
641 }
642
643 int is_zombie(struct Client *cptr, struct Channel *chptr)
644 {
645   struct Membership* member;
646
647   assert(0 != chptr);
648
649   if ((member = find_member_link(chptr, cptr)))
650       return IsZombie(member);
651   return 0;
652 }
653
654 int has_voice(struct Client* cptr, struct Channel* chptr)
655 {
656   struct Membership* member;
657
658   assert(0 != chptr);
659   if ((member = find_member_link(chptr, cptr)))
660     return (!IsZombie(member) && HasVoice(member));
661
662   return 0;
663 }
664
665 int member_can_send_to_channel(struct Membership* member)
666 {
667   assert(0 != member);
668
669   if (IsVoicedOrOpped(member))
670     return 1;
671   /*
672    * If it's moderated, and you aren't a priviledged user, you can't
673    * speak.  
674    */
675   if (member->channel->mode.mode & MODE_MODERATED)
676     return 0;
677   /*
678    * If you're banned then you can't speak either.
679    * but because of the amount of CPU time that is_banned chews
680    * we only check it for our clients.
681    */
682   if (MyUser(member->user) && is_banned(member->user, member->channel, member))
683     return 0;
684   return 1;
685 }
686
687 int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr)
688 {
689   struct Membership *member;
690   assert(0 != cptr); 
691   /*
692    * Servers can always speak on channels.
693    */
694   if (IsServer(cptr))
695     return 1;
696
697   member = find_channel_member(cptr, chptr);
698
699   /*
700    * You can't speak if your off channel, if the channel is modeless, or
701    * +n (no external messages) or +m (moderated).
702    */
703   if (!member) {
704     if ((chptr->mode.mode & (MODE_NOPRIVMSGS|MODE_MODERATED)) 
705         || IsModelessChannel(chptr->chname)) 
706       return 0;
707     else
708       return 1;
709   }
710   return member_can_send_to_channel(member); 
711 }
712
713 /*
714  * find_no_nickchange_channel
715  * if a member and not opped or voiced and banned
716  * return the name of the first channel banned on
717  */
718 const char* find_no_nickchange_channel(struct Client* cptr)
719 {
720   if (MyUser(cptr)) {
721     struct Membership* member;
722     for (member = (cli_user(cptr))->channel; member;
723          member = member->next_channel) {
724       if (!IsVoicedOrOpped(member) && is_banned(cptr, member->channel, member))
725         return member->channel->chname;
726     }
727   }
728   return 0;
729 }
730
731
732 /*
733  * write the "simple" list of channel modes for channel chptr onto buffer mbuf
734  * with the parameters in pbuf.
735  */
736 void channel_modes(struct Client *cptr, char *mbuf, char *pbuf,
737                           struct Channel *chptr)
738 {
739   assert(0 != mbuf);
740   assert(0 != pbuf);
741   assert(0 != chptr);
742
743   *mbuf++ = '+';
744   if (chptr->mode.mode & MODE_SECRET)
745     *mbuf++ = 's';
746   else if (chptr->mode.mode & MODE_PRIVATE)
747     *mbuf++ = 'p';
748   if (chptr->mode.mode & MODE_MODERATED)
749     *mbuf++ = 'm';
750   if (chptr->mode.mode & MODE_TOPICLIMIT)
751     *mbuf++ = 't';
752   if (chptr->mode.mode & MODE_INVITEONLY)
753     *mbuf++ = 'i';
754   if (chptr->mode.mode & MODE_NOPRIVMSGS)
755     *mbuf++ = 'n';
756   if (chptr->mode.limit) {
757     *mbuf++ = 'l';
758     ircd_snprintf(0, pbuf, sizeof(pbuf), "%d", chptr->mode.limit);
759   }
760
761   if (*chptr->mode.key) {
762     *mbuf++ = 'k';
763     if (chptr->mode.limit)
764       strcat(pbuf, " ");
765     if (is_chan_op(cptr, chptr) || IsServer(cptr)) {
766       strcat(pbuf, chptr->mode.key);
767     } else
768       strcat(pbuf, "*");
769   }
770   *mbuf = '\0';
771 }
772
773 /*
774  * send "cptr" a full list of the modes for channel chptr.
775  */
776 void send_channel_modes(struct Client *cptr, struct Channel *chptr)
777 {
778   static unsigned int current_flags[4] =
779       { 0, CHFL_CHANOP | CHFL_VOICE, CHFL_VOICE, CHFL_CHANOP };
780   int                first = 1;
781   int                full  = 1;
782   int                flag_cnt = 0;
783   int                new_mode = 0;
784   size_t             len;
785   struct Membership* member;
786   struct SLink*      lp2;
787   char modebuf[MODEBUFLEN];
788   char parabuf[MODEBUFLEN];
789   struct MsgBuf *mb;
790
791   assert(0 != cptr);
792   assert(0 != chptr); 
793
794   if (IsLocalChannel(chptr->chname))
795     return;
796
797   member = chptr->members;
798   lp2 = chptr->banlist;
799
800   *modebuf = *parabuf = '\0';
801   channel_modes(cptr, modebuf, parabuf, chptr);
802
803   for (first = 1; full; first = 0)      /* Loop for multiple messages */
804   {
805     full = 0;                   /* Assume by default we get it
806                                  all in one message */
807
808     /* (Continued) prefix: "<Y> B <channel> <TS>" */
809     /* is there any better way we can do this? */
810     mb = msgq_make(&me, "%C " TOK_BURST " %H %Tu", &me, chptr,
811                    chptr->creationtime);
812
813     if (first && modebuf[1])    /* Add simple modes (iklmnpst)
814                                  if first message */
815     {
816       /* prefix: "<Y> B <channel> <TS>[ <modes>[ <params>]]" */
817       msgq_append(&me, mb, " %s", modebuf);
818
819       if (*parabuf)
820         msgq_append(&me, mb, " %s", parabuf);
821     }
822
823     /*
824      * Attach nicks, comma seperated " nick[:modes],nick[:modes],..."
825      *
826      * Run 4 times over all members, to group the members with the
827      * same mode together
828      */
829     for (first = 1; flag_cnt < 4;
830          member = chptr->members, new_mode = 1, flag_cnt++)
831     {
832       for (; member; member = member->next_member)
833       {
834         if ((member->status & CHFL_VOICED_OR_OPPED) !=
835             current_flags[flag_cnt])
836           continue;             /* Skip members with different flags */
837         if (msgq_bufleft(mb) < NUMNICKLEN + 4)
838           /* The 4 is a possible ",:ov" */
839         {
840           full = 1;           /* Make sure we continue after
841                                  sending it so far */
842           new_mode = 1;       /* Ensure the new BURST line contains the current
843                                  mode. --Gte */
844           break;              /* Do not add this member to this message */
845         }
846         msgq_append(&me, mb, "%c%C", first ? ' ' : ',', member->user);
847         first = 0;              /* From now on, us comma's to add new nicks */
848
849         /*
850          * Do we have a nick with a new mode ?
851          * Or are we starting a new BURST line?
852          */
853         if (new_mode)
854         {
855           new_mode = 0;
856           if (IsVoicedOrOpped(member)) {
857             char tbuf[4] = ":";
858             int loc = 1;
859
860             if (IsChanOp(member))
861               tbuf[loc++] = 'o';
862             if (HasVoice(member))
863               tbuf[loc++] = 'v';
864             tbuf[loc] = '\0';
865             msgq_append(&me, mb, tbuf);
866           }
867         }
868       }
869       if (full)
870         break;
871     }
872
873     if (!full)
874     {
875       /* Attach all bans, space seperated " :%ban ban ..." */
876       for (first = 2; lp2; lp2 = lp2->next)
877       {
878         len = strlen(lp2->value.ban.banstr);
879         if (msgq_bufleft(mb) < len + 1 + first)
880           /* The +1 stands for the added ' '.
881            * The +first stands for the added ":%".
882            */
883         {
884           full = 1;
885           break;
886         }
887         msgq_append(&me, mb, " %s%s", first ? ":%" : "",
888                     lp2->value.ban.banstr);
889         first = 0;
890       }
891     }
892
893     send_buffer(cptr, mb, 0);  /* Send this message */
894     msgq_clean(mb);
895   }                             /* Continue when there was something
896                                  that didn't fit (full==1) */
897 }
898
899 /*
900  * pretty_mask
901  *
902  * by Carlo Wood (Run), 05 Oct 1998.
903  *
904  * Canonify a mask.
905  *
906  * When the nick is longer then NICKLEN, it is cut off (its an error of course).
907  * When the user name or host name are too long (USERLEN and HOSTLEN
908  * respectively) then they are cut off at the start with a '*'.
909  *
910  * The following transformations are made:
911  *
912  * 1)   xxx             -> nick!*@*
913  * 2)   xxx.xxx         -> *!*@host
914  * 3)   xxx!yyy         -> nick!user@*
915  * 4)   xxx@yyy         -> *!user@host
916  * 5)   xxx!yyy@zzz     -> nick!user@host
917  */
918 char *pretty_mask(char *mask)
919 {
920   static char star[2] = { '*', 0 };
921   char *last_dot = NULL;
922   char *ptr;
923
924   /* Case 1: default */
925   char *nick = mask;
926   char *user = star;
927   char *host = star;
928
929   /* Do a _single_ pass through the characters of the mask: */
930   for (ptr = mask; *ptr; ++ptr)
931   {
932     if (*ptr == '!')
933     {
934       /* Case 3 or 5: Found first '!' (without finding a '@' yet) */
935       user = ++ptr;
936       host = star;
937     }
938     else if (*ptr == '@')
939     {
940       /* Case 4: Found last '@' (without finding a '!' yet) */
941       nick = star;
942       user = mask;
943       host = ++ptr;
944     }
945     else if (*ptr == '.')
946     {
947       /* Case 2: Found last '.' (without finding a '!' or '@' yet) */
948       last_dot = ptr;
949       continue;
950     }
951     else
952       continue;
953     for (; *ptr; ++ptr)
954     {
955       if (*ptr == '@')
956       {
957         /* Case 4 or 5: Found last '@' */
958         host = ptr + 1;
959       }
960     }
961     break;
962   }
963   if (user == star && last_dot)
964   {
965     /* Case 2: */
966     nick = star;
967     user = star;
968     host = mask;
969   }
970   /* Check lengths */
971   if (nick != star)
972   {
973     char *nick_end = (user != star) ? user - 1 : ptr;
974     if (nick_end - nick > NICKLEN)
975       nick[NICKLEN] = 0;
976     *nick_end = 0;
977   }
978   if (user != star)
979   {
980     char *user_end = (host != star) ? host - 1 : ptr;
981     if (user_end - user > USERLEN)
982     {
983       user = user_end - USERLEN;
984       *user = '*';
985     }
986     *user_end = 0;
987   }
988   if (host != star && ptr - host > HOSTLEN)
989   {
990     host = ptr - HOSTLEN;
991     *host = '*';
992   }
993   return make_nick_user_host(nick, user, host);
994 }
995
996 static void send_ban_list(struct Client* cptr, struct Channel* chptr)
997 {
998   struct SLink* lp;
999
1000   assert(0 != cptr);
1001   assert(0 != chptr);
1002
1003   for (lp = chptr->banlist; lp; lp = lp->next)
1004     send_reply(cptr, RPL_BANLIST, chptr->chname, lp->value.ban.banstr,
1005                lp->value.ban.who, lp->value.ban.when);
1006
1007   send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
1008 }
1009
1010 /* We are now treating the <key> part of /join <channel list> <key> as a key
1011  * ring; that is, we try one key against the actual channel key, and if that
1012  * doesn't work, we try the next one, and so on. -Kev -Texaco
1013  * Returns: 0 on match, 1 otherwise
1014  * This version contributed by SeKs <intru@info.polymtl.ca>
1015  */
1016 static int compall(char *key, char *keyring)
1017 {
1018   char *p1;
1019
1020 top:
1021   p1 = key;                     /* point to the key... */
1022   while (*p1 && *p1 == *keyring)
1023   {                             /* step through the key and ring until they
1024                                    don't match... */
1025     p1++;
1026     keyring++;
1027   }
1028
1029   if (!*p1 && (!*keyring || *keyring == ','))
1030     /* ok, if we're at the end of the and also at the end of one of the keys
1031        in the keyring, we have a match */
1032     return 0;
1033
1034   if (!*keyring)                /* if we're at the end of the key ring, there
1035                                    weren't any matches, so we return 1 */
1036     return 1;
1037
1038   /* Not at the end of the key ring, so step
1039      through to the next key in the ring: */
1040   while (*keyring && *(keyring++) != ',');
1041
1042   goto top;                     /* and check it against the key */
1043 }
1044
1045 int can_join(struct Client *sptr, struct Channel *chptr, char *key)
1046 {
1047   struct SLink *lp;
1048   int overrideJoin = 0;  
1049   
1050   /*
1051    * Now a banned user CAN join if invited -- Nemesi
1052    * Now a user CAN escape channel limit if invited -- bfriendly
1053    * Now a user CAN escape anything if invited -- Isomer
1054    */
1055
1056   for (lp = (cli_user(sptr))->invited; lp; lp = lp->next)
1057     if (lp->value.chptr == chptr)
1058       return 0;
1059   
1060   /* An oper can force a join on a local channel using "OVERRIDE" as the key. 
1061      a HACK(4) notice will be sent if he would not have been supposed
1062      to join normally. */ 
1063   if (IsLocalChannel(chptr->chname) && HasPriv(sptr, PRIV_WALK_LCHAN) &&
1064       !BadPtr(key) && compall("OVERRIDE",key) == 0)
1065     overrideJoin = MAGIC_OPER_OVERRIDE;
1066
1067   if (chptr->mode.mode & MODE_INVITEONLY)
1068         return overrideJoin + ERR_INVITEONLYCHAN;
1069         
1070   if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
1071         return overrideJoin + ERR_CHANNELISFULL;
1072         
1073   if (is_banned(sptr, chptr, NULL))
1074         return overrideJoin + ERR_BANNEDFROMCHAN;
1075   
1076   /*
1077    * now using compall (above) to test against a whole key ring -Kev
1078    */
1079   if (*chptr->mode.key && (EmptyString(key) || compall(chptr->mode.key, key)))
1080     return overrideJoin + ERR_BADCHANNELKEY;
1081
1082   if (overrideJoin)     
1083         return ERR_DONTCHEAT;
1084         
1085   return 0;
1086 }
1087
1088 /*
1089  * Remove bells and commas from channel name
1090  */
1091 void clean_channelname(char *cn)
1092 {
1093   int i;
1094
1095   for (i = 0; cn[i]; i++) {
1096     if (i >= CHANNELLEN || !IsChannelChar(cn[i])) {
1097       cn[i] = '\0';
1098       return;
1099     }
1100     if (IsChannelLower(cn[i])) {
1101       cn[i] = ToLower(cn[i]);
1102 #ifndef FIXME
1103       /*
1104        * Remove for .08+
1105        * toupper(0xd0)
1106        */
1107       if ((unsigned char)(cn[i]) == 0xd0)
1108         cn[i] = (char) 0xf0;
1109 #endif
1110     }
1111   }
1112 }
1113
1114 /*
1115  *  Get Channel block for i (and allocate a new channel
1116  *  block, if it didn't exists before).
1117  */
1118 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
1119 {
1120   struct Channel *chptr;
1121   int len;
1122
1123   if (EmptyString(chname))
1124     return NULL;
1125
1126   len = strlen(chname);
1127   if (MyUser(cptr) && len > CHANNELLEN)
1128   {
1129     len = CHANNELLEN;
1130     *(chname + CHANNELLEN) = '\0';
1131   }
1132   if ((chptr = FindChannel(chname)))
1133     return (chptr);
1134   if (flag == CGT_CREATE)
1135   {
1136     chptr = (struct Channel*) MyMalloc(sizeof(struct Channel) + len);
1137     assert(0 != chptr);
1138     ++UserStats.channels;
1139     memset(chptr, 0, sizeof(struct Channel));
1140     strcpy(chptr->chname, chname);
1141     if (GlobalChannelList)
1142       GlobalChannelList->prev = chptr;
1143     chptr->prev = NULL;
1144     chptr->next = GlobalChannelList;
1145     chptr->creationtime = MyUser(cptr) ? TStime() : (time_t) 0;
1146     GlobalChannelList = chptr;
1147     hAddChannel(chptr);
1148   }
1149   return chptr;
1150 }
1151
1152 void add_invite(struct Client *cptr, struct Channel *chptr)
1153 {
1154   struct SLink *inv, **tmp;
1155
1156   del_invite(cptr, chptr);
1157   /*
1158    * Delete last link in chain if the list is max length
1159    */
1160   assert(list_length((cli_user(cptr))->invited) == (cli_user(cptr))->invites);
1161   if ((cli_user(cptr))->invites >= feature_int(FEAT_MAXCHANNELSPERUSER))
1162     del_invite(cptr, (cli_user(cptr))->invited->value.chptr);
1163   /*
1164    * Add client to channel invite list
1165    */
1166   inv = make_link();
1167   inv->value.cptr = cptr;
1168   inv->next = chptr->invites;
1169   chptr->invites = inv;
1170   /*
1171    * Add channel to the end of the client invite list
1172    */
1173   for (tmp = &((cli_user(cptr))->invited); *tmp; tmp = &((*tmp)->next));
1174   inv = make_link();
1175   inv->value.chptr = chptr;
1176   inv->next = NULL;
1177   (*tmp) = inv;
1178   (cli_user(cptr))->invites++;
1179 }
1180
1181 /*
1182  * Delete Invite block from channel invite list and client invite list
1183  */
1184 void del_invite(struct Client *cptr, struct Channel *chptr)
1185 {
1186   struct SLink **inv, *tmp;
1187
1188   for (inv = &(chptr->invites); (tmp = *inv); inv = &tmp->next)
1189     if (tmp->value.cptr == cptr)
1190     {
1191       *inv = tmp->next;
1192       free_link(tmp);
1193       tmp = 0;
1194       (cli_user(cptr))->invites--;
1195       break;
1196     }
1197
1198   for (inv = &((cli_user(cptr))->invited); (tmp = *inv); inv = &tmp->next)
1199     if (tmp->value.chptr == chptr)
1200     {
1201       *inv = tmp->next;
1202       free_link(tmp);
1203       tmp = 0;
1204       break;
1205     }
1206 }
1207
1208 /* List and skip all channels that are listen */
1209 void list_next_channels(struct Client *cptr, int nr)
1210 {
1211   struct ListingArgs *args = cli_listing(cptr);
1212   struct Channel *chptr = args->chptr;
1213   chptr->mode.mode &= ~MODE_LISTED;
1214   while (is_listed(chptr) || --nr >= 0)
1215   {
1216     for (; chptr; chptr = chptr->next)
1217     {
1218       if (!cli_user(cptr) || (SecretChannel(chptr) && !find_channel_member(cptr, chptr)))
1219         continue;
1220       if (chptr->users > args->min_users && chptr->users < args->max_users &&
1221           chptr->creationtime > args->min_time &&
1222           chptr->creationtime < args->max_time &&
1223           (!args->topic_limits || (*chptr->topic &&
1224           chptr->topic_time > args->min_topic_time &&
1225           chptr->topic_time < args->max_topic_time)))
1226       {
1227         if (ShowChannel(cptr,chptr))
1228           send_reply(cptr, RPL_LIST, chptr->chname, chptr->users,
1229                      chptr->topic);
1230         chptr = chptr->next;
1231         break;
1232       }
1233     }
1234     if (!chptr)
1235     {
1236       MyFree(cli_listing(cptr));
1237       cli_listing(cptr) = NULL;
1238       send_reply(cptr, RPL_LISTEND);
1239       break;
1240     }
1241   }
1242   if (chptr)
1243   {
1244     (cli_listing(cptr))->chptr = chptr;
1245     chptr->mode.mode |= MODE_LISTED;
1246   }
1247
1248   update_write(cptr);
1249 }
1250
1251 /*
1252  * Consider:
1253  *
1254  *                     client
1255  *                       |
1256  *                       c
1257  *                       |
1258  *     X --a--> A --b--> B --d--> D
1259  *                       |
1260  *                      who
1261  *
1262  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
1263  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
1264  *
1265  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
1266  *    Remove the user immedeately when no users are left on the channel.
1267  * b) On server B : remove the user (who/lp) from the channel, send a
1268  *    PART upstream (to A) and pass on the KICK.
1269  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
1270  *    channel, and pass on the KICK.
1271  * d) On server D : remove the user (who/lp) from the channel, and pass on
1272  *    the KICK.
1273  *
1274  * Note:
1275  * - Setting the ZOMBIE flag never hurts, we either remove the
1276  *   client after that or we don't.
1277  * - The KICK message was already passed on, as should be in all cases.
1278  * - `who' is removed in all cases except case a) when users are left.
1279  * - A PART is only sent upstream in case b).
1280  *
1281  * 2 aug 97:
1282  *
1283  *              6
1284  *              |
1285  *  1 --- 2 --- 3 --- 4 --- 5
1286  *        |           |
1287  *      kicker       who
1288  *
1289  * We also need to turn 'who' into a zombie on servers 1 and 6,
1290  * because a KICK from 'who' (kicking someone else in that direction)
1291  * can arrive there afterwards - which should not be bounced itself.
1292  * Therefore case a) also applies for servers 1 and 6.
1293  *
1294  * --Run
1295  */
1296 void make_zombie(struct Membership* member, struct Client* who, struct Client* cptr,
1297                  struct Client* sptr, struct Channel* chptr)
1298 {
1299   assert(0 != member);
1300   assert(0 != who);
1301   assert(0 != cptr);
1302   assert(0 != chptr);
1303
1304   /* Default for case a): */
1305   SetZombie(member);
1306
1307   /* Case b) or c) ?: */
1308   if (MyUser(who))      /* server 4 */
1309   {
1310     if (IsServer(cptr)) /* Case b) ? */
1311       sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
1312     remove_user_from_channel(who, chptr);
1313     return;
1314   }
1315   if (cli_from(who) == cptr)        /* True on servers 1, 5 and 6 */
1316   {
1317     struct Client *acptr = IsServer(sptr) ? sptr : (cli_user(sptr))->server;
1318     for (; acptr != &me; acptr = (cli_serv(acptr))->up)
1319       if (acptr == (cli_user(who))->server)   /* Case d) (server 5) */
1320       {
1321         remove_user_from_channel(who, chptr);
1322         return;
1323       }
1324   }
1325
1326   /* Case a) (servers 1, 2, 3 and 6) */
1327   if (channel_all_zombies(chptr))
1328     remove_user_from_channel(who, chptr);
1329
1330   /* XXX Can't actually call Debug here; if the channel is all zombies,
1331    * chptr will no longer exist when we get here.
1332   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
1333   */
1334 }
1335
1336 int number_of_zombies(struct Channel *chptr)
1337 {
1338   struct Membership* member;
1339   int                count = 0;
1340
1341   assert(0 != chptr);
1342   for (member = chptr->members; member; member = member->next_member) {
1343     if (IsZombie(member))
1344       ++count;
1345   }
1346   return count;
1347 }
1348
1349 /*
1350  * This helper function builds an argument string in strptr, consisting
1351  * of the original string, a space, and str1 and str2 concatenated (if,
1352  * of course, str2 is not NULL)
1353  */
1354 static void
1355 build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
1356 {
1357   if (c)
1358     strptr[(*strptr_i)++] = c;
1359
1360   while (*str1)
1361     strptr[(*strptr_i)++] = *(str1++);
1362
1363   if (str2)
1364     while (*str2)
1365       strptr[(*strptr_i)++] = *(str2++);
1366
1367   strptr[(*strptr_i)] = '\0';
1368 }
1369
1370 /*
1371  * This is the workhorse of our ModeBuf suite; this actually generates the
1372  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
1373  */
1374 static int
1375 modebuf_flush_int(struct ModeBuf *mbuf, int all)
1376 {
1377   /* we only need the flags that don't take args right now */
1378   static int flags[] = {
1379 /*  MODE_CHANOP,        'o', */
1380 /*  MODE_VOICE,         'v', */
1381     MODE_PRIVATE,       'p',
1382     MODE_SECRET,        's',
1383     MODE_MODERATED,     'm',
1384     MODE_TOPICLIMIT,    't',
1385     MODE_INVITEONLY,    'i',
1386     MODE_NOPRIVMSGS,    'n',
1387 /*  MODE_KEY,           'k', */
1388 /*  MODE_BAN,           'b', */
1389 /*  MODE_LIMIT,         'l', */
1390     0x0, 0x0
1391   };
1392   int i;
1393   int *flag_p;
1394
1395   struct Client *app_source; /* where the MODE appears to come from */
1396
1397   char addbuf[20]; /* accumulates +psmtin, etc. */
1398   int addbuf_i = 0;
1399   char rembuf[20]; /* accumulates -psmtin, etc. */
1400   int rembuf_i = 0;
1401   char *bufptr; /* we make use of indirection to simplify the code */
1402   int *bufptr_i;
1403
1404   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
1405   int addstr_i;
1406   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
1407   int remstr_i;
1408   char *strptr; /* more indirection to simplify the code */
1409   int *strptr_i;
1410
1411   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
1412   int tmp;
1413
1414   char limitbuf[20]; /* convert limits to strings */
1415
1416   unsigned int limitdel = MODE_LIMIT;
1417
1418   assert(0 != mbuf);
1419
1420   /* If the ModeBuf is empty, we have nothing to do */
1421   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
1422     return 0;
1423
1424   /* Ok, if we were given the OPMODE flag, hide the source if its a user */
1425   if (mbuf->mb_dest & MODEBUF_DEST_OPMODE && !IsServer(mbuf->mb_source))
1426     app_source = &me;
1427   else
1428     app_source = mbuf->mb_source;
1429
1430   /*
1431    * Account for user we're bouncing; we have to get it in on the first
1432    * bounced MODE, or we could have problems
1433    */
1434   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
1435     totalbuflen -= 6; /* numeric nick == 5, plus one space */
1436
1437   /* Calculate the simple flags */
1438   for (flag_p = flags; flag_p[0]; flag_p += 2) {
1439     if (*flag_p & mbuf->mb_add)
1440       addbuf[addbuf_i++] = flag_p[1];
1441     else if (*flag_p & mbuf->mb_rem)
1442       rembuf[rembuf_i++] = flag_p[1];
1443   }
1444
1445   /* Now go through the modes with arguments... */
1446   for (i = 0; i < mbuf->mb_count; i++) {
1447     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1448       bufptr = addbuf;
1449       bufptr_i = &addbuf_i;
1450     } else {
1451       bufptr = rembuf;
1452       bufptr_i = &rembuf_i;
1453     }
1454
1455     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
1456       tmp = strlen(cli_name(MB_CLIENT(mbuf, i)));
1457
1458       if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
1459         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1460       else {
1461         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
1462         totalbuflen -= IRCD_MAX(5, tmp) + 1;
1463       }
1464     } else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN)) {
1465       tmp = strlen(MB_STRING(mbuf, i));
1466
1467       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1468         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1469       else {
1470         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_KEY ? 'k' : 'b';
1471         totalbuflen -= tmp + 1;
1472       }
1473     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
1474       /* if it's a limit, we also format the number */
1475       ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%d", MB_UINT(mbuf, i));
1476
1477       tmp = strlen(limitbuf);
1478
1479       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1480         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1481       else {
1482         bufptr[(*bufptr_i)++] = 'l';
1483         totalbuflen -= tmp + 1;
1484       }
1485     }
1486   }
1487
1488   /* terminate the mode strings */
1489   addbuf[addbuf_i] = '\0';
1490   rembuf[rembuf_i] = '\0';
1491
1492   /* If we're building a user visible MODE or HACK... */
1493   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
1494                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
1495                        MODEBUF_DEST_LOG)) {
1496     /* Set up the parameter strings */
1497     addstr[0] = '\0';
1498     addstr_i = 0;
1499     remstr[0] = '\0';
1500     remstr_i = 0;
1501
1502     for (i = 0; i < mbuf->mb_count; i++) {
1503       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1504         continue;
1505
1506       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1507         strptr = addstr;
1508         strptr_i = &addstr_i;
1509       } else {
1510         strptr = remstr;
1511         strptr_i = &remstr_i;
1512       }
1513
1514       /* deal with clients... */
1515       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1516         build_string(strptr, strptr_i, cli_name(MB_CLIENT(mbuf, i)), 0, ' ');
1517
1518       /* deal with strings... */
1519       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
1520         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1521
1522       /*
1523        * deal with limit; note we cannot include the limit parameter if we're
1524        * removing it
1525        */
1526       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
1527                (MODE_ADD | MODE_LIMIT))
1528         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1529     }
1530
1531     /* send the messages off to their destination */
1532     if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
1533       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
1534                            "[%Tu]",
1535 #ifdef HEAD_IN_SAND_SNOTICES
1536                            cli_name(mbuf->mb_source),
1537 #else
1538                            cli_name(app_source),
1539 #endif
1540                            mbuf->mb_channel->chname,
1541                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1542                            addbuf, remstr, addstr,
1543                            mbuf->mb_channel->creationtime);
1544       sendcmdto_serv_butone(&me, CMD_DESYNCH, mbuf->mb_connect,
1545                             ":HACK: %s MODE %s %s%s%s%s%s%s [%Tu]",
1546 #ifdef HEAD_IN_SAND_SNOTICES
1547                             cli_name(mbuf->mb_source),
1548 #else
1549                             cli_name(app_source),
1550 #endif
1551                             mbuf->mb_channel->chname,
1552                             rembuf_i ? "-" : "", rembuf,
1553                             addbuf_i ? "+" : "", addbuf, remstr, addstr,
1554                             mbuf->mb_channel->creationtime);
1555     }
1556
1557     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
1558       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
1559                            "%s%s%s%s%s%s [%Tu]",
1560 #ifdef HEAD_IN_SAND_SNOTICES
1561                            cli_name(mbuf->mb_source),
1562 #else
1563                            cli_name(app_source),
1564 #endif
1565                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
1566                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
1567                            mbuf->mb_channel->creationtime);
1568
1569     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
1570       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
1571                            "[%Tu]",
1572 #ifdef HEAD_IN_SAND_SNOTICES
1573                            cli_name(mbuf->mb_source),
1574 #else
1575                            cli_name(app_source),
1576 #endif
1577                            mbuf->mb_channel->chname,
1578                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1579                            addbuf, remstr, addstr,
1580                            mbuf->mb_channel->creationtime);
1581
1582     if (mbuf->mb_dest & MODEBUF_DEST_LOG)
1583       log_write(LS_OPERMODE, L_INFO, LOG_NOSNOTICE,
1584                 "%#C OPMODE %H %s%s%s%s%s%s", mbuf->mb_source,
1585                 mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
1586                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1587
1588     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
1589       sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
1590                                 "%H %s%s%s%s%s%s", mbuf->mb_channel,
1591                                 rembuf_i ? "-" : "", rembuf,
1592                                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1593   }
1594
1595   /* Now are we supposed to propagate to other servers? */
1596   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
1597     /* set up parameter string */
1598     addstr[0] = '\0';
1599     addstr_i = 0;
1600     remstr[0] = '\0';
1601     remstr_i = 0;
1602
1603     /*
1604      * limit is supressed if we're removing it; we have to figure out which
1605      * direction is the direction for it to be removed, though...
1606      */
1607     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
1608
1609     for (i = 0; i < mbuf->mb_count; i++) {
1610       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1611         continue;
1612
1613       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1614         strptr = addstr;
1615         strptr_i = &addstr_i;
1616       } else {
1617         strptr = remstr;
1618         strptr_i = &remstr_i;
1619       }
1620
1621       /* deal with modes that take clients */
1622       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1623         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
1624
1625       /* deal with modes that take strings */
1626       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
1627         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1628
1629       /*
1630        * deal with the limit.  Logic here is complicated; if HACK2 is set,
1631        * we're bouncing the mode, so sense is reversed, and we have to
1632        * include the original limit if it looks like it's being removed
1633        */
1634       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
1635         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1636     }
1637
1638     /* we were told to deop the source */
1639     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
1640       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
1641       addbuf[addbuf_i] = '\0'; /* terminate the string... */
1642       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
1643
1644       /* mark that we've done this, so we don't do it again */
1645       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
1646     }
1647
1648     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
1649       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
1650       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
1651                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
1652                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1653                             addbuf, remstr, addstr);
1654     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
1655       /*
1656        * If HACK2 was set, we're bouncing; we send the MODE back to the
1657        * connection we got it from with the senses reversed and a TS of 0;
1658        * origin is us
1659        */
1660       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
1661                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
1662                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
1663                     mbuf->mb_channel->creationtime);
1664     } else {
1665       /*
1666        * We're propagating a normal MODE command to the rest of the network;
1667        * we send the actual channel TS unless this is a HACK3 or a HACK4
1668        */
1669       if (IsServer(mbuf->mb_source))
1670         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1671                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
1672                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1673                               addbuf, remstr, addstr,
1674                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
1675                               mbuf->mb_channel->creationtime);
1676       else
1677         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1678                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
1679                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1680                               addbuf, remstr, addstr);
1681     }
1682   }
1683
1684   /* We've drained the ModeBuf... */
1685   mbuf->mb_add = 0;
1686   mbuf->mb_rem = 0;
1687   mbuf->mb_count = 0;
1688
1689   /* reinitialize the mode-with-arg slots */
1690   for (i = 0; i < MAXMODEPARAMS; i++) {
1691     /* If we saved any, pack them down */
1692     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
1693       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
1694       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
1695
1696       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
1697         continue;
1698     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
1699       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
1700
1701     MB_TYPE(mbuf, i) = 0;
1702     MB_UINT(mbuf, i) = 0;
1703   }
1704
1705   /* If we're supposed to flush it all, do so--all hail tail recursion */
1706   if (all && mbuf->mb_count)
1707     return modebuf_flush_int(mbuf, 1);
1708
1709   return 0;
1710 }
1711
1712 /*
1713  * This routine just initializes a ModeBuf structure with the information
1714  * needed and the options given.
1715  */
1716 void
1717 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
1718              struct Client *connect, struct Channel *chan, unsigned int dest)
1719 {
1720   int i;
1721
1722   assert(0 != mbuf);
1723   assert(0 != source);
1724   assert(0 != chan);
1725   assert(0 != dest);
1726
1727   mbuf->mb_add = 0;
1728   mbuf->mb_rem = 0;
1729   mbuf->mb_source = source;
1730   mbuf->mb_connect = connect;
1731   mbuf->mb_channel = chan;
1732   mbuf->mb_dest = dest;
1733   mbuf->mb_count = 0;
1734
1735   /* clear each mode-with-parameter slot */
1736   for (i = 0; i < MAXMODEPARAMS; i++) {
1737     MB_TYPE(mbuf, i) = 0;
1738     MB_UINT(mbuf, i) = 0;
1739   }
1740 }
1741
1742 /*
1743  * This routine simply adds modes to be added or deleted; do a binary OR
1744  * with either MODE_ADD or MODE_DEL
1745  */
1746 void
1747 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
1748 {
1749   assert(0 != mbuf);
1750   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1751
1752   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
1753            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
1754
1755   if (!(mode & ~(MODE_ADD | MODE_DEL))) /* don't add empty modes... */
1756     return;
1757
1758   if (mode & MODE_ADD) {
1759     mbuf->mb_rem &= ~mode;
1760     mbuf->mb_add |= mode;
1761   } else {
1762     mbuf->mb_add &= ~mode;
1763     mbuf->mb_rem |= mode;
1764   }
1765 }
1766
1767 /*
1768  * This routine adds a mode to be added or deleted that takes a unsigned
1769  * int parameter; mode may *only* be the relevant mode flag ORed with one
1770  * of MODE_ADD or MODE_DEL
1771  */
1772 void
1773 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
1774 {
1775   assert(0 != mbuf);
1776   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1777
1778   MB_TYPE(mbuf, mbuf->mb_count) = mode;
1779   MB_UINT(mbuf, mbuf->mb_count) = uint;
1780
1781   /* when we've reached the maximal count, flush the buffer */
1782   if (++mbuf->mb_count >=
1783       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1784     modebuf_flush_int(mbuf, 0);
1785 }
1786
1787 /*
1788  * This routine adds a mode to be added or deleted that takes a string
1789  * parameter; mode may *only* be the relevant mode flag ORed with one of
1790  * MODE_ADD or MODE_DEL
1791  */
1792 void
1793 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
1794                     int free)
1795 {
1796   assert(0 != mbuf);
1797   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1798
1799   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
1800   MB_STRING(mbuf, mbuf->mb_count) = string;
1801
1802   /* when we've reached the maximal count, flush the buffer */
1803   if (++mbuf->mb_count >=
1804       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1805     modebuf_flush_int(mbuf, 0);
1806 }
1807
1808 /*
1809  * This routine adds a mode to be added or deleted that takes a client
1810  * parameter; mode may *only* be the relevant mode flag ORed with one of
1811  * MODE_ADD or MODE_DEL
1812  */
1813 void
1814 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
1815                     struct Client *client)
1816 {
1817   assert(0 != mbuf);
1818   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1819
1820   MB_TYPE(mbuf, mbuf->mb_count) = mode;
1821   MB_CLIENT(mbuf, mbuf->mb_count) = client;
1822
1823   /* when we've reached the maximal count, flush the buffer */
1824   if (++mbuf->mb_count >=
1825       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1826     modebuf_flush_int(mbuf, 0);
1827 }
1828
1829 /*
1830  * This is the exported binding for modebuf_flush()
1831  */
1832 int
1833 modebuf_flush(struct ModeBuf *mbuf)
1834 {
1835   return modebuf_flush_int(mbuf, 1);
1836 }
1837
1838 /*
1839  * This extracts the simple modes contained in mbuf
1840  */
1841 void
1842 modebuf_extract(struct ModeBuf *mbuf, char *buf)
1843 {
1844   static int flags[] = {
1845 /*  MODE_CHANOP,        'o', */
1846 /*  MODE_VOICE,         'v', */
1847     MODE_PRIVATE,       'p',
1848     MODE_SECRET,        's',
1849     MODE_MODERATED,     'm',
1850     MODE_TOPICLIMIT,    't',
1851     MODE_INVITEONLY,    'i',
1852     MODE_NOPRIVMSGS,    'n',
1853     MODE_KEY,           'k',
1854 /*  MODE_BAN,           'b', */
1855     MODE_LIMIT,         'l',
1856     0x0, 0x0
1857   };
1858   unsigned int add;
1859   int i, bufpos = 0, len;
1860   int *flag_p;
1861   char *key = 0, limitbuf[20];
1862
1863   assert(0 != mbuf);
1864   assert(0 != buf);
1865
1866   buf[0] = '\0';
1867
1868   add = mbuf->mb_add;
1869
1870   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
1871     if (MB_TYPE(mbuf, i) & MODE_ADD) {
1872       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT);
1873
1874       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
1875         key = MB_STRING(mbuf, i);
1876       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
1877         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%d", MB_UINT(mbuf, i));
1878     }
1879   }
1880
1881   if (!add)
1882     return;
1883
1884   buf[bufpos++] = '+'; /* start building buffer */
1885
1886   for (flag_p = flags; flag_p[0]; flag_p += 2)
1887     if (*flag_p & add)
1888       buf[bufpos++] = flag_p[1];
1889
1890   for (i = 0, len = bufpos; i < len; i++) {
1891     if (buf[i] == 'k')
1892       build_string(buf, &bufpos, key, 0, ' ');
1893     else if (buf[i] == 'l')
1894       build_string(buf, &bufpos, limitbuf, 0, ' ');
1895   }
1896
1897   buf[bufpos] = '\0';
1898
1899   return;
1900 }
1901
1902 /*
1903  * Simple function to invalidate bans
1904  */
1905 void
1906 mode_ban_invalidate(struct Channel *chan)
1907 {
1908   struct Membership *member;
1909
1910   for (member = chan->members; member; member = member->next_member)
1911     ClearBanValid(member);
1912 }
1913
1914 /*
1915  * Simple function to drop invite structures
1916  */
1917 void
1918 mode_invite_clear(struct Channel *chan)
1919 {
1920   while (chan->invites)
1921     del_invite(chan->invites->value.cptr, chan);
1922 }
1923
1924 /* What we've done for mode_parse so far... */
1925 #define DONE_LIMIT      0x01    /* We've set the limit */
1926 #define DONE_KEY        0x02    /* We've set the key */
1927 #define DONE_BANLIST    0x04    /* We've sent the ban list */
1928 #define DONE_NOTOPER    0x08    /* We've sent a "Not oper" error */
1929 #define DONE_BANCLEAN   0x10    /* We've cleaned bans... */
1930
1931 struct ParseState {
1932   struct ModeBuf *mbuf;
1933   struct Client *cptr;
1934   struct Client *sptr;
1935   struct Channel *chptr;
1936   int parc;
1937   char **parv;
1938   unsigned int flags;
1939   unsigned int dir;
1940   unsigned int done;
1941   unsigned int add;
1942   unsigned int del;
1943   int args_used;
1944   int max_args;
1945   int numbans;
1946   struct SLink banlist[MAXPARA];
1947   struct {
1948     unsigned int flag;
1949     struct Client *client;
1950   } cli_change[MAXPARA];
1951 };
1952
1953 /*
1954  * Here's a helper function to deal with sending along "Not oper" or
1955  * "Not member" messages
1956  */
1957 static void
1958 send_notoper(struct ParseState *state)
1959 {
1960   if (state->done & DONE_NOTOPER)
1961     return;
1962
1963   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
1964              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
1965
1966   state->done |= DONE_NOTOPER;
1967 }
1968
1969 /*
1970  * Helper function to convert limits
1971  */
1972 static void
1973 mode_parse_limit(struct ParseState *state, int *flag_p)
1974 {
1975   unsigned int t_limit;
1976
1977   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
1978     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
1979       return;
1980
1981     if (state->parc <= 0) { /* warn if not enough args */
1982       if (MyUser(state->sptr))
1983         need_more_params(state->sptr, "MODE +l");
1984       return;
1985     }
1986
1987     t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
1988     state->parc--;
1989     state->max_args--;
1990
1991     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
1992         (!t_limit || t_limit == state->chptr->mode.limit))
1993       return;
1994   } else
1995     t_limit = state->chptr->mode.limit;
1996
1997   /* If they're not an oper, they can't change modes */
1998   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
1999     send_notoper(state);
2000     return;
2001   }
2002
2003   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
2004     return;
2005   state->done |= DONE_LIMIT;
2006
2007   if (!state->mbuf)
2008     return;
2009
2010   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
2011
2012   if (state->flags & MODE_PARSE_SET) { /* set the limit */
2013     if (state->dir & MODE_ADD) {
2014       state->chptr->mode.mode |= flag_p[0];
2015       state->chptr->mode.limit = t_limit;
2016     } else {
2017       state->chptr->mode.mode &= ~flag_p[0];
2018       state->chptr->mode.limit = 0;
2019     }
2020   }
2021 }
2022
2023 /*
2024  * Helper function to convert keys
2025  */
2026 static void
2027 mode_parse_key(struct ParseState *state, int *flag_p)
2028 {
2029   char *t_str, *s;
2030   int t_len;
2031
2032   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2033     return;
2034
2035   if (state->parc <= 0) { /* warn if not enough args */
2036     if (MyUser(state->sptr))
2037       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2038                        "MODE -k");
2039     return;
2040   }
2041
2042   t_str = state->parv[state->args_used++]; /* grab arg */
2043   state->parc--;
2044   state->max_args--;
2045
2046   /* If they're not an oper, they can't change modes */
2047   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2048     send_notoper(state);
2049     return;
2050   }
2051
2052   if (state->done & DONE_KEY) /* allow key to be set only once */
2053     return;
2054   state->done |= DONE_KEY;
2055
2056   t_len = KEYLEN + 1;
2057
2058   /* clean up the key string */
2059   s = t_str;
2060   while (*++s > ' ' && *s != ':' && --t_len)
2061     ;
2062   *s = '\0';
2063
2064   if (!*t_str) { /* warn if empty */
2065     if (MyUser(state->sptr))
2066       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2067                        "MODE -k");
2068     return;
2069   }
2070
2071   if (!state->mbuf)
2072     return;
2073
2074   /* can't add a key if one is set, nor can one remove the wrong key */
2075   if (!(state->flags & MODE_PARSE_FORCE))
2076     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
2077         (state->dir == MODE_DEL &&
2078          ircd_strcmp(state->chptr->mode.key, t_str))) {
2079       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2080       return;
2081     }
2082
2083   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2084       !ircd_strcmp(state->chptr->mode.key, t_str))
2085     return; /* no key change */
2086
2087   if (state->flags & MODE_PARSE_BOUNCE) {
2088     if (*state->chptr->mode.key) /* reset old key */
2089       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2090                           state->chptr->mode.key, 0);
2091     else /* remove new bogus key */
2092       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2093   } else /* send new key */
2094     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2095
2096   if (state->flags & MODE_PARSE_SET) {
2097     if (state->dir == MODE_ADD) /* set the new key */
2098       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
2099     else /* remove the old key */
2100       *state->chptr->mode.key = '\0';
2101   }
2102 }
2103
2104 /*
2105  * Helper function to convert bans
2106  */
2107 static void
2108 mode_parse_ban(struct ParseState *state, int *flag_p)
2109 {
2110   char *t_str, *s;
2111   struct SLink *ban, *newban = 0;
2112
2113   if (state->parc <= 0) { /* Not enough args, send ban list */
2114     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
2115       send_ban_list(state->sptr, state->chptr);
2116       state->done |= DONE_BANLIST;
2117     }
2118
2119     return;
2120   }
2121
2122   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2123     return;
2124
2125   t_str = state->parv[state->args_used++]; /* grab arg */
2126   state->parc--;
2127   state->max_args--;
2128
2129   /* If they're not an oper, they can't change modes */
2130   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2131     send_notoper(state);
2132     return;
2133   }
2134
2135   if ((s = strchr(t_str, ' ')))
2136     *s = '\0';
2137
2138   if (!*t_str || *t_str == ':') { /* warn if empty */
2139     if (MyUser(state->sptr))
2140       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
2141                        "MODE -b");
2142     return;
2143   }
2144
2145   t_str = collapse(pretty_mask(t_str));
2146
2147   /* remember the ban for the moment... */
2148   if (state->dir == MODE_ADD) {
2149     newban = state->banlist + (state->numbans++);
2150     newban->next = 0;
2151
2152     DupString(newban->value.ban.banstr, t_str);
2153     newban->value.ban.who = cli_name(state->sptr);
2154     newban->value.ban.when = TStime();
2155
2156     newban->flags = CHFL_BAN | MODE_ADD;
2157
2158     if ((s = strrchr(t_str, '@')) && check_if_ipmask(s + 1))
2159       newban->flags |= CHFL_BAN_IPMASK;
2160   }
2161
2162   if (!state->chptr->banlist) {
2163     state->chptr->banlist = newban; /* add our ban with its flags */
2164     state->done |= DONE_BANCLEAN;
2165     return;
2166   }
2167
2168   /* Go through all bans */
2169   for (ban = state->chptr->banlist; ban; ban = ban->next) {
2170     /* first, clean the ban flags up a bit */
2171     if (!(state->done & DONE_BANCLEAN))
2172       /* Note: We're overloading *lots* of bits here; be careful! */
2173       ban->flags &= ~(MODE_ADD | MODE_DEL | CHFL_BAN_OVERLAPPED);
2174
2175     /* Bit meanings:
2176      *
2177      * MODE_ADD            - Ban was added; if we're bouncing modes,
2178      *                       then we'll remove it below; otherwise,
2179      *                       we'll have to allocate a real ban
2180      *
2181      * MODE_DEL            - Ban was marked for deletion; if we're
2182      *                       bouncing modes, we'll have to re-add it,
2183      *                       otherwise, we'll have to remove it
2184      *
2185      * CHFL_BAN_OVERLAPPED - The ban we added turns out to overlap
2186      *                       with a ban already set; if we're
2187      *                       bouncing modes, we'll have to bounce
2188      *                       this one; otherwise, we'll just ignore
2189      *                       it when we process added bans
2190      */
2191
2192     if (state->dir == MODE_DEL && !ircd_strcmp(ban->value.ban.banstr, t_str)) {
2193       ban->flags |= MODE_DEL; /* delete one ban */
2194
2195       if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
2196         break;
2197     } else if (state->dir == MODE_ADD) {
2198       /* if the ban already exists, don't worry about it */
2199       if (!ircd_strcmp(ban->value.ban.banstr, t_str)) {
2200         newban->flags &= ~MODE_ADD; /* don't add ban at all */
2201         MyFree(newban->value.ban.banstr); /* stopper a leak */
2202         state->numbans--; /* deallocate last ban */
2203         if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
2204           break;
2205       } else if (!mmatch(ban->value.ban.banstr, t_str)) {
2206         if (!(ban->flags & MODE_DEL))
2207           newban->flags |= CHFL_BAN_OVERLAPPED; /* our ban overlaps */
2208       } else if (!mmatch(t_str, ban->value.ban.banstr))
2209         ban->flags |= MODE_DEL; /* mark ban for deletion: overlapping */
2210
2211       if (!ban->next && (newban->flags & MODE_ADD)) {
2212         ban->next = newban; /* add our ban with its flags */
2213         break; /* get out of loop */
2214       }
2215     }
2216   }
2217   state->done |= DONE_BANCLEAN;
2218 }
2219
2220 /*
2221  * This is the bottom half of the ban processor
2222  */
2223 static void
2224 mode_process_bans(struct ParseState *state)
2225 {
2226   struct SLink *ban, *newban, *prevban, *nextban;
2227   int count = 0;
2228   int len = 0;
2229   int banlen;
2230   int changed = 0;
2231
2232   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
2233     count++;
2234     banlen = strlen(ban->value.ban.banstr);
2235     len += banlen;
2236     nextban = ban->next;
2237
2238     if ((ban->flags & (MODE_DEL | MODE_ADD)) == (MODE_DEL | MODE_ADD)) {
2239       if (prevban)
2240         prevban->next = 0; /* Break the list; ban isn't a real ban */
2241       else
2242         state->chptr->banlist = 0;
2243
2244       count--;
2245       len -= banlen;
2246
2247       MyFree(ban->value.ban.banstr);
2248
2249       continue;
2250     } else if (ban->flags & MODE_DEL) { /* Deleted a ban? */
2251       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
2252                           ban->value.ban.banstr,
2253                           state->flags & MODE_PARSE_SET);
2254
2255       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
2256         if (prevban) /* clip it out of the list... */
2257           prevban->next = ban->next;
2258         else
2259           state->chptr->banlist = ban->next;
2260
2261         count--;
2262         len -= banlen;
2263
2264         MyFree(ban->value.ban.who);
2265         free_link(ban);
2266
2267         changed++;
2268         continue; /* next ban; keep prevban like it is */
2269       } else
2270         ban->flags &= (CHFL_BAN | CHFL_BAN_IPMASK); /* unset other flags */
2271     } else if (ban->flags & MODE_ADD) { /* adding a ban? */
2272       if (prevban)
2273         prevban->next = 0; /* Break the list; ban isn't a real ban */
2274       else
2275         state->chptr->banlist = 0;
2276
2277       /* If we're supposed to ignore it, do so. */
2278       if (ban->flags & CHFL_BAN_OVERLAPPED &&
2279           !(state->flags & MODE_PARSE_BOUNCE)) {
2280         count--;
2281         len -= banlen;
2282
2283         MyFree(ban->value.ban.banstr);
2284       } else {
2285         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
2286             (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
2287              count >= feature_int(FEAT_MAXBANS))) {
2288           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
2289                      ban->value.ban.banstr);
2290           count--;
2291           len -= banlen;
2292
2293           MyFree(ban->value.ban.banstr);
2294         } else {
2295           /* add the ban to the buffer */
2296           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
2297                               ban->value.ban.banstr,
2298                               !(state->flags & MODE_PARSE_SET));
2299
2300           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
2301             newban = make_link();
2302             newban->value.ban.banstr = ban->value.ban.banstr;
2303             DupString(newban->value.ban.who, ban->value.ban.who);
2304             newban->value.ban.when = ban->value.ban.when;
2305             newban->flags = ban->flags & (CHFL_BAN | CHFL_BAN_IPMASK);
2306
2307             newban->next = state->chptr->banlist; /* and link it in */
2308             state->chptr->banlist = newban;
2309
2310             changed++;
2311           }
2312         }
2313       }
2314     }
2315
2316     prevban = ban;
2317   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
2318
2319   if (changed) /* if we changed the ban list, we must invalidate the bans */
2320     mode_ban_invalidate(state->chptr);
2321 }
2322
2323 /*
2324  * Helper function to process client changes
2325  */
2326 static void
2327 mode_parse_client(struct ParseState *state, int *flag_p)
2328 {
2329   char *t_str;
2330   struct Client *acptr;
2331   int i;
2332
2333   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2334     return;
2335
2336   if (state->parc <= 0) /* return if not enough args */
2337     return;
2338
2339   t_str = state->parv[state->args_used++]; /* grab arg */
2340   state->parc--;
2341   state->max_args--;
2342
2343   /* If they're not an oper, they can't change modes */
2344   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2345     send_notoper(state);
2346     return;
2347   }
2348
2349   if (MyUser(state->sptr)) /* find client we're manipulating */
2350     acptr = find_chasing(state->sptr, t_str, NULL);
2351   else
2352     acptr = findNUser(t_str);
2353
2354   if (!acptr)
2355     return; /* find_chasing() already reported an error to the user */
2356
2357   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
2358     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
2359                                        state->cli_change[i].flag & flag_p[0]))
2360       break; /* found a slot */
2361
2362   /* Store what we're doing to them */
2363   state->cli_change[i].flag = state->dir | flag_p[0];
2364   state->cli_change[i].client = acptr;
2365 }
2366
2367 /*
2368  * Helper function to process the changed client list
2369  */
2370 static void
2371 mode_process_clients(struct ParseState *state)
2372 {
2373   int i;
2374   struct Membership *member;
2375
2376   for (i = 0; state->cli_change[i].flag; i++) {
2377     assert(0 != state->cli_change[i].client);
2378
2379     /* look up member link */
2380     if (!(member = find_member_link(state->chptr,
2381                                     state->cli_change[i].client)) ||
2382         (MyUser(state->sptr) && IsZombie(member))) {
2383       if (MyUser(state->sptr))
2384         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
2385                    cli_name(state->cli_change[i].client),
2386                    state->chptr->chname);
2387       continue;
2388     }
2389
2390     if ((state->cli_change[i].flag & MODE_ADD &&
2391          (state->cli_change[i].flag & member->status)) ||
2392         (state->cli_change[i].flag & MODE_DEL &&
2393          !(state->cli_change[i].flag & member->status)))
2394       continue; /* no change made, don't do anything */
2395
2396     /* see if the deop is allowed */
2397     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
2398         (MODE_DEL | MODE_CHANOP)) {
2399       /* prevent +k users from being deopped */
2400       if (IsChannelService(state->cli_change[i].client)) {
2401         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
2402           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
2403                                state->chptr,
2404                                (IsServer(state->sptr) ? cli_name(state->sptr) :
2405                                 cli_name((cli_user(state->sptr))->server)));
2406
2407         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
2408           send_reply(state->sptr, ERR_ISCHANSERVICE,
2409                      cli_name(state->cli_change[i].client),
2410                      state->chptr->chname);
2411           continue;
2412         }
2413       }
2414
2415       /* don't allow local opers to be deopped on local channels */
2416       if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
2417           IsLocalChannel(state->chptr->chname) &&
2418           HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
2419         send_reply(state->sptr, ERR_ISOPERLCHAN,
2420                    cli_name(state->cli_change[i].client),
2421                    state->chptr->chname);
2422         continue;
2423       }
2424     }
2425
2426     /* accumulate the change */
2427     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
2428                         state->cli_change[i].client);
2429
2430     /* actually effect the change */
2431     if (state->flags & MODE_PARSE_SET) {
2432       if (state->cli_change[i].flag & MODE_ADD) {
2433         member->status |= (state->cli_change[i].flag &
2434                            (MODE_CHANOP | MODE_VOICE));
2435         if (state->cli_change[i].flag & MODE_CHANOP)
2436           ClearDeopped(member);
2437       } else
2438         member->status &= ~(state->cli_change[i].flag &
2439                             (MODE_CHANOP | MODE_VOICE));
2440     }
2441   } /* for (i = 0; state->cli_change[i].flags; i++) { */
2442 }
2443
2444 /*
2445  * Helper function to process the simple modes
2446  */
2447 static void
2448 mode_parse_mode(struct ParseState *state, int *flag_p)
2449 {
2450   /* If they're not an oper, they can't change modes */
2451   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2452     send_notoper(state);
2453     return;
2454   }
2455
2456   if (!state->mbuf)
2457     return;
2458
2459   if (state->dir == MODE_ADD) {
2460     state->add |= flag_p[0];
2461     state->del &= ~flag_p[0];
2462
2463     if (flag_p[0] & MODE_SECRET) {
2464       state->add &= ~MODE_PRIVATE;
2465       state->del |= MODE_PRIVATE;
2466     } else if (flag_p[0] & MODE_PRIVATE) {
2467       state->add &= ~MODE_SECRET;
2468       state->del |= MODE_SECRET;
2469     }
2470   } else {
2471     state->add &= ~flag_p[0];
2472     state->del |= flag_p[0];
2473   }
2474
2475   assert(0 == (state->add & state->del));
2476   assert((MODE_SECRET | MODE_PRIVATE) !=
2477          (state->add & (MODE_SECRET | MODE_PRIVATE)));
2478 }
2479
2480 /*
2481  * This routine is intended to parse MODE or OPMODE commands and effect the
2482  * changes (or just build the bounce buffer).  We pass the starting offset
2483  * as a 
2484  */
2485 int
2486 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
2487            struct Channel *chptr, int parc, char *parv[], unsigned int flags)
2488 {
2489   static int chan_flags[] = {
2490     MODE_CHANOP,        'o',
2491     MODE_VOICE,         'v',
2492     MODE_PRIVATE,       'p',
2493     MODE_SECRET,        's',
2494     MODE_MODERATED,     'm',
2495     MODE_TOPICLIMIT,    't',
2496     MODE_INVITEONLY,    'i',
2497     MODE_NOPRIVMSGS,    'n',
2498     MODE_KEY,           'k',
2499     MODE_BAN,           'b',
2500     MODE_LIMIT,         'l',
2501     MODE_ADD,           '+',
2502     MODE_DEL,           '-',
2503     0x0, 0x0
2504   };
2505   int i;
2506   int *flag_p;
2507   unsigned int t_mode;
2508   char *modestr;
2509   struct ParseState state;
2510
2511   assert(0 != cptr);
2512   assert(0 != sptr);
2513   assert(0 != chptr);
2514   assert(0 != parc);
2515   assert(0 != parv);
2516
2517   state.mbuf = mbuf;
2518   state.cptr = cptr;
2519   state.sptr = sptr;
2520   state.chptr = chptr;
2521   state.parc = parc;
2522   state.parv = parv;
2523   state.flags = flags;
2524   state.dir = MODE_ADD;
2525   state.done = 0;
2526   state.add = 0;
2527   state.del = 0;
2528   state.args_used = 0;
2529   state.max_args = MAXMODEPARAMS;
2530   state.numbans = 0;
2531
2532   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
2533     state.banlist[i].next = 0;
2534     state.banlist[i].value.ban.banstr = 0;
2535     state.banlist[i].value.ban.who = 0;
2536     state.banlist[i].value.ban.when = 0;
2537     state.banlist[i].flags = 0;
2538     state.cli_change[i].flag = 0;
2539     state.cli_change[i].client = 0;
2540   }
2541
2542   modestr = state.parv[state.args_used++];
2543   state.parc--;
2544
2545   while (*modestr) {
2546     for (; *modestr; modestr++) {
2547       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
2548         if (flag_p[1] == *modestr)
2549           break;
2550
2551       if (!flag_p[0]) { /* didn't find it?  complain and continue */
2552         if (MyUser(state.sptr))
2553           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
2554         continue;
2555       }
2556
2557       switch (*modestr) {
2558       case '+': /* switch direction to MODE_ADD */
2559       case '-': /* switch direction to MODE_DEL */
2560         state.dir = flag_p[0];
2561         break;
2562
2563       case 'l': /* deal with limits */
2564         mode_parse_limit(&state, flag_p);
2565         break;
2566
2567       case 'k': /* deal with keys */
2568         mode_parse_key(&state, flag_p);
2569         break;
2570
2571       case 'b': /* deal with bans */
2572         mode_parse_ban(&state, flag_p);
2573         break;
2574
2575       case 'o': /* deal with ops/voice */
2576       case 'v':
2577         mode_parse_client(&state, flag_p);
2578         break;
2579
2580       default: /* deal with other modes */
2581         mode_parse_mode(&state, flag_p);
2582         break;
2583       } /* switch (*modestr) { */
2584     } /* for (; *modestr; modestr++) { */
2585
2586     if (state.flags & MODE_PARSE_BURST)
2587       break; /* don't interpret any more arguments */
2588
2589     if (state.parc > 0) { /* process next argument in string */
2590       modestr = state.parv[state.args_used++];
2591       state.parc--;
2592
2593       /* is it a TS? */
2594       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
2595         time_t recv_ts;
2596
2597         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
2598           break;                     /* we're then going to bounce the mode! */
2599
2600         recv_ts = atoi(modestr);
2601
2602         if (recv_ts && recv_ts < state.chptr->creationtime)
2603           state.chptr->creationtime = recv_ts; /* respect earlier TS */
2604
2605         break; /* break out of while loop */
2606       } else if (state.flags & MODE_PARSE_STRICT ||
2607                  (MyUser(state.sptr) && state.max_args <= 0)) {
2608         state.parc++; /* we didn't actually gobble the argument */
2609         state.args_used--;
2610         break; /* break out of while loop */
2611       }
2612     }
2613   } /* while (*modestr) { */
2614
2615   /*
2616    * the rest of the function finishes building resultant MODEs; if the
2617    * origin isn't a member or an oper, skip it.
2618    */
2619   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
2620     return state.args_used; /* tell our parent how many args we gobbled */
2621
2622   t_mode = state.chptr->mode.mode;
2623
2624   if (state.del & t_mode) { /* delete any modes to be deleted... */
2625     modebuf_mode(state.mbuf, MODE_DEL | (state.del & t_mode));
2626
2627     t_mode &= ~state.del;
2628   }
2629   if (state.add & ~t_mode) { /* add any modes to be added... */
2630     modebuf_mode(state.mbuf, MODE_ADD | (state.add & ~t_mode));
2631
2632     t_mode |= state.add;
2633   }
2634
2635   if (state.flags & MODE_PARSE_SET) { /* set the channel modes */
2636     if ((state.chptr->mode.mode & MODE_INVITEONLY) &&
2637         !(t_mode & MODE_INVITEONLY))
2638       mode_invite_clear(state.chptr);
2639
2640     state.chptr->mode.mode = t_mode;
2641   }
2642
2643   if (state.flags & MODE_PARSE_WIPEOUT) {
2644     if (state.chptr->mode.limit && !(state.done & DONE_LIMIT))
2645       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
2646                         state.chptr->mode.limit);
2647     if (*state.chptr->mode.key && !(state.done & DONE_KEY))
2648       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
2649                           state.chptr->mode.key, 0);
2650   }
2651
2652   if (state.done & DONE_BANCLEAN) /* process bans */
2653     mode_process_bans(&state);
2654
2655   /* process client changes */
2656   if (state.cli_change[0].flag)
2657     mode_process_clients(&state);
2658
2659   return state.args_used; /* tell our parent how many args we gobbled */
2660 }
2661
2662 /*
2663  * Initialize a join buffer
2664  */
2665 void
2666 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
2667              struct Client *connect, unsigned int type, char *comment,
2668              time_t create)
2669 {
2670   int i;
2671
2672   assert(0 != jbuf);
2673   assert(0 != source);
2674   assert(0 != connect);
2675
2676   jbuf->jb_source = source; /* just initialize struct JoinBuf */
2677   jbuf->jb_connect = connect;
2678   jbuf->jb_type = type;
2679   jbuf->jb_comment = comment;
2680   jbuf->jb_create = create;
2681   jbuf->jb_count = 0;
2682   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
2683                        type == JOINBUF_TYPE_PART ||
2684                        type == JOINBUF_TYPE_PARTALL) ?
2685                       STARTJOINLEN : STARTCREATELEN) +
2686                      (comment ? strlen(comment) + 2 : 0));
2687
2688   for (i = 0; i < MAXJOINARGS; i++)
2689     jbuf->jb_channels[i] = 0;
2690 }
2691
2692 /*
2693  * Add a channel to the join buffer
2694  */
2695 void
2696 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
2697 {
2698   unsigned int len;
2699
2700   assert(0 != jbuf);
2701
2702   if (!chan) {
2703     if (jbuf->jb_type == JOINBUF_TYPE_JOIN)
2704       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect, "0");
2705
2706     return;
2707   }
2708
2709   if (jbuf->jb_type == JOINBUF_TYPE_PART ||
2710       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
2711     /* Send notification to channel */
2712     if (!(flags & CHFL_ZOMBIE))
2713       sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
2714                                 (flags & CHFL_BANNED || !jbuf->jb_comment) ?
2715                                 ":%H" : "%H :%s", chan, jbuf->jb_comment);
2716     else if (MyUser(jbuf->jb_source))
2717       sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
2718                     (flags & CHFL_BANNED || !jbuf->jb_comment) ?
2719                     ":%H" : "%H :%s", chan, jbuf->jb_comment);
2720     /* XXX: Shouldn't we send a PART here anyway? */
2721     /* to users on the channel?  Why?  From their POV, the user isn't on
2722      * the channel anymore anyway.  We don't send to servers until below,
2723      * when we gang all the channel parts together.  Note that this is
2724      * exactly the same logic, albeit somewhat more concise, as was in
2725      * the original m_part.c */
2726
2727     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
2728         IsLocalChannel(chan->chname)) /* got to remove user here */
2729       remove_user_from_channel(jbuf->jb_source, chan);
2730   } else {
2731     /* Add user to channel */
2732     add_user_to_channel(chan, jbuf->jb_source, flags);
2733
2734     /* send notification to all servers */
2735     if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !IsLocalChannel(chan->chname))
2736       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
2737                             "%H %Tu", chan, chan->creationtime);
2738
2739     /* Send the notification to the channel */
2740     sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
2741
2742     /* send an op, too, if needed */
2743     if (!MyUser(jbuf->jb_source) && jbuf->jb_type == JOINBUF_TYPE_CREATE &&
2744         !IsModelessChannel(chan->chname))
2745       sendcmdto_channel_butserv(jbuf->jb_source, CMD_MODE, chan, "%H +o %C",
2746                                 chan, jbuf->jb_source);
2747   }
2748
2749   if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
2750     return; /* don't send to remote */
2751
2752   /* figure out if channel name will cause buffer to be overflowed */
2753   len = chan ? strlen(chan->chname) + 1 : 2;
2754   if (jbuf->jb_strlen + len > BUFSIZE)
2755     joinbuf_flush(jbuf);
2756
2757   /* add channel to list of channels to send and update counts */
2758   jbuf->jb_channels[jbuf->jb_count++] = chan;
2759   jbuf->jb_strlen += len;
2760
2761   /* if we've used up all slots, flush */
2762   if (jbuf->jb_count >= MAXJOINARGS)
2763     joinbuf_flush(jbuf);
2764 }
2765
2766 /*
2767  * Flush the channel list to remote servers
2768  */
2769 int
2770 joinbuf_flush(struct JoinBuf *jbuf)
2771 {
2772   char chanlist[BUFSIZE];
2773   int chanlist_i = 0;
2774   int i;
2775
2776   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
2777       jbuf->jb_type == JOINBUF_TYPE_JOIN)
2778     return 0; /* no joins to process */
2779
2780   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
2781     build_string(chanlist, &chanlist_i,
2782                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
2783                  i == 0 ? '\0' : ',');
2784     if (JOINBUF_TYPE_PART == jbuf->jb_type)
2785       /* Remove user from channel */
2786       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
2787
2788     jbuf->jb_channels[i] = 0; /* mark slot empty */
2789   }
2790
2791   jbuf->jb_count = 0; /* reset base counters */
2792   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_PART ?
2793                       STARTJOINLEN : STARTCREATELEN) +
2794                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
2795
2796   /* and send the appropriate command */
2797   switch (jbuf->jb_type) {
2798   case JOINBUF_TYPE_CREATE:
2799     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
2800                           "%s %Tu", chanlist, jbuf->jb_create);
2801     break;
2802
2803   case JOINBUF_TYPE_PART:
2804     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
2805                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
2806                           jbuf->jb_comment);
2807     break;
2808   }
2809
2810   return 0;
2811 }