bd13efe77be1e6ae0327ff17fe8e7bd58539f5cb
[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
1252 /*
1253  * Consider:
1254  *
1255  *                     client
1256  *                       |
1257  *                       c
1258  *                       |
1259  *     X --a--> A --b--> B --d--> D
1260  *                       |
1261  *                      who
1262  *
1263  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
1264  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
1265  *
1266  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
1267  *    Remove the user immedeately when no users are left on the channel.
1268  * b) On server B : remove the user (who/lp) from the channel, send a
1269  *    PART upstream (to A) and pass on the KICK.
1270  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
1271  *    channel, and pass on the KICK.
1272  * d) On server D : remove the user (who/lp) from the channel, and pass on
1273  *    the KICK.
1274  *
1275  * Note:
1276  * - Setting the ZOMBIE flag never hurts, we either remove the
1277  *   client after that or we don't.
1278  * - The KICK message was already passed on, as should be in all cases.
1279  * - `who' is removed in all cases except case a) when users are left.
1280  * - A PART is only sent upstream in case b).
1281  *
1282  * 2 aug 97:
1283  *
1284  *              6
1285  *              |
1286  *  1 --- 2 --- 3 --- 4 --- 5
1287  *        |           |
1288  *      kicker       who
1289  *
1290  * We also need to turn 'who' into a zombie on servers 1 and 6,
1291  * because a KICK from 'who' (kicking someone else in that direction)
1292  * can arrive there afterwards - which should not be bounced itself.
1293  * Therefore case a) also applies for servers 1 and 6.
1294  *
1295  * --Run
1296  */
1297 void make_zombie(struct Membership* member, struct Client* who, struct Client* cptr,
1298                  struct Client* sptr, struct Channel* chptr)
1299 {
1300   assert(0 != member);
1301   assert(0 != who);
1302   assert(0 != cptr);
1303   assert(0 != chptr);
1304
1305   /* Default for case a): */
1306   SetZombie(member);
1307
1308   /* Case b) or c) ?: */
1309   if (MyUser(who))      /* server 4 */
1310   {
1311     if (IsServer(cptr)) /* Case b) ? */
1312       sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
1313     remove_user_from_channel(who, chptr);
1314     return;
1315   }
1316   if (cli_from(who) == cptr)        /* True on servers 1, 5 and 6 */
1317   {
1318     struct Client *acptr = IsServer(sptr) ? sptr : (cli_user(sptr))->server;
1319     for (; acptr != &me; acptr = (cli_serv(acptr))->up)
1320       if (acptr == (cli_user(who))->server)   /* Case d) (server 5) */
1321       {
1322         remove_user_from_channel(who, chptr);
1323         return;
1324       }
1325   }
1326
1327   /* Case a) (servers 1, 2, 3 and 6) */
1328   if (channel_all_zombies(chptr))
1329     remove_user_from_channel(who, chptr);
1330
1331   /* XXX Can't actually call Debug here; if the channel is all zombies,
1332    * chptr will no longer exist when we get here.
1333   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
1334   */
1335 }
1336
1337 int number_of_zombies(struct Channel *chptr)
1338 {
1339   struct Membership* member;
1340   int                count = 0;
1341
1342   assert(0 != chptr);
1343   for (member = chptr->members; member; member = member->next_member) {
1344     if (IsZombie(member))
1345       ++count;
1346   }
1347   return count;
1348 }
1349
1350 /*
1351  * This helper function builds an argument string in strptr, consisting
1352  * of the original string, a space, and str1 and str2 concatenated (if,
1353  * of course, str2 is not NULL)
1354  */
1355 static void
1356 build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
1357 {
1358   if (c)
1359     strptr[(*strptr_i)++] = c;
1360
1361   while (*str1)
1362     strptr[(*strptr_i)++] = *(str1++);
1363
1364   if (str2)
1365     while (*str2)
1366       strptr[(*strptr_i)++] = *(str2++);
1367
1368   strptr[(*strptr_i)] = '\0';
1369 }
1370
1371 /*
1372  * This is the workhorse of our ModeBuf suite; this actually generates the
1373  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
1374  */
1375 static int
1376 modebuf_flush_int(struct ModeBuf *mbuf, int all)
1377 {
1378   /* we only need the flags that don't take args right now */
1379   static int flags[] = {
1380 /*  MODE_CHANOP,        'o', */
1381 /*  MODE_VOICE,         'v', */
1382     MODE_PRIVATE,       'p',
1383     MODE_SECRET,        's',
1384     MODE_MODERATED,     'm',
1385     MODE_TOPICLIMIT,    't',
1386     MODE_INVITEONLY,    'i',
1387     MODE_NOPRIVMSGS,    'n',
1388 /*  MODE_KEY,           'k', */
1389 /*  MODE_BAN,           'b', */
1390 /*  MODE_LIMIT,         'l', */
1391     0x0, 0x0
1392   };
1393   int i;
1394   int *flag_p;
1395
1396   struct Client *app_source; /* where the MODE appears to come from */
1397
1398   char addbuf[20]; /* accumulates +psmtin, etc. */
1399   int addbuf_i = 0;
1400   char rembuf[20]; /* accumulates -psmtin, etc. */
1401   int rembuf_i = 0;
1402   char *bufptr; /* we make use of indirection to simplify the code */
1403   int *bufptr_i;
1404
1405   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
1406   int addstr_i;
1407   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
1408   int remstr_i;
1409   char *strptr; /* more indirection to simplify the code */
1410   int *strptr_i;
1411
1412   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
1413   int tmp;
1414
1415   char limitbuf[20]; /* convert limits to strings */
1416
1417   unsigned int limitdel = MODE_LIMIT;
1418
1419   assert(0 != mbuf);
1420
1421   /* If the ModeBuf is empty, we have nothing to do */
1422   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
1423     return 0;
1424
1425   /* Ok, if we were given the OPMODE flag, hide the source if its a user */
1426   if (mbuf->mb_dest & MODEBUF_DEST_OPMODE && !IsServer(mbuf->mb_source))
1427     app_source = (cli_user(mbuf->mb_source))->server;
1428   else
1429     app_source = mbuf->mb_source;
1430
1431   /*
1432    * Account for user we're bouncing; we have to get it in on the first
1433    * bounced MODE, or we could have problems
1434    */
1435   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
1436     totalbuflen -= 6; /* numeric nick == 5, plus one space */
1437
1438   /* Calculate the simple flags */
1439   for (flag_p = flags; flag_p[0]; flag_p += 2) {
1440     if (*flag_p & mbuf->mb_add)
1441       addbuf[addbuf_i++] = flag_p[1];
1442     else if (*flag_p & mbuf->mb_rem)
1443       rembuf[rembuf_i++] = flag_p[1];
1444   }
1445
1446   /* Now go through the modes with arguments... */
1447   for (i = 0; i < mbuf->mb_count; i++) {
1448     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1449       bufptr = addbuf;
1450       bufptr_i = &addbuf_i;
1451     } else {
1452       bufptr = rembuf;
1453       bufptr_i = &rembuf_i;
1454     }
1455
1456     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
1457       tmp = strlen(cli_name(MB_CLIENT(mbuf, i)));
1458
1459       if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
1460         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1461       else {
1462         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
1463         totalbuflen -= IRCD_MAX(5, tmp) + 1;
1464       }
1465     } else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN)) {
1466       tmp = strlen(MB_STRING(mbuf, i));
1467
1468       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1469         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1470       else {
1471         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_KEY ? 'k' : 'b';
1472         totalbuflen -= tmp + 1;
1473       }
1474     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
1475       /* if it's a limit, we also format the number */
1476       sprintf_irc(limitbuf, "%d", MB_UINT(mbuf, i));
1477
1478       tmp = strlen(limitbuf);
1479
1480       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1481         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1482       else {
1483         bufptr[(*bufptr_i)++] = 'l';
1484         totalbuflen -= tmp + 1;
1485       }
1486     }
1487   }
1488
1489   /* terminate the mode strings */
1490   addbuf[addbuf_i] = '\0';
1491   rembuf[rembuf_i] = '\0';
1492
1493   /* If we're building a user visible MODE or HACK... */
1494   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
1495                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
1496                        MODEBUF_DEST_LOG)) {
1497     /* Set up the parameter strings */
1498     addstr[0] = '\0';
1499     addstr_i = 0;
1500     remstr[0] = '\0';
1501     remstr_i = 0;
1502
1503     for (i = 0; i < mbuf->mb_count; i++) {
1504       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1505         continue;
1506
1507       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1508         strptr = addstr;
1509         strptr_i = &addstr_i;
1510       } else {
1511         strptr = remstr;
1512         strptr_i = &remstr_i;
1513       }
1514
1515       /* deal with clients... */
1516       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1517         build_string(strptr, strptr_i, cli_name(MB_CLIENT(mbuf, i)), 0, ' ');
1518
1519       /* deal with strings... */
1520       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
1521         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1522
1523       /*
1524        * deal with limit; note we cannot include the limit parameter if we're
1525        * removing it
1526        */
1527       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
1528                (MODE_ADD | MODE_LIMIT))
1529         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1530     }
1531
1532     /* send the messages off to their destination */
1533     if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
1534       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
1535                            "[%Tu]", cli_name(app_source),
1536                            mbuf->mb_channel->chname,
1537                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1538                            addbuf, remstr, addstr,
1539                            mbuf->mb_channel->creationtime);
1540       sendcmdto_serv_butone(&me, CMD_DESYNCH, mbuf->mb_connect,
1541                             ":HACK: %s MODE %s %s%s%s%s%s%s [%Tu]",
1542                             cli_name(app_source), mbuf->mb_channel->chname,
1543                             rembuf_i ? "-" : "", rembuf,
1544                             addbuf_i ? "+" : "", addbuf, remstr, addstr,
1545                             mbuf->mb_channel->creationtime);
1546     }
1547
1548     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
1549       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
1550                            "%s%s%s%s%s%s [%Tu]", cli_name(app_source),
1551                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
1552                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
1553                            mbuf->mb_channel->creationtime);
1554
1555     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
1556       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
1557                            "[%Tu]", cli_name(app_source),
1558                            mbuf->mb_channel->chname,
1559                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1560                            addbuf, remstr, addstr,
1561                            mbuf->mb_channel->creationtime);
1562
1563     if (mbuf->mb_dest & MODEBUF_DEST_LOG)
1564       log_write(LS_OPERMODE, L_INFO, LOG_NOSNOTICE,
1565                 "%#C OPMODE %H %s%s%s%s%s%s", mbuf->mb_source,
1566                 mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
1567                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1568
1569     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
1570       sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
1571                                 "%H %s%s%s%s%s%s", mbuf->mb_channel,
1572                                 rembuf_i ? "-" : "", rembuf,
1573                                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1574   }
1575
1576   /* Now are we supposed to propagate to other servers? */
1577   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
1578     /* set up parameter string */
1579     addstr[0] = '\0';
1580     addstr_i = 0;
1581     remstr[0] = '\0';
1582     remstr_i = 0;
1583
1584     /*
1585      * limit is supressed if we're removing it; we have to figure out which
1586      * direction is the direction for it to be removed, though...
1587      */
1588     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
1589
1590     for (i = 0; i < mbuf->mb_count; i++) {
1591       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1592         continue;
1593
1594       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1595         strptr = addstr;
1596         strptr_i = &addstr_i;
1597       } else {
1598         strptr = remstr;
1599         strptr_i = &remstr_i;
1600       }
1601
1602       /* deal with modes that take clients */
1603       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1604         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
1605
1606       /* deal with modes that take strings */
1607       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
1608         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1609
1610       /*
1611        * deal with the limit.  Logic here is complicated; if HACK2 is set,
1612        * we're bouncing the mode, so sense is reversed, and we have to
1613        * include the original limit if it looks like it's being removed
1614        */
1615       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
1616         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1617     }
1618
1619     /* we were told to deop the source */
1620     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
1621       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
1622       addbuf[addbuf_i] = '\0'; /* terminate the string... */
1623       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
1624
1625       /* mark that we've done this, so we don't do it again */
1626       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
1627     }
1628
1629     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
1630       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
1631       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
1632                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
1633                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1634                             addbuf, remstr, addstr);
1635     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
1636       /*
1637        * If HACK2 was set, we're bouncing; we send the MODE back to the
1638        * connection we got it from with the senses reversed and a TS of 0;
1639        * origin is us
1640        */
1641       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
1642                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
1643                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
1644                     mbuf->mb_channel->creationtime);
1645     } else {
1646       /*
1647        * We're propagating a normal MODE command to the rest of the network;
1648        * we send the actual channel TS unless this is a HACK3 or a HACK4
1649        */
1650       if (IsServer(mbuf->mb_source))
1651         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1652                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
1653                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1654                               addbuf, remstr, addstr,
1655                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
1656                               mbuf->mb_channel->creationtime);
1657       else
1658         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1659                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
1660                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1661                               addbuf, remstr, addstr);
1662     }
1663   }
1664
1665   /* We've drained the ModeBuf... */
1666   mbuf->mb_add = 0;
1667   mbuf->mb_rem = 0;
1668   mbuf->mb_count = 0;
1669
1670   /* reinitialize the mode-with-arg slots */
1671   for (i = 0; i < MAXMODEPARAMS; i++) {
1672     /* If we saved any, pack them down */
1673     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
1674       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
1675       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
1676
1677       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
1678         continue;
1679     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
1680       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
1681
1682     MB_TYPE(mbuf, i) = 0;
1683     MB_UINT(mbuf, i) = 0;
1684   }
1685
1686   /* If we're supposed to flush it all, do so--all hail tail recursion */
1687   if (all && mbuf->mb_count)
1688     return modebuf_flush_int(mbuf, 1);
1689
1690   return 0;
1691 }
1692
1693 /*
1694  * This routine just initializes a ModeBuf structure with the information
1695  * needed and the options given.
1696  */
1697 void
1698 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
1699              struct Client *connect, struct Channel *chan, unsigned int dest)
1700 {
1701   int i;
1702
1703   assert(0 != mbuf);
1704   assert(0 != source);
1705   assert(0 != chan);
1706   assert(0 != dest);
1707
1708   mbuf->mb_add = 0;
1709   mbuf->mb_rem = 0;
1710   mbuf->mb_source = source;
1711   mbuf->mb_connect = connect;
1712   mbuf->mb_channel = chan;
1713   mbuf->mb_dest = dest;
1714   mbuf->mb_count = 0;
1715
1716   /* clear each mode-with-parameter slot */
1717   for (i = 0; i < MAXMODEPARAMS; i++) {
1718     MB_TYPE(mbuf, i) = 0;
1719     MB_UINT(mbuf, i) = 0;
1720   }
1721 }
1722
1723 /*
1724  * This routine simply adds modes to be added or deleted; do a binary OR
1725  * with either MODE_ADD or MODE_DEL
1726  */
1727 void
1728 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
1729 {
1730   assert(0 != mbuf);
1731   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1732
1733   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
1734            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
1735
1736   if (!(mode & ~(MODE_ADD | MODE_DEL))) /* don't add empty modes... */
1737     return;
1738
1739   if (mode & MODE_ADD) {
1740     mbuf->mb_rem &= ~mode;
1741     mbuf->mb_add |= mode;
1742   } else {
1743     mbuf->mb_add &= ~mode;
1744     mbuf->mb_rem |= mode;
1745   }
1746 }
1747
1748 /*
1749  * This routine adds a mode to be added or deleted that takes a unsigned
1750  * int parameter; mode may *only* be the relevant mode flag ORed with one
1751  * of MODE_ADD or MODE_DEL
1752  */
1753 void
1754 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
1755 {
1756   assert(0 != mbuf);
1757   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1758
1759   MB_TYPE(mbuf, mbuf->mb_count) = mode;
1760   MB_UINT(mbuf, mbuf->mb_count) = uint;
1761
1762   /* when we've reached the maximal count, flush the buffer */
1763   if (++mbuf->mb_count >=
1764       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1765     modebuf_flush_int(mbuf, 0);
1766 }
1767
1768 /*
1769  * This routine adds a mode to be added or deleted that takes a string
1770  * parameter; mode may *only* be the relevant mode flag ORed with one of
1771  * MODE_ADD or MODE_DEL
1772  */
1773 void
1774 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
1775                     int free)
1776 {
1777   assert(0 != mbuf);
1778   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1779
1780   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
1781   MB_STRING(mbuf, mbuf->mb_count) = string;
1782
1783   /* when we've reached the maximal count, flush the buffer */
1784   if (++mbuf->mb_count >=
1785       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1786     modebuf_flush_int(mbuf, 0);
1787 }
1788
1789 /*
1790  * This routine adds a mode to be added or deleted that takes a client
1791  * parameter; mode may *only* be the relevant mode flag ORed with one of
1792  * MODE_ADD or MODE_DEL
1793  */
1794 void
1795 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
1796                     struct Client *client)
1797 {
1798   assert(0 != mbuf);
1799   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1800
1801   MB_TYPE(mbuf, mbuf->mb_count) = mode;
1802   MB_CLIENT(mbuf, mbuf->mb_count) = client;
1803
1804   /* when we've reached the maximal count, flush the buffer */
1805   if (++mbuf->mb_count >=
1806       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1807     modebuf_flush_int(mbuf, 0);
1808 }
1809
1810 /*
1811  * This is the exported binding for modebuf_flush()
1812  */
1813 int
1814 modebuf_flush(struct ModeBuf *mbuf)
1815 {
1816   return modebuf_flush_int(mbuf, 1);
1817 }
1818
1819 /*
1820  * This extracts the simple modes contained in mbuf
1821  */
1822 void
1823 modebuf_extract(struct ModeBuf *mbuf, char *buf)
1824 {
1825   static int flags[] = {
1826 /*  MODE_CHANOP,        'o', */
1827 /*  MODE_VOICE,         'v', */
1828     MODE_PRIVATE,       'p',
1829     MODE_SECRET,        's',
1830     MODE_MODERATED,     'm',
1831     MODE_TOPICLIMIT,    't',
1832     MODE_INVITEONLY,    'i',
1833     MODE_NOPRIVMSGS,    'n',
1834     MODE_KEY,           'k',
1835 /*  MODE_BAN,           'b', */
1836     MODE_LIMIT,         'l',
1837     0x0, 0x0
1838   };
1839   unsigned int add;
1840   int i, bufpos = 0, len;
1841   int *flag_p;
1842   char *key = 0, limitbuf[20];
1843
1844   assert(0 != mbuf);
1845   assert(0 != buf);
1846
1847   buf[0] = '\0';
1848
1849   add = mbuf->mb_add;
1850
1851   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
1852     if (MB_TYPE(mbuf, i) & MODE_ADD) {
1853       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT);
1854
1855       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
1856         key = MB_STRING(mbuf, i);
1857       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
1858         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%d", MB_UINT(mbuf, i));
1859     }
1860   }
1861
1862   if (!add)
1863     return;
1864
1865   buf[bufpos++] = '+'; /* start building buffer */
1866
1867   for (flag_p = flags; flag_p[0]; flag_p += 2)
1868     if (*flag_p & add)
1869       buf[bufpos++] = flag_p[1];
1870
1871   for (i = 0, len = bufpos; i < len; i++) {
1872     if (buf[i] == 'k')
1873       build_string(buf, &bufpos, key, 0, ' ');
1874     else if (buf[i] == 'l')
1875       build_string(buf, &bufpos, limitbuf, 0, ' ');
1876   }
1877
1878   buf[bufpos] = '\0';
1879
1880   return;
1881 }
1882
1883 /*
1884  * Simple function to invalidate bans
1885  */
1886 void
1887 mode_ban_invalidate(struct Channel *chan)
1888 {
1889   struct Membership *member;
1890
1891   for (member = chan->members; member; member = member->next_member)
1892     ClearBanValid(member);
1893 }
1894
1895 /*
1896  * Simple function to drop invite structures
1897  */
1898 void
1899 mode_invite_clear(struct Channel *chan)
1900 {
1901   while (chan->invites)
1902     del_invite(chan->invites->value.cptr, chan);
1903 }
1904
1905 /* What we've done for mode_parse so far... */
1906 #define DONE_LIMIT      0x01    /* We've set the limit */
1907 #define DONE_KEY        0x02    /* We've set the key */
1908 #define DONE_BANLIST    0x04    /* We've sent the ban list */
1909 #define DONE_NOTOPER    0x08    /* We've sent a "Not oper" error */
1910 #define DONE_BANCLEAN   0x10    /* We've cleaned bans... */
1911
1912 struct ParseState {
1913   struct ModeBuf *mbuf;
1914   struct Client *cptr;
1915   struct Client *sptr;
1916   struct Channel *chptr;
1917   int parc;
1918   char **parv;
1919   unsigned int flags;
1920   unsigned int dir;
1921   unsigned int done;
1922   unsigned int add;
1923   unsigned int del;
1924   int args_used;
1925   int max_args;
1926   int numbans;
1927   struct SLink banlist[MAXPARA];
1928   struct {
1929     unsigned int flag;
1930     struct Client *client;
1931   } cli_change[MAXPARA];
1932 };
1933
1934 /*
1935  * Here's a helper function to deal with sending along "Not oper" or
1936  * "Not member" messages
1937  */
1938 static void
1939 send_notoper(struct ParseState *state)
1940 {
1941   if (state->done & DONE_NOTOPER)
1942     return;
1943
1944   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
1945              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
1946
1947   state->done |= DONE_NOTOPER;
1948 }
1949
1950 /*
1951  * Helper function to convert limits
1952  */
1953 static void
1954 mode_parse_limit(struct ParseState *state, int *flag_p)
1955 {
1956   unsigned int t_limit;
1957
1958   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
1959     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
1960       return;
1961
1962     if (state->parc <= 0) { /* warn if not enough args */
1963       if (MyUser(state->sptr))
1964         need_more_params(state->sptr, "MODE +l");
1965       return;
1966     }
1967
1968     t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
1969     state->parc--;
1970     state->max_args--;
1971
1972     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
1973         (!t_limit || t_limit == state->chptr->mode.limit))
1974       return;
1975   } else
1976     t_limit = state->chptr->mode.limit;
1977
1978   /* If they're not an oper, they can't change modes */
1979   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
1980     send_notoper(state);
1981     return;
1982   }
1983
1984   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
1985     return;
1986   state->done |= DONE_LIMIT;
1987
1988   if (!state->mbuf)
1989     return;
1990
1991   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
1992
1993   if (state->flags & MODE_PARSE_SET) { /* set the limit */
1994     if (state->dir & MODE_ADD) {
1995       state->chptr->mode.mode |= flag_p[0];
1996       state->chptr->mode.limit = t_limit;
1997     } else {
1998       state->chptr->mode.mode &= ~flag_p[0];
1999       state->chptr->mode.limit = 0;
2000     }
2001   }
2002 }
2003
2004 /*
2005  * Helper function to convert keys
2006  */
2007 static void
2008 mode_parse_key(struct ParseState *state, int *flag_p)
2009 {
2010   char *t_str, *s;
2011   int t_len;
2012
2013   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2014     return;
2015
2016   if (state->parc <= 0) { /* warn if not enough args */
2017     if (MyUser(state->sptr))
2018       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2019                        "MODE -k");
2020     return;
2021   }
2022
2023   t_str = state->parv[state->args_used++]; /* grab arg */
2024   state->parc--;
2025   state->max_args--;
2026
2027   /* If they're not an oper, they can't change modes */
2028   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2029     send_notoper(state);
2030     return;
2031   }
2032
2033   if (state->done & DONE_KEY) /* allow key to be set only once */
2034     return;
2035   state->done |= DONE_KEY;
2036
2037   t_len = KEYLEN + 1;
2038
2039   /* clean up the key string */
2040   s = t_str;
2041   while (*++s > ' ' && *s != ':' && --t_len)
2042     ;
2043   *s = '\0';
2044
2045   if (!*t_str) { /* warn if empty */
2046     if (MyUser(state->sptr))
2047       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2048                        "MODE -k");
2049     return;
2050   }
2051
2052   if (!state->mbuf)
2053     return;
2054
2055   /* can't add a key if one is set, nor can one remove the wrong key */
2056   if (!(state->flags & MODE_PARSE_FORCE))
2057     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
2058         (state->dir == MODE_DEL &&
2059          ircd_strcmp(state->chptr->mode.key, t_str))) {
2060       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2061       return;
2062     }
2063
2064   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2065       !ircd_strcmp(state->chptr->mode.key, t_str))
2066     return; /* no key change */
2067
2068   if (state->flags & MODE_PARSE_BOUNCE) {
2069     if (*state->chptr->mode.key) /* reset old key */
2070       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2071                           state->chptr->mode.key, 0);
2072     else /* remove new bogus key */
2073       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2074   } else /* send new key */
2075     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2076
2077   if (state->flags & MODE_PARSE_SET) {
2078     if (state->dir == MODE_ADD) /* set the new key */
2079       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
2080     else /* remove the old key */
2081       *state->chptr->mode.key = '\0';
2082   }
2083 }
2084
2085 /*
2086  * Helper function to convert bans
2087  */
2088 static void
2089 mode_parse_ban(struct ParseState *state, int *flag_p)
2090 {
2091   char *t_str, *s;
2092   struct SLink *ban, *newban = 0;
2093
2094   if (state->parc <= 0) { /* Not enough args, send ban list */
2095     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
2096       send_ban_list(state->sptr, state->chptr);
2097       state->done |= DONE_BANLIST;
2098     }
2099
2100     return;
2101   }
2102
2103   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2104     return;
2105
2106   t_str = state->parv[state->args_used++]; /* grab arg */
2107   state->parc--;
2108   state->max_args--;
2109
2110   /* If they're not an oper, they can't change modes */
2111   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2112     send_notoper(state);
2113     return;
2114   }
2115
2116   if ((s = strchr(t_str, ' ')))
2117     *s = '\0';
2118
2119   if (!*t_str || *t_str == ':') { /* warn if empty */
2120     if (MyUser(state->sptr))
2121       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
2122                        "MODE -b");
2123     return;
2124   }
2125
2126   t_str = collapse(pretty_mask(t_str));
2127
2128   /* remember the ban for the moment... */
2129   if (state->dir == MODE_ADD) {
2130     newban = state->banlist + (state->numbans++);
2131     newban->next = 0;
2132
2133     DupString(newban->value.ban.banstr, t_str);
2134     newban->value.ban.who = cli_name(state->sptr);
2135     newban->value.ban.when = TStime();
2136
2137     newban->flags = CHFL_BAN | MODE_ADD;
2138
2139     if ((s = strrchr(t_str, '@')) && check_if_ipmask(s + 1))
2140       newban->flags |= CHFL_BAN_IPMASK;
2141   }
2142
2143   if (!state->chptr->banlist) {
2144     state->chptr->banlist = newban; /* add our ban with its flags */
2145     state->done |= DONE_BANCLEAN;
2146     return;
2147   }
2148
2149   /* Go through all bans */
2150   for (ban = state->chptr->banlist; ban; ban = ban->next) {
2151     /* first, clean the ban flags up a bit */
2152     if (!(state->done & DONE_BANCLEAN))
2153       /* Note: We're overloading *lots* of bits here; be careful! */
2154       ban->flags &= ~(MODE_ADD | MODE_DEL | CHFL_BAN_OVERLAPPED);
2155
2156     /* Bit meanings:
2157      *
2158      * MODE_ADD            - Ban was added; if we're bouncing modes,
2159      *                       then we'll remove it below; otherwise,
2160      *                       we'll have to allocate a real ban
2161      *
2162      * MODE_DEL            - Ban was marked for deletion; if we're
2163      *                       bouncing modes, we'll have to re-add it,
2164      *                       otherwise, we'll have to remove it
2165      *
2166      * CHFL_BAN_OVERLAPPED - The ban we added turns out to overlap
2167      *                       with a ban already set; if we're
2168      *                       bouncing modes, we'll have to bounce
2169      *                       this one; otherwise, we'll just ignore
2170      *                       it when we process added bans
2171      */
2172
2173     if (state->dir == MODE_DEL && !ircd_strcmp(ban->value.ban.banstr, t_str)) {
2174       ban->flags |= MODE_DEL; /* delete one ban */
2175
2176       if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
2177         break;
2178     } else if (state->dir == MODE_ADD) {
2179       /* if the ban already exists, don't worry about it */
2180       if (!ircd_strcmp(ban->value.ban.banstr, t_str)) {
2181         newban->flags &= ~MODE_ADD; /* don't add ban at all */
2182         MyFree(newban->value.ban.banstr); /* stopper a leak */
2183         state->numbans--; /* deallocate last ban */
2184         if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
2185           break;
2186       } else if (!mmatch(ban->value.ban.banstr, t_str)) {
2187         if (!(ban->flags & MODE_DEL))
2188           newban->flags |= CHFL_BAN_OVERLAPPED; /* our ban overlaps */
2189       } else if (!mmatch(t_str, ban->value.ban.banstr))
2190         ban->flags |= MODE_DEL; /* mark ban for deletion: overlapping */
2191
2192       if (!ban->next && (newban->flags & MODE_ADD)) {
2193         ban->next = newban; /* add our ban with its flags */
2194         break; /* get out of loop */
2195       }
2196     }
2197   }
2198   state->done |= DONE_BANCLEAN;
2199 }
2200
2201 /*
2202  * This is the bottom half of the ban processor
2203  */
2204 static void
2205 mode_process_bans(struct ParseState *state)
2206 {
2207   struct SLink *ban, *newban, *prevban, *nextban;
2208   int count = 0;
2209   int len = 0;
2210   int banlen;
2211   int changed = 0;
2212
2213   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
2214     count++;
2215     banlen = strlen(ban->value.ban.banstr);
2216     len += banlen;
2217     nextban = ban->next;
2218
2219     if ((ban->flags & (MODE_DEL | MODE_ADD)) == (MODE_DEL | MODE_ADD)) {
2220       if (prevban)
2221         prevban->next = 0; /* Break the list; ban isn't a real ban */
2222       else
2223         state->chptr->banlist = 0;
2224
2225       count--;
2226       len -= banlen;
2227
2228       MyFree(ban->value.ban.banstr);
2229
2230       continue;
2231     } else if (ban->flags & MODE_DEL) { /* Deleted a ban? */
2232       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
2233                           ban->value.ban.banstr,
2234                           state->flags & MODE_PARSE_SET);
2235
2236       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
2237         if (prevban) /* clip it out of the list... */
2238           prevban->next = ban->next;
2239         else
2240           state->chptr->banlist = ban->next;
2241
2242         count--;
2243         len -= banlen;
2244
2245         MyFree(ban->value.ban.who);
2246         free_link(ban);
2247
2248         changed++;
2249         continue; /* next ban; keep prevban like it is */
2250       } else
2251         ban->flags &= (CHFL_BAN | CHFL_BAN_IPMASK); /* unset other flags */
2252     } else if (ban->flags & MODE_ADD) { /* adding a ban? */
2253       if (prevban)
2254         prevban->next = 0; /* Break the list; ban isn't a real ban */
2255       else
2256         state->chptr->banlist = 0;
2257
2258       /* If we're supposed to ignore it, do so. */
2259       if (ban->flags & CHFL_BAN_OVERLAPPED &&
2260           !(state->flags & MODE_PARSE_BOUNCE)) {
2261         count--;
2262         len -= banlen;
2263
2264         MyFree(ban->value.ban.banstr);
2265       } else {
2266         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
2267             (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
2268              count >= feature_int(FEAT_MAXBANS))) {
2269           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
2270                      ban->value.ban.banstr);
2271           count--;
2272           len -= banlen;
2273
2274           MyFree(ban->value.ban.banstr);
2275         } else {
2276           /* add the ban to the buffer */
2277           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
2278                               ban->value.ban.banstr,
2279                               !(state->flags & MODE_PARSE_SET));
2280
2281           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
2282             newban = make_link();
2283             newban->value.ban.banstr = ban->value.ban.banstr;
2284             DupString(newban->value.ban.who, ban->value.ban.who);
2285             newban->value.ban.when = ban->value.ban.when;
2286             newban->flags = ban->flags & (CHFL_BAN | CHFL_BAN_IPMASK);
2287
2288             newban->next = state->chptr->banlist; /* and link it in */
2289             state->chptr->banlist = newban;
2290
2291             changed++;
2292           }
2293         }
2294       }
2295     }
2296
2297     prevban = ban;
2298   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
2299
2300   if (changed) /* if we changed the ban list, we must invalidate the bans */
2301     mode_ban_invalidate(state->chptr);
2302 }
2303
2304 /*
2305  * Helper function to process client changes
2306  */
2307 static void
2308 mode_parse_client(struct ParseState *state, int *flag_p)
2309 {
2310   char *t_str;
2311   struct Client *acptr;
2312   int i;
2313
2314   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2315     return;
2316
2317   if (state->parc <= 0) /* return if not enough args */
2318     return;
2319
2320   t_str = state->parv[state->args_used++]; /* grab arg */
2321   state->parc--;
2322   state->max_args--;
2323
2324   /* If they're not an oper, they can't change modes */
2325   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2326     send_notoper(state);
2327     return;
2328   }
2329
2330   if (MyUser(state->sptr)) /* find client we're manipulating */
2331     acptr = find_chasing(state->sptr, t_str, NULL);
2332   else
2333     acptr = findNUser(t_str);
2334
2335   if (!acptr)
2336     return; /* find_chasing() already reported an error to the user */
2337
2338   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
2339     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
2340                                        state->cli_change[i].flag & flag_p[0]))
2341       break; /* found a slot */
2342
2343   /* Store what we're doing to them */
2344   state->cli_change[i].flag = state->dir | flag_p[0];
2345   state->cli_change[i].client = acptr;
2346 }
2347
2348 /*
2349  * Helper function to process the changed client list
2350  */
2351 static void
2352 mode_process_clients(struct ParseState *state)
2353 {
2354   int i;
2355   struct Membership *member;
2356
2357   for (i = 0; state->cli_change[i].flag; i++) {
2358     assert(0 != state->cli_change[i].client);
2359
2360     /* look up member link */
2361     if (!(member = find_member_link(state->chptr,
2362                                     state->cli_change[i].client)) ||
2363         (MyUser(state->sptr) && IsZombie(member))) {
2364       if (MyUser(state->sptr))
2365         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
2366                    cli_name(state->cli_change[i].client),
2367                    state->chptr->chname);
2368       continue;
2369     }
2370
2371     if ((state->cli_change[i].flag & MODE_ADD &&
2372          (state->cli_change[i].flag & member->status)) ||
2373         (state->cli_change[i].flag & MODE_DEL &&
2374          !(state->cli_change[i].flag & member->status)))
2375       continue; /* no change made, don't do anything */
2376
2377     /* see if the deop is allowed */
2378     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
2379         (MODE_DEL | MODE_CHANOP)) {
2380       /* prevent +k users from being deopped */
2381       if (IsChannelService(state->cli_change[i].client)) {
2382         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
2383           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
2384                                state->chptr,
2385                                (IsServer(state->sptr) ? cli_name(state->sptr) :
2386                                 cli_name((cli_user(state->sptr))->server)));
2387
2388         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
2389           send_reply(state->sptr, ERR_ISCHANSERVICE,
2390                      cli_name(state->cli_change[i].client),
2391                      state->chptr->chname);
2392           continue;
2393         }
2394       }
2395
2396       /* don't allow local opers to be deopped on local channels */
2397       if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
2398           IsLocalChannel(state->chptr->chname) &&
2399           HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
2400         send_reply(state->sptr, ERR_ISOPERLCHAN,
2401                    cli_name(state->cli_change[i].client),
2402                    state->chptr->chname);
2403         continue;
2404       }
2405     }
2406
2407     /* accumulate the change */
2408     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
2409                         state->cli_change[i].client);
2410
2411     /* actually effect the change */
2412     if (state->flags & MODE_PARSE_SET) {
2413       if (state->cli_change[i].flag & MODE_ADD) {
2414         member->status |= (state->cli_change[i].flag &
2415                            (MODE_CHANOP | MODE_VOICE));
2416         if (state->cli_change[i].flag & MODE_CHANOP)
2417           ClearDeopped(member);
2418       } else
2419         member->status &= ~(state->cli_change[i].flag &
2420                             (MODE_CHANOP | MODE_VOICE));
2421     }
2422   } /* for (i = 0; state->cli_change[i].flags; i++) { */
2423 }
2424
2425 /*
2426  * Helper function to process the simple modes
2427  */
2428 static void
2429 mode_parse_mode(struct ParseState *state, int *flag_p)
2430 {
2431   /* If they're not an oper, they can't change modes */
2432   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2433     send_notoper(state);
2434     return;
2435   }
2436
2437   if (!state->mbuf)
2438     return;
2439
2440   if (state->dir == MODE_ADD) {
2441     state->add |= flag_p[0];
2442     state->del &= ~flag_p[0];
2443
2444     if (flag_p[0] & MODE_SECRET) {
2445       state->add &= ~MODE_PRIVATE;
2446       state->del |= MODE_PRIVATE;
2447     } else if (flag_p[0] & MODE_PRIVATE) {
2448       state->add &= ~MODE_SECRET;
2449       state->del |= MODE_SECRET;
2450     }
2451   } else {
2452     state->add &= ~flag_p[0];
2453     state->del |= flag_p[0];
2454   }
2455
2456   assert(0 == (state->add & state->del));
2457   assert((MODE_SECRET | MODE_PRIVATE) !=
2458          (state->add & (MODE_SECRET | MODE_PRIVATE)));
2459 }
2460
2461 /*
2462  * This routine is intended to parse MODE or OPMODE commands and effect the
2463  * changes (or just build the bounce buffer).  We pass the starting offset
2464  * as a 
2465  */
2466 int
2467 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
2468            struct Channel *chptr, int parc, char *parv[], unsigned int flags)
2469 {
2470   static int chan_flags[] = {
2471     MODE_CHANOP,        'o',
2472     MODE_VOICE,         'v',
2473     MODE_PRIVATE,       'p',
2474     MODE_SECRET,        's',
2475     MODE_MODERATED,     'm',
2476     MODE_TOPICLIMIT,    't',
2477     MODE_INVITEONLY,    'i',
2478     MODE_NOPRIVMSGS,    'n',
2479     MODE_KEY,           'k',
2480     MODE_BAN,           'b',
2481     MODE_LIMIT,         'l',
2482     MODE_ADD,           '+',
2483     MODE_DEL,           '-',
2484     0x0, 0x0
2485   };
2486   int i;
2487   int *flag_p;
2488   unsigned int t_mode;
2489   char *modestr;
2490   struct ParseState state;
2491
2492   assert(0 != cptr);
2493   assert(0 != sptr);
2494   assert(0 != chptr);
2495   assert(0 != parc);
2496   assert(0 != parv);
2497
2498   state.mbuf = mbuf;
2499   state.cptr = cptr;
2500   state.sptr = sptr;
2501   state.chptr = chptr;
2502   state.parc = parc;
2503   state.parv = parv;
2504   state.flags = flags;
2505   state.dir = MODE_ADD;
2506   state.done = 0;
2507   state.add = 0;
2508   state.del = 0;
2509   state.args_used = 0;
2510   state.max_args = MAXMODEPARAMS;
2511   state.numbans = 0;
2512
2513   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
2514     state.banlist[i].next = 0;
2515     state.banlist[i].value.ban.banstr = 0;
2516     state.banlist[i].value.ban.who = 0;
2517     state.banlist[i].value.ban.when = 0;
2518     state.banlist[i].flags = 0;
2519     state.cli_change[i].flag = 0;
2520     state.cli_change[i].client = 0;
2521   }
2522
2523   modestr = state.parv[state.args_used++];
2524   state.parc--;
2525
2526   while (*modestr) {
2527     for (; *modestr; modestr++) {
2528       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
2529         if (flag_p[1] == *modestr)
2530           break;
2531
2532       if (!flag_p[0]) { /* didn't find it?  complain and continue */
2533         if (MyUser(state.sptr))
2534           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
2535         continue;
2536       }
2537
2538       switch (*modestr) {
2539       case '+': /* switch direction to MODE_ADD */
2540       case '-': /* switch direction to MODE_DEL */
2541         state.dir = flag_p[0];
2542         break;
2543
2544       case 'l': /* deal with limits */
2545         mode_parse_limit(&state, flag_p);
2546         break;
2547
2548       case 'k': /* deal with keys */
2549         mode_parse_key(&state, flag_p);
2550         break;
2551
2552       case 'b': /* deal with bans */
2553         mode_parse_ban(&state, flag_p);
2554         break;
2555
2556       case 'o': /* deal with ops/voice */
2557       case 'v':
2558         mode_parse_client(&state, flag_p);
2559         break;
2560
2561       default: /* deal with other modes */
2562         mode_parse_mode(&state, flag_p);
2563         break;
2564       } /* switch (*modestr) { */
2565     } /* for (; *modestr; modestr++) { */
2566
2567     if (state.flags & MODE_PARSE_BURST)
2568       break; /* don't interpret any more arguments */
2569
2570     if (state.parc > 0) { /* process next argument in string */
2571       modestr = state.parv[state.args_used++];
2572       state.parc--;
2573
2574       /* is it a TS? */
2575       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
2576         time_t recv_ts;
2577
2578         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
2579           break;                     /* we're then going to bounce the mode! */
2580
2581         recv_ts = atoi(modestr);
2582
2583         if (recv_ts && recv_ts < state.chptr->creationtime)
2584           state.chptr->creationtime = recv_ts; /* respect earlier TS */
2585
2586         break; /* break out of while loop */
2587       } else if (state.flags & MODE_PARSE_STRICT ||
2588                  (MyUser(state.sptr) && state.max_args <= 0)) {
2589         state.parc++; /* we didn't actually gobble the argument */
2590         state.args_used--;
2591         break; /* break out of while loop */
2592       }
2593     }
2594   } /* while (*modestr) { */
2595
2596   /*
2597    * the rest of the function finishes building resultant MODEs; if the
2598    * origin isn't a member or an oper, skip it.
2599    */
2600   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
2601     return state.args_used; /* tell our parent how many args we gobbled */
2602
2603   t_mode = state.chptr->mode.mode;
2604
2605   if (state.del & t_mode) { /* delete any modes to be deleted... */
2606     modebuf_mode(state.mbuf, MODE_DEL | (state.del & t_mode));
2607
2608     t_mode &= ~state.del;
2609   }
2610   if (state.add & ~t_mode) { /* add any modes to be added... */
2611     modebuf_mode(state.mbuf, MODE_ADD | (state.add & ~t_mode));
2612
2613     t_mode |= state.add;
2614   }
2615
2616   if (state.flags & MODE_PARSE_SET) { /* set the channel modes */
2617     if ((state.chptr->mode.mode & MODE_INVITEONLY) &&
2618         !(t_mode & MODE_INVITEONLY))
2619       mode_invite_clear(state.chptr);
2620
2621     state.chptr->mode.mode = t_mode;
2622   }
2623
2624   if (state.flags & MODE_PARSE_WIPEOUT) {
2625     if (state.chptr->mode.limit && !(state.done & DONE_LIMIT))
2626       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
2627                         state.chptr->mode.limit);
2628     if (*state.chptr->mode.key && !(state.done & DONE_KEY))
2629       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
2630                           state.chptr->mode.key, 0);
2631   }
2632
2633   if (state.done & DONE_BANCLEAN) /* process bans */
2634     mode_process_bans(&state);
2635
2636   /* process client changes */
2637   if (state.cli_change[0].flag)
2638     mode_process_clients(&state);
2639
2640   return state.args_used; /* tell our parent how many args we gobbled */
2641 }
2642
2643 /*
2644  * Initialize a join buffer
2645  */
2646 void
2647 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
2648              struct Client *connect, unsigned int type, char *comment,
2649              time_t create)
2650 {
2651   int i;
2652
2653   assert(0 != jbuf);
2654   assert(0 != source);
2655   assert(0 != connect);
2656
2657   jbuf->jb_source = source; /* just initialize struct JoinBuf */
2658   jbuf->jb_connect = connect;
2659   jbuf->jb_type = type;
2660   jbuf->jb_comment = comment;
2661   jbuf->jb_create = create;
2662   jbuf->jb_count = 0;
2663   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
2664                        type == JOINBUF_TYPE_PART ||
2665                        type == JOINBUF_TYPE_PARTALL) ?
2666                       STARTJOINLEN : STARTCREATELEN) +
2667                      (comment ? strlen(comment) + 2 : 0));
2668
2669   for (i = 0; i < MAXJOINARGS; i++)
2670     jbuf->jb_channels[i] = 0;
2671 }
2672
2673 /*
2674  * Add a channel to the join buffer
2675  */
2676 void
2677 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
2678 {
2679   unsigned int len;
2680
2681   assert(0 != jbuf);
2682
2683   if (!chan) {
2684     if (jbuf->jb_type == JOINBUF_TYPE_JOIN)
2685       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect, "0");
2686
2687     return;
2688   }
2689
2690   if (jbuf->jb_type == JOINBUF_TYPE_PART ||
2691       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
2692     /* Send notification to channel */
2693     if (!(flags & CHFL_ZOMBIE))
2694       sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
2695                                 (flags & CHFL_BANNED || !jbuf->jb_comment) ?
2696                                 ":%H" : "%H :%s", chan, jbuf->jb_comment);
2697     else if (MyUser(jbuf->jb_source))
2698       sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
2699                     (flags & CHFL_BANNED || !jbuf->jb_comment) ?
2700                     ":%H" : "%H :%s", chan, jbuf->jb_comment);
2701     /* XXX: Shouldn't we send a PART here anyway? */
2702     /* to users on the channel?  Why?  From their POV, the user isn't on
2703      * the channel anymore anyway.  We don't send to servers until below,
2704      * when we gang all the channel parts together.  Note that this is
2705      * exactly the same logic, albeit somewhat more concise, as was in
2706      * the original m_part.c */
2707
2708     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
2709         IsLocalChannel(chan->chname)) /* got to remove user here */
2710       remove_user_from_channel(jbuf->jb_source, chan);
2711   } else {
2712     /* Add user to channel */
2713     add_user_to_channel(chan, jbuf->jb_source, flags);
2714
2715     /* send notification to all servers */
2716     if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !IsLocalChannel(chan->chname))
2717       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
2718                             "%H %Tu", chan, chan->creationtime);
2719
2720     /* Send the notification to the channel */
2721     sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
2722
2723     /* send an op, too, if needed */
2724     if (!MyUser(jbuf->jb_source) && jbuf->jb_type == JOINBUF_TYPE_CREATE &&
2725         !IsModelessChannel(chan->chname))
2726       sendcmdto_channel_butserv(jbuf->jb_source, CMD_MODE, chan, "%H +o %C",
2727                                 chan, jbuf->jb_source);
2728   }
2729
2730   if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
2731     return; /* don't send to remote */
2732
2733   /* figure out if channel name will cause buffer to be overflowed */
2734   len = chan ? strlen(chan->chname) + 1 : 2;
2735   if (jbuf->jb_strlen + len > BUFSIZE)
2736     joinbuf_flush(jbuf);
2737
2738   /* add channel to list of channels to send and update counts */
2739   jbuf->jb_channels[jbuf->jb_count++] = chan;
2740   jbuf->jb_strlen += len;
2741
2742   /* if we've used up all slots, flush */
2743   if (jbuf->jb_count >= MAXJOINARGS)
2744     joinbuf_flush(jbuf);
2745 }
2746
2747 /*
2748  * Flush the channel list to remote servers
2749  */
2750 int
2751 joinbuf_flush(struct JoinBuf *jbuf)
2752 {
2753   char chanlist[BUFSIZE];
2754   int chanlist_i = 0;
2755   int i;
2756
2757   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
2758       jbuf->jb_type == JOINBUF_TYPE_JOIN)
2759     return 0; /* no joins to process */
2760
2761   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
2762     build_string(chanlist, &chanlist_i,
2763                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
2764                  i == 0 ? '\0' : ',');
2765     if (JOINBUF_TYPE_PART == jbuf->jb_type)
2766       /* Remove user from channel */
2767       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
2768
2769     jbuf->jb_channels[i] = 0; /* mark slot empty */
2770   }
2771
2772   jbuf->jb_count = 0; /* reset base counters */
2773   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_PART ?
2774                       STARTJOINLEN : STARTCREATELEN) +
2775                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
2776
2777   /* and send the appropriate command */
2778   switch (jbuf->jb_type) {
2779   case JOINBUF_TYPE_CREATE:
2780     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
2781                           "%s %Tu", chanlist, jbuf->jb_create);
2782     break;
2783
2784   case JOINBUF_TYPE_PART:
2785     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
2786                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
2787                           jbuf->jb_comment);
2788     break;
2789   }
2790
2791   return 0;
2792 }