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_reply.h"
29 #include "ircd_snprintf.h"
30 #include "ircd_string.h"
31 #include "list.h"
32 #include "match.h"
33 #include "msg.h"
34 #include "numeric.h"
35 #include "numnicks.h"
36 #include "querycmds.h"
37 #include "s_bsd.h"
38 #include "s_conf.h"
39 #include "s_debug.h"
40 #include "s_misc.h"
41 #include "s_user.h"
42 #include "send.h"
43 #include "sprintf_irc.h"
44 #include "struct.h"
45 #include "support.h"
46 #include "sys.h"
47 #include "whowas.h"
48
49 #include <assert.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53
54 struct Channel* GlobalChannelList = 0;
55
56 static struct SLink *next_overlapped_ban(void);
57 static int del_banid(struct Channel *, char *, int);
58 void del_invite(struct Client *, struct Channel *);
59
60 const char* const PartFmt1     = ":%s " MSG_PART " %s";
61 const char* const PartFmt2     = ":%s " MSG_PART " %s :%s";
62 const char* const PartFmt1serv = "%s%s " TOK_PART " %s";
63 const char* const PartFmt2serv = "%s%s " TOK_PART " %s :%s";
64
65
66 static struct SLink* next_ban;
67 static struct SLink* prev_ban;
68 static struct SLink* removed_bans_list;
69
70 /*
71  * Use a global variable to remember if an oper set a mode on a local channel. Ugly,
72  * but the only way to do it without changing set_mode intensively.
73  */
74 int LocalChanOperMode = 0;
75
76 #if !defined(NDEBUG)
77 /*
78  * return the length (>=0) of a chain of links.
79  */
80 static int list_length(struct SLink *lp)
81 {
82   int count = 0;
83
84   for (; lp; lp = lp->next)
85     ++count;
86   return count;
87 }
88 #endif
89
90 struct Membership* find_member_link(struct Channel* chptr, const struct Client* cptr)
91 {
92   struct Membership *m;
93   assert(0 != cptr);
94   assert(0 != chptr);
95   
96   /* Servers don't have member links */
97   if (IsServer(cptr))
98      return 0;
99   
100   /* +k users are typically on a LOT of channels.  So we iterate over who
101    * is in the channel.  X/W are +k and are in about 5800 channels each.
102    * however there are typically no more than 1000 people in a channel
103    * at a time.
104    */
105   if (IsChannelService(cptr)) {
106     m = chptr->members;
107     while (m) {
108       assert(m->channel == chptr);
109       if (m->user == cptr)
110         return m;
111       m = m->next_member;
112     }
113   }
114   /* Users on the other hand aren't allowed on more than 15 channels.  50%
115    * of users that are on channels are on 2 or less, 95% are on 7 or less,
116    * and 99% are on 10 or less.
117    */
118   else {
119    m = cptr->user->channel;
120    while (m) {
121      assert(m->user == cptr);
122      if (m->channel == chptr)
123        return m;
124      m = m->next_channel;
125    }
126   }
127   return 0;
128 }
129
130 /*
131  * find_chasing - Find the client structure for a nick name (user)
132  * using history mechanism if necessary. If the client is not found, an error
133  * message (NO SUCH NICK) is generated. If the client was found
134  * through the history, chasing will be 1 and otherwise 0.
135  */
136 struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
137 {
138   struct Client* who = FindClient(user);
139
140   if (chasing)
141     *chasing = 0;
142   if (who)
143     return who;
144
145   if (!(who = get_history(user, KILLCHASETIMELIMIT))) {
146     send_reply(sptr, ERR_NOSUCHNICK, user);
147     return 0;
148   }
149   if (chasing)
150     *chasing = 1;
151   return who;
152 }
153
154 /*
155  * Create a string of form "foo!bar@fubar" given foo, bar and fubar
156  * as the parameters.  If NULL, they become "*".
157  */
158 static char *make_nick_user_host(const char *nick, const char *name,
159                                  const char *host)
160 {
161   static char namebuf[NICKLEN + USERLEN + HOSTLEN + 3];
162   sprintf_irc(namebuf, "%s!%s@%s", nick, name, host);
163   return namebuf;
164 }
165
166 /*
167  * Create a string of form "foo!bar@123.456.789.123" given foo, bar and the
168  * IP-number as the parameters.  If NULL, they become "*".
169  */
170 static char *make_nick_user_ip(char *nick, char *name, struct in_addr ip)
171 {
172   static char ipbuf[NICKLEN + USERLEN + 16 + 3];
173   sprintf_irc(ipbuf, "%s!%s@%s", nick, name, ircd_ntoa((const char*) &ip));
174   return ipbuf;
175 }
176
177 #if 0
178 static int DoesOp(const char* modebuf)
179 {
180   assert(0 != modebuf);
181   while (*modebuf) {
182     if (*modebuf == 'o' || *modebuf == 'v')
183       return 1;
184     ++modebuf;
185   }
186   return 0;
187 }
188
189 /*
190  * This function should be removed when all servers are 2.10
191  */
192 static void sendmodeto_one(struct Client* cptr, const char* from,
193                            const char* name, const char* mode,
194                            const char* param, time_t creationtime)
195 {
196   if (IsServer(cptr) && DoesOp(mode) && creationtime)
197     sendto_one(cptr, ":%s MODE %s %s %s " TIME_T_FMT, /* XXX DEAD */
198                from, name, mode, param, creationtime);
199   else
200     sendto_one(cptr, ":%s MODE %s %s %s", from, name, mode, param); /* XXX DEAD */
201 }
202 #endif /* 0 */
203
204 /*
205  * Subtract one user from channel i (and free channel
206  * block, if channel became empty).
207  * Returns: true  (1) if channel still exists
208  *          false (0) if the channel was destroyed
209  */
210 int sub1_from_channel(struct Channel* chptr)
211 {
212   struct SLink *tmp;
213   struct SLink *obtmp;
214
215   if (chptr->users > 1)         /* Can be 0, called for an empty channel too */
216   {
217     assert(0 != chptr->members);
218     --chptr->users;
219     return 1;
220   }
221
222   assert(0 == chptr->members);
223
224   /* Channel became (or was) empty: Remove channel */
225   if (is_listed(chptr))
226   {
227     int i;
228     for (i = 0; i <= HighestFd; i++)
229     {
230       struct Client *acptr;
231       if ((acptr = LocalClientArray[i]) && acptr->listing &&
232           acptr->listing->chptr == chptr)
233       {
234         list_next_channels(acptr, 1);
235         break;                  /* Only one client can list a channel */
236       }
237     }
238   }
239   /*
240    * Now, find all invite links from channel structure
241    */
242   while ((tmp = chptr->invites))
243     del_invite(tmp->value.cptr, chptr);
244
245   tmp = chptr->banlist;
246   while (tmp)
247   {
248     obtmp = tmp;
249     tmp = tmp->next;
250     MyFree(obtmp->value.ban.banstr);
251     MyFree(obtmp->value.ban.who);
252     free_link(obtmp);
253   }
254   if (chptr->prev)
255     chptr->prev->next = chptr->next;
256   else
257     GlobalChannelList = chptr->next;
258   if (chptr->next)
259     chptr->next->prev = chptr->prev;
260   hRemChannel(chptr);
261   --UserStats.channels;
262   /*
263    * make sure that channel actually got removed from hash table
264    */
265   assert(chptr->hnext == chptr);
266   MyFree(chptr);
267   return 0;
268 }
269
270 /*
271  * add_banid
272  *
273  * `cptr' must be the client adding the ban.
274  *
275  * If `change' is true then add `banid' to channel `chptr'.
276  * Returns 0 if the ban was added.
277  * Returns -2 if the ban already existed and was marked CHFL_BURST_BAN_WIPEOUT.
278  * Return -1 otherwise.
279  *
280  * Those bans that overlapped with `banid' are flagged with CHFL_BAN_OVERLAPPED
281  * when `change' is false, otherwise they will be removed from the banlist.
282  * Subsequently calls to next_overlapped_ban() or next_removed_overlapped_ban()
283  * respectively will return these bans until NULL is returned.
284  *
285  * If `firsttime' is true, the ban list as returned by next_overlapped_ban()
286  * is reset (unless a non-zero value is returned, in which case the
287  * CHFL_BAN_OVERLAPPED flag might not have been reset!).
288  *
289  * --Run
290  */
291 int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
292                      int change, int firsttime)
293 {
294   struct SLink*  ban;
295   struct SLink** banp;
296   int            cnt = 0;
297   int            removed_bans = 0;
298   int            len = strlen(banid);
299
300   if (firsttime)
301   {
302     next_ban = NULL;
303     assert(0 == prev_ban);
304     assert(0 == removed_bans_list);
305   }
306   if (MyUser(cptr))
307     collapse(banid);
308   for (banp = &chptr->banlist; *banp;)
309   {
310     len += strlen((*banp)->value.ban.banstr);
311     ++cnt;
312     if (((*banp)->flags & CHFL_BURST_BAN_WIPEOUT))
313     {
314       if (!strcmp((*banp)->value.ban.banstr, banid))
315       {
316         (*banp)->flags &= ~CHFL_BURST_BAN_WIPEOUT;
317         return -2;
318       }
319     }
320     else if (!mmatch((*banp)->value.ban.banstr, banid))
321       return -1;
322     if (!mmatch(banid, (*banp)->value.ban.banstr))
323     {
324       struct SLink *tmp = *banp;
325       if (change)
326       {
327         if (MyUser(cptr))
328         {
329           cnt--;
330           len -= strlen(tmp->value.ban.banstr);
331         }
332         *banp = tmp->next;
333 #if 0
334         /* Silently remove overlapping bans */
335         MyFree(tmp->value.ban.banstr);
336         MyFree(tmp->value.ban.who);
337         free_link(tmp);
338         tmp = 0;
339 #else
340         /* These will be sent to the user later as -b */
341         tmp->next = removed_bans_list;
342         removed_bans_list = tmp;
343         removed_bans = 1;
344 #endif
345       }
346       else if (!(tmp->flags & CHFL_BURST_BAN_WIPEOUT))
347       {
348         tmp->flags |= CHFL_BAN_OVERLAPPED;
349         if (!next_ban)
350           next_ban = tmp;
351         banp = &tmp->next;
352       }
353       else
354         banp = &tmp->next;
355     }
356     else
357     {
358       if (firsttime)
359         (*banp)->flags &= ~CHFL_BAN_OVERLAPPED;
360       banp = &(*banp)->next;
361     }
362   }
363   if (MyUser(cptr) && !removed_bans && (len > MAXBANLENGTH || (cnt >= MAXBANS)))
364   {
365     send_reply(cptr, ERR_BANLISTFULL, chptr->chname, banid);
366     return -1;
367   }
368   if (change)
369   {
370     char*              ip_start;
371     struct Membership* member;
372     ban = make_link();
373     ban->next = chptr->banlist;
374
375     ban->value.ban.banstr = (char*) MyMalloc(strlen(banid) + 1);
376     assert(0 != ban->value.ban.banstr);
377     strcpy(ban->value.ban.banstr, banid);
378
379     ban->value.ban.who = (char*) MyMalloc(strlen(cptr->name) + 1);
380     assert(0 != ban->value.ban.who);
381     strcpy(ban->value.ban.who, cptr->name);
382
383     ban->value.ban.when = TStime();
384     ban->flags = CHFL_BAN;      /* This bit is never used I think... */
385     if ((ip_start = strrchr(banid, '@')) && check_if_ipmask(ip_start + 1))
386       ban->flags |= CHFL_BAN_IPMASK;
387     chptr->banlist = ban;
388
389     /*
390      * Erase ban-valid-bit
391      */
392     for (member = chptr->members; member; member = member->next_member)
393       ClearBanValid(member);     /* `ban' == channel member ! */
394   }
395   return 0;
396 }
397
398 static struct SLink *next_overlapped_ban(void)
399 {
400   struct SLink *tmp = next_ban;
401   if (tmp)
402   {
403     struct SLink *ban;
404     for (ban = tmp->next; ban; ban = ban->next)
405       if ((ban->flags & CHFL_BAN_OVERLAPPED))
406         break;
407     next_ban = ban;
408   }
409   return tmp;
410 }
411
412 struct SLink *next_removed_overlapped_ban(void)
413 {
414   struct SLink *tmp = removed_bans_list;
415   if (prev_ban)
416   {
417     if (prev_ban->value.ban.banstr)     /* Can be set to NULL in set_mode() */
418       MyFree(prev_ban->value.ban.banstr);
419     MyFree(prev_ban->value.ban.who);
420     free_link(prev_ban);
421     prev_ban = 0;
422   }
423   if (tmp)
424     removed_bans_list = removed_bans_list->next;
425   prev_ban = tmp;
426   return tmp;
427 }
428
429 /*
430  * del_banid
431  *
432  * If `change' is true, delete `banid' from channel `chptr'.
433  * Returns `false' if removal was (or would have been) successful.
434  */
435 static int del_banid(struct Channel *chptr, char *banid, int change)
436 {
437   struct SLink **ban;
438   struct SLink *tmp;
439
440   if (!banid)
441     return -1;
442   for (ban = &(chptr->banlist); *ban; ban = &((*ban)->next)) {
443     if (0 == ircd_strcmp(banid, (*ban)->value.ban.banstr))
444     {
445       tmp = *ban;
446       if (change)
447       {
448         struct Membership* member;
449         *ban = tmp->next;
450         MyFree(tmp->value.ban.banstr);
451         MyFree(tmp->value.ban.who);
452         free_link(tmp);
453         /*
454          * Erase ban-valid-bit, for channel members that are banned
455          */
456         for (member = chptr->members; member; member = member->next_member)
457           if (CHFL_BANVALIDMASK == (member->status & CHFL_BANVALIDMASK))
458             ClearBanValid(member);       /* `tmp' == channel member */
459       }
460       return 0;
461     }
462   }
463   return -1;
464 }
465
466 /*
467  * find_channel_member - returns Membership * if a person is joined and not a zombie
468  */
469 struct Membership* find_channel_member(struct Client* cptr, struct Channel* chptr)
470 {
471   struct Membership* member;
472   assert(0 != chptr);
473
474   member = find_member_link(chptr, cptr);
475   return (member && !IsZombie(member)) ? member : 0;
476 }
477
478 /*
479  * is_banned - a non-zero value if banned else 0.
480  */
481 static int is_banned(struct Client *cptr, struct Channel *chptr,
482                      struct Membership* member)
483 {
484   struct SLink* tmp;
485   char*         s;
486   char*         ip_s = NULL;
487
488   if (!IsUser(cptr))
489     return 0;
490
491   if (member && IsBanValid(member))
492     return IsBanned(member);
493
494   s = make_nick_user_host(cptr->name, cptr->user->username, cptr->user->host);
495
496   for (tmp = chptr->banlist; tmp; tmp = tmp->next) {
497     if ((tmp->flags & CHFL_BAN_IPMASK)) {
498       if (!ip_s)
499         ip_s = make_nick_user_ip(cptr->name, cptr->user->username, cptr->ip);
500       if (match(tmp->value.ban.banstr, ip_s) == 0)
501         break;
502     }
503     else if (match(tmp->value.ban.banstr, s) == 0)
504       break;
505   }
506
507   if (member) {
508     SetBanValid(member);
509     if (tmp) {
510       SetBanned(member);
511       return 1;
512     }
513     else {
514       ClearBanned(member);
515       return 0;
516     }
517   }
518
519   return (tmp != NULL);
520 }
521
522 /*
523  * adds a user to a channel by adding another link to the channels member
524  * chain.
525  */
526 void add_user_to_channel(struct Channel* chptr, struct Client* who,
527                                 unsigned int flags)
528 {
529   assert(0 != chptr);
530   assert(0 != who);
531
532   if (who->user) {
533     struct Membership* member = 
534             (struct Membership*) MyMalloc(sizeof(struct Membership));
535     assert(0 != member);
536     member->user         = who;
537     member->channel      = chptr;
538     member->status       = flags;
539
540     member->next_member  = chptr->members;
541     if (member->next_member)
542       member->next_member->prev_member = member;
543     member->prev_member  = 0; 
544     chptr->members       = member;
545
546     member->next_channel = who->user->channel;
547     if (member->next_channel)
548       member->next_channel->prev_channel = member;
549     member->prev_channel = 0;
550     who->user->channel = member;
551
552     ++chptr->users;
553     ++who->user->joined;
554   }
555 }
556
557 static int remove_member_from_channel(struct Membership* member)
558 {
559   struct Channel* chptr;
560   assert(0 != member);
561   chptr = member->channel;
562   /*
563    * unlink channel member list
564    */
565   if (member->next_member)
566     member->next_member->prev_member = member->prev_member;
567   if (member->prev_member)
568     member->prev_member->next_member = member->next_member;
569   else
570     member->channel->members = member->next_member; 
571       
572   /*
573    * unlink client channel list
574    */
575   if (member->next_channel)
576     member->next_channel->prev_channel = member->prev_channel;
577   if (member->prev_channel)
578     member->prev_channel->next_channel = member->next_channel;
579   else
580     member->user->user->channel = member->next_channel;
581
582   --member->user->user->joined;
583   MyFree(member);
584
585   return sub1_from_channel(chptr);
586 }
587
588 static int channel_all_zombies(struct Channel* chptr)
589 {
590   struct Membership* member;
591
592   for (member = chptr->members; member; member = member->next_member) {
593     if (!IsZombie(member))
594       return 0;
595   }
596   return 1;
597 }
598       
599
600 void remove_user_from_channel(struct Client* cptr, struct Channel* chptr)
601 {
602   
603   struct Membership* member;
604   assert(0 != chptr);
605
606   if ((member = find_member_link(chptr, cptr))) {
607     if (remove_member_from_channel(member)) {
608       if (channel_all_zombies(chptr)) {
609         /*
610          * XXX - this looks dangerous but isn't if we got the referential
611          * integrity right for channels
612          */
613         while (remove_member_from_channel(chptr->members))
614           ;
615       }
616     }
617   }
618 }
619
620 void remove_user_from_all_channels(struct Client* cptr)
621 {
622   struct Membership* chan;
623   assert(0 != cptr);
624   assert(0 != cptr->user);
625
626   while ((chan = cptr->user->channel))
627     remove_user_from_channel(cptr, chan->channel);
628 }
629
630 int is_chan_op(struct Client *cptr, struct Channel *chptr)
631 {
632   struct Membership* member;
633   assert(chptr);
634   if ((member = find_member_link(chptr, cptr)))
635     return (!IsZombie(member) && IsChanOp(member));
636
637   return 0;
638 }
639
640 static int is_deopped(struct Client *cptr, struct Channel *chptr)
641 {
642   struct Membership* member;
643
644   assert(0 != chptr);
645   if ((member = find_member_link(chptr, cptr)))
646     return IsDeopped(member);
647
648   return (IsUser(cptr) ? 1 : 0);
649 }
650
651 int is_zombie(struct Client *cptr, struct Channel *chptr)
652 {
653   struct Membership* member;
654
655   assert(0 != chptr);
656
657   if ((member = find_member_link(chptr, cptr)))
658       return IsZombie(member);
659   return 0;
660 }
661
662 int has_voice(struct Client* cptr, struct Channel* chptr)
663 {
664   struct Membership* member;
665
666   assert(0 != chptr);
667   if ((member = find_member_link(chptr, cptr)))
668     return (!IsZombie(member) && HasVoice(member));
669
670   return 0;
671 }
672
673 int member_can_send_to_channel(struct Membership* member)
674 {
675   assert(0 != member);
676
677   if (IsVoicedOrOpped(member))
678     return 1;
679   /*
680    * If it's moderated, and you aren't a priviledged user, you can't
681    * speak.  
682    */
683   if (member->channel->mode.mode & MODE_MODERATED)
684     return 0;
685   /*
686    * If you're banned then you can't speak either.
687    * but because of the amount of CPU time that is_banned chews
688    * we only check it for our clients.
689    */
690   if (MyUser(member->user) && is_banned(member->user, member->channel, member))
691     return 0;
692   return 1;
693 }
694
695 int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr)
696 {
697   struct Membership *member;
698   assert(0 != cptr); 
699   /*
700    * Servers can always speak on channels.
701    */
702   if (IsServer(cptr))
703     return 1;
704
705   member = find_channel_member(cptr, chptr);
706
707   /*
708    * You can't speak if your off channel, if the channel is modeless, or
709    * +n.(no external messages)
710    */
711   if (!member) {
712     if ((chptr->mode.mode & MODE_NOPRIVMSGS) || IsModelessChannel(chptr->chname)) 
713       return 0;
714     else
715       return 1;
716   }
717   return member_can_send_to_channel(member); 
718 }
719
720 /*
721  * find_no_nickchange_channel
722  * if a member and not opped or voiced and banned
723  * return the name of the first channel banned on
724  */
725 const char* find_no_nickchange_channel(struct Client* cptr)
726 {
727   if (MyUser(cptr)) {
728     struct Membership* member;
729     for (member = cptr->user->channel; member; member = member->next_channel) {
730       if (!IsVoicedOrOpped(member) && is_banned(cptr, member->channel, member))
731         return member->channel->chname;
732     }
733   }
734   return 0;
735 }
736
737
738 /*
739  * write the "simple" list of channel modes for channel chptr onto buffer mbuf
740  * with the parameters in pbuf.
741  */
742 void channel_modes(struct Client *cptr, char *mbuf, char *pbuf,
743                           struct Channel *chptr)
744 {
745   assert(0 != mbuf);
746   assert(0 != pbuf);
747   assert(0 != chptr);
748
749   *mbuf++ = '+';
750   if (chptr->mode.mode & MODE_SECRET)
751     *mbuf++ = 's';
752   else if (chptr->mode.mode & MODE_PRIVATE)
753     *mbuf++ = 'p';
754   if (chptr->mode.mode & MODE_MODERATED)
755     *mbuf++ = 'm';
756   if (chptr->mode.mode & MODE_TOPICLIMIT)
757     *mbuf++ = 't';
758   if (chptr->mode.mode & MODE_INVITEONLY)
759     *mbuf++ = 'i';
760   if (chptr->mode.mode & MODE_NOPRIVMSGS)
761     *mbuf++ = 'n';
762   if (chptr->mode.limit) {
763     *mbuf++ = 'l';
764     sprintf_irc(pbuf, "%d", chptr->mode.limit);
765   }
766
767   if (*chptr->mode.key) {
768     *mbuf++ = 'k';
769     if (is_chan_op(cptr, chptr) || IsServer(cptr)) {
770       if (chptr->mode.limit)
771         strcat(pbuf, " ");
772       strcat(pbuf, chptr->mode.key);
773     }
774   }
775   *mbuf = '\0';
776 }
777
778 #if 0
779 static int send_mode_list(struct Client *cptr, char *chname,
780                           time_t creationtime, struct SLink *top,
781                           int mask, char flag)
782 {
783   struct SLink* lp;
784   char*         cp;
785   char*         name;
786   int           count = 0;
787   int           send = 0;
788   int           sent = 0;
789
790   cp = modebuf + strlen(modebuf);
791   if (*parabuf)                 /* mode +l or +k xx */
792     count = 1;
793   for (lp = top; lp; lp = lp->next)
794   {
795     if (!(lp->flags & mask))
796       continue;
797     if (mask == CHFL_BAN)
798       name = lp->value.ban.banstr;
799     else
800       name = lp->value.cptr->name;
801     if (strlen(parabuf) + strlen(name) + 11 < MODEBUFLEN)
802     {
803       strcat(parabuf, " ");
804       strcat(parabuf, name);
805       count++;
806       *cp++ = flag;
807       *cp = '\0';
808     }
809     else if (*parabuf)
810       send = 1;
811     if (count == 6)
812       send = 1;
813     if (send)
814     {
815       /* cptr is always a server! So we send creationtimes */
816       sendmodeto_one(cptr, me.name, chname, modebuf, parabuf, creationtime);
817       sent = 1;
818       send = 0;
819       *parabuf = '\0';
820       cp = modebuf;
821       *cp++ = '+';
822       if (count != 6)
823       {
824         strcpy(parabuf, name);
825         *cp++ = flag;
826       }
827       count = 0;
828       *cp = '\0';
829     }
830   }
831   return sent;
832 }
833
834 #endif /* 0 */
835
836 /*
837  * send "cptr" a full list of the modes for channel chptr.
838  */
839 void send_channel_modes(struct Client *cptr, struct Channel *chptr)
840 {
841   static unsigned int current_flags[4] =
842       { 0, CHFL_CHANOP | CHFL_VOICE, CHFL_VOICE, CHFL_CHANOP };
843   int                first = 1;
844   int                full  = 1;
845   int                flag_cnt = 0;
846   int                new_mode = 0;
847   size_t             len;
848   size_t             sblen;
849   struct Membership* member;
850   struct SLink*      lp2;
851   char modebuf[MODEBUFLEN];
852   char parabuf[MODEBUFLEN];
853
854   assert(0 != cptr);
855   assert(0 != chptr); 
856
857   if (IsLocalChannel(chptr->chname))
858     return;
859
860   member = chptr->members;
861   lp2 = chptr->banlist;
862
863   *modebuf = *parabuf = '\0';
864   channel_modes(cptr, modebuf, parabuf, chptr);
865
866   for (first = 1; full; first = 0)      /* Loop for multiple messages */
867   {
868     full = 0;                   /* Assume by default we get it
869                                  all in one message */
870
871     /* (Continued) prefix: "<Y> B <channel> <TS>" */
872     sprintf_irc(sendbuf, "%s B %s " TIME_T_FMT, NumServ(&me),
873                 chptr->chname, chptr->creationtime);
874     sblen = strlen(sendbuf);
875
876     if (first && modebuf[1])    /* Add simple modes (iklmnpst)
877                                  if first message */
878     {
879       /* prefix: "<Y> B <channel> <TS>[ <modes>[ <params>]]" */
880       sendbuf[sblen++] = ' ';
881       strcpy(sendbuf + sblen, modebuf);
882       sblen += strlen(modebuf);
883       if (*parabuf)
884       {
885         sendbuf[sblen++] = ' ';
886         strcpy(sendbuf + sblen, parabuf);
887         sblen += strlen(parabuf);
888       }
889     }
890
891     /*
892      * Attach nicks, comma seperated " nick[:modes],nick[:modes],..."
893      *
894      * Run 4 times over all members, to group the members with the
895      * same mode together
896      */
897     for (first = 1; flag_cnt < 4;
898          member = chptr->members, new_mode = 1, flag_cnt++)
899     {
900       for (; member; member = member->next_member)
901       {
902         if ((member->status & CHFL_VOICED_OR_OPPED) !=
903             current_flags[flag_cnt])
904           continue;             /* Skip members with different flags */
905         if (sblen + NUMNICKLEN + 4 > BUFSIZE - 3)
906           /* The 4 is a possible ",:ov"
907              The -3 is for the "\r\n\0" that is added in send.c */
908         {
909           full = 1;           /* Make sure we continue after
910                                  sending it so far */
911           new_mode = 1;       /* Ensure the new BURST line contains the current
912                                  mode. --Gte */
913           break;              /* Do not add this member to this message */
914         }
915         sendbuf[sblen++] = first ? ' ' : ',';
916         first = 0;              /* From now on, us comma's to add new nicks */
917
918         sprintf_irc(sendbuf + sblen, "%s%s", NumNick(member->user));
919         sblen += strlen(sendbuf + sblen);
920         /*
921          * Do we have a nick with a new mode ?
922          * Or are we starting a new BURST line?
923          */
924         if (new_mode)
925         {
926           new_mode = 0;
927           if (IsVoicedOrOpped(member)) {
928             sendbuf[sblen++] = ':';
929             if (IsChanOp(member))
930               sendbuf[sblen++] = 'o';
931             if (HasVoice(member))
932               sendbuf[sblen++] = 'v';
933           }
934         }
935       }
936       if (full)
937         break;
938     }
939
940     if (!full)
941     {
942       /* Attach all bans, space seperated " :%ban ban ..." */
943       for (first = 2; lp2; lp2 = lp2->next)
944       {
945         len = strlen(lp2->value.ban.banstr);
946         if (sblen + len + 1 + first > BUFSIZE - 3)
947           /* The +1 stands for the added ' '.
948            * The +first stands for the added ":%".
949            * The -3 is for the "\r\n\0" that is added in send.c
950            */
951         {
952           full = 1;
953           break;
954         }
955         if (first)
956         {
957           first = 0;
958           sendbuf[sblen++] = ' ';
959           sendbuf[sblen++] = ':';       /* Will be last parameter */
960           sendbuf[sblen++] = '%';       /* To tell bans apart */
961         }
962         else
963           sendbuf[sblen++] = ' ';
964         strcpy(sendbuf + sblen, lp2->value.ban.banstr);
965         sblen += len;
966       }
967     }
968
969     sendbuf[sblen] = '\0';
970     sendbufto_one(cptr);        /* Send this message */
971   }                             /* Continue when there was something
972                                  that didn't fit (full==1) */
973 }
974
975 /*
976  * pretty_mask
977  *
978  * by Carlo Wood (Run), 05 Oct 1998.
979  *
980  * Canonify a mask.
981  *
982  * When the nick is longer then NICKLEN, it is cut off (its an error of course).
983  * When the user name or host name are too long (USERLEN and HOSTLEN
984  * respectively) then they are cut off at the start with a '*'.
985  *
986  * The following transformations are made:
987  *
988  * 1)   xxx             -> nick!*@*
989  * 2)   xxx.xxx         -> *!*@host
990  * 3)   xxx!yyy         -> nick!user@*
991  * 4)   xxx@yyy         -> *!user@host
992  * 5)   xxx!yyy@zzz     -> nick!user@host
993  */
994 char *pretty_mask(char *mask)
995 {
996   static char star[2] = { '*', 0 };
997   char *last_dot = NULL;
998   char *ptr;
999
1000   /* Case 1: default */
1001   char *nick = mask;
1002   char *user = star;
1003   char *host = star;
1004
1005   /* Do a _single_ pass through the characters of the mask: */
1006   for (ptr = mask; *ptr; ++ptr)
1007   {
1008     if (*ptr == '!')
1009     {
1010       /* Case 3 or 5: Found first '!' (without finding a '@' yet) */
1011       user = ++ptr;
1012       host = star;
1013     }
1014     else if (*ptr == '@')
1015     {
1016       /* Case 4: Found last '@' (without finding a '!' yet) */
1017       nick = star;
1018       user = mask;
1019       host = ++ptr;
1020     }
1021     else if (*ptr == '.')
1022     {
1023       /* Case 2: Found last '.' (without finding a '!' or '@' yet) */
1024       last_dot = ptr;
1025       continue;
1026     }
1027     else
1028       continue;
1029     for (; *ptr; ++ptr)
1030     {
1031       if (*ptr == '@')
1032       {
1033         /* Case 4 or 5: Found last '@' */
1034         host = ptr + 1;
1035       }
1036     }
1037     break;
1038   }
1039   if (user == star && last_dot)
1040   {
1041     /* Case 2: */
1042     nick = star;
1043     user = star;
1044     host = mask;
1045   }
1046   /* Check lengths */
1047   if (nick != star)
1048   {
1049     char *nick_end = (user != star) ? user - 1 : ptr;
1050     if (nick_end - nick > NICKLEN)
1051       nick[NICKLEN] = 0;
1052     *nick_end = 0;
1053   }
1054   if (user != star)
1055   {
1056     char *user_end = (host != star) ? host - 1 : ptr;
1057     if (user_end - user > USERLEN)
1058     {
1059       user = user_end - USERLEN;
1060       *user = '*';
1061     }
1062     *user_end = 0;
1063   }
1064   if (host != star && ptr - host > HOSTLEN)
1065   {
1066     host = ptr - HOSTLEN;
1067     *host = '*';
1068   }
1069   return make_nick_user_host(nick, user, host);
1070 }
1071
1072 static void send_ban_list(struct Client* cptr, struct Channel* chptr)
1073 {
1074   struct SLink* lp;
1075
1076   assert(0 != cptr);
1077   assert(0 != chptr);
1078
1079   for (lp = chptr->banlist; lp; lp = lp->next)
1080     send_reply(cptr, RPL_BANLIST, chptr->chname, lp->value.ban.banstr,
1081                lp->value.ban.who, lp->value.ban.when);
1082
1083   send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
1084 }
1085
1086 /*
1087  * Check and try to apply the channel modes passed in the parv array for
1088  * the client ccptr to channel chptr.  The resultant changes are printed
1089  * into mbuf and pbuf (if any) and applied to the channel.
1090  */
1091 int set_mode(struct Client* cptr, struct Client* sptr,
1092                     struct Channel* chptr, int parc, char* parv[],
1093                     char* mbuf, char* pbuf, char* npbuf, int* badop)
1094
1095   /* 
1096    * This size is only needed when a broken
1097    * server sends more then MAXMODEPARAMS
1098    * parameters
1099    */
1100   static struct SLink chops[MAXPARA - 2];
1101   static int flags[] = {
1102     MODE_PRIVATE,    'p',
1103     MODE_SECRET,     's',
1104     MODE_MODERATED,  'm',
1105     MODE_NOPRIVMSGS, 'n',
1106     MODE_TOPICLIMIT, 't',
1107     MODE_INVITEONLY, 'i',
1108     MODE_VOICE,      'v',
1109     MODE_KEY,        'k',
1110     0x0, 0x0
1111   };
1112
1113   char bmodebuf[MODEBUFLEN];
1114   char bparambuf[MODEBUFLEN];
1115   char nbparambuf[MODEBUFLEN];     /* "Numeric" Bounce Parameter Buffer */
1116   struct SLink*      lp;
1117   char*              curr = parv[0];
1118   char*              cp = NULL;
1119   int*               ip;
1120   struct Membership* member_x;
1121   struct Membership* member_y;
1122   unsigned int       whatt = MODE_ADD;
1123   unsigned int       bwhatt = 0;
1124   int                limitset = 0;
1125   int                bounce;
1126   int                add_banid_called = 0;
1127   size_t             len;
1128   size_t             nlen;
1129   size_t             blen;
1130   size_t             nblen;
1131   int                keychange = 0;
1132   unsigned int       nusers = 0;
1133   unsigned int       newmode;
1134   int                opcnt = 0;
1135   int                banlsent = 0;
1136   int                doesdeop = 0;
1137   int                doesop = 0;
1138   int                hacknotice = 0;
1139   int                change;
1140   int                gotts = 0;
1141   struct Client*     who;
1142   struct Mode*       mode;
1143   struct Mode        oldm;
1144   static char        numeric[16];
1145   char*              bmbuf = bmodebuf;
1146   char*              bpbuf = bparambuf;
1147   char*              nbpbuf = nbparambuf;
1148   time_t             newtime = 0;
1149   struct ConfItem*   aconf;
1150
1151   *mbuf = *pbuf = *npbuf = *bmbuf = *bpbuf = *nbpbuf = '\0';
1152   *badop = 0;
1153   if (parc < 1)
1154     return 0;
1155   /*
1156    * Mode is accepted when sptr is a channel operator
1157    * but also when the mode is received from a server.
1158    * At this point, let any member pass, so they are allowed
1159    * to see the bans.
1160    */
1161   member_y = find_channel_member(sptr, chptr);
1162   if (!(IsServer(cptr) || member_y))
1163     return 0;
1164
1165 #ifdef OPER_MODE_LCHAN
1166   if (IsOperOnLocalChannel(sptr, chptr->chname) && !IsChanOp(member_y))
1167     LocalChanOperMode = 1;
1168 #endif
1169
1170   mode = &(chptr->mode);
1171   memcpy(&oldm, mode, sizeof(struct Mode));
1172
1173   newmode = mode->mode;
1174
1175   while (curr && *curr) {
1176     switch (*curr) {
1177       case '+':
1178         whatt = MODE_ADD;
1179         break;
1180       case '-':
1181         whatt = MODE_DEL;
1182         break;
1183       case 'o':
1184       case 'v':
1185         if (--parc <= 0)
1186           break;
1187         parv++;
1188         if (MyUser(sptr) && opcnt >= MAXMODEPARAMS)
1189           break;
1190         /*
1191          * Check for nickname changes and try to follow these
1192          * to make sure the right client is affected by the
1193          * mode change.
1194          * Even if we find a nick with find_chasing() there
1195          * is still a reason to ignore in a special case.
1196          * We need to ignore the mode when:
1197          * - It is part of a net.burst (from a server and
1198          *   a MODE_ADD). Ofcourse we don't ignore mode
1199          *   changes from Uworld.
1200          * - The found nick is not on the right side off
1201          *   the net.junction.
1202          * This fixes the bug that when someone (tries to)
1203          * ride a net.break and does so with the nick of
1204          * someone on the otherside, that he is nick collided
1205          * (killed) but his +o still ops the other person.
1206          */
1207         if (MyUser(sptr))
1208         {
1209           if (!(who = find_chasing(sptr, parv[0], NULL)))
1210             break;
1211         }
1212         else
1213         {
1214           if (!(who = findNUser(parv[0])))
1215             break;
1216         }
1217         if (whatt == MODE_ADD && IsServer(sptr) && who->from != sptr->from &&
1218             !find_conf_byhost(cptr->confs, sptr->name, CONF_UWORLD))
1219           break;
1220
1221         if (!(member_x = find_member_link(chptr, who)) ||
1222             (MyUser(sptr) && IsZombie(member_x)))
1223         {
1224           send_reply(cptr, ERR_USERNOTINCHANNEL, who->name, chptr->chname);
1225           break;
1226         }
1227         /*
1228          * if the user is +k, prevent a deop from local user
1229          */
1230         if (whatt == MODE_DEL && IsChannelService(who) && *curr == 'o') {
1231           /*
1232            * XXX - CHECKME
1233            */
1234           if (MyUser(cptr)) {
1235             send_reply(cptr, ERR_ISCHANSERVICE, parv[0], chptr->chname);
1236             break;
1237            }
1238            else {
1239              sprintf_irc(sendbuf,":%s NOTICE * :*** Notice -- Deop of +k user on %s by %s",
1240                          me.name,chptr->chname,cptr->name);             
1241            }
1242         }
1243 #ifdef NO_OPER_DEOP_LCHAN
1244         /*
1245          * if the user is an oper on a local channel, prevent him
1246          * from being deoped. that oper can deop himself though.
1247          */
1248         if (whatt == MODE_DEL && IsOperOnLocalChannel(who, chptr->chname) &&
1249             (who != sptr) && MyUser(cptr) && *curr == 'o')
1250         {
1251           send_reply(cptr, ERR_ISOPERLCHAN, parv[0], chptr->chname);
1252           break;
1253         }
1254 #endif
1255         if (whatt == MODE_ADD)
1256         {
1257           lp = &chops[opcnt++];
1258           lp->value.cptr = who;
1259           if (IsServer(sptr) && (!(who->flags & FLAGS_TS8) || ((*curr == 'o') &&
1260               !(member_x->status & (CHFL_SERVOPOK | CHFL_CHANOP)))))
1261             *badop = ((member_x->status & CHFL_DEOPPED) && (*curr == 'o')) ? 2 : 3;
1262           lp->flags = (*curr == 'o') ? MODE_CHANOP : MODE_VOICE;
1263           lp->flags |= MODE_ADD;
1264         }
1265         else if (whatt == MODE_DEL)
1266         {
1267           lp = &chops[opcnt++];
1268           lp->value.cptr = who;
1269           doesdeop = 1;         /* Also when -v */
1270           lp->flags = (*curr == 'o') ? MODE_CHANOP : MODE_VOICE;
1271           lp->flags |= MODE_DEL;
1272         }
1273         if (*curr == 'o')
1274           doesop = 1;
1275         break;
1276       case 'k':
1277         if (--parc <= 0)
1278           break;
1279         parv++;
1280         /* check now so we eat the parameter if present */
1281         if (keychange)
1282           break;
1283         else
1284         {
1285           char *s = &(*parv)[-1];
1286           unsigned short count = KEYLEN + 1;
1287
1288           while (*++s > ' ' && *s != ':' && --count);
1289           *s = '\0';
1290           if (!**parv)          /* nothing left in key */
1291             break;
1292         }
1293         if (MyUser(sptr) && opcnt >= MAXMODEPARAMS)
1294           break;
1295         if (whatt == MODE_ADD)
1296         {
1297           if (*mode->key && !IsServer(cptr))
1298             send_reply(cptr, ERR_KEYSET, chptr->chname);
1299           else if (!*mode->key || IsServer(cptr))
1300           {
1301             lp = &chops[opcnt++];
1302             lp->value.cp = *parv;
1303             if (strlen(lp->value.cp) > KEYLEN)
1304               lp->value.cp[KEYLEN] = '\0';
1305             lp->flags = MODE_KEY | MODE_ADD;
1306             keychange = 1;
1307           }
1308         }
1309         else if (whatt == MODE_DEL)
1310         {
1311           /* Debug((DEBUG_INFO, "removing key: mode->key: >%s< *parv: >%s<", mode->key, *parv)); */
1312           if (0 == ircd_strcmp(mode->key, *parv) || IsServer(cptr))
1313           {
1314             /* Debug((DEBUG_INFO, "key matched")); */
1315             lp = &chops[opcnt++];
1316             lp->value.cp = mode->key;
1317             lp->flags = MODE_KEY | MODE_DEL;
1318             keychange = 1;
1319           }
1320         }
1321         break;
1322       case 'b':
1323         if (--parc <= 0) {
1324           if (0 == banlsent) {
1325             /*
1326              * Only send it once
1327              */
1328             send_ban_list(cptr, chptr);
1329             banlsent = 1;
1330           }
1331           break;
1332         }
1333         parv++;
1334         if (EmptyString(*parv))
1335           break;
1336         if (MyUser(sptr))
1337         {
1338           if ((cp = strchr(*parv, ' ')))
1339             *cp = 0;
1340           if (opcnt >= MAXMODEPARAMS || **parv == ':' || **parv == '\0')
1341             break;
1342         }
1343         if (whatt == MODE_ADD)
1344         {
1345           lp = &chops[opcnt++];
1346           lp->value.cp = *parv;
1347           lp->flags = MODE_ADD | MODE_BAN;
1348         }
1349         else if (whatt == MODE_DEL)
1350         {
1351           lp = &chops[opcnt++];
1352           lp->value.cp = *parv;
1353           lp->flags = MODE_DEL | MODE_BAN;
1354         }
1355         break;
1356       case 'l':
1357         /*
1358          * limit 'l' to only *1* change per mode command but
1359          * eat up others.
1360          */
1361         if (limitset)
1362         {
1363           if (whatt == MODE_ADD && --parc > 0)
1364             parv++;
1365           break;
1366         }
1367         if (whatt == MODE_DEL)
1368         {
1369           limitset = 1;
1370           nusers = 0;
1371           break;
1372         }
1373         if (--parc > 0)
1374         {
1375           if (EmptyString(*parv))
1376             break;
1377           if (MyUser(sptr) && opcnt >= MAXMODEPARAMS)
1378             break;
1379           if (!(nusers = atoi(*++parv)))
1380             continue;
1381           lp = &chops[opcnt++];
1382           lp->flags = MODE_ADD | MODE_LIMIT;
1383           limitset = 1;
1384           break;
1385         }
1386         need_more_params(cptr, "MODE +l");
1387         break;
1388       case 'i':         /* falls through for default case */
1389         if (whatt == MODE_DEL)
1390           while ((lp = chptr->invites))
1391             del_invite(lp->value.cptr, chptr);
1392       default:
1393         for (ip = flags; *ip; ip += 2)
1394           if (*(ip + 1) == *curr)
1395             break;
1396
1397         if (*ip)
1398         {
1399           if (whatt == MODE_ADD)
1400           {
1401             if (*ip == MODE_PRIVATE)
1402               newmode &= ~MODE_SECRET;
1403             else if (*ip == MODE_SECRET)
1404               newmode &= ~MODE_PRIVATE;
1405             newmode |= *ip;
1406           }
1407           else
1408             newmode &= ~*ip;
1409         }
1410         else if (!IsServer(cptr))
1411           send_reply(cptr, ERR_UNKNOWNMODE, *curr);
1412         break;
1413     }
1414     curr++;
1415     /*
1416      * Make sure mode strings such as "+m +t +p +i" are parsed
1417      * fully.
1418      */
1419     if (!*curr && parc > 0)
1420     {
1421       curr = *++parv;
1422       parc--;
1423       /* If this was from a server, and it is the last
1424        * parameter and it starts with a digit, it must
1425        * be the creationtime.  --Run
1426        */
1427       if (IsServer(sptr))
1428       {
1429         if (parc == 1 && IsDigit(*curr))
1430         {
1431           newtime = atoi(curr);
1432           if (newtime && chptr->creationtime == MAGIC_REMOTE_JOIN_TS)
1433           {
1434             chptr->creationtime = newtime;
1435             *badop = 0;
1436           }
1437           gotts = 1;
1438           if (newtime == 0)
1439           {
1440             *badop = 2;
1441             hacknotice = 1;
1442           }
1443           else if (newtime > chptr->creationtime)
1444           {                     /* It is a net-break ride if we have ops.
1445                                    bounce modes if we have ops.  --Run */
1446             if (doesdeop)
1447               *badop = 2;
1448             else if (chptr->creationtime == 0)
1449             {
1450               if (chptr->creationtime == 0 || doesop)
1451                 chptr->creationtime = newtime;
1452               *badop = 0;
1453             }
1454             /* Bounce: */
1455             else
1456               *badop = 1;
1457           }
1458           /*
1459            * A legal *badop can occur when two
1460            * people join simultaneously a channel,
1461            * Allow for 10 min of lag (and thus hacking
1462            * on channels younger then 10 min) --Run
1463            */
1464           else if (*badop == 0 ||
1465               chptr->creationtime > (TStime() - TS_LAG_TIME))
1466           {
1467             if (newtime < chptr->creationtime)
1468               chptr->creationtime = newtime;
1469             *badop = 0;
1470           }
1471           break;
1472         }
1473       }
1474       else
1475         *badop = 0;
1476     }
1477   }                             /* end of while loop for MODE processing */
1478
1479 #ifdef OPER_MODE_LCHAN
1480   /*
1481    * Now reject non chan ops. Accept modes from opers on local channels
1482    * even if they are deopped
1483    */
1484   if (!IsServer(cptr) &&
1485       (!member_y || !(IsChanOp(member_y) ||
1486                  IsOperOnLocalChannel(sptr, chptr->chname))))
1487 #else
1488   if (!IsServer(cptr) && (!member_y || !IsChanOp(member_y)))
1489 #endif
1490   {
1491     *badop = 0;
1492     return (opcnt || newmode != mode->mode || limitset || keychange) ? 0 : -1;
1493   }
1494
1495   if (doesop && newtime == 0 && IsServer(sptr))
1496     *badop = 2;
1497
1498   if (*badop >= 2 &&
1499       (aconf = find_conf_byhost(cptr->confs, sptr->name, CONF_UWORLD)))
1500     *badop = 4;
1501
1502 #ifdef OPER_MODE_LCHAN
1503   bounce = (*badop == 1 || *badop == 2 ||
1504             (is_deopped(sptr, chptr) &&
1505              !IsOperOnLocalChannel(sptr, chptr->chname))) ? 1 : 0;
1506 #else
1507   bounce = (*badop == 1 || *badop == 2 || is_deopped(sptr, chptr)) ? 1 : 0;
1508 #endif
1509
1510   whatt = 0;
1511   for (ip = flags; *ip; ip += 2) {
1512     if ((*ip & newmode) && !(*ip & oldm.mode))
1513     {
1514       if (bounce)
1515       {
1516         if (bwhatt != MODE_DEL)
1517         {
1518           *bmbuf++ = '-';
1519           bwhatt = MODE_DEL;
1520         }
1521         *bmbuf++ = *(ip + 1);
1522       }
1523       else
1524       {
1525         if (whatt != MODE_ADD)
1526         {
1527           *mbuf++ = '+';
1528           whatt = MODE_ADD;
1529         }
1530         mode->mode |= *ip;
1531         *mbuf++ = *(ip + 1);
1532       }
1533     }
1534   }
1535   for (ip = flags; *ip; ip += 2) {
1536     if ((*ip & oldm.mode) && !(*ip & newmode))
1537     {
1538       if (bounce)
1539       {
1540         if (bwhatt != MODE_ADD)
1541         {
1542           *bmbuf++ = '+';
1543           bwhatt = MODE_ADD;
1544         }
1545         *bmbuf++ = *(ip + 1);
1546       }
1547       else
1548       {
1549         if (whatt != MODE_DEL)
1550         {
1551           *mbuf++ = '-';
1552           whatt = MODE_DEL;
1553         }
1554         mode->mode &= ~*ip;
1555         *mbuf++ = *(ip + 1);
1556       }
1557     }
1558   }
1559   blen = nblen = 0;
1560   if (limitset && !nusers && mode->limit)
1561   {
1562     if (bounce)
1563     {
1564       if (bwhatt != MODE_ADD)
1565       {
1566         *bmbuf++ = '+';
1567         bwhatt = MODE_ADD;
1568       }
1569       *bmbuf++ = 'l';
1570       sprintf(numeric, "%-15d", mode->limit);
1571       if ((cp = strchr(numeric, ' ')))
1572         *cp = '\0';
1573       strcat(bpbuf, numeric);
1574       blen += strlen(numeric);
1575       strcat(bpbuf, " ");
1576       strcat(nbpbuf, numeric);
1577       nblen += strlen(numeric);
1578       strcat(nbpbuf, " ");
1579     }
1580     else
1581     {
1582       if (whatt != MODE_DEL)
1583       {
1584         *mbuf++ = '-';
1585         whatt = MODE_DEL;
1586       }
1587       mode->mode &= ~MODE_LIMIT;
1588       mode->limit = 0;
1589       *mbuf++ = 'l';
1590     }
1591   }
1592   /*
1593    * Reconstruct "+bkov" chain.
1594    */
1595   if (opcnt)
1596   {
1597     int i = 0;
1598     char c = 0;
1599     unsigned int prev_whatt = 0;
1600
1601     for (; i < opcnt; i++)
1602     {
1603       lp = &chops[i];
1604       /*
1605        * make sure we have correct mode change sign
1606        */
1607       if (whatt != (lp->flags & (MODE_ADD | MODE_DEL)))
1608       {
1609         if (lp->flags & MODE_ADD)
1610         {
1611           *mbuf++ = '+';
1612           prev_whatt = whatt;
1613           whatt = MODE_ADD;
1614         }
1615         else
1616         {
1617           *mbuf++ = '-';
1618           prev_whatt = whatt;
1619           whatt = MODE_DEL;
1620         }
1621       }
1622       len = strlen(pbuf);
1623       nlen = strlen(npbuf);
1624       /*
1625        * get c as the mode char and tmp as a pointer to
1626        * the parameter for this mode change.
1627        */
1628       switch (lp->flags & MODE_WPARAS)
1629       {
1630         case MODE_CHANOP:
1631           c = 'o';
1632           cp = lp->value.cptr->name;
1633           break;
1634         case MODE_VOICE:
1635           c = 'v';
1636           cp = lp->value.cptr->name;
1637           break;
1638         case MODE_BAN:
1639           /*
1640            * I made this a bit more user-friendly (tm):
1641            * nick = nick!*@*
1642            * nick!user = nick!user@*
1643            * user@host = *!user@host
1644            * host.name = *!*@host.name    --Run
1645            */
1646           c = 'b';
1647           cp = pretty_mask(lp->value.cp);
1648           break;
1649         case MODE_KEY:
1650           c = 'k';
1651           cp = lp->value.cp;
1652           break;
1653         case MODE_LIMIT:
1654           c = 'l';
1655           sprintf(numeric, "%-15d", nusers);
1656           if ((cp = strchr(numeric, ' ')))
1657             *cp = '\0';
1658           cp = numeric;
1659           break;
1660       }
1661
1662       /* What could be added: cp+' '+' '+<TS>+'\0' */
1663       if (len + strlen(cp) + 13 > MODEBUFLEN ||
1664           nlen + strlen(cp) + NUMNICKLEN + 12 > MODEBUFLEN)
1665         break;
1666
1667       switch (lp->flags & MODE_WPARAS)
1668       {
1669         case MODE_KEY:
1670           if (strlen(cp) > KEYLEN)
1671             *(cp + KEYLEN) = '\0';
1672           if ((whatt == MODE_ADD && (*mode->key == '\0' ||
1673                0 != ircd_strcmp(mode->key, cp))) ||
1674               (whatt == MODE_DEL && (*mode->key != '\0')))
1675           {
1676             if (bounce)
1677             {
1678               if (*mode->key == '\0')
1679               {
1680                 if (bwhatt != MODE_DEL)
1681                 {
1682                   *bmbuf++ = '-';
1683                   bwhatt = MODE_DEL;
1684                 }
1685                 strcat(bpbuf, cp);
1686                 blen += strlen(cp);
1687                 strcat(bpbuf, " ");
1688                 blen++;
1689                 strcat(nbpbuf, cp);
1690                 nblen += strlen(cp);
1691                 strcat(nbpbuf, " ");
1692                 nblen++;
1693               }
1694               else
1695               {
1696                 if (bwhatt != MODE_ADD)
1697                 {
1698                   *bmbuf++ = '+';
1699                   bwhatt = MODE_ADD;
1700                 }
1701                 strcat(bpbuf, mode->key);
1702                 blen += strlen(mode->key);
1703                 strcat(bpbuf, " ");
1704                 blen++;
1705                 strcat(nbpbuf, mode->key);
1706                 nblen += strlen(mode->key);
1707                 strcat(nbpbuf, " ");
1708                 nblen++;
1709               }
1710               *bmbuf++ = c;
1711               mbuf--;
1712               if (*mbuf != '+' && *mbuf != '-')
1713                 mbuf++;
1714               else
1715                 whatt = prev_whatt;
1716             }
1717             else
1718             {
1719               *mbuf++ = c;
1720               strcat(pbuf, cp);
1721               len += strlen(cp);
1722               strcat(pbuf, " ");
1723               len++;
1724               strcat(npbuf, cp);
1725               nlen += strlen(cp);
1726               strcat(npbuf, " ");
1727               nlen++;
1728               if (whatt == MODE_ADD)
1729                 ircd_strncpy(mode->key, cp, KEYLEN);
1730               else
1731                 *mode->key = '\0';
1732             }
1733           }
1734           break;
1735         case MODE_LIMIT:
1736           if (nusers && nusers != mode->limit)
1737           {
1738             if (bounce)
1739             {
1740               if (mode->limit == 0)
1741               {
1742                 if (bwhatt != MODE_DEL)
1743                 {
1744                   *bmbuf++ = '-';
1745                   bwhatt = MODE_DEL;
1746                 }
1747               }
1748               else
1749               {
1750                 if (bwhatt != MODE_ADD)
1751                 {
1752                   *bmbuf++ = '+';
1753                   bwhatt = MODE_ADD;
1754                 }
1755                 sprintf(numeric, "%-15d", mode->limit);
1756                 if ((cp = strchr(numeric, ' ')))
1757                   *cp = '\0';
1758                 strcat(bpbuf, numeric);
1759                 blen += strlen(numeric);
1760                 strcat(bpbuf, " ");
1761                 blen++;
1762                 strcat(nbpbuf, numeric);
1763                 nblen += strlen(numeric);
1764                 strcat(nbpbuf, " ");
1765                 nblen++;
1766               }
1767               *bmbuf++ = c;
1768               mbuf--;
1769               if (*mbuf != '+' && *mbuf != '-')
1770                 mbuf++;
1771               else
1772                 whatt = prev_whatt;
1773             }
1774             else
1775             {
1776               *mbuf++ = c;
1777               strcat(pbuf, cp);
1778               len += strlen(cp);
1779               strcat(pbuf, " ");
1780               len++;
1781               strcat(npbuf, cp);
1782               nlen += strlen(cp);
1783               strcat(npbuf, " ");
1784               nlen++;
1785               mode->limit = nusers;
1786             }
1787           }
1788           break;
1789         case MODE_CHANOP:
1790         case MODE_VOICE:
1791           member_y = find_member_link(chptr, lp->value.cptr);
1792           if (lp->flags & MODE_ADD)
1793           {
1794             change = (~member_y->status) & CHFL_VOICED_OR_OPPED & lp->flags;
1795             if (change && bounce)
1796             {
1797               if (lp->flags & MODE_CHANOP)
1798                 SetDeopped(member_y);
1799
1800               if (bwhatt != MODE_DEL)
1801               {
1802                 *bmbuf++ = '-';
1803                 bwhatt = MODE_DEL;
1804               }
1805               *bmbuf++ = c;
1806               strcat(bpbuf, lp->value.cptr->name);
1807               blen += strlen(lp->value.cptr->name);
1808               strcat(bpbuf, " ");
1809               blen++;
1810               sprintf_irc(nbpbuf + nblen, "%s%s ", NumNick(lp->value.cptr));
1811               nblen += strlen(nbpbuf + nblen);
1812               change = 0;
1813             }
1814             else if (change)
1815             {
1816               member_y->status |= lp->flags & CHFL_VOICED_OR_OPPED;
1817               if (IsChanOp(member_y))
1818               {
1819                 ClearDeopped(member_y);
1820                 if (IsServer(sptr))
1821                   ClearServOpOk(member_y);
1822               }
1823             }
1824           }
1825           else
1826           {
1827             change = member_y->status & CHFL_VOICED_OR_OPPED & lp->flags;
1828             if (change && bounce)
1829             {
1830               if (lp->flags & MODE_CHANOP)
1831                 ClearDeopped(member_y);
1832               if (bwhatt != MODE_ADD)
1833               {
1834                 *bmbuf++ = '+';
1835                 bwhatt = MODE_ADD;
1836               }
1837               *bmbuf++ = c;
1838               strcat(bpbuf, lp->value.cptr->name);
1839               blen += strlen(lp->value.cptr->name);
1840               strcat(bpbuf, " ");
1841               blen++;
1842               sprintf_irc(nbpbuf + nblen, "%s%s ", NumNick(lp->value.cptr));
1843               blen += strlen(bpbuf + blen);
1844               change = 0;
1845             }
1846             else
1847             {
1848               member_y->status &= ~change;
1849               if ((change & MODE_CHANOP) && IsServer(sptr))
1850                 SetDeopped(member_y);
1851             }
1852           }
1853           if (change || *badop == 2 || *badop == 4)
1854           {
1855             *mbuf++ = c;
1856             strcat(pbuf, cp);
1857             len += strlen(cp);
1858             strcat(pbuf, " ");
1859             len++;
1860             sprintf_irc(npbuf + nlen, "%s%s ", NumNick(lp->value.cptr));
1861             nlen += strlen(npbuf + nlen);
1862             npbuf[nlen++] = ' ';
1863             npbuf[nlen] = 0;
1864           }
1865           else
1866           {
1867             mbuf--;
1868             if (*mbuf != '+' && *mbuf != '-')
1869               mbuf++;
1870             else
1871               whatt = prev_whatt;
1872           }
1873           break;
1874         case MODE_BAN:
1875 /*
1876  * Only bans aren't bounced, it makes no sense to bounce last second
1877  * bans while propagating bans done before the net.rejoin. The reason
1878  * why I don't bounce net.rejoin bans is because it is too much
1879  * work to take care of too long strings adding the necessary TS to
1880  * net.burst bans -- RunLazy
1881  * We do have to check for *badop==2 now, we don't want HACKs to take
1882  * effect.
1883  *
1884  * Since BURST - I *did* implement net.rejoin ban bouncing. So now it
1885  * certainly makes sense to also bounce 'last second' bans (bans done
1886  * after the net.junction). -- RunHardWorker
1887  */
1888           if ((change = (whatt & MODE_ADD) &&
1889               !add_banid(sptr, chptr, cp, !bounce, !add_banid_called)))
1890             add_banid_called = 1;
1891           else
1892             change = (whatt & MODE_DEL) && !del_banid(chptr, cp, !bounce);
1893
1894           if (bounce && change)
1895           {
1896             change = 0;
1897             if ((whatt & MODE_ADD))
1898             {
1899               if (bwhatt != MODE_DEL)
1900               {
1901                 *bmbuf++ = '-';
1902                 bwhatt = MODE_DEL;
1903               }
1904             }
1905             else if ((whatt & MODE_DEL))
1906             {
1907               if (bwhatt != MODE_ADD)
1908               {
1909                 *bmbuf++ = '+';
1910                 bwhatt = MODE_ADD;
1911               }
1912             }
1913             *bmbuf++ = c;
1914             strcat(bpbuf, cp);
1915             blen += strlen(cp);
1916             strcat(bpbuf, " ");
1917             blen++;
1918             strcat(nbpbuf, cp);
1919             nblen += strlen(cp);
1920             strcat(nbpbuf, " ");
1921             nblen++;
1922           }
1923           if (change)
1924           {
1925             *mbuf++ = c;
1926             strcat(pbuf, cp);
1927             len += strlen(cp);
1928             strcat(pbuf, " ");
1929             len++;
1930             strcat(npbuf, cp);
1931             nlen += strlen(cp);
1932             strcat(npbuf, " ");
1933             nlen++;
1934           }
1935           else
1936           {
1937             mbuf--;
1938             if (*mbuf != '+' && *mbuf != '-')
1939               mbuf++;
1940             else
1941               whatt = prev_whatt;
1942           }
1943           break;
1944       }
1945     }                           /* for (; i < opcnt; i++) */
1946   }                             /* if (opcnt) */
1947
1948   *mbuf++ = '\0';
1949   *bmbuf++ = '\0';
1950
1951   /* Bounce here */
1952   if (!hacknotice && *bmodebuf && chptr->creationtime)
1953   {
1954     sendcmdto_one(&me, CMD_MODE, cptr, "%H %s %s %Tu", chptr, bmodebuf,
1955                   nbparambuf, *badop == 2 ? (time_t) 0 : chptr->creationtime);
1956   }
1957   /* If there are possibly bans to re-add, bounce them now */
1958   if (add_banid_called && bounce)
1959   {
1960     struct SLink *ban[6];               /* Max 6 bans at a time */
1961     size_t len[6], sblen, total_len;
1962     int cnt, delayed = 0;
1963     while (delayed || (ban[0] = next_overlapped_ban()))
1964     {
1965       len[0] = strlen(ban[0]->value.ban.banstr);
1966       cnt = 1;                  /* We already got one ban :) */
1967       /* XXX sendbuf used to send ban bounces! */
1968       sblen = sprintf_irc(sendbuf, ":%s MODE %s +b",
1969           me.name, chptr->chname) - sendbuf;
1970       total_len = sblen + 1 + len[0];   /* 1 = ' ' */
1971       /* Find more bans: */
1972       delayed = 0;
1973       while (cnt < 6 && (ban[cnt] = next_overlapped_ban()))
1974       {
1975         len[cnt] = strlen(ban[cnt]->value.ban.banstr);
1976         if (total_len + 5 + len[cnt] > BUFSIZE) /* 5 = "b \r\n\0" */
1977         {
1978           delayed = cnt + 1;    /* != 0 */
1979           break;                /* Flush */
1980         }
1981         sendbuf[sblen++] = 'b';
1982         total_len += 2 + len[cnt++];    /* 2 = "b " */
1983       }
1984       while (cnt--)
1985       {
1986         sendbuf[sblen++] = ' ';
1987         strcpy(sendbuf + sblen, ban[cnt]->value.ban.banstr);
1988         sblen += len[cnt];
1989       }
1990       sendbufto_one(cptr);      /* Send bounce to uplink */
1991       if (delayed)
1992         ban[0] = ban[delayed - 1];
1993     }
1994   }
1995   /* Send -b's of overlapped bans to clients to keep them synchronized */
1996   if (add_banid_called && !bounce)
1997   {
1998     struct SLink *ban;
1999     char *banstr[6];            /* Max 6 bans at a time */
2000     size_t len[6], sblen, psblen, total_len;
2001     int cnt, delayed = 0;
2002     struct Membership* member_z;
2003     struct Client *acptr;
2004     if (IsServer(sptr))
2005       /* XXX sendbuf used to send ban bounces! */
2006       psblen = sprintf_irc(sendbuf, ":%s MODE %s -b",
2007           sptr->name, chptr->chname) - sendbuf;
2008     else                        /* We rely on IsRegistered(sptr) being true for MODE */
2009       psblen = sprintf_irc(sendbuf, ":%s!%s@%s MODE %s -b", sptr->name,
2010           sptr->user->username, sptr->user->host, chptr->chname) - sendbuf;
2011     while (delayed || (ban = next_removed_overlapped_ban()))
2012     {
2013       if (!delayed)
2014       {
2015         len[0] = strlen((banstr[0] = ban->value.ban.banstr));
2016         ban->value.ban.banstr = NULL;
2017       }
2018       cnt = 1;                  /* We already got one ban :) */
2019       sblen = psblen;
2020       total_len = sblen + 1 + len[0];   /* 1 = ' ' */
2021       /* Find more bans: */
2022       delayed = 0;
2023       while (cnt < 6 && (ban = next_removed_overlapped_ban()))
2024       {
2025         len[cnt] = strlen((banstr[cnt] = ban->value.ban.banstr));
2026         ban->value.ban.banstr = NULL;
2027         if (total_len + 5 + len[cnt] > BUFSIZE) /* 5 = "b \r\n\0" */
2028         {
2029           delayed = cnt + 1;    /* != 0 */
2030           break;                /* Flush */
2031         }
2032         sendbuf[sblen++] = 'b';
2033         total_len += 2 + len[cnt++];    /* 2 = "b " */
2034       }
2035       while (cnt--)
2036       {
2037         sendbuf[sblen++] = ' ';
2038         strcpy(sendbuf + sblen, banstr[cnt]);
2039         MyFree(banstr[cnt]);
2040         sblen += len[cnt];
2041       }
2042       for (member_z = chptr->members; member_z; member_z = member_z->next_member) {
2043         acptr = member_z->user;
2044         if (MyConnect(acptr) && !IsZombie(member_z))
2045           sendbufto_one(acptr);
2046       }
2047       if (delayed)
2048       {
2049         banstr[0] = banstr[delayed - 1];
2050         len[0] = len[delayed - 1];
2051       }
2052     }
2053   }
2054
2055   return gotts ? 1 : -1;
2056 }
2057
2058 /* We are now treating the <key> part of /join <channel list> <key> as a key
2059  * ring; that is, we try one key against the actual channel key, and if that
2060  * doesn't work, we try the next one, and so on. -Kev -Texaco
2061  * Returns: 0 on match, 1 otherwise
2062  * This version contributed by SeKs <intru@info.polymtl.ca>
2063  */
2064 static int compall(char *key, char *keyring)
2065 {
2066   char *p1;
2067
2068 top:
2069   p1 = key;                     /* point to the key... */
2070   while (*p1 && *p1 == *keyring)
2071   {                             /* step through the key and ring until they
2072                                    don't match... */
2073     p1++;
2074     keyring++;
2075   }
2076
2077   if (!*p1 && (!*keyring || *keyring == ','))
2078     /* ok, if we're at the end of the and also at the end of one of the keys
2079        in the keyring, we have a match */
2080     return 0;
2081
2082   if (!*keyring)                /* if we're at the end of the key ring, there
2083                                    weren't any matches, so we return 1 */
2084     return 1;
2085
2086   /* Not at the end of the key ring, so step
2087      through to the next key in the ring: */
2088   while (*keyring && *(keyring++) != ',');
2089
2090   goto top;                     /* and check it against the key */
2091 }
2092
2093 int can_join(struct Client *sptr, struct Channel *chptr, char *key)
2094 {
2095   struct SLink *lp;
2096   int overrideJoin = 0;  
2097   
2098   /*
2099    * Now a banned user CAN join if invited -- Nemesi
2100    * Now a user CAN escape channel limit if invited -- bfriendly
2101    * Now a user CAN escape anything if invited -- Isomer
2102    */
2103
2104   for (lp = sptr->user->invited; lp; lp = lp->next)
2105     if (lp->value.chptr == chptr)
2106       return 0;
2107   
2108 #ifdef OPER_WALK_THROUGH_LMODES
2109   /* An oper can force a join on a local channel using "OVERRIDE" as the key. 
2110      a HACK(4) notice will be sent if he would not have been supposed
2111      to join normally. */ 
2112   if (IsOperOnLocalChannel(sptr,chptr->chname) && !BadPtr(key) && compall("OVERRIDE",key) == 0)
2113   {
2114     overrideJoin = MAGIC_OPER_OVERRIDE;
2115   }
2116 #endif
2117
2118   if (chptr->mode.mode & MODE_INVITEONLY)
2119         return overrideJoin + ERR_INVITEONLYCHAN;
2120         
2121   if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
2122         return overrideJoin + ERR_CHANNELISFULL;
2123         
2124   if (is_banned(sptr, chptr, NULL))
2125         return overrideJoin + ERR_BANNEDFROMCHAN;
2126   
2127   /*
2128    * now using compall (above) to test against a whole key ring -Kev
2129    */
2130   if (*chptr->mode.key && (EmptyString(key) || compall(chptr->mode.key, key)))
2131     return overrideJoin + ERR_BADCHANNELKEY;
2132
2133   if (overrideJoin)     
2134         return ERR_DONTCHEAT;
2135         
2136   return 0;
2137 }
2138
2139 /*
2140  * Remove bells and commas from channel name
2141  */
2142 void clean_channelname(char *cn)
2143 {
2144   int i;
2145
2146   for (i = 0; cn[i]; i++) {
2147     if (i >= CHANNELLEN || !IsChannelChar(cn[i])) {
2148       cn[i] = '\0';
2149       return;
2150     }
2151     if (IsChannelLower(cn[i])) {
2152       cn[i] = ToLower(cn[i]);
2153 #ifndef FIXME
2154       /*
2155        * Remove for .08+
2156        * toupper(0xd0)
2157        */
2158       if ((unsigned char)(cn[i]) == 0xd0)
2159         cn[i] = (char) 0xf0;
2160 #endif
2161     }
2162   }
2163 }
2164
2165 /*
2166  *  Get Channel block for i (and allocate a new channel
2167  *  block, if it didn't exists before).
2168  */
2169 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
2170 {
2171   struct Channel *chptr;
2172   int len;
2173
2174   if (EmptyString(chname))
2175     return NULL;
2176
2177   len = strlen(chname);
2178   if (MyUser(cptr) && len > CHANNELLEN)
2179   {
2180     len = CHANNELLEN;
2181     *(chname + CHANNELLEN) = '\0';
2182   }
2183   if ((chptr = FindChannel(chname)))
2184     return (chptr);
2185   if (flag == CGT_CREATE)
2186   {
2187     chptr = (struct Channel*) MyMalloc(sizeof(struct Channel) + len);
2188     assert(0 != chptr);
2189     ++UserStats.channels;
2190     memset(chptr, 0, sizeof(struct Channel));
2191     strcpy(chptr->chname, chname);
2192     if (GlobalChannelList)
2193       GlobalChannelList->prev = chptr;
2194     chptr->prev = NULL;
2195     chptr->next = GlobalChannelList;
2196     chptr->creationtime = MyUser(cptr) ? TStime() : (time_t) 0;
2197     GlobalChannelList = chptr;
2198     hAddChannel(chptr);
2199   }
2200   return chptr;
2201 }
2202
2203 void add_invite(struct Client *cptr, struct Channel *chptr)
2204 {
2205   struct SLink *inv, **tmp;
2206
2207   del_invite(cptr, chptr);
2208   /*
2209    * Delete last link in chain if the list is max length
2210    */
2211   assert(list_length(cptr->user->invited) == cptr->user->invites);
2212   if (cptr->user->invites>=MAXCHANNELSPERUSER)
2213     del_invite(cptr, cptr->user->invited->value.chptr);
2214   /*
2215    * Add client to channel invite list
2216    */
2217   inv = make_link();
2218   inv->value.cptr = cptr;
2219   inv->next = chptr->invites;
2220   chptr->invites = inv;
2221   /*
2222    * Add channel to the end of the client invite list
2223    */
2224   for (tmp = &(cptr->user->invited); *tmp; tmp = &((*tmp)->next));
2225   inv = make_link();
2226   inv->value.chptr = chptr;
2227   inv->next = NULL;
2228   (*tmp) = inv;
2229   cptr->user->invites++;
2230 }
2231
2232 /*
2233  * Delete Invite block from channel invite list and client invite list
2234  */
2235 void del_invite(struct Client *cptr, struct Channel *chptr)
2236 {
2237   struct SLink **inv, *tmp;
2238
2239   for (inv = &(chptr->invites); (tmp = *inv); inv = &tmp->next)
2240     if (tmp->value.cptr == cptr)
2241     {
2242       *inv = tmp->next;
2243       free_link(tmp);
2244       tmp = 0;
2245       cptr->user->invites--;
2246       break;
2247     }
2248
2249   for (inv = &(cptr->user->invited); (tmp = *inv); inv = &tmp->next)
2250     if (tmp->value.chptr == chptr)
2251     {
2252       *inv = tmp->next;
2253       free_link(tmp);
2254       tmp = 0;
2255       break;
2256     }
2257 }
2258
2259 /* List and skip all channels that are listen */
2260 void list_next_channels(struct Client *cptr, int nr)
2261 {
2262   struct ListingArgs *args = cptr->listing;
2263   struct Channel *chptr = args->chptr;
2264   chptr->mode.mode &= ~MODE_LISTED;
2265   while (is_listed(chptr) || --nr >= 0)
2266   {
2267     for (; chptr; chptr = chptr->next)
2268     {
2269       if (!cptr->user || (SecretChannel(chptr) && !find_channel_member(cptr, chptr)))
2270         continue;
2271       if (chptr->users > args->min_users && chptr->users < args->max_users &&
2272           chptr->creationtime > args->min_time &&
2273           chptr->creationtime < args->max_time &&
2274           (!args->topic_limits || (*chptr->topic &&
2275           chptr->topic_time > args->min_topic_time &&
2276           chptr->topic_time < args->max_topic_time)))
2277       {
2278         if (ShowChannel(cptr,chptr))
2279           send_reply(cptr, RPL_LIST, chptr->chname, chptr->users,
2280                      chptr->topic);
2281         chptr = chptr->next;
2282         break;
2283       }
2284     }
2285     if (!chptr)
2286     {
2287       MyFree(cptr->listing);
2288       cptr->listing = NULL;
2289       send_reply(cptr, RPL_LISTEND);
2290       break;
2291     }
2292   }
2293   if (chptr)
2294   {
2295     cptr->listing->chptr = chptr;
2296     chptr->mode.mode |= MODE_LISTED;
2297   }
2298 }
2299
2300 /* XXX AIEEEE! sendbuf is an institution here :( */
2301 void add_token_to_sendbuf(char *token, size_t *sblenp, int *firstp,
2302     int *send_itp, char is_a_ban, int mode)
2303 {
2304   int first = *firstp;
2305
2306   /*
2307    * Heh - we do not need to test if it still fits in the buffer, because
2308    * this BURST message is reconstructed from another BURST message, and
2309    * it only can become smaller. --Run
2310    */
2311
2312   if (*firstp)                  /* First token in this parameter ? */
2313   {
2314     *firstp = 0;
2315     if (*send_itp == 0)
2316       *send_itp = 1;            /* Buffer contains data to be sent */
2317     sendbuf[(*sblenp)++] = ' ';
2318     if (is_a_ban)
2319     {
2320       sendbuf[(*sblenp)++] = ':';       /* Bans are always the last "parv" */
2321       sendbuf[(*sblenp)++] = is_a_ban;
2322     }
2323   }
2324   else                          /* Of course, 'send_it' is already set here */
2325     /* Seperate banmasks with a space because
2326        they can contain commas themselfs: */
2327     sendbuf[(*sblenp)++] = is_a_ban ? ' ' : ',';
2328   strcpy(sendbuf + *sblenp, token);
2329   *sblenp += strlen(token);
2330   if (!is_a_ban)                /* nick list ? Need to take care
2331                                    of modes for nicks: */
2332   {
2333     static int last_mode = 0;
2334     mode &= CHFL_CHANOP | CHFL_VOICE;
2335     if (first)
2336       last_mode = 0;
2337     if (last_mode != mode)      /* Append mode like ':ov' if changed */
2338     {
2339       last_mode = mode;
2340       sendbuf[(*sblenp)++] = ':';
2341       if (mode & CHFL_CHANOP)
2342         sendbuf[(*sblenp)++] = 'o';
2343       if (mode & CHFL_VOICE)
2344         sendbuf[(*sblenp)++] = 'v';
2345     }
2346     sendbuf[*sblenp] = '\0';
2347   }
2348 }
2349
2350 void cancel_mode(struct Client *sptr, struct Channel *chptr, char m,
2351                         const char *param, int *count)
2352 {
2353   static char* pb;
2354   static char* sbp;
2355   static char* sbpi;
2356   int          paramdoesntfit = 0;
2357   char parabuf[MODEBUFLEN];
2358
2359   assert(0 != sptr);
2360   assert(0 != chptr);
2361   assert(0 != count);
2362   
2363   if (*count == -1)             /* initialize ? */
2364   {
2365     /* XXX sendbuf used! */
2366     sbp = sbpi =
2367         sprintf_irc(sendbuf, ":%s MODE %s -", sptr->name, chptr->chname);
2368     pb = parabuf;
2369     *count = 0;
2370   }
2371   /* m == 0 means flush */
2372   if (m)
2373   {
2374     if (param)
2375     {
2376       size_t nplen = strlen(param);
2377       if (pb - parabuf + nplen + 23 > MODEBUFLEN)
2378         paramdoesntfit = 1;
2379       else
2380       {
2381         *sbp++ = m;
2382         *pb++ = ' ';
2383         strcpy(pb, param);
2384         pb += nplen;
2385         ++*count;
2386       }
2387     }
2388     else
2389       *sbp++ = m;
2390   }
2391   else if (*count == 0)
2392     return;
2393   if (*count == 6 || !m || paramdoesntfit)
2394   {
2395     struct Membership* member;
2396     strcpy(sbp, parabuf);
2397     for (member = chptr->members; member; member = member->next_member)
2398       if (MyUser(member->user))
2399         sendbufto_one(member->user);
2400     sbp = sbpi;
2401     pb = parabuf;
2402     *count = 0;
2403   }
2404   if (paramdoesntfit)
2405   {
2406     *sbp++ = m;
2407     *pb++ = ' ';
2408     strcpy(pb, param);
2409     pb += strlen(param);
2410     ++*count;
2411   }
2412 }
2413
2414
2415 /*
2416  * Consider:
2417  *
2418  *                     client
2419  *                       |
2420  *                       c
2421  *                       |
2422  *     X --a--> A --b--> B --d--> D
2423  *                       |
2424  *                      who
2425  *
2426  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
2427  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
2428  *
2429  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
2430  *    Remove the user immedeately when no users are left on the channel.
2431  * b) On server B : remove the user (who/lp) from the channel, send a
2432  *    PART upstream (to A) and pass on the KICK.
2433  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
2434  *    channel, and pass on the KICK.
2435  * d) On server D : remove the user (who/lp) from the channel, and pass on
2436  *    the KICK.
2437  *
2438  * Note:
2439  * - Setting the ZOMBIE flag never hurts, we either remove the
2440  *   client after that or we don't.
2441  * - The KICK message was already passed on, as should be in all cases.
2442  * - `who' is removed in all cases except case a) when users are left.
2443  * - A PART is only sent upstream in case b).
2444  *
2445  * 2 aug 97:
2446  *
2447  *              6
2448  *              |
2449  *  1 --- 2 --- 3 --- 4 --- 5
2450  *        |           |
2451  *      kicker       who
2452  *
2453  * We also need to turn 'who' into a zombie on servers 1 and 6,
2454  * because a KICK from 'who' (kicking someone else in that direction)
2455  * can arrive there afterwards - which should not be bounced itself.
2456  * Therefore case a) also applies for servers 1 and 6.
2457  *
2458  * --Run
2459  */
2460 void make_zombie(struct Membership* member, struct Client* who, struct Client* cptr,
2461                  struct Client* sptr, struct Channel* chptr)
2462 {
2463   assert(0 != member);
2464   assert(0 != who);
2465   assert(0 != cptr);
2466   assert(0 != chptr);
2467
2468   /* Default for case a): */
2469   SetZombie(member);
2470
2471   /* Case b) or c) ?: */
2472   if (MyUser(who))      /* server 4 */
2473   {
2474     if (IsServer(cptr)) /* Case b) ? */
2475       sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
2476     remove_user_from_channel(who, chptr);
2477     return;
2478   }
2479   if (who->from == cptr)        /* True on servers 1, 5 and 6 */
2480   {
2481     struct Client *acptr = IsServer(sptr) ? sptr : sptr->user->server;
2482     for (; acptr != &me; acptr = acptr->serv->up)
2483       if (acptr == who->user->server)   /* Case d) (server 5) */
2484       {
2485         remove_user_from_channel(who, chptr);
2486         return;
2487       }
2488   }
2489
2490   /* Case a) (servers 1, 2, 3 and 6) */
2491   if (channel_all_zombies(chptr))
2492     remove_user_from_channel(who, chptr);
2493
2494   /* XXX Can't actually call Debug here; if the channel is all zombies,
2495    * chptr will no longer exist when we get here.
2496   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
2497   */
2498 }
2499
2500 int number_of_zombies(struct Channel *chptr)
2501 {
2502   struct Membership* member;
2503   int                count = 0;
2504
2505   assert(0 != chptr);
2506   for (member = chptr->members; member; member = member->next_member) {
2507     if (IsZombie(member))
2508       ++count;
2509   }
2510   return count;
2511 }
2512
2513 /*
2514  * send_hack_notice()
2515  *
2516  * parc & parv[] are the same as that of the calling function:
2517  *   mtype == 1 is from m_mode, 2 is from m_create, 3 is from m_kick.
2518  *
2519  * This function prepares sendbuf with the server notices and wallops
2520  *   to be sent for all hacks.  -Ghostwolf 18-May-97
2521  */
2522 /* XXX let's get rid of this if we can */
2523 void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
2524                       char *parv[], int badop, int mtype)
2525 {
2526   struct Channel *chptr;
2527   static char params[MODEBUFLEN];
2528   int i = 3;
2529   chptr = FindChannel(parv[1]);
2530   *params = '\0';
2531
2532   /* P10 servers require numeric nick conversion before sending. */
2533   switch (mtype)
2534   {
2535     case 1:                     /* Convert nicks for MODE HACKs here  */
2536     {
2537       char *mode = parv[2];
2538       while (i < parc)
2539       {
2540         while (*mode && *mode != 'o' && *mode != 'v')
2541           ++mode;
2542         strcat(params, " ");
2543         if (*mode == 'o' || *mode == 'v')
2544         {
2545           /*
2546            * blindly stumble through parameter list hoping one of them
2547            * might turn out to be a numeric nick
2548            * NOTE: this should not cause a problem but _may_ end up finding
2549            * something we aren't looking for. findNUser should be able to
2550            * handle any garbage that is thrown at it, but may return a client
2551            * if we happen to get lucky with a mode string or a timestamp
2552            */
2553           struct Client *acptr;
2554           if ((acptr = findNUser(parv[i])) != NULL)     /* Convert nicks here */
2555             strcat(params, acptr->name);
2556           else
2557           {
2558             strcat(params, "<");
2559             strcat(params, parv[i]);
2560             strcat(params, ">");
2561           }
2562         }
2563         else                    /* If it isn't a numnick, send it 'as is' */
2564           strcat(params, parv[i]);
2565         i++;
2566       }
2567       sprintf_irc(sendbuf,
2568           ":%s NOTICE * :*** Notice -- %sHACK(%d): %s MODE %s %s%s ["
2569           TIME_T_FMT "]", me.name, (badop == 3) ? "BOUNCE or " : "", badop,
2570           parv[0], parv[1], parv[2], params, chptr->creationtime);
2571       sendbufto_op_mask((badop == 3) ? SNO_HACK3 : (badop == /* XXX DYING */
2572           4) ? SNO_HACK4 : SNO_HACK2);
2573
2574       if ((IsServer(sptr)) && (badop == 2))
2575       {
2576         sprintf_irc(sendbuf, ":%s DESYNCH :HACK: %s MODE %s %s%s",
2577             me.name, parv[0], parv[1], parv[2], params);
2578         sendbufto_serv_butone(cptr); /* XXX DYING */
2579       }
2580       break;
2581     }
2582     case 2:                     /* No conversion is needed for CREATE; the only numnick is sptr */
2583     {
2584       sendto_serv_butone(cptr, ":%s DESYNCH :HACK: %s CREATE %s %s", /* XXX DYING */
2585           me.name, sptr->name, chptr->chname, parv[2]);
2586       sendto_op_mask(SNO_HACK2, "HACK(2): %s CREATE %s %s", /* XXX DYING */
2587           sptr->name, chptr->chname, parv[2]);
2588       break;
2589     }
2590     case 3:                     /* Convert nick in KICK message */
2591     {
2592       struct Client *acptr;
2593       if ((acptr = findNUser(parv[2])) != NULL) /* attempt to convert nick */
2594         sprintf_irc(sendbuf,
2595             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s %s :%s",
2596             me.name, sptr->name, parv[1], acptr->name, parv[3]);
2597       else                      /* if conversion fails, send it 'as is' in <>'s */
2598         sprintf_irc(sendbuf,
2599             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s <%s> :%s",
2600             me.name, sptr->name, parv[1], parv[2], parv[3]);
2601       sendbufto_op_mask(SNO_HACK4); /* XXX DYING */
2602       break;
2603     }
2604   }
2605 }
2606
2607 /*
2608  * This helper function builds an argument string in strptr, consisting
2609  * of the original string, a space, and str1 and str2 concatenated (if,
2610  * of course, str2 is not NULL)
2611  */
2612 static void
2613 build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
2614 {
2615   if (c)
2616     strptr[(*strptr_i)++] = c;
2617
2618   while (*str1)
2619     strptr[(*strptr_i)++] = *(str1++);
2620
2621   if (str2)
2622     while (*str2)
2623       strptr[(*strptr_i)++] = *(str2++);
2624
2625   strptr[(*strptr_i)] = '\0';
2626 }
2627
2628 /*
2629  * This is the workhorse of our ModeBuf suite; this actually generates the
2630  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
2631  */
2632 static int
2633 modebuf_flush_int(struct ModeBuf *mbuf, int all)
2634 {
2635   /* we only need the flags that don't take args right now */
2636   static int flags[] = {
2637 /*  MODE_CHANOP,        'o', */
2638 /*  MODE_VOICE,         'v', */
2639     MODE_PRIVATE,       'p',
2640     MODE_SECRET,        's',
2641     MODE_MODERATED,     'm',
2642     MODE_TOPICLIMIT,    't',
2643     MODE_INVITEONLY,    'i',
2644     MODE_NOPRIVMSGS,    'n',
2645 /*  MODE_KEY,           'k', */
2646 /*  MODE_BAN,           'b', */
2647 /*  MODE_LIMIT,         'l', */
2648     0x0, 0x0
2649   };
2650   int i;
2651   int *flag_p;
2652
2653   struct Client *app_source; /* where the MODE appears to come from */
2654
2655   char addbuf[20]; /* accumulates +psmtin, etc. */
2656   int addbuf_i = 0;
2657   char rembuf[20]; /* accumulates -psmtin, etc. */
2658   int rembuf_i = 0;
2659   char *bufptr; /* we make use of indirection to simplify the code */
2660   int *bufptr_i;
2661
2662   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
2663   int addstr_i;
2664   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
2665   int remstr_i;
2666   char *strptr; /* more indirection to simplify the code */
2667   int *strptr_i;
2668
2669   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
2670   int tmp;
2671
2672   char limitbuf[20]; /* convert limits to strings */
2673
2674   unsigned int limitdel = MODE_LIMIT;
2675
2676   assert(0 != mbuf);
2677
2678   /* If the ModeBuf is empty, we have nothing to do */
2679   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
2680     return 0;
2681
2682   /* Ok, if we were given the OPMODE flag, hide the source if its a user */
2683   if (mbuf->mb_dest & MODEBUF_DEST_OPMODE && !IsServer(mbuf->mb_source))
2684     app_source = mbuf->mb_source->user->server;
2685   else
2686     app_source = mbuf->mb_source;
2687
2688   /*
2689    * Account for user we're bouncing; we have to get it in on the first
2690    * bounced MODE, or we could have problems
2691    */
2692   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
2693     totalbuflen -= 6; /* numeric nick == 5, plus one space */
2694
2695   /* Calculate the simple flags */
2696   for (flag_p = flags; flag_p[0]; flag_p += 2) {
2697     if (*flag_p & mbuf->mb_add)
2698       addbuf[addbuf_i++] = flag_p[1];
2699     else if (*flag_p & mbuf->mb_rem)
2700       rembuf[rembuf_i++] = flag_p[1];
2701   }
2702
2703   /* Now go through the modes with arguments... */
2704   for (i = 0; i < mbuf->mb_count; i++) {
2705     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2706       bufptr = addbuf;
2707       bufptr_i = &addbuf_i;
2708     } else {
2709       bufptr = rembuf;
2710       bufptr_i = &rembuf_i;
2711     }
2712
2713     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
2714       tmp = strlen(MB_CLIENT(mbuf, i)->name);
2715
2716       if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
2717         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2718       else {
2719         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
2720         totalbuflen -= IRCD_MAX(5, tmp) + 1;
2721       }
2722     } else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN)) {
2723       tmp = strlen(MB_STRING(mbuf, i));
2724
2725       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
2726         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2727       else {
2728         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_KEY ? 'k' : 'b';
2729         totalbuflen -= tmp + 1;
2730       }
2731     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
2732       /* if it's a limit, we also format the number */
2733       sprintf_irc(limitbuf, "%d", MB_UINT(mbuf, i));
2734
2735       tmp = strlen(limitbuf);
2736
2737       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
2738         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2739       else {
2740         bufptr[(*bufptr_i)++] = 'l';
2741         totalbuflen -= tmp + 1;
2742       }
2743     }
2744   }
2745
2746   /* terminate the mode strings */
2747   addbuf[addbuf_i] = '\0';
2748   rembuf[rembuf_i] = '\0';
2749
2750   /* If we're building a user visible MODE or HACK... */
2751   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
2752                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
2753                        MODEBUF_DEST_LOG)) {
2754     /* Set up the parameter strings */
2755     addstr[0] = '\0';
2756     addstr_i = 0;
2757     remstr[0] = '\0';
2758     remstr_i = 0;
2759
2760     for (i = 0; i < mbuf->mb_count; i++) {
2761       if (MB_TYPE(mbuf, i) & MODE_SAVE)
2762         continue;
2763
2764       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2765         strptr = addstr;
2766         strptr_i = &addstr_i;
2767       } else {
2768         strptr = remstr;
2769         strptr_i = &remstr_i;
2770       }
2771
2772       /* deal with clients... */
2773       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
2774         build_string(strptr, strptr_i, MB_CLIENT(mbuf, i)->name, 0, ' ');
2775
2776       /* deal with strings... */
2777       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
2778         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
2779
2780       /*
2781        * deal with limit; note we cannot include the limit parameter if we're
2782        * removing it
2783        */
2784       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
2785                (MODE_ADD | MODE_LIMIT))
2786         build_string(strptr, strptr_i, limitbuf, 0, ' ');
2787     }
2788
2789     /* send the messages off to their destination */
2790     if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
2791       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
2792                            "[%Tu]", app_source->name, mbuf->mb_channel->chname,
2793                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2794                            addbuf, remstr, addstr,
2795                            mbuf->mb_channel->creationtime);
2796       sendcmdto_serv_butone(&me, CMD_DESYNCH, mbuf->mb_connect,
2797                             ":HACK: %s MODE %s %s%s%s%s%s%s [%Tu]",
2798                             app_source->name, mbuf->mb_channel->chname,
2799                             rembuf_i ? "-" : "", rembuf,
2800                             addbuf_i ? "+" : "", addbuf, remstr, addstr,
2801                             mbuf->mb_channel->creationtime);
2802     }
2803
2804     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
2805       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
2806                            "%s%s%s%s%s%s [%Tu]", app_source->name,
2807                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
2808                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
2809                            mbuf->mb_channel->creationtime);
2810
2811     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
2812       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
2813                            "[%Tu]", app_source->name, mbuf->mb_channel->chname,
2814                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2815                            addbuf, remstr, addstr,
2816                            mbuf->mb_channel->creationtime);
2817
2818 #ifdef OPATH
2819     if (mbuf->mb_dest & MODEBUF_DEST_LOG) {
2820       write_log(OPATH, "%Tu %#C OPMODE %H %s%s%s%s%s%s\n", TStime(),
2821                 mbuf->mb_source, mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
2822                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
2823     }
2824 #endif
2825
2826     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
2827       sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
2828                                 "%H %s%s%s%s%s%s", mbuf->mb_channel,
2829                                 rembuf_i ? "-" : "", rembuf,
2830                                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
2831   }
2832
2833   /* Now are we supposed to propagate to other servers? */
2834   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
2835     /* set up parameter string */
2836     addstr[0] = '\0';
2837     addstr_i = 0;
2838     remstr[0] = '\0';
2839     remstr_i = 0;
2840
2841     /*
2842      * limit is supressed if we're removing it; we have to figure out which
2843      * direction is the direction for it to be removed, though...
2844      */
2845     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
2846
2847     for (i = 0; i < mbuf->mb_count; i++) {
2848       if (MB_TYPE(mbuf, i) & MODE_SAVE)
2849         continue;
2850
2851       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2852         strptr = addstr;
2853         strptr_i = &addstr_i;
2854       } else {
2855         strptr = remstr;
2856         strptr_i = &remstr_i;
2857       }
2858
2859       /* deal with modes that take clients */
2860       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
2861         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
2862
2863       /* deal with modes that take strings */
2864       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
2865         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
2866
2867       /*
2868        * deal with the limit.  Logic here is complicated; if HACK2 is set,
2869        * we're bouncing the mode, so sense is reversed, and we have to
2870        * include the original limit if it looks like it's being removed
2871        */
2872       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
2873         build_string(strptr, strptr_i, limitbuf, 0, ' ');
2874     }
2875
2876     /* we were told to deop the source */
2877     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
2878       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
2879       addbuf[addbuf_i] = '\0'; /* terminate the string... */
2880       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
2881
2882       /* mark that we've done this, so we don't do it again */
2883       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
2884     }
2885
2886     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
2887       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
2888       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
2889                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
2890                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2891                             addbuf, remstr, addstr);
2892     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
2893       /*
2894        * If HACK2 was set, we're bouncing; we send the MODE back to the
2895        * connection we got it from with the senses reversed and a TS of 0;
2896        * origin is us
2897        */
2898       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
2899                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
2900                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
2901                     mbuf->mb_channel->creationtime);
2902     } else {
2903       /*
2904        * We're propagating a normal MODE command to the rest of the network;
2905        * we send the actual channel TS unless this is a HACK3 or a HACK4
2906        */
2907       if (IsServer(mbuf->mb_source))
2908         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
2909                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
2910                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2911                               addbuf, remstr, addstr,
2912                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
2913                               mbuf->mb_channel->creationtime);
2914       else
2915         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
2916                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
2917                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2918                               addbuf, remstr, addstr);
2919     }
2920   }
2921
2922   /* We've drained the ModeBuf... */
2923   mbuf->mb_add = 0;
2924   mbuf->mb_rem = 0;
2925   mbuf->mb_count = 0;
2926
2927   /* reinitialize the mode-with-arg slots */
2928   for (i = 0; i < MAXMODEPARAMS; i++) {
2929     /* If we saved any, pack them down */
2930     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
2931       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
2932       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
2933
2934       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
2935         continue;
2936     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
2937       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
2938
2939     MB_TYPE(mbuf, i) = 0;
2940     MB_UINT(mbuf, i) = 0;
2941   }
2942
2943   /* If we're supposed to flush it all, do so--all hail tail recursion */
2944   if (all && mbuf->mb_count)
2945     return modebuf_flush_int(mbuf, 1);
2946
2947   return 0;
2948 }
2949
2950 /*
2951  * This routine just initializes a ModeBuf structure with the information
2952  * needed and the options given.
2953  */
2954 void
2955 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
2956              struct Client *connect, struct Channel *chan, unsigned int dest)
2957 {
2958   int i;
2959
2960   assert(0 != mbuf);
2961   assert(0 != source);
2962   assert(0 != chan);
2963   assert(0 != dest);
2964
2965   mbuf->mb_add = 0;
2966   mbuf->mb_rem = 0;
2967   mbuf->mb_source = source;
2968   mbuf->mb_connect = connect;
2969   mbuf->mb_channel = chan;
2970   mbuf->mb_dest = dest;
2971   mbuf->mb_count = 0;
2972
2973   /* clear each mode-with-parameter slot */
2974   for (i = 0; i < MAXMODEPARAMS; i++) {
2975     MB_TYPE(mbuf, i) = 0;
2976     MB_UINT(mbuf, i) = 0;
2977   }
2978 }
2979
2980 /*
2981  * This routine simply adds modes to be added or deleted; do a binary OR
2982  * with either MODE_ADD or MODE_DEL
2983  */
2984 void
2985 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
2986 {
2987   assert(0 != mbuf);
2988   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2989
2990   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
2991            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
2992
2993   if (mode & MODE_ADD) {
2994     mbuf->mb_rem &= ~mode;
2995     mbuf->mb_add |= mode;
2996   } else {
2997     mbuf->mb_add &= ~mode;
2998     mbuf->mb_rem |= mode;
2999   }
3000 }
3001
3002 /*
3003  * This routine adds a mode to be added or deleted that takes a unsigned
3004  * int parameter; mode may *only* be the relevant mode flag ORed with one
3005  * of MODE_ADD or MODE_DEL
3006  */
3007 void
3008 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
3009 {
3010   assert(0 != mbuf);
3011   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3012
3013   MB_TYPE(mbuf, mbuf->mb_count) = mode;
3014   MB_UINT(mbuf, mbuf->mb_count) = uint;
3015
3016   /* when we've reached the maximal count, flush the buffer */
3017   if (++mbuf->mb_count >=
3018       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3019     modebuf_flush_int(mbuf, 0);
3020 }
3021
3022 /*
3023  * This routine adds a mode to be added or deleted that takes a string
3024  * parameter; mode may *only* be the relevant mode flag ORed with one of
3025  * MODE_ADD or MODE_DEL
3026  */
3027 void
3028 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
3029                     int free)
3030 {
3031   assert(0 != mbuf);
3032   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3033
3034   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
3035   MB_STRING(mbuf, mbuf->mb_count) = string;
3036
3037   /* when we've reached the maximal count, flush the buffer */
3038   if (++mbuf->mb_count >=
3039       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3040     modebuf_flush_int(mbuf, 0);
3041 }
3042
3043 /*
3044  * This routine adds a mode to be added or deleted that takes a client
3045  * parameter; mode may *only* be the relevant mode flag ORed with one of
3046  * MODE_ADD or MODE_DEL
3047  */
3048 void
3049 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
3050                     struct Client *client)
3051 {
3052   assert(0 != mbuf);
3053   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3054
3055   MB_TYPE(mbuf, mbuf->mb_count) = mode;
3056   MB_CLIENT(mbuf, mbuf->mb_count) = client;
3057
3058   /* when we've reached the maximal count, flush the buffer */
3059   if (++mbuf->mb_count >=
3060       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3061     modebuf_flush_int(mbuf, 0);
3062 }
3063
3064 /*
3065  * This is the exported binding for modebuf_flush()
3066  */
3067 int
3068 modebuf_flush(struct ModeBuf *mbuf)
3069 {
3070   return modebuf_flush_int(mbuf, 1);
3071 }
3072
3073 /*
3074  * This extracts the simple modes contained in mbuf
3075  */
3076 void
3077 modebuf_extract(struct ModeBuf *mbuf, char *buf)
3078 {
3079   static int flags[] = {
3080 /*  MODE_CHANOP,        'o', */
3081 /*  MODE_VOICE,         'v', */
3082     MODE_PRIVATE,       'p',
3083     MODE_SECRET,        's',
3084     MODE_MODERATED,     'm',
3085     MODE_TOPICLIMIT,    't',
3086     MODE_INVITEONLY,    'i',
3087     MODE_NOPRIVMSGS,    'n',
3088     MODE_KEY,           'k',
3089 /*  MODE_BAN,           'b', */
3090     MODE_LIMIT,         'l',
3091     0x0, 0x0
3092   };
3093   unsigned int add;
3094   int i, bufpos = 0, len;
3095   int *flag_p;
3096   char *key = 0, limitbuf[20];
3097
3098   assert(0 != mbuf);
3099   assert(0 != buf);
3100
3101   buf[0] = '\0';
3102
3103   add = mbuf->mb_add;
3104
3105   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
3106     if (MB_TYPE(mbuf, i) & MODE_ADD) {
3107       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT);
3108
3109       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
3110         key = MB_STRING(mbuf, i);
3111       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
3112         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%d", MB_UINT(mbuf, i));
3113     }
3114   }
3115
3116   if (!add)
3117     return;
3118
3119   buf[bufpos++] = '+'; /* start building buffer */
3120
3121   for (flag_p = flags; flag_p[0]; flag_p += 2)
3122     if (*flag_p & add)
3123       buf[bufpos++] = flag_p[1];
3124
3125   for (i = 0, len = bufpos; i < len; i++) {
3126     if (buf[i] == 'k')
3127       build_string(buf, &bufpos, key, 0, ' ');
3128     else if (buf[i] == 'l')
3129       build_string(buf, &bufpos, limitbuf, 0, ' ');
3130   }
3131
3132   buf[bufpos] = '\0';
3133
3134   return;
3135 }
3136
3137 /*
3138  * Simple function to invalidate bans
3139  */
3140 void
3141 mode_ban_invalidate(struct Channel *chan)
3142 {
3143   struct Membership *member;
3144
3145   for (member = chan->members; member; member = member->next_member)
3146     ClearBanValid(member);
3147 }
3148
3149 /*
3150  * Simple function to drop invite structures
3151  */
3152 void
3153 mode_invite_clear(struct Channel *chan)
3154 {
3155   while (chan->invites)
3156     del_invite(chan->invites->value.cptr, chan);
3157 }
3158
3159 /* What we've done for mode_parse so far... */
3160 #define DONE_LIMIT      0x01    /* We've set the limit */
3161 #define DONE_KEY        0x02    /* We've set the key */
3162 #define DONE_BANLIST    0x04    /* We've sent the ban list */
3163 #define DONE_NOTOPER    0x08    /* We've sent a "Not oper" error */
3164 #define DONE_BANCLEAN   0x10    /* We've cleaned bans... */
3165
3166 struct ParseState {
3167   struct ModeBuf *mbuf;
3168   struct Client *cptr;
3169   struct Client *sptr;
3170   struct Channel *chptr;
3171   int parc;
3172   char **parv;
3173   unsigned int flags;
3174   unsigned int dir;
3175   unsigned int done;
3176   int args_used;
3177   int max_args;
3178   int numbans;
3179   struct SLink banlist[MAXPARA];
3180   struct {
3181     unsigned int flag;
3182     struct Client *client;
3183   } cli_change[MAXPARA];
3184 };
3185
3186 /*
3187  * Here's a helper function to deal with sending along "Not oper" or
3188  * "Not member" messages
3189  */
3190 static void
3191 send_notoper(struct ParseState *state)
3192 {
3193   if (state->done & DONE_NOTOPER)
3194     return;
3195
3196   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
3197              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
3198
3199   state->done |= DONE_NOTOPER;
3200 }
3201
3202 /*
3203  * Helper function to convert limits
3204  */
3205 static void
3206 mode_parse_limit(struct ParseState *state, int *flag_p)
3207 {
3208   unsigned int t_limit;
3209
3210   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
3211     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
3212       return;
3213
3214     if (state->parc <= 0) { /* warn if not enough args */
3215       if (MyUser(state->sptr))
3216         need_more_params(state->sptr, "MODE +l");
3217       return;
3218     }
3219
3220     t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
3221     state->parc--;
3222     state->max_args--;
3223
3224     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
3225         (!t_limit || t_limit == state->chptr->mode.limit))
3226       return;
3227   } else
3228     t_limit = state->chptr->mode.limit;
3229
3230   /* If they're not an oper, they can't change modes */
3231   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3232     send_notoper(state);
3233     return;
3234   }
3235
3236   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
3237     return;
3238   state->done |= DONE_LIMIT;
3239
3240   assert(0 != state->mbuf);
3241
3242   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
3243
3244   if (state->flags & MODE_PARSE_SET) { /* set the limit */
3245     if (state->dir & MODE_ADD) {
3246       state->chptr->mode.mode |= flag_p[0];
3247       state->chptr->mode.limit = t_limit;
3248     } else {
3249       state->chptr->mode.mode &= flag_p[0];
3250       state->chptr->mode.limit = 0;
3251     }
3252   }
3253 }
3254
3255 /*
3256  * Helper function to convert keys
3257  */
3258 static void
3259 mode_parse_key(struct ParseState *state, int *flag_p)
3260 {
3261   char *t_str, *s;
3262   int t_len;
3263
3264   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3265     return;
3266
3267   if (state->parc <= 0) { /* warn if not enough args */
3268     if (MyUser(state->sptr))
3269       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
3270                        "MODE -k");
3271     return;
3272   }
3273
3274   t_str = state->parv[state->args_used++]; /* grab arg */
3275   state->parc--;
3276   state->max_args--;
3277
3278   /* If they're not an oper, they can't change modes */
3279   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3280     send_notoper(state);
3281     return;
3282   }
3283
3284   if (state->done & DONE_KEY) /* allow key to be set only once */
3285     return;
3286   state->done |= DONE_KEY;
3287
3288   t_len = KEYLEN + 1;
3289
3290   /* clean up the key string */
3291   s = t_str;
3292   while (*++s > ' ' && *s != ':' && --t_len)
3293     ;
3294   *s = '\0';
3295
3296   if (!*t_str) { /* warn if empty */
3297     if (MyUser(state->sptr))
3298       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
3299                        "MODE -k");
3300     return;
3301   }
3302
3303   /* can't add a key if one is set, nor can one remove the wrong key */
3304   if (!(state->flags & MODE_PARSE_FORCE))
3305     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
3306         (state->dir == MODE_DEL &&
3307          ircd_strcmp(state->chptr->mode.key, t_str))) {
3308       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
3309       return;
3310     }
3311
3312   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
3313       !ircd_strcmp(state->chptr->mode.key, t_str))
3314     return; /* no key change */
3315
3316   assert(0 != state->mbuf);
3317
3318   if (state->flags & MODE_PARSE_BOUNCE) {
3319     if (*state->chptr->mode.key) /* reset old key */
3320       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
3321                           state->chptr->mode.key, 0);
3322     else /* remove new bogus key */
3323       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
3324   } else /* send new key */
3325     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
3326
3327   if (state->flags & MODE_PARSE_SET) {
3328     if (state->dir == MODE_ADD) /* set the new key */
3329       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
3330     else /* remove the old key */
3331       *state->chptr->mode.key = '\0';
3332   }
3333 }
3334
3335 /*
3336  * Helper function to convert bans
3337  */
3338 static void
3339 mode_parse_ban(struct ParseState *state, int *flag_p)
3340 {
3341   char *t_str, *s;
3342   struct SLink *ban, *newban = 0;
3343
3344   if (state->parc <= 0) { /* Not enough args, send ban list */
3345     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
3346       send_ban_list(state->sptr, state->chptr);
3347       state->done |= DONE_BANLIST;
3348     }
3349
3350     return;
3351   }
3352
3353   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3354     return;
3355
3356   t_str = state->parv[state->args_used++]; /* grab arg */
3357   state->parc--;
3358   state->max_args--;
3359
3360   /* If they're not an oper, they can't change modes */
3361   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3362     send_notoper(state);
3363     return;
3364   }
3365
3366   if ((s = strchr(t_str, ' ')))
3367     *s = '\0';
3368
3369   if (!*t_str || *t_str == ':') { /* warn if empty */
3370     if (MyUser(state->sptr))
3371       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
3372                        "MODE -b");
3373     return;
3374   }
3375
3376   t_str = collapse(pretty_mask(t_str));
3377
3378   /* remember the ban for the moment... */
3379   if (state->dir == MODE_ADD) {
3380     newban = state->banlist + (state->numbans++);
3381     newban->next = 0;
3382
3383     DupString(newban->value.ban.banstr, t_str);
3384     newban->value.ban.who = state->sptr->name;
3385     newban->value.ban.when = TStime();
3386
3387     newban->flags = CHFL_BAN | MODE_ADD;
3388
3389     if ((s = strrchr(t_str, '@')) && check_if_ipmask(s + 1))
3390       newban->flags |= CHFL_BAN_IPMASK;
3391   }
3392
3393   if (!state->chptr->banlist) {
3394     state->chptr->banlist = newban; /* add our ban with its flags */
3395     state->done |= DONE_BANCLEAN;
3396     return;
3397   }
3398
3399   /* Go through all bans */
3400   for (ban = state->chptr->banlist; ban; ban = ban->next) {
3401     /* first, clean the ban flags up a bit */
3402     if (!(state->done & DONE_BANCLEAN))
3403       /* Note: We're overloading *lots* of bits here; be careful! */
3404       ban->flags &= ~(MODE_ADD | MODE_DEL | CHFL_BAN_OVERLAPPED);
3405
3406     /* Bit meanings:
3407      *
3408      * MODE_ADD            - Ban was added; if we're bouncing modes,
3409      *                       then we'll remove it below; otherwise,
3410      *                       we'll have to allocate a real ban
3411      *
3412      * MODE_DEL            - Ban was marked for deletion; if we're
3413      *                       bouncing modes, we'll have to re-add it,
3414      *                       otherwise, we'll have to remove it
3415      *
3416      * CHFL_BAN_OVERLAPPED - The ban we added turns out to overlap
3417      *                       with a ban already set; if we're
3418      *                       bouncing modes, we'll have to bounce
3419      *                       this one; otherwise, we'll just ignore
3420      *                       it when we process added bans
3421      */
3422
3423     if (state->dir == MODE_DEL && !ircd_strcmp(ban->value.ban.banstr, t_str)) {
3424       ban->flags |= MODE_DEL; /* delete one ban */
3425
3426       if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
3427         break;
3428     } else if (state->dir == MODE_ADD) {
3429       /* if the ban already exists, don't worry about it */
3430       if (!ircd_strcmp(ban->value.ban.banstr, t_str)) {
3431         if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
3432           break;
3433         continue;
3434       } else if (!mmatch(ban->value.ban.banstr, t_str)) {
3435         if (!(ban->flags & MODE_DEL))
3436           newban->flags |= CHFL_BAN_OVERLAPPED; /* our ban overlaps */
3437       } else if (!mmatch(t_str, ban->value.ban.banstr))
3438         ban->flags |= MODE_DEL; /* mark ban for deletion: overlapping */
3439
3440       if (!ban->next) {
3441         ban->next = newban; /* add our ban with its flags */
3442         break; /* get out of loop */
3443       }
3444     }
3445   }
3446   state->done |= DONE_BANCLEAN;
3447 }
3448
3449 /*
3450  * This is the bottom half of the ban processor
3451  */
3452 static void
3453 mode_process_bans(struct ParseState *state)
3454 {
3455   struct SLink *ban, *newban, *prevban, *nextban;
3456   int count = 0;
3457   int len = 0;
3458   int banlen;
3459   int changed = 0;
3460
3461   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
3462     count++;
3463     banlen = strlen(ban->value.ban.banstr);
3464     len += banlen;
3465     nextban = ban->next;
3466
3467     if ((ban->flags & (MODE_DEL | MODE_ADD)) == (MODE_DEL | MODE_ADD)) {
3468       if (prevban)
3469         prevban->next = 0; /* Break the list; ban isn't a real ban */
3470       else
3471         state->chptr->banlist = 0;
3472
3473       count--;
3474       len -= banlen;
3475
3476       MyFree(ban->value.ban.banstr);
3477
3478       continue;
3479     } else if (ban->flags & MODE_DEL) { /* Deleted a ban? */
3480       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
3481                           ban->value.ban.banstr,
3482                           state->flags & MODE_PARSE_SET);
3483
3484       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
3485         if (prevban) /* clip it out of the list... */
3486           prevban->next = ban->next;
3487         else
3488           state->chptr->banlist = ban->next;
3489
3490         count--;
3491         len -= banlen;
3492
3493         MyFree(ban->value.ban.who);
3494         free_link(ban);
3495
3496         changed++;
3497         continue; /* next ban; keep prevban like it is */
3498       } else
3499         ban->flags &= (CHFL_BAN | CHFL_BAN_IPMASK); /* unset other flags */
3500     } else if (ban->flags & MODE_ADD) { /* adding a ban? */
3501       if (prevban)
3502         prevban->next = 0; /* Break the list; ban isn't a real ban */
3503       else
3504         state->chptr->banlist = 0;
3505
3506       /* If we're supposed to ignore it, do so. */
3507       if (ban->flags & CHFL_BAN_OVERLAPPED &&
3508           !(state->flags & MODE_PARSE_BOUNCE)) {
3509         count--;
3510         len -= banlen;
3511
3512         MyFree(ban->value.ban.banstr);
3513       } else {
3514         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
3515             (len > MAXBANLENGTH || count >= MAXBANS)) {
3516           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
3517                      ban->value.ban.banstr);
3518           count--;
3519           len -= banlen;
3520
3521           MyFree(ban->value.ban.banstr);
3522         } else {
3523           /* add the ban to the buffer */
3524           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
3525                               ban->value.ban.banstr,
3526                               !(state->flags & MODE_PARSE_SET));
3527
3528           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
3529             newban = make_link();
3530             newban->value.ban.banstr = ban->value.ban.banstr;
3531             DupString(newban->value.ban.who, ban->value.ban.who);
3532             newban->value.ban.when = ban->value.ban.when;
3533             newban->flags = ban->flags & (CHFL_BAN | CHFL_BAN_IPMASK);
3534
3535             newban->next = state->chptr->banlist; /* and link it in */
3536             state->chptr->banlist = newban;
3537
3538             changed++;
3539           }
3540         }
3541       }
3542     }
3543
3544     prevban = ban;
3545   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
3546
3547   if (changed) /* if we changed the ban list, we must invalidate the bans */
3548     mode_ban_invalidate(state->chptr);
3549 }
3550
3551 /*
3552  * Helper function to process client changes
3553  */
3554 static void
3555 mode_parse_client(struct ParseState *state, int *flag_p)
3556 {
3557   char *t_str;
3558   struct Client *acptr;
3559   int i;
3560
3561   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3562     return;
3563
3564   if (state->parc <= 0) { /* warn if not enough args */
3565     if (MyUser(state->sptr))
3566       need_more_params(state->sptr, state->dir == MODE_ADD ?
3567                        (flag_p[0] == MODE_CHANOP ? "MODE +o" : "MODE +v") :
3568                        (flag_p[0] == MODE_CHANOP ? "MODE -o" : "MODE -v"));
3569     return;
3570   }
3571
3572   t_str = state->parv[state->args_used++]; /* grab arg */
3573   state->parc--;
3574   state->max_args--;
3575
3576   /* If they're not an oper, they can't change modes */
3577   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3578     send_notoper(state);
3579     return;
3580   }
3581
3582   if (MyUser(state->sptr)) /* find client we're manipulating */
3583     acptr = find_chasing(state->sptr, t_str, NULL);
3584   else
3585     acptr = findNUser(t_str);
3586
3587   if (!acptr)
3588     return; /* find_chasing() already reported an error to the user */
3589
3590   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
3591     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
3592                                        state->cli_change[i].flag & flag_p[0]))
3593       break; /* found a slot */
3594
3595   /* Store what we're doing to them */
3596   state->cli_change[i].flag = state->dir | flag_p[0];
3597   state->cli_change[i].client = acptr;
3598 }
3599
3600 /*
3601  * Helper function to process the changed client list
3602  */
3603 static void
3604 mode_process_clients(struct ParseState *state)
3605 {
3606   int i;
3607   struct Membership *member;
3608
3609   for (i = 0; state->cli_change[i].flag; i++) {
3610     assert(0 != state->cli_change[i].client);
3611
3612     /* look up member link */
3613     if (!(member = find_member_link(state->chptr,
3614                                     state->cli_change[i].client)) ||
3615         (MyUser(state->sptr) && IsZombie(member))) {
3616       if (MyUser(state->sptr))
3617         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
3618                    state->cli_change[i].client->name, state->chptr->chname);
3619       continue;
3620     }
3621
3622     if ((state->cli_change[i].flag & MODE_ADD &&
3623          (state->cli_change[i].flag & member->status)) ||
3624         (state->cli_change[i].flag & MODE_DEL &&
3625          !(state->cli_change[i].flag & member->status)))
3626       continue; /* no change made, don't do anything */
3627
3628     /* see if the deop is allowed */
3629     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
3630         (MODE_DEL | MODE_CHANOP)) {
3631       /* prevent +k users from being deopped */
3632       if (IsChannelService(state->cli_change[i].client)) {
3633         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
3634           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
3635                                state->chptr,
3636                                (IsServer(state->sptr) ? state->sptr->name :
3637                                 state->sptr->user->server->name));
3638
3639         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
3640           send_reply(state->sptr, ERR_ISCHANSERVICE,
3641                      state->cli_change[i].client->name, state->chptr->chname);
3642           continue;
3643         }
3644       }
3645
3646 #ifdef NO_OPER_DEOP_LCHAN
3647       /* don't allow local opers to be deopped on local channels */
3648       if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
3649           IsOperOnLocalChannel(state->cli_change[i].client,
3650                                state->chptr->chname)) {
3651         send_reply(state->sptr, ERR_ISOPERLCHAN,
3652                    state->cli_change[i].client->name, state->chptr->chname);
3653         continue;
3654       }
3655 #endif
3656     }
3657
3658     /* accumulate the change */
3659     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
3660                         state->cli_change[i].client);
3661
3662     /* actually effect the change */
3663     if (state->flags & MODE_PARSE_SET) {
3664       if (state->cli_change[i].flag & MODE_ADD) {
3665         member->status |= (state->cli_change[i].flag &
3666                            (MODE_CHANOP | MODE_VOICE));
3667         if (state->cli_change[i].flag & MODE_CHANOP)
3668           ClearDeopped(member);
3669       } else
3670         member->status &= ~(state->cli_change[i].flag &
3671                             (MODE_CHANOP | MODE_VOICE));
3672     }
3673   } /* for (i = 0; state->cli_change[i].flags; i++) { */
3674 }
3675
3676 /*
3677  * Helper function to process the simple modes
3678  */
3679 static void
3680 mode_parse_mode(struct ParseState *state, int *flag_p)
3681 {
3682   if ((state->dir == MODE_ADD &&  (flag_p[0] & state->chptr->mode.mode)) ||
3683       (state->dir == MODE_DEL && !(flag_p[0] & state->chptr->mode.mode)))
3684     return; /* no change */
3685
3686   /* If they're not an oper, they can't change modes */
3687   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3688     send_notoper(state);
3689     return;
3690   }
3691
3692   assert(0 != state->mbuf);
3693
3694   modebuf_mode(state->mbuf, state->dir | flag_p[0]);
3695
3696   /* make +p and +s mutually exclusive */
3697   if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
3698     if (flag_p[0] == MODE_SECRET && (state->chptr->mode.mode & MODE_PRIVATE))
3699       modebuf_mode(state->mbuf, MODE_DEL | MODE_PRIVATE);
3700     else if (flag_p[0] == MODE_PRIVATE &&
3701              (state->chptr->mode.mode & MODE_SECRET))
3702       modebuf_mode(state->mbuf, MODE_DEL | MODE_SECRET);
3703   }
3704
3705   if (state->flags & MODE_PARSE_SET) { /* set the flags */
3706     if (state->dir == MODE_ADD) { /* add the mode to the channel */
3707       state->chptr->mode.mode |= flag_p[0];
3708
3709       /* make +p and +s mutually exclusive */
3710       if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
3711         if (flag_p[0] == MODE_PRIVATE)
3712           state->chptr->mode.mode &= ~MODE_SECRET;
3713         else
3714           state->chptr->mode.mode &= ~MODE_PRIVATE;
3715       }
3716     } else /* remove the mode from the channel */
3717       state->chptr->mode.mode &= ~flag_p[0];
3718   }
3719
3720   /* Clear out invite structures if we're removing invites */
3721   if (state->flags & MODE_PARSE_SET && state->dir == MODE_DEL &&
3722       flag_p[0] == MODE_INVITEONLY)
3723     mode_invite_clear(state->chptr);
3724 }
3725
3726 /*
3727  * This routine is intended to parse MODE or OPMODE commands and effect the
3728  * changes (or just build the bounce buffer).  We pass the starting offset
3729  * as a 
3730  */
3731 int
3732 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
3733            struct Channel *chptr, int parc, char *parv[], unsigned int flags)
3734 {
3735   static int chan_flags[] = {
3736     MODE_CHANOP,        'o',
3737     MODE_VOICE,         'v',
3738     MODE_PRIVATE,       'p',
3739     MODE_SECRET,        's',
3740     MODE_MODERATED,     'm',
3741     MODE_TOPICLIMIT,    't',
3742     MODE_INVITEONLY,    'i',
3743     MODE_NOPRIVMSGS,    'n',
3744     MODE_KEY,           'k',
3745     MODE_BAN,           'b',
3746     MODE_LIMIT,         'l',
3747     MODE_ADD,           '+',
3748     MODE_DEL,           '-',
3749     0x0, 0x0
3750   };
3751   int i;
3752   int *flag_p;
3753   char *modestr;
3754   struct ParseState state;
3755
3756   assert(0 != cptr);
3757   assert(0 != sptr);
3758   assert(0 != chptr);
3759   assert(0 != parc);
3760   assert(0 != parv);
3761
3762   state.mbuf = mbuf;
3763   state.cptr = cptr;
3764   state.sptr = sptr;
3765   state.chptr = chptr;
3766   state.parc = parc;
3767   state.parv = parv;
3768   state.flags = flags;
3769   state.dir = MODE_ADD;
3770   state.done = 0;
3771   state.args_used = 0;
3772   state.max_args = MAXMODEPARAMS;
3773   state.numbans = 0;
3774
3775   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
3776     state.banlist[i].next = 0;
3777     state.banlist[i].value.ban.banstr = 0;
3778     state.banlist[i].value.ban.who = 0;
3779     state.banlist[i].value.ban.when = 0;
3780     state.banlist[i].flags = 0;
3781     state.cli_change[i].flag = 0;
3782     state.cli_change[i].client = 0;
3783   }
3784
3785   modestr = state.parv[state.args_used++];
3786   state.parc--;
3787
3788   while (*modestr) {
3789     for (; *modestr; modestr++) {
3790       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
3791         if (flag_p[1] == *modestr)
3792           break;
3793
3794       if (!flag_p[0]) { /* didn't find it?  complain and continue */
3795         if (MyUser(state.sptr))
3796           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
3797         continue;
3798       }
3799
3800       switch (*modestr) {
3801       case '+': /* switch direction to MODE_ADD */
3802       case '-': /* switch direction to MODE_DEL */
3803         state.dir = flag_p[0];
3804         break;
3805
3806       case 'l': /* deal with limits */
3807         mode_parse_limit(&state, flag_p);
3808         break;
3809
3810       case 'k': /* deal with keys */
3811         mode_parse_key(&state, flag_p);
3812         break;
3813
3814       case 'b': /* deal with bans */
3815         mode_parse_ban(&state, flag_p);
3816         break;
3817
3818       case 'o': /* deal with ops/voice */
3819       case 'v':
3820         mode_parse_client(&state, flag_p);
3821         break;
3822
3823       default: /* deal with other modes */
3824         mode_parse_mode(&state, flag_p);
3825         break;
3826       } /* switch (*modestr) { */
3827     } /* for (; *modestr; modestr++) { */
3828
3829     if (state.flags & MODE_PARSE_BURST)
3830       break; /* don't interpret any more arguments */
3831
3832     if (state.parc > 0) { /* process next argument in string */
3833       modestr = state.parv[state.args_used++];
3834       state.parc--;
3835
3836       /* is it a TS? */
3837       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
3838         time_t recv_ts;
3839
3840         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
3841           break;                     /* we're then going to bounce the mode! */
3842
3843         recv_ts = atoi(modestr);
3844
3845         if (recv_ts && recv_ts < state.chptr->creationtime)
3846           state.chptr->creationtime = recv_ts; /* respect earlier TS */
3847
3848         break; /* break out of while loop */
3849       } else if (state.flags & MODE_PARSE_STRICT ||
3850                  (MyUser(state.sptr) && state.max_args <= 0)) {
3851         state.parc++; /* we didn't actually gobble the argument */
3852         state.args_used--;
3853         break; /* break out of while loop */
3854       }
3855     }
3856   } /* while (*modestr) { */
3857
3858   /*
3859    * the rest of the function finishes building resultant MODEs; if the
3860    * origin isn't a member or an oper, skip it.
3861    */
3862   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
3863     return state.args_used; /* tell our parent how many args we gobbled */
3864
3865   if (state.flags & MODE_PARSE_WIPEOUT) {
3866     if (!(state.done & DONE_LIMIT)) /* remove the old limit */
3867       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
3868                         state.chptr->mode.limit);
3869     if (!(state.done & DONE_KEY)) /* remove the old key */
3870       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
3871                           state.chptr->mode.key, 0);
3872   }
3873
3874   if (state.done & DONE_BANCLEAN) /* process bans */
3875     mode_process_bans(&state);
3876
3877   /* process client changes */
3878   if (state.cli_change[0].flag)
3879     mode_process_clients(&state);
3880
3881   return state.args_used; /* tell our parent how many args we gobbled */
3882 }
3883
3884 /*
3885  * Initialize a join buffer
3886  */
3887 void
3888 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
3889              struct Client *connect, unsigned int type, char *comment,
3890              time_t create)
3891 {
3892   int i;
3893
3894   assert(0 != jbuf);
3895   assert(0 != source);
3896   assert(0 != connect);
3897
3898   jbuf->jb_source = source; /* just initialize struct JoinBuf */
3899   jbuf->jb_connect = connect;
3900   jbuf->jb_type = type;
3901   jbuf->jb_comment = comment;
3902   jbuf->jb_create = create;
3903   jbuf->jb_count = 0;
3904   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
3905                        type == JOINBUF_TYPE_PART ||
3906                        type == JOINBUF_TYPE_PARTALL) ?
3907                       STARTJOINLEN : STARTCREATELEN) +
3908                      (comment ? strlen(comment) + 2 : 0));
3909
3910   for (i = 0; i < MAXJOINARGS; i++)
3911     jbuf->jb_channels[i] = 0;
3912 }
3913
3914 /*
3915  * Add a channel to the join buffer
3916  */
3917 void
3918 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
3919 {
3920   unsigned int len;
3921
3922   assert(0 != jbuf);
3923
3924   if (chan) {
3925     if (jbuf->jb_type == JOINBUF_TYPE_PART ||
3926         jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
3927       /* Send notification to channel */
3928       if (!(flags & CHFL_ZOMBIE))
3929         sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
3930                                   (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3931                                   ":%H" : "%H :%s", chan, jbuf->jb_comment);
3932       else if (MyUser(jbuf->jb_source))
3933         sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
3934                       (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3935                       ":%H" : "%H :%s", chan, jbuf->jb_comment);
3936       /* XXX: Shouldn't we send a PART here anyway? */
3937       /* to users on the channel?  Why?  From their POV, the user isn't on
3938        * the channel anymore anyway.  We don't send to servers until below,
3939        * when we gang all the channel parts together.  Note that this is
3940        * exactly the same logic, albeit somewhat more concise, as was in
3941        * the original m_part.c */
3942     } else {
3943       /* Add user to channel */
3944       add_user_to_channel(chan, jbuf->jb_source, flags);
3945
3946       /* Send the notification to the channel */
3947       sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
3948
3949       /* send an op, too, if needed */
3950       if (jbuf->jb_type == JOINBUF_TYPE_CREATE &&
3951           !IsModelessChannel(chan->chname))
3952         sendcmdto_channel_butserv(jbuf->jb_source, CMD_MODE, chan, "%H +o %C",
3953                                   chan, jbuf->jb_source);
3954     }
3955
3956     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
3957       return; /* don't send to remote */
3958   }
3959
3960   /* figure out if channel name will cause buffer to be overflowed */
3961   len = chan ? strlen(chan->chname) + 1 : 2;
3962   if (jbuf->jb_strlen + len > IRC_BUFSIZE)
3963     joinbuf_flush(jbuf);
3964
3965   /* add channel to list of channels to send and update counts */
3966   jbuf->jb_channels[jbuf->jb_count++] = chan;
3967   jbuf->jb_strlen += len;
3968
3969   /* if we've used up all slots, flush */
3970   if (jbuf->jb_count >= MAXJOINARGS)
3971     joinbuf_flush(jbuf);
3972 }
3973
3974 /*
3975  * Flush the channel list to remote servers
3976  */
3977 int
3978 joinbuf_flush(struct JoinBuf *jbuf)
3979 {
3980   char chanlist[IRC_BUFSIZE];
3981   int chanlist_i = 0;
3982   int i;
3983
3984   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL)
3985     return 0; /* no joins to process */
3986
3987   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
3988     build_string(chanlist, &chanlist_i,
3989                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
3990                  i == 0 ? '\0' : ',');
3991     if (JOINBUF_TYPE_PART == jbuf->jb_type)
3992       /* Remove user from channel */
3993       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
3994
3995     jbuf->jb_channels[i] = 0; /* mark slot empty */
3996   }
3997
3998   jbuf->jb_count = 0; /* reset base counters */
3999   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_JOIN ||
4000                       jbuf->jb_type == JOINBUF_TYPE_PART ?
4001                       STARTJOINLEN : STARTCREATELEN) +
4002                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
4003
4004   /* and send the appropriate command */
4005   switch (jbuf->jb_type) {
4006   case JOINBUF_TYPE_JOIN:
4007     sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
4008                           "%s", chanlist);
4009     break;
4010
4011   case JOINBUF_TYPE_CREATE:
4012     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
4013                           "%s %Tu", chanlist, jbuf->jb_create);
4014     break;
4015
4016   case JOINBUF_TYPE_PART:
4017     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
4018                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
4019                           jbuf->jb_comment);
4020     break;
4021   }
4022
4023   return 0;
4024 }