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