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