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