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