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