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