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