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