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