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