868a82f052c7d94496dff10b62c2815dafd3d239
[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 /** @file
21  * @brief Channel management and maintenance
22  * @version $Id: channel.c 1906 2009-02-09 03:39:42Z entrope $
23  */
24 #include "config.h"
25
26 #include "channel.h"
27 #include "class.h"
28 #include "client.h"
29 #include "destruct_event.h"
30 #include "hash.h"
31 #include "ircd.h"
32 #include "ircd_alloc.h"
33 #include "ircd_chattr.h"
34 #include "ircd_defs.h"
35 #include "ircd_features.h"
36 #include "ircd_log.h"
37 #include "ircd_reply.h"
38 #include "ircd_snprintf.h"
39 #include "ircd_string.h"
40 #include "list.h"
41 #include "match.h"
42 #include "msg.h"
43 #include "msgq.h"
44 #include "numeric.h"
45 #include "numnicks.h"
46 #include "querycmds.h"
47 #include "s_bsd.h"
48 #include "s_conf.h"
49 #include "s_debug.h"
50 #include "s_misc.h"
51 #include "s_user.h"
52 #include "send.h"
53 #include "struct.h"
54 #include "sys.h"
55 #include "whowas.h"
56
57 /* #include <assert.h> -- Now using assert in ircd_log.h */
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61
62 /** Linked list containing the full list of all channels */
63 struct Channel* GlobalChannelList = 0;
64
65 /** Number of struct Membership*'s allocated */
66 static unsigned int membershipAllocCount;
67 /** Freelist for struct Membership*'s */
68 static struct Membership* membershipFreeList;
69 /** Freelist for struct Ban*'s */
70 static struct Ban* free_bans;
71 /** Freelist for struct MemberFlood*'s */
72 static struct MemberFlood* free_MemberFlood;
73 /** Number of ban structures allocated. */
74 static size_t bans_alloc;
75 /** Number of ban structures in use. */
76 static size_t bans_inuse;
77
78 #if !defined(NDEBUG)
79 /** return the length (>=0) of a chain of links.
80  * @param lp    pointer to the start of the linked list
81  * @return the number of items in the list
82  */
83 static int list_length(struct SLink *lp)
84 {
85   int count = 0;
86
87   for (; lp; lp = lp->next)
88     ++count;
89   return count;
90 }
91 #endif
92
93 /** Set the mask for a ban, checking for IP masks.
94  * @param[in,out] ban Ban structure to modify.
95  * @param[in] banstr Mask to ban.
96  */
97 static void
98 set_ban_mask(struct Ban *ban, const char *banstr)
99 {
100   char *sep;
101   assert(banstr != NULL);
102   ircd_strncpy(ban->banstr, banstr, sizeof(ban->banstr) - 1);
103   sep = strrchr(banstr, '@');
104   if (sep) {
105     ban->nu_len = sep - banstr;
106     if (ipmask_parse(sep + 1, &ban->address, &ban->addrbits))
107       ban->flags |= BAN_IPMASK;
108   }
109 }
110
111 /** Allocate a new Ban structure.
112  * @param[in] banstr Ban mask to use.
113  * @return Newly allocated ban.
114  */
115 struct Ban *
116 make_ban(const char *banstr)
117 {
118   struct Ban *ban;
119   if (free_bans) {
120     ban = free_bans;
121     free_bans = free_bans->next;
122   }
123   else if (!(ban = MyMalloc(sizeof(*ban))))
124     return NULL;
125   else
126     bans_alloc++;
127   bans_inuse++;
128   memset(ban, 0, sizeof(*ban));
129   set_ban_mask(ban, banstr);
130   return ban;
131 }
132
133 /** Deallocate a ban structure.
134  * @param[in] ban Ban to deallocate.
135  */
136 void
137 free_ban(struct Ban *ban)
138 {
139   ban->next = free_bans;
140   free_bans = ban;
141   bans_inuse--;
142 }
143
144 /** Report ban usage to \a cptr.
145  * @param[in] cptr Client requesting information.
146  */
147 void bans_send_meminfo(struct Client *cptr)
148 {
149   struct Ban *ban;
150   size_t num_free;
151   for (num_free = 0, ban = free_bans; ban; ban = ban->next)
152     num_free++;
153   send_reply(cptr, SND_EXPLICIT | RPL_STATSDEBUG, ":Bans: inuse %zu(%zu) free %zu alloc %zu",
154              bans_inuse, bans_inuse * sizeof(*ban), num_free, bans_alloc);
155 }
156
157 /** return the struct Membership* that represents a client on a channel
158  * This function finds a struct Membership* which holds the state about
159  * a client on a specific channel.  The code is smart enough to iterate
160  * over the channels a user is in, or the users in a channel to find the
161  * user depending on which is likely to be more efficient.
162  *
163  * @param chptr pointer to the channel struct
164  * @param cptr pointer to the client struct
165  *
166  * @returns pointer to the struct Membership representing this client on 
167  *          this channel.  Returns NULL if the client is not on the channel.
168  *          Returns NULL if the client is actually a server.
169  * @see find_channel_member()
170  */
171 struct Membership* find_member_link(struct Channel* chptr, const struct Client* cptr)
172 {
173   struct Membership *m;
174   assert(0 != cptr);
175   assert(0 != chptr);
176   
177   /* Servers don't have member links */
178   if (IsServer(cptr)||IsMe(cptr))
179      return 0;
180   
181   /* +k users are typically on a LOT of channels.  So we iterate over who
182    * is in the channel.  X/W are +k and are in about 5800 channels each.
183    * however there are typically no more than 1000 people in a channel
184    * at a time.
185    */
186   if (IsChannelService(cptr)) {
187     m = chptr->members;
188     while (m) {
189       assert(m->channel == chptr);
190       if (m->user == cptr)
191         return m;
192       m = m->next_member;
193     }
194   }
195   /* Users on the other hand aren't allowed on more than 15 channels.  50%
196    * of users that are on channels are on 2 or less, 95% are on 7 or less,
197    * and 99% are on 10 or less.
198    */
199   else {
200    m = (cli_user(cptr))->channel;
201    while (m) {
202      assert(m->user == cptr);
203      if (m->channel == chptr)
204        return m;
205      m = m->next_channel;
206    }
207   }
208   return 0;
209 }
210
211 /** Find the client structure for a nick name (user) 
212  * Find the client structure for a nick name (user)
213  * using history mechanism if necessary. If the client is not found, an error
214  * message (NO SUCH NICK) is generated. If the client was found
215  * through the history, chasing will be 1 and otherwise 0.
216  *
217  * This function was used extensively in the P09 days, and since we now have
218  * numeric nicks is no longer quite as important.
219  *
220  * @param sptr  Pointer to the client that has requested the search
221  * @param user  a string representing the client to be found
222  * @param chasing a variable set to 0 if the user was found directly, 
223  *              1 otherwise
224  * @returns a pointer the client, or NULL if the client wasn't found.
225  */
226 struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
227 {
228   struct Client* who = FindClient(user);
229   
230   if (chasing)
231     *chasing = 0;
232   if (who)
233     return who;
234
235   if (!(who = get_history(user, feature_int(FEAT_KILLCHASETIMELIMIT)))) {
236     send_reply(sptr, ERR_NOSUCHNICK, user);
237     return 0;
238   }
239   if (chasing)
240     *chasing = 1;
241   return who;
242 }
243
244 /** Decrement the count of users, and free if empty.
245  * Subtract one user from channel i (and free channel * block, if channel 
246  * became empty).
247  *
248  * @param chptr The channel to subtract one from.
249  *
250  * @returns true  (1) if channel still has members.
251  *          false (0) if the channel is now empty.
252  */
253 int sub1_from_channel(struct Channel* chptr)
254 {
255   if (chptr->users > 1)         /* Can be 0, called for an empty channel too */
256   {
257     assert(0 != chptr->members);
258     --chptr->users;
259     return 1;
260   }
261
262   chptr->users = 0;
263
264   if(chptr->mode.mode & MODE_PERSIST)
265     return 0;
266
267   /*
268    * Also channels without Apass set need to be kept alive,
269    * otherwise Bad Guys(tm) would be able to takeover
270    * existing channels too easily, and then set an Apass!
271    * However, if a channel without Apass becomes empty
272    * then we try to be kind to them and remove possible
273    * limiting modes.
274    */
275   chptr->mode.mode &= ~MODE_INVITEONLY;
276   chptr->mode.limit = 0;
277   /*
278    * We do NOT reset a possible key or bans because when
279    * the 'channel owners' can't get in because of a key
280    * or ban then apparently there was a fight/takeover
281    * on the channel and we want them to contact IRC opers
282    * who then will educate them on the use of Apass/Upass.
283    */
284   if (!chptr->mode.apass[0])                    /* If no Apass, reset all modes. */
285   {
286     struct Ban *link, *next;
287     chptr->mode.mode = 0;
288     *chptr->mode.key = '\0';
289     while (chptr->invites)
290       del_invite(chptr->invites->value.cptr, chptr);
291     for (link = chptr->banlist; link; link = next) {
292       next = link->next;
293       free_ban(link);
294     }
295     chptr->banlist = NULL;
296
297     /* Immediately destruct empty -A channels if not using apass. */
298     if (!feature_bool(FEAT_OPLEVELS))
299     {
300       destruct_channel(chptr);
301       return 0;
302     }
303   }
304   if (TStime() - chptr->creationtime < 172800)  /* Channel younger than 48 hours? */
305     schedule_destruct_event_1m(chptr);          /* Get rid of it in approximately 4-5 minutes */
306   else
307     schedule_destruct_event_48h(chptr);         /* Get rid of it in approximately 48 hours */
308
309   return 0;
310 }
311
312 /** Destroy an empty channel
313  * This function destroys an empty channel, removing it from hashtables,
314  * and removing any resources it may have consumed.
315  *
316  * @param chptr The channel to destroy
317  *
318  * @returns 0 (success)
319  *
320  * FIXME: Change to return void, this function never fails.
321  */
322 int destruct_channel(struct Channel* chptr)
323 {
324   struct Ban *ban, *next;
325
326   assert(0 == chptr->members);
327
328   /*
329    * Now, find all invite links from channel structure
330    */
331   while (chptr->invites)
332     del_invite(chptr->invites->value.cptr, chptr);
333
334   for (ban = chptr->banlist; ban; ban = next)
335   {
336     next = ban->next;
337     free_ban(ban);
338   }
339   if (chptr->prev)
340     chptr->prev->next = chptr->next;
341   else
342     GlobalChannelList = chptr->next;
343   if (chptr->next)
344     chptr->next->prev = chptr->prev;
345   hRemChannel(chptr);
346   --UserStats.channels;
347   /*
348    * make sure that channel actually got removed from hash table
349    */
350   assert(chptr->hnext == chptr);
351   MyFree(chptr);
352   return 0;
353 }
354
355 /** returns Membership * if a person is joined and not a zombie
356  * @param cptr Client
357  * @param chptr Channel
358  * @returns pointer to the client's struct Membership * on the channel if that
359  *          user is a full member of the channel, or NULL otherwise.
360  *
361  * @see find_member_link()
362  */
363 struct Membership* find_channel_member(struct Client* cptr, struct Channel* chptr)
364 {
365   struct Membership* member;
366   assert(0 != chptr);
367
368   member = find_member_link(chptr, cptr);
369   return (member && !IsZombie(member)) ? member : 0;
370 }
371
372 /** Searches for a ban from a ban list that matches a user.
373  * @param[in] cptr The client to test.
374  * @param[in] banlist The list of bans to test.
375  * @return Pointer to a matching ban, or NULL if none exit.
376  */
377 static struct Ban *find_ban_with_nick(struct Client *cptr, const char *nick, struct Ban *banlist)
378 {
379   char        nu[NICKLEN + USERLEN + 2];
380   char        tmphost[HOSTLEN + 1];
381   char        iphost[SOCKIPLEN + 1];
382   char       *hostmask;
383   char       *sr = NULL;
384   char       *account_host = NULL;
385   struct Ban *found;
386
387   /* Build nick!user and alternate host names. */
388   ircd_snprintf(0, nu, sizeof(nu), "%s!%s",
389                 (nick ? nick : cli_name(cptr)), cli_user(cptr)->username);
390   ircd_ntoa_r(iphost, &cli_ip(cptr));
391
392   /* Check for all three possible hosts:
393    *   - account host
394    *   - fakehost
395    *   - real host
396    * But only if they are set.
397    *  --gix */
398   if(IsAccount(cptr)) {
399     ircd_snprintf(0, tmphost, HOSTLEN, "%s.%s", cli_user(cptr)->account, feature_str(FEAT_HIDDEN_HOST));
400     account_host = tmphost;
401   }
402   if(IsFakeHost(cptr)) {
403     if(HasHiddenHost(cptr)) {
404       sr = cli_user(cptr)->realhost;
405     }
406     else sr = cli_user(cptr)->fakehost;
407   }
408   else if(HasHiddenHost(cptr)) {
409     account_host = NULL;
410     sr = cli_user(cptr)->realhost;
411   }
412
413   /* Walk through ban list. */
414   for (found = NULL; banlist; banlist = banlist->next) {
415     int res;
416     /* If we have found a positive ban already, only consider exceptions. */
417     if (found && !(banlist->flags & BAN_EXCEPTION))
418       continue;
419     /* Compare nick!user portion of ban. */
420     banlist->banstr[banlist->nu_len] = '\0';
421     res = match(banlist->banstr, nu);
422     banlist->banstr[banlist->nu_len] = '@';
423     if (res)
424       continue;
425     /* Compare host portion of ban. */
426     hostmask = banlist->banstr + banlist->nu_len + 1;
427     if (!((banlist->flags & BAN_IPMASK)
428          && ipmask_check(&cli_ip(cptr), &banlist->address, banlist->addrbits))
429         && match(hostmask, cli_user(cptr)->host)
430         && !(account_host && !match(hostmask, account_host))
431         && !(sr && !match(hostmask, sr)))
432         continue;
433     /* If an exception matches, no ban can match. */
434     if (banlist->flags & BAN_EXCEPTION)
435       return NULL;
436     /* Otherwise, remember this ban but keep searching for an exception. */
437     found = banlist;
438   }
439   return found;
440 }
441
442 struct Ban *find_ban(struct Client *cptr, struct Ban *banlist) {
443     return find_ban_with_nick(cptr, NULL, banlist);
444 }
445
446 /**
447  * This function returns true if the user is banned on the said channel.
448  * This function will check the ban cache if applicable, otherwise will
449  * do the comparisons and cache the result.
450  *
451  * @param[in] member The Membership to test for banned-ness.
452  * @return Non-zero if the member is banned, zero if not.
453  */
454 static int is_banned(struct Membership* member)
455 {
456   if (IsBanValid(member))
457     return IsBanned(member);
458
459   SetBanValid(member);
460   if (find_ban(member->user, member->channel->banlist)) {
461     SetBanned(member);
462     return 1;
463   } else {
464     ClearBanned(member);
465     return 0;
466   }
467 }
468
469 static int is_banned_with_nick(struct Membership* member, const char *nick) {
470   if (find_ban_with_nick(member->user, nick, member->channel->banlist))
471     return 1;
472   else
473     return 0;
474 }
475
476 /** add a user to a channel.
477  * adds a user to a channel by adding another link to the channels member
478  * chain.
479  *
480  * @param chptr The channel to add to.
481  * @param who   The user to add.
482  * @param flags The flags the user gets initially.
483  * @param oplevel The oplevel the user starts with.
484  */
485 void add_user_to_channel(struct Channel* chptr, struct Client* who,
486                                 unsigned int flags, int oplevel)
487 {
488   assert(0 != chptr);
489   assert(0 != who);
490
491   if (cli_user(who)) {
492    
493     struct Membership* member = membershipFreeList;
494     if (member)
495       membershipFreeList = member->next_member;
496     else {
497       member = (struct Membership*) MyMalloc(sizeof(struct Membership));
498       ++membershipAllocCount;
499     }
500
501     assert(0 != member);
502     member->user         = who;
503     member->channel      = chptr;
504     member->status       = flags;
505     member->flood        = NULL;
506     SetOpLevel(member, oplevel);
507
508     member->next_member  = chptr->members;
509     if (member->next_member)
510       member->next_member->prev_member = member;
511     member->prev_member  = 0; 
512     chptr->members       = member;
513
514     member->next_channel = (cli_user(who))->channel;
515     if (member->next_channel)
516       member->next_channel->prev_channel = member;
517     member->prev_channel = 0;
518     (cli_user(who))->channel = member;
519
520     if (chptr->destruct_event)
521       remove_destruct_event(chptr);
522     ++chptr->users;
523     ++((cli_user(who))->joined);
524   }
525 }
526
527 /** Remove a person from a channel, given their Membership*
528  *
529  * @param member A member of a channel.
530  *
531  * @returns true if there are more people in the channel.
532  */
533 static int remove_member_from_channel(struct Membership* member)
534 {
535   struct Channel* chptr;
536   assert(0 != member);
537   chptr = member->channel;
538   /*
539    * unlink channel member list
540    */
541   if (member->next_member)
542     member->next_member->prev_member = member->prev_member;
543   if (member->prev_member)
544     member->prev_member->next_member = member->next_member;
545   else
546     member->channel->members = member->next_member; 
547
548   /*
549    * If this is the last delayed-join user, may have to clear WASDELJOINS.
550    */
551   if (IsDelayedJoin(member))
552     CheckDelayedJoins(chptr);
553
554   /*
555    * unlink client channel list
556    */
557   if (member->next_channel)
558     member->next_channel->prev_channel = member->prev_channel;
559   if (member->prev_channel)
560     member->prev_channel->next_channel = member->next_channel;
561   else
562     (cli_user(member->user))->channel = member->next_channel;
563
564   --(cli_user(member->user))->joined;
565
566   member->flood = NULL;
567   
568   member->next_member = membershipFreeList;
569   membershipFreeList = member;
570
571   return sub1_from_channel(chptr);
572 }
573
574 /** Check if all the remaining members on the channel are zombies
575  *
576  * @returns False if the channel has any non zombie members, True otherwise.
577  * @see \ref zombie
578  */
579 static int channel_all_zombies(struct Channel* chptr)
580 {
581   struct Membership* member;
582
583   /* Though, there are no real users we pretend this channel to have members
584    * to protect it from being destroyed.
585    */
586   if(chptr->mode.mode & MODE_PERSIST)
587     return 0;
588
589   for (member = chptr->members; member; member = member->next_member) {
590     if (!IsZombie(member))
591       return 0;
592   }
593   return 1;
594 }
595       
596
597 /** Remove a user from a channel
598  * This is the generic entry point for removing a user from a channel, this
599  * function will remove the client from the channel, and destroy the channel
600  * if there are no more normal users left.
601  *
602  * @param cptr          The client
603  * @param chptr         The channel
604  */
605 void remove_user_from_channel(struct Client* cptr, struct Channel* chptr)
606 {
607   
608   struct Membership* member;
609   assert(0 != chptr);
610
611   if ((member = find_member_link(chptr, cptr))) {
612     if (remove_member_from_channel(member)) {
613       if (channel_all_zombies(chptr)) {
614         /*
615          * XXX - this looks dangerous but isn't if we got the referential
616          * integrity right for channels
617          */
618         while (remove_member_from_channel(chptr->members))
619           ;
620       }
621     }
622   }
623 }
624
625 /** Remove a user from all channels they are on.
626  *
627  * This function removes a user from all channels they are on.
628  *
629  * @param cptr  The client to remove.
630  */
631 void remove_user_from_all_channels(struct Client* cptr)
632 {
633   struct Membership* chan;
634   assert(0 != cptr);
635   assert(0 != cli_user(cptr));
636
637   while ((chan = (cli_user(cptr))->channel))
638     remove_user_from_channel(cptr, chan->channel);
639 }
640
641 /** Check if this user is a legitimate chanop
642  *
643  * @param cptr  Client to check
644  * @param chptr Channel to check
645  *
646  * @returns True if the user is a chanop (And not a zombie), False otherwise.
647  * @see \ref zombie
648  */
649 int is_chan_op(struct Client *cptr, struct Channel *chptr)
650 {
651   struct Membership* member;
652   assert(chptr);
653   if ((member = find_member_link(chptr, cptr)))
654     return (!IsZombie(member) && IsChanOp(member));
655
656   return 0;
657 }
658
659 /** Check if a user is a Zombie on a specific channel.
660  *
661  * @param cptr          The client to check.
662  * @param chptr         The channel to check.
663  *
664  * @returns True if the client (cptr) is a zombie on the channel (chptr),
665  *          False otherwise.
666  *
667  * @see \ref zombie
668  */
669 int is_zombie(struct Client *cptr, struct Channel *chptr)
670 {
671   struct Membership* member;
672
673   assert(0 != chptr);
674
675   if ((member = find_member_link(chptr, cptr)))
676       return IsZombie(member);
677   return 0;
678 }
679
680 /** Returns if a user has voice on a channel.
681  *
682  * @param cptr  The client
683  * @param chptr The channel
684  *
685  * @returns True if the client (cptr) is voiced on (chptr) and is not a zombie.
686  * @see \ref zombie
687  */
688 int has_voice(struct Client* cptr, struct Channel* chptr)
689 {
690   struct Membership* member;
691
692   assert(0 != chptr);
693   if ((member = find_member_link(chptr, cptr)))
694     return (!IsZombie(member) && HasVoice(member));
695
696   return 0;
697 }
698
699 /** Can this member send to a channel
700  *
701  * A user can speak on a channel iff:
702  * <ol>
703  *  <li> They didn't use the Apass to gain ops.
704  *  <li> They are op'd or voice'd.
705  *  <li> You aren't banned.
706  *  <li> The channel isn't +m
707  *  <li> The channel isn't +n or you are on the channel.
708  * </ol>
709  *
710  * This function will optionally reveal a user on a delayed join channel if
711  * they are allowed to send to the channel.
712  *
713  * @param member        The membership of the user
714  * @param reveal        If true, the user will be "revealed" on a delayed
715  *                      joined channel.
716  *
717  * @returns True if the client can speak on the channel.
718  */
719 int member_can_send_to_channel(struct Membership* member, int reveal)
720 {
721   assert(0 != member);
722
723   /* Do not check for users on other servers: This should be a
724    * temporary desynch, or maybe they are on an older server, but
725    * we do not want to send ERR_CANNOTSENDTOCHAN more than once.
726    * Also allow XtraOps to be always able to speak.
727    */
728   if (!MyUser(member->user) || IsXtraOp(member->user))
729   {
730     if (IsDelayedJoin(member) && !IsInvisibleJoin(member) && reveal)
731       RevealDelayedJoin(member);
732     return 1;
733   }
734
735   /* Discourage using the Apass to get op.  They should use the Upass. */
736   if (IsChannelManager(member) && member->channel->mode.apass[0])
737     return 0;
738
739   /* If you have voice or ops, you can speak. */
740   if (IsVoicedOrOpped(member))
741     return 1;
742
743   /*
744    * If it's moderated, and you aren't a privileged user, you can't
745    * speak.
746    */
747   if (member->channel->mode.mode & MODE_MODERATED)
748     return 0;
749
750   /* If only logged in users may join and you're not one, you can't speak. */
751   if (member->channel->mode.mode & MODE_REGONLY && !IsAccount(member->user))
752     return 0;
753
754   /* If you're banned then you can't speak either. */
755   if (is_banned(member))
756     return 0;
757
758   if (IsDelayedJoin(member) && reveal && !IsInvisibleJoin(member))
759     RevealDelayedJoin(member);
760
761   return 1;
762 }
763
764 /** Check if a client can send to a channel.
765  *
766  * Has the added check over member_can_send_to_channel() of servers can
767  * always speak.
768  *
769  * @param cptr  The client to check
770  * @param chptr The channel to check
771  * @param reveal If the user should be revealed (see 
772  *              member_can_send_to_channel())
773  *
774  * @returns true if the client is allowed to speak on the channel, false 
775  *              otherwise
776  *
777  * @see member_can_send_to_channel()
778  */
779 int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr, int reveal)
780 {
781   struct Membership *member;
782   assert(0 != cptr); 
783   /*
784    * Servers and extra ops can always speak on channels.
785    */
786   if (IsServer(cptr) || IsXtraOp(cptr))
787     return 1;
788
789   member = find_channel_member(cptr, chptr);
790
791   /*
792    * You can't speak if you're off channel, and it is +n (no external messages)
793    * or +m (moderated).
794    */
795   if (!member) {
796     if ((chptr->mode.mode & (MODE_NOPRIVMSGS|MODE_MODERATED)) ||
797         ((chptr->mode.mode & MODE_REGONLY) && !IsAccount(cptr)))
798       return 0;
799     else
800       return !find_ban(cptr, chptr->banlist);
801   }
802   return member_can_send_to_channel(member, reveal);
803 }
804
805 /** Returns the name of a channel that prevents the user from changing nick.
806  * if a member and not (opped or voiced) and (banned or moderated), return
807  * the name of the first channel banned on.
808  *
809  * @param cptr  The client
810  * @param new_nick The new nick of the client
811  *
812  * @returns the name of the first channel banned on, or NULL if the user
813  *          can change nicks.
814  */
815 const char* find_no_nickchange_channel(struct Client* cptr, const char *new_nick)
816 {
817   if (MyUser(cptr)) {
818     struct Membership* member;
819     for (member = (cli_user(cptr))->channel; member;
820          member = member->next_channel) {
821       if (IsVoicedOrOpped(member))
822         continue;
823       if ((member->channel->mode.mode & MODE_MODERATED)
824           || (member->channel->mode.mode & MODE_REGONLY && !IsAccount(cptr))
825           || is_banned(member) || (new_nick && is_banned_with_nick(member, new_nick)))
826         return member->channel->chname;
827     }
828   }
829   return 0;
830 }
831
832
833 /** Fill mbuf/pbuf with modes from chptr
834  * write the "simple" list of channel modes for channel chptr onto buffer mbuf
835  * with the parameters in pbuf as visible by cptr.
836  *
837  * This function will hide keys from non-op'd, non-server clients.
838  *
839  * @param cptr  The client to generate the mode for.
840  * @param mbuf  The buffer to write the modes into.
841  * @param pbuf  The buffer to write the mode parameters into.
842  * @param buflen The length of the buffers.
843  * @param chptr The channel to get the modes from.
844  * @param member The membership of this client on this channel (or NULL
845  *              if this client isn't on this channel)
846  *
847  */
848 void channel_modes(struct Client *cptr, char *mbuf, char *pbuf, int buflen,
849                           struct Channel *chptr, struct Membership *member)
850 {
851   int previous_parameter = 0;
852
853   assert(0 != mbuf);
854   assert(0 != pbuf);
855   assert(0 != chptr);
856
857   *mbuf++ = '+';
858   if (chptr->mode.mode & MODE_SECRET)
859     *mbuf++ = 's';
860   else if (chptr->mode.mode & MODE_PRIVATE)
861     *mbuf++ = 'p';
862   if (chptr->mode.mode & MODE_MODERATED)
863     *mbuf++ = 'm';
864   if (chptr->mode.mode & MODE_TOPICLIMIT)
865     *mbuf++ = 't';
866   if (chptr->mode.mode & MODE_INVITEONLY)
867     *mbuf++ = 'i';
868   if (chptr->mode.mode & MODE_NOPRIVMSGS)
869     *mbuf++ = 'n';
870   if (chptr->mode.mode & MODE_REGONLY)
871     *mbuf++ = 'r';
872   if (chptr->mode.mode & MODE_DELJOINS)
873     *mbuf++ = 'D';
874   else if (MyUser(cptr) && (chptr->mode.mode & MODE_WASDELJOINS))
875     *mbuf++ = 'd';
876   if (chptr->mode.mode & MODE_NOCOLOUR)
877     *mbuf++ = 'c';
878   if (chptr->mode.mode & MODE_NOCTCP)
879     *mbuf++ = 'C';
880   if (chptr->mode.mode & MODE_PERSIST)
881     *mbuf++ = 'z';
882   if (chptr->mode.mode & MODE_REGISTERED)
883     *mbuf++ = 'R';
884   if (chptr->mode.mode & MODE_NONOTICE)
885     *mbuf++ = 'N';
886   if (chptr->mode.mode & MODE_NOAMSGS)
887     *mbuf++ = 'M';
888   if (chptr->mode.mode & MODE_QUARANTINE)
889     *mbuf++ = 'Q';
890   if (chptr->mode.mode & MODE_AUDITORIUM)
891     *mbuf++ = 'u';
892   if (chptr->mode.limit) {
893     *mbuf++ = 'l';
894     ircd_snprintf(0, pbuf, buflen, "%u", chptr->mode.limit);
895     previous_parameter = 1;
896   }
897   if (chptr->mode.access) {
898     *mbuf++ = 'a';
899     if (previous_parameter)
900       strcat(pbuf, " ");
901     ircd_snprintf(0, pbuf, buflen, "%u", chptr->mode.access);
902     previous_parameter = 1;
903   }
904   if (*chptr->mode.altchan) {
905     *mbuf++ = 'F';
906     if (previous_parameter)
907       strcat(pbuf, " ");
908     strcat(pbuf, chptr->mode.altchan);
909     previous_parameter = 1;
910   }
911   if (*chptr->mode.noflood) {
912     *mbuf++ = 'f';
913     if (previous_parameter)
914       strcat(pbuf, " ");
915     strcat(pbuf, chptr->mode.noflood);
916     previous_parameter = 1;
917   }
918   if (*chptr->mode.key) {
919     *mbuf++ = 'k';
920     if (previous_parameter)
921       strcat(pbuf, " ");
922     if (is_chan_op(cptr, chptr) || IsServer(cptr) || IsOper(cptr)) {
923       strcat(pbuf, chptr->mode.key);
924     } else
925       strcat(pbuf, "*");
926     previous_parameter = 1;
927   }
928   if (*chptr->mode.apass) {
929     *mbuf++ = 'A';
930     if (previous_parameter)
931       strcat(pbuf, " ");
932     if (IsServer(cptr) || IsOper(cptr)) {
933       strcat(pbuf, chptr->mode.apass);
934     } else
935       strcat(pbuf, "*");
936     previous_parameter = 1;
937   }
938   if (*chptr->mode.upass) {
939     *mbuf++ = 'U';
940     if (previous_parameter)
941       strcat(pbuf, " ");
942     if (IsServer(cptr) || (member && IsChanOp(member) && OpLevel(member) == 0) || IsOper(cptr)) {
943       strcat(pbuf, chptr->mode.upass);
944     } else
945       strcat(pbuf, "*");
946   }
947   *mbuf = '\0';
948 }
949
950 /** Compare two members oplevel
951  *
952  * @param mp1   Pointer to a pointer to a membership
953  * @param mp2   Pointer to a pointer to a membership
954  *
955  * @returns 0 if equal, -1 if mp1 is lower, +1 otherwise.
956  *
957  * Used for qsort(3).
958  */
959 int compare_member_oplevel(const void *mp1, const void *mp2)
960 {
961   struct Membership const* member1 = *(struct Membership const**)mp1;
962   struct Membership const* member2 = *(struct Membership const**)mp2;
963   if (member1->oplevel == member2->oplevel)
964     return 0;
965   return (member1->oplevel < member2->oplevel) ? -1 : 1;
966 }
967
968 /* send "cptr" a full list of the modes for channel chptr.
969  *
970  * Sends a BURST line to cptr, bursting all the modes for the channel.
971  *
972  * @param cptr  Client pointer
973  * @param chptr Channel pointer
974  */
975 void send_channel_modes(struct Client *cptr, struct Channel *chptr)
976 {
977   /* The order in which modes are generated is now mandatory */
978   static unsigned int current_flags[4] =
979       { 0, CHFL_VOICE, CHFL_CHANOP, CHFL_CHANOP | CHFL_VOICE };
980   int                first = 1;
981   int                full  = 1;
982   int                flag_cnt = 0;
983   int                new_mode = 0;
984   size_t             len;
985   struct Membership* member;
986   struct Ban*        lp2;
987   char modebuf[MODEBUFLEN];
988   char parabuf[MODEBUFLEN];
989   struct MsgBuf *mb;
990   int                 number_of_ops = 0;
991   int                 opped_members_index = 0;
992   struct Membership** opped_members = NULL;
993   int                 last_oplevel = 0;
994   int                 send_oplevels = 0;
995
996   assert(0 != cptr);
997   assert(0 != chptr); 
998
999   if (IsLocalChannel(chptr->chname))
1000     return;
1001
1002   member = chptr->members;
1003   lp2 = chptr->banlist;
1004
1005   *modebuf = *parabuf = '\0';
1006   channel_modes(cptr, modebuf, parabuf, sizeof(parabuf), chptr, 0);
1007
1008   for (first = 1; full; first = 0)      /* Loop for multiple messages */
1009   {
1010     full = 0;                   /* Assume by default we get it
1011                                  all in one message */
1012
1013     /* (Continued) prefix: "<Y> B <channel> <TS>" */
1014     /* is there any better way we can do this? */
1015     mb = msgq_make(&me, "%C " TOK_BURST " %H %Tu", &me, chptr,
1016                    chptr->creationtime);
1017
1018     if (first && modebuf[1])    /* Add simple modes (Aiklmnpstu)
1019                                  if first message */
1020     {
1021       /* prefix: "<Y> B <channel> <TS>[ <modes>[ <params>]]" */
1022       msgq_append(&me, mb, " %s", modebuf);
1023
1024       if (*parabuf)
1025         msgq_append(&me, mb, " %s", parabuf);
1026     }
1027
1028     /*
1029      * Attach nicks, comma separated " nick[:modes],nick[:modes],..."
1030      *
1031      * First find all opless members.
1032      * Run 2 times over all members, to group the members with
1033      * and without voice together.
1034      * Then run 2 times over all opped members (which are ordered
1035      * by op-level) to also group voice and non-voice together.
1036      */
1037     for (first = 1; flag_cnt < 4; new_mode = 1, ++flag_cnt)
1038     {
1039       while (member)
1040       {
1041         if (flag_cnt < 2 && IsChanOp(member))
1042         {
1043           /*
1044            * The first loop (to find all non-voice/op), we count the ops.
1045            * The second loop (to find all voiced non-ops), store the ops
1046            * in a dynamic array.
1047            */
1048           if (flag_cnt == 0)
1049             ++number_of_ops;
1050           else
1051             opped_members[opped_members_index++] = member;
1052           /* We also send oplevels if anyone is below the weakest level.  */
1053           if (OpLevel(member) < MAXOPLEVEL)
1054             send_oplevels = 1;
1055         }
1056         /* Only handle the members with the flags that we are interested in. */
1057         if ((member->status & CHFL_VOICED_OR_OPPED) == current_flags[flag_cnt])
1058         {
1059           if (msgq_bufleft(mb) < NUMNICKLEN + 3 + MAXOPLEVELDIGITS)
1060             /* The 3 + MAXOPLEVELDIGITS is a possible ",:v999". */
1061           {
1062             full = 1;           /* Make sure we continue after
1063                                    sending it so far */
1064             /* Ensure the new BURST line contains the current
1065              * ":mode", except when there is no mode yet. */
1066             new_mode = (flag_cnt > 0) ? 1 : 0;
1067             break;              /* Do not add this member to this message */
1068           }
1069           msgq_append(&me, mb, "%c%C", first ? ' ' : ',', member->user);
1070           first = 0;              /* From now on, use commas to add new nicks */
1071
1072           /*
1073            * Do we have a nick with a new mode ?
1074            * Or are we starting a new BURST line?
1075            */
1076           if (new_mode)
1077           {
1078             /*
1079              * This means we are at the _first_ member that has only
1080              * voice, or the first member that has only ops, or the
1081              * first member that has voice and ops (so we get here
1082              * at most three times, plus once for every start of
1083              * a continued BURST line where only these modes is current.
1084              * In the two cases where the current mode includes ops,
1085              * we need to add the _absolute_ value of the oplevel to the mode.
1086              */
1087             char tbuf[3 + MAXOPLEVELDIGITS] = ":";
1088             int loc = 1;
1089
1090             if (HasVoice(member))       /* flag_cnt == 1 or 3 */
1091               tbuf[loc++] = 'v';
1092             if (IsChanOp(member))       /* flag_cnt == 2 or 3 */
1093             {
1094               /* append the absolute value of the oplevel */
1095               if (send_oplevels)
1096                 loc += ircd_snprintf(0, tbuf + loc, sizeof(tbuf) - loc, "%u", last_oplevel = member->oplevel);
1097               else
1098                 tbuf[loc++] = 'o';
1099             }
1100             tbuf[loc] = '\0';
1101             msgq_append(&me, mb, tbuf);
1102             new_mode = 0;
1103           }
1104           else if (send_oplevels && flag_cnt > 1 && last_oplevel != member->oplevel)
1105           {
1106             /*
1107              * This can't be the first member of a (continued) BURST
1108              * message because then either flag_cnt == 0 or new_mode == 1
1109              * Now we need to append the incremental value of the oplevel.
1110              */
1111             char tbuf[2 + MAXOPLEVELDIGITS];
1112             ircd_snprintf(0, tbuf, sizeof(tbuf), ":%u", member->oplevel - last_oplevel);
1113             last_oplevel = member->oplevel;
1114             msgq_append(&me, mb, tbuf);
1115           }
1116         }
1117         /* Go to the next `member'. */
1118         if (flag_cnt < 2)
1119           member = member->next_member;
1120         else
1121           member = opped_members[++opped_members_index];
1122       }
1123       if (full)
1124         break;
1125
1126       /* Point `member' at the start of the list again. */
1127       if (flag_cnt == 0)
1128       {
1129         member = chptr->members;
1130         /* Now, after one loop, we know the number of ops and can
1131          * allocate the dynamic array with pointer to the ops. */
1132         opped_members = (struct Membership**)
1133           MyMalloc((number_of_ops + 1) * sizeof(struct Membership*));
1134         opped_members[number_of_ops] = NULL;    /* Needed for loop termination */
1135       }
1136       else
1137       {
1138         /* At the end of the second loop, sort the opped members with
1139          * increasing op-level, so that we will output them in the
1140          * correct order (and all op-level increments stay positive) */
1141         if (flag_cnt == 1)
1142           qsort(opped_members, number_of_ops,
1143                 sizeof(struct Membership*), compare_member_oplevel);
1144         /* The third and fourth loop run only over the opped members. */
1145         member = opped_members[(opped_members_index = 0)];
1146       }
1147
1148     } /* loop over 0,+v,+o,+ov */
1149
1150     if (!full)
1151     {
1152       /* Attach all bans, space separated " :%ban ban ..." */
1153       for (first = 2; lp2; lp2 = lp2->next)
1154       {
1155         len = strlen(lp2->banstr);
1156         if (msgq_bufleft(mb) < len + 1 + first)
1157           /* The +1 stands for the added ' '.
1158            * The +first stands for the added ":%".
1159            */
1160         {
1161           full = 1;
1162           break;
1163         }
1164         msgq_append(&me, mb, " %s%s", first ? ":%" : "",
1165                     lp2->banstr);
1166         first = 0;
1167       }
1168     }
1169
1170     send_buffer(cptr, mb, 0);  /* Send this message */
1171     msgq_clean(mb);
1172   }                             /* Continue when there was something
1173                                  that didn't fit (full==1) */
1174   if (opped_members)
1175     MyFree(opped_members);
1176   if (feature_bool(FEAT_TOPIC_BURST) && (chptr->topic[0] != '\0'))
1177       sendcmdto_one(&me, CMD_TOPIC, cptr, "%H %Tu %Tu :%s", chptr,
1178                     chptr->creationtime, chptr->topic_time, chptr->topic);
1179 }
1180
1181 /** Canonify a mask.
1182  * pretty_mask
1183  *
1184  * @author Carlo Wood (Run), 
1185  * 05 Oct 1998.
1186  *
1187  * When the nick is longer then NICKLEN, it is cut off (its an error of course).
1188  * When the user name or host name are too long (USERLEN and HOSTLEN
1189  * respectively) then they are cut off at the start with a '*'.
1190  *
1191  * The following transformations are made:
1192  *
1193  * 1)   xxx             -> nick!*@*
1194  * 2)   xxx.xxx         -> *!*\@host
1195  * 3)   xxx\!yyy         -> nick!user\@*
1196  * 4)   xxx\@yyy         -> *!user\@host
1197  * 5)   xxx!yyy\@zzz     -> nick!user\@host
1198  *
1199  * @param mask  The uncanonified mask.
1200  * @returns The updated mask in a static buffer.
1201  */
1202 char *pretty_mask(char *mask)
1203 {
1204   static char star[2] = { '*', 0 };
1205   static char retmask[NICKLEN + USERLEN + HOSTLEN + 3];
1206   char *last_dot = NULL;
1207   char *ptr;
1208
1209   /* Case 1: default */
1210   char *nick = mask;
1211   char *user = star;
1212   char *host = star;
1213
1214   /* Do a _single_ pass through the characters of the mask: */
1215   for (ptr = mask; *ptr; ++ptr)
1216   {
1217     if (*ptr == '!')
1218     {
1219       /* Case 3 or 5: Found first '!' (without finding a '@' yet) */
1220       user = ++ptr;
1221       host = star;
1222     }
1223     else if (*ptr == '@')
1224     {
1225       /* Case 4: Found last '@' (without finding a '!' yet) */
1226       nick = star;
1227       user = mask;
1228       host = ++ptr;
1229     }
1230     else if (*ptr == '.' || *ptr == ':')
1231     {
1232       /* Case 2: Found character specific to IP or hostname (without
1233        * finding a '!' or '@' yet) */
1234       last_dot = ptr;
1235       continue;
1236     }
1237     else
1238       continue;
1239     for (; *ptr; ++ptr)
1240     {
1241       if (*ptr == '@')
1242       {
1243         /* Case 4 or 5: Found last '@' */
1244         host = ptr + 1;
1245       }
1246     }
1247     break;
1248   }
1249   if (user == star && last_dot)
1250   {
1251     /* Case 2: */
1252     nick = star;
1253     user = star;
1254     host = mask;
1255   }
1256   /* Check lengths */
1257   if (nick != star)
1258   {
1259     char *nick_end = (user != star) ? user - 1 : ptr;
1260     if (nick_end - nick > NICKLEN)
1261       nick[NICKLEN] = 0;
1262     *nick_end = 0;
1263   }
1264   if (user != star)
1265   {
1266     char *user_end = (host != star) ? host - 1 : ptr;
1267     if (user_end - user > USERLEN)
1268     {
1269       user = user_end - USERLEN;
1270       *user = '*';
1271     }
1272     *user_end = 0;
1273   }
1274   if (host != star && ptr - host > HOSTLEN)
1275   {
1276     host = ptr - HOSTLEN;
1277     *host = '*';
1278   }
1279   ircd_snprintf(0, retmask, sizeof(retmask), "%s!%s@%s", nick, user, host);
1280   return retmask;
1281 }
1282
1283 /** send a banlist to a client for a channel
1284  *
1285  * @param cptr  Client to send the banlist to.
1286  * @param chptr Channel whose banlist to send.
1287  */
1288 static void send_ban_list(struct Client* cptr, struct Channel* chptr)
1289 {
1290   struct Ban* lp;
1291
1292   assert(0 != cptr);
1293   assert(0 != chptr);
1294
1295   for (lp = chptr->banlist; lp; lp = lp->next)
1296     send_reply(cptr, RPL_BANLIST, chptr->chname, lp->banstr, lp->who, lp->when);
1297
1298   send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
1299 }
1300
1301 /** Get a channel block, creating if necessary.
1302  *  Get Channel block for chname (and allocate a new channel
1303  *  block, if it didn't exists before).
1304  *
1305  * @param cptr          Client joining the channel.
1306  * @param chname        The name of the channel to join.
1307  * @param flag          set to CGT_CREATE to create the channel if it doesn't 
1308  *                      exist
1309  *
1310  * @returns NULL if the channel is invalid, doesn't exist and CGT_CREATE 
1311  *      wasn't specified or a pointer to the channel structure
1312  */
1313 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
1314 {
1315   struct Channel *chptr;
1316   int len;
1317
1318   if (EmptyString(chname))
1319     return NULL;
1320
1321   len = strlen(chname);
1322   if (MyUser(cptr) && len > CHANNELLEN)
1323   {
1324     len = CHANNELLEN;
1325     *(chname + CHANNELLEN) = '\0';
1326   }
1327   if ((chptr = FindChannel(chname)))
1328     return (chptr);
1329   if (flag == CGT_CREATE)
1330   {
1331     chptr = (struct Channel*) MyMalloc(sizeof(struct Channel) + len);
1332     assert(0 != chptr);
1333     ++UserStats.channels;
1334     memset(chptr, 0, sizeof(struct Channel));
1335     strcpy(chptr->chname, chname);
1336     if (GlobalChannelList)
1337       GlobalChannelList->prev = chptr;
1338     chptr->prev = NULL;
1339     chptr->next = GlobalChannelList;
1340     chptr->creationtime = MyUser(cptr) ? TStime() : (time_t) 0;
1341     GlobalChannelList = chptr;
1342     hAddChannel(chptr);
1343   }
1344   return chptr;
1345 }
1346
1347 /** invite a user to a channel.
1348  *
1349  * Adds an invite for a user to a channel.  Limits the number of invites
1350  * to FEAT_MAXCHANNELSPERUSER.  Does not sent notification to the user.
1351  *
1352  * @param cptr  The client to be invited.
1353  * @param chptr The channel to be invited to.
1354  */
1355 void add_invite(struct Client *cptr, struct Channel *chptr)
1356 {
1357   struct SLink *inv, **tmp;
1358   unsigned int maxchans;
1359
1360   del_invite(cptr, chptr);
1361   /*
1362    * Delete last link in chain if the list is max length
1363    */
1364   assert(list_length((cli_user(cptr))->invited) == (cli_user(cptr))->invites);
1365   maxchans = cli_confs(cptr)->value.aconf ? ConfMaxChannels(cli_confs(cptr)->value.aconf) : feature_int(FEAT_MAXCHANNELSPERUSER);
1366   if (((cli_user(cptr))->invites >= maxchans && !HasPriv(cptr, PRIV_CHAN_LIMIT)) || cli_user(cptr)->invites > 100) /* Hard limit of 100. */
1367     del_invite(cptr, (cli_user(cptr))->invited->value.chptr);
1368   /*
1369    * Add client to channel invite list
1370    */
1371   inv = make_link();
1372   inv->value.cptr = cptr;
1373   inv->next = chptr->invites;
1374   chptr->invites = inv;
1375   /*
1376    * Add channel to the end of the client invite list
1377    */
1378   for (tmp = &((cli_user(cptr))->invited); *tmp; tmp = &((*tmp)->next));
1379   inv = make_link();
1380   inv->value.chptr = chptr;
1381   inv->next = NULL;
1382   (*tmp) = inv;
1383   (cli_user(cptr))->invites++;
1384 }
1385
1386 /** Delete an invite
1387  * Delete Invite block from channel invite list and client invite list
1388  *
1389  * @param cptr  Client pointer
1390  * @param chptr Channel pointer
1391  */
1392 void del_invite(struct Client *cptr, struct Channel *chptr)
1393 {
1394   struct SLink **inv, *tmp;
1395
1396   for (inv = &(chptr->invites); (tmp = *inv); inv = &tmp->next)
1397     if (tmp->value.cptr == cptr)
1398     {
1399       *inv = tmp->next;
1400       free_link(tmp);
1401       tmp = 0;
1402       (cli_user(cptr))->invites--;
1403       break;
1404     }
1405
1406   for (inv = &((cli_user(cptr))->invited); (tmp = *inv); inv = &tmp->next)
1407     if (tmp->value.chptr == chptr)
1408     {
1409       *inv = tmp->next;
1410       free_link(tmp);
1411       tmp = 0;
1412       break;
1413     }
1414 }
1415
1416 /** @page zombie Explanation of Zombies
1417  *
1418  * Synopsis:
1419  *
1420  * A channel member is turned into a zombie when he is kicked from a
1421  * channel but his server has not acknowledged the kick.  Servers that
1422  * see the member as a zombie can accept actions he performed before
1423  * being kicked, without allowing chanop operations from outsiders or
1424  * desyncing the network.
1425  *
1426  * Consider:
1427  * <pre>
1428  *                     client
1429  *                       |
1430  *                       c
1431  *                       |
1432  *     X --a--> A --b--> B --d--> D
1433  *                       |
1434  *                      who
1435  * </pre>
1436  *
1437  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
1438  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
1439  *
1440  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
1441  *    Remove the user immediately when no users are left on the channel.
1442  * b) On server B : remove the user (who/lp) from the channel, send a
1443  *    PART upstream (to A) and pass on the KICK.
1444  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
1445  *    channel, and pass on the KICK.
1446  * d) On server D : remove the user (who/lp) from the channel, and pass on
1447  *    the KICK.
1448  *
1449  * Note:
1450  * - Setting the ZOMBIE flag never hurts, we either remove the
1451  *   client after that or we don't.
1452  * - The KICK message was already passed on, as should be in all cases.
1453  * - `who' is removed in all cases except case a) when users are left.
1454  * - A PART is only sent upstream in case b).
1455  *
1456  * 2 aug 97:
1457  * <pre>
1458  *              6
1459  *              |
1460  *  1 --- 2 --- 3 --- 4 --- 5
1461  *        |           |
1462  *      kicker       who
1463  * </pre>
1464  *
1465  * We also need to turn 'who' into a zombie on servers 1 and 6,
1466  * because a KICK from 'who' (kicking someone else in that direction)
1467  * can arrive there afterward - which should not be bounced itself.
1468  * Therefore case a) also applies for servers 1 and 6.
1469  *
1470  * --Run
1471  */
1472
1473 /** Turn a user on a channel into a zombie
1474  * This function turns a user into a zombie (see \ref zombie)
1475  *
1476  * @param member  The structure representing this user on this channel.
1477  * @param who     The client that is being kicked.
1478  * @param cptr    The connection the kick came from.
1479  * @param sptr    The client that is doing the kicking.
1480  * @param chptr   The channel the user is being kicked from.
1481  */
1482 void make_zombie(struct Membership* member, struct Client* who, 
1483                 struct Client* cptr, struct Client* sptr, struct Channel* chptr)
1484 {
1485   assert(0 != member);
1486   assert(0 != who);
1487   assert(0 != cptr);
1488   assert(0 != chptr);
1489
1490   /* Default for case a): */
1491   SetZombie(member);
1492
1493   /* Case b) or c) ?: */
1494   if (MyUser(who))      /* server 4 */
1495   {
1496     if (IsServer(cptr)) /* Case b) ? */
1497       sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
1498     remove_user_from_channel(who, chptr);
1499     return;
1500   }
1501   if (cli_from(who) == cptr)        /* True on servers 1, 5 and 6 */
1502   {
1503     struct Client *acptr = IsServer(sptr) ? sptr : (cli_user(sptr))->server;
1504     for (; acptr != &me; acptr = (cli_serv(acptr))->up)
1505       if (acptr == (cli_user(who))->server)   /* Case d) (server 5) */
1506       {
1507         remove_user_from_channel(who, chptr);
1508         return;
1509       }
1510   }
1511
1512   /* Case a) (servers 1, 2, 3 and 6) */
1513   if (channel_all_zombies(chptr))
1514     remove_user_from_channel(who, chptr);
1515
1516   /* XXX Can't actually call Debug here; if the channel is all zombies,
1517    * chptr will no longer exist when we get here.
1518   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
1519   */
1520 }
1521
1522 /** returns the number of zombies on a channel
1523  * @param chptr Channel to count zombies in.
1524  *
1525  * @returns The number of zombies on the channel.
1526  */
1527 int number_of_zombies(struct Channel *chptr)
1528 {
1529   struct Membership* member;
1530   int                count = 0;
1531
1532   assert(0 != chptr);
1533   for (member = chptr->members; member; member = member->next_member) {
1534     if (IsZombie(member))
1535       ++count;
1536   }
1537   return count;
1538 }
1539
1540 /** Concatenate some strings together.
1541  * This helper function builds an argument string in strptr, consisting
1542  * of the original string, a space, and str1 and str2 concatenated (if,
1543  * of course, str2 is not NULL)
1544  *
1545  * @param strptr        The buffer to concatenate into
1546  * @param strptr_i      modified offset to the position to modify
1547  * @param str1          The string to concatenate from.
1548  * @param str2          The second string to contatenate from.
1549  * @param c             Charactor to separate the string from str1 and str2.
1550  */
1551 static void
1552 build_string(char *strptr, int *strptr_i, const char *str1,
1553              const char *str2, char c)
1554 {
1555   if (c)
1556     strptr[(*strptr_i)++] = c;
1557
1558   while (*str1)
1559     strptr[(*strptr_i)++] = *(str1++);
1560
1561   if (str2)
1562     while (*str2)
1563       strptr[(*strptr_i)++] = *(str2++);
1564
1565   strptr[(*strptr_i)] = '\0';
1566 }
1567
1568 /** Flush out the modes
1569  * This is the workhorse of our ModeBuf suite; this actually generates the
1570  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
1571  *
1572  * @param mbuf  The mode buffer to flush
1573  * @param all   If true, flush all modes, otherwise leave partial modes in the
1574  *              buffer.
1575  *
1576  * @returns 0
1577  */
1578 static int
1579 modebuf_flush_int(struct ModeBuf *mbuf, int all)
1580 {
1581   /* we only need the flags that don't take args right now */
1582   static ulong64 flags[] = {
1583 /*  MODE_CHANOP,        'o', */
1584 /*  MODE_VOICE,         'v', */
1585     MODE_PRIVATE,       'p',
1586     MODE_SECRET,        's',
1587     MODE_MODERATED,     'm',
1588     MODE_TOPICLIMIT,    't',
1589     MODE_INVITEONLY,    'i',
1590     MODE_NOPRIVMSGS,    'n',
1591     MODE_REGONLY,       'r',
1592     MODE_DELJOINS,      'D',
1593     MODE_REGISTERED,    'R',
1594 /*  MODE_KEY,           'k', */
1595 /*  MODE_BAN,           'b', */
1596     MODE_LIMIT,         'l',
1597 /*  MODE_APASS,         'A', */
1598 /*  MODE_UPASS,         'U', */
1599     MODE_PERSIST,       'z',
1600     MODE_NOCOLOUR,  'c',
1601     MODE_NOCTCP,    'C',
1602 /*  MODE_ALTCHAN,   'F', */
1603 /*  MODE_NOFLOOD,   'f', */
1604     MODE_ACCESS,    'a',
1605     MODE_NOAMSGS,   'M',
1606         MODE_NONOTICE,  'N',
1607         MODE_QUARANTINE,  'Q',
1608         MODE_AUDITORIUM,  'u',
1609     0x0, 0x0
1610   };
1611   static ulong64 local_flags[] = {
1612     MODE_WASDELJOINS,   'd',
1613     0x0, 0x0
1614   };
1615   int i;
1616   ulong64 *flag_p;
1617
1618   struct Client *app_source; /* where the MODE appears to come from */
1619
1620   char addbuf[20], addbuf_local[20]; /* accumulates +psmtin, etc. */
1621   int addbuf_i = 0, addbuf_local_i = 0;
1622   char rembuf[20], rembuf_local[20]; /* accumulates -psmtin, etc. */
1623   int rembuf_i = 0, rembuf_local_i = 0;
1624   char *bufptr; /* we make use of indirection to simplify the code */
1625   int *bufptr_i;
1626
1627   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
1628   int addstr_i;
1629   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
1630   int remstr_i;
1631   char *strptr; /* more indirection to simplify the code */
1632   int *strptr_i;
1633
1634   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
1635   int tmp;
1636
1637   char limitbuf[20],accessbuf[20]; /* convert limits to strings */
1638
1639   ulong64 limitdel = MODE_LIMIT;
1640   ulong64 accessdel = MODE_ACCESS;
1641
1642   assert(0 != mbuf);
1643
1644   /* If the ModeBuf is empty, we have nothing to do */
1645   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
1646     return 0;
1647
1648   /* Ok, if we were given the OPMODE flag, or its a server, hide the source.
1649    */
1650   if (feature_bool(FEAT_HIS_MODEWHO) &&
1651       (mbuf->mb_dest & MODEBUF_DEST_OPMODE ||
1652        IsServer(mbuf->mb_source) ||
1653        IsMe(mbuf->mb_source)))
1654     app_source = &his;
1655   else
1656     app_source = mbuf->mb_source;
1657
1658   /*
1659    * Account for user we're bouncing; we have to get it in on the first
1660    * bounced MODE, or we could have problems
1661    */
1662   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
1663     totalbuflen -= 6; /* numeric nick == 5, plus one space */
1664
1665   /* Calculate the simple flags */
1666   for (flag_p = flags; flag_p[0]; flag_p += 2) {
1667     if (*flag_p & mbuf->mb_add)
1668       addbuf[addbuf_i++] = flag_p[1];
1669     else if (*flag_p & mbuf->mb_rem)
1670       rembuf[rembuf_i++] = flag_p[1];
1671   }
1672
1673   /* Some flags may be for local display only. */
1674   for (flag_p = local_flags; flag_p[0]; flag_p += 2) {
1675     if (*flag_p & mbuf->mb_add)
1676       addbuf_local[addbuf_local_i++] = flag_p[1];
1677     else if (*flag_p & mbuf->mb_rem)
1678       rembuf_local[rembuf_local_i++] = flag_p[1];
1679   }
1680
1681   /* Now go through the modes with arguments... */
1682   for (i = 0; i < mbuf->mb_count; i++) {
1683     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1684       bufptr = addbuf;
1685       bufptr_i = &addbuf_i;
1686     } else {
1687       bufptr = rembuf;
1688       bufptr_i = &rembuf_i;
1689     }
1690
1691     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
1692       tmp = strlen(cli_name(MB_CLIENT(mbuf, i)));
1693
1694       if ((totalbuflen - IRCD_MAX(9, tmp)) <= 0) /* don't overflow buffer */
1695         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1696       else {
1697         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
1698         totalbuflen -= IRCD_MAX(9, tmp) + 1;
1699       }
1700     } else if (MB_TYPE(mbuf, i) & (MODE_BAN | MODE_APASS | MODE_UPASS | MODE_ALTCHAN | MODE_NOFLOOD)) {
1701       tmp = strlen(MB_STRING(mbuf, i));
1702
1703       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1704         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1705       else {
1706         char mode_char;
1707         switch(MB_TYPE(mbuf, i) & (MODE_BAN | MODE_APASS | MODE_UPASS | MODE_ALTCHAN | MODE_NOFLOOD))
1708         {
1709           case MODE_APASS:
1710             mode_char = 'A';
1711             break;
1712           case MODE_UPASS:
1713             mode_char = 'U';
1714             break;
1715       case MODE_ALTCHAN:
1716                 mode_char = 'F';
1717                 break;
1718           case MODE_NOFLOOD:
1719                 mode_char = 'f';
1720                 break;
1721           default:
1722             mode_char = 'b';
1723             break;
1724         }
1725         bufptr[(*bufptr_i)++] = mode_char;
1726         totalbuflen -= tmp + 1;
1727       }
1728     } else if (MB_TYPE(mbuf, i) & MODE_KEY) {
1729       tmp = (mbuf->mb_dest & MODEBUF_DEST_NOKEY ? 1 :
1730              strlen(MB_STRING(mbuf, i)));
1731
1732       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1733         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1734       else {
1735         bufptr[(*bufptr_i)++] = 'k';
1736         totalbuflen -= tmp + 1;
1737       }
1738     } else if (MB_TYPE(mbuf, i) & (MODE_LIMIT)) {
1739       /* if it's a limit, we also format the number */
1740       ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
1741
1742       tmp = strlen(limitbuf);
1743
1744       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1745         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1746       else {
1747         bufptr[(*bufptr_i)++] = 'l';
1748         totalbuflen -= tmp + 1;
1749       }
1750     } else if (MB_TYPE(mbuf, i) & (MODE_ACCESS)) {
1751       /* if it's a limit, we also format the number */
1752       ircd_snprintf(0, accessbuf, sizeof(accessbuf), "%u", MB_UINT(mbuf, i));
1753
1754       tmp = strlen(accessbuf);
1755
1756       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1757         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1758       else {
1759         bufptr[(*bufptr_i)++] = 'a';
1760         totalbuflen -= tmp + 1;
1761       }
1762     }
1763   }
1764
1765   /* terminate the mode strings */
1766   addbuf[addbuf_i] = '\0';
1767   rembuf[rembuf_i] = '\0';
1768   addbuf_local[addbuf_local_i] = '\0';
1769   rembuf_local[rembuf_local_i] = '\0';
1770
1771   /* If we're building a user visible MODE or HACK... */
1772   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
1773                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
1774                        MODEBUF_DEST_LOG)) {
1775     /* Set up the parameter strings */
1776     addstr[0] = '\0';
1777     addstr_i = 0;
1778     remstr[0] = '\0';
1779     remstr_i = 0;
1780
1781     for (i = 0; i < mbuf->mb_count; i++) {
1782       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1783         continue;
1784
1785       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1786         strptr = addstr;
1787         strptr_i = &addstr_i;
1788       } else {
1789         strptr = remstr;
1790         strptr_i = &remstr_i;
1791       }
1792
1793       /* deal with clients... */
1794       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1795         build_string(strptr, strptr_i, cli_name(MB_CLIENT(mbuf, i)), 0, ' ');
1796
1797       /* deal with bans... */
1798       else if (MB_TYPE(mbuf, i) & (MODE_BAN))
1799         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1800
1801       /* deal with keys... */
1802       else if (MB_TYPE(mbuf, i) & MODE_KEY)
1803         build_string(strptr, strptr_i, mbuf->mb_dest & MODEBUF_DEST_NOKEY ?
1804                      "*" : MB_STRING(mbuf, i), 0, ' ');
1805
1806       /* deal with invisible passwords */
1807       else if (MB_TYPE(mbuf, i) & (MODE_APASS | MODE_UPASS))
1808         build_string(strptr, strptr_i, "*", 0, ' ');
1809
1810       /*
1811        * deal with limit; note we cannot include the limit parameter if we're
1812        * removing it
1813        */
1814       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
1815                (MODE_ADD | MODE_LIMIT))
1816         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1817           else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_ACCESS)) ==
1818                (MODE_ADD | MODE_ACCESS))
1819         build_string(strptr, strptr_i, accessbuf, 0, ' ');
1820         
1821           else if (MB_TYPE(mbuf, i) & MODE_ALTCHAN)
1822         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1823           else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_NOFLOOD)) ==
1824                (MODE_ADD | MODE_NOFLOOD))
1825         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1826     }
1827
1828     /* send the messages off to their destination */
1829     if (mbuf->mb_dest & MODEBUF_DEST_HACK2)
1830       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
1831                            "[%Tu]",
1832                            cli_name(feature_bool(FEAT_HIS_SNOTICES) ?
1833                                     mbuf->mb_source : app_source),
1834                            mbuf->mb_channel->chname,
1835                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1836                            addbuf, remstr, addstr,
1837                            mbuf->mb_channel->creationtime);
1838
1839     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
1840       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
1841                            "%s%s%s%s%s%s [%Tu]",
1842                            cli_name(feature_bool(FEAT_HIS_SNOTICES) ? 
1843                                     mbuf->mb_source : app_source),
1844                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
1845                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
1846                            mbuf->mb_channel->creationtime);
1847
1848     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
1849       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
1850                            "[%Tu]",
1851                            cli_name(feature_bool(FEAT_HIS_SNOTICES) ?
1852                                     mbuf->mb_source : app_source),
1853                            mbuf->mb_channel->chname,
1854                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1855                            addbuf, remstr, addstr,
1856                            mbuf->mb_channel->creationtime);
1857
1858     if (mbuf->mb_dest & MODEBUF_DEST_LOG)
1859       log_write(LS_OPERMODE, L_INFO, LOG_NOSNOTICE,
1860                 "%#C OPMODE %H %s%s%s%s%s%s", mbuf->mb_source,
1861                 mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
1862                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1863
1864     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
1865       sendcmdto_channel_butserv_butone(app_source, CMD_MODE, mbuf->mb_channel, NULL, 0,
1866                                        "%H %s%s%s%s%s%s%s%s", mbuf->mb_channel,
1867                                        rembuf_i || rembuf_local_i ? "-" : "",
1868                                        rembuf, rembuf_local,
1869                                        addbuf_i || addbuf_local_i ? "+" : "",
1870                                        addbuf, addbuf_local,
1871                                        remstr, addstr);
1872   }
1873
1874   /* Now are we supposed to propagate to other servers? */
1875   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
1876     /* set up parameter string */
1877     addstr[0] = '\0';
1878     addstr_i = 0;
1879     remstr[0] = '\0';
1880     remstr_i = 0;
1881
1882     /*
1883      * limit is supressed if we're removing it; we have to figure out which
1884      * direction is the direction for it to be removed, though...
1885      */
1886     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) ? MODE_DEL : MODE_ADD;
1887         accessdel |= (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) ? MODE_DEL : MODE_ADD;
1888
1889     for (i = 0; i < mbuf->mb_count; i++) {
1890       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1891         continue;
1892
1893       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1894         strptr = addstr;
1895         strptr_i = &addstr_i;
1896       } else {
1897         strptr = remstr;
1898         strptr_i = &remstr_i;
1899       }
1900
1901       /* if we're changing oplevels and we know the oplevel, pass it on */
1902       if ((MB_TYPE(mbuf, i) & MODE_CHANOP)
1903           && MB_OPLEVEL(mbuf, i) < MAXOPLEVEL)
1904           *strptr_i += ircd_snprintf(0, strptr + *strptr_i, BUFSIZE - *strptr_i,
1905                                      " %s%s:%d",
1906                                      NumNick(MB_CLIENT(mbuf, i)),
1907                                      MB_OPLEVEL(mbuf, i));
1908
1909       /* deal with other modes that take clients */
1910       else if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1911         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
1912
1913       /* deal with modes that take strings */
1914       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN | MODE_APASS | MODE_UPASS | MODE_ALTCHAN | MODE_NOFLOOD))
1915         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1916
1917       /*
1918        * deal with the limit.  Logic here is complicated; if HACK2 is set,
1919        * we're bouncing the mode, so sense is reversed, and we have to
1920        * include the original limit if it looks like it's being removed
1921        */
1922       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
1923         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1924           else if ((MB_TYPE(mbuf, i) & accessdel) == accessdel)
1925         build_string(strptr, strptr_i, accessbuf, 0, ' ');
1926     }
1927
1928     /* we were told to deop the source */
1929     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
1930       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
1931       addbuf[addbuf_i] = '\0'; /* terminate the string... */
1932       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
1933
1934       /* mark that we've done this, so we don't do it again */
1935       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
1936     }
1937
1938     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
1939       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
1940       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
1941                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
1942                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1943                             addbuf, remstr, addstr);
1944     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
1945       /*
1946        * If HACK2 was set, we're bouncing; we send the MODE back to
1947        * the connection we got it from with the senses reversed and
1948        * the proper TS; origin is us
1949        */
1950       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
1951                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
1952                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
1953                     mbuf->mb_channel->creationtime);
1954     } else {
1955       /*
1956        * We're propagating a normal (or HACK3 or HACK4) MODE command
1957        * to the rest of the network.  We send the actual channel TS.
1958        */
1959       sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1960                             "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
1961                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1962                             addbuf, remstr, addstr,
1963                             mbuf->mb_channel->creationtime);
1964     }
1965   }
1966
1967   /* We've drained the ModeBuf... */
1968   mbuf->mb_add = 0;
1969   mbuf->mb_rem = 0;
1970   mbuf->mb_count = 0;
1971
1972   /* reinitialize the mode-with-arg slots */
1973   for (i = 0; i < MAXMODEPARAMS; i++) {
1974     /* If we saved any, pack them down */
1975     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
1976       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
1977       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
1978
1979       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
1980         continue;
1981     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
1982       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
1983
1984     MB_TYPE(mbuf, i) = 0;
1985     MB_UINT(mbuf, i) = 0;
1986   }
1987
1988   /* If we're supposed to flush it all, do so--all hail tail recursion */
1989   if (all && mbuf->mb_count)
1990     return modebuf_flush_int(mbuf, 1);
1991
1992   return 0;
1993 }
1994
1995 /** Initialise a modebuf
1996  * This routine just initializes a ModeBuf structure with the information
1997  * needed and the options given.
1998  *
1999  * @param mbuf          The mode buffer to initialise.
2000  * @param source        The client that is performing the mode.
2001  * @param connect       ?
2002  * @param chan          The channel that the mode is being performed upon.
2003  * @param dest          ?
2004  */
2005 void
2006 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
2007              struct Client *connect, struct Channel *chan, unsigned int dest)
2008 {
2009   int i;
2010
2011   assert(0 != mbuf);
2012   assert(0 != source);
2013   assert(0 != chan);
2014   assert(0 != dest);
2015
2016   if (IsLocalChannel(chan->chname)) dest &= ~MODEBUF_DEST_SERVER;
2017
2018   mbuf->mb_add = 0;
2019   mbuf->mb_rem = 0;
2020   mbuf->mb_source = source;
2021   mbuf->mb_connect = connect;
2022   mbuf->mb_channel = chan;
2023   mbuf->mb_dest = dest;
2024   mbuf->mb_count = 0;
2025
2026   /* clear each mode-with-parameter slot */
2027   for (i = 0; i < MAXMODEPARAMS; i++) {
2028     MB_TYPE(mbuf, i) = 0;
2029     MB_UINT(mbuf, i) = 0;
2030   }
2031 }
2032
2033 /** Append a new mode to a modebuf
2034  * This routine simply adds modes to be added or deleted; do a binary OR
2035  * with either MODE_ADD or MODE_DEL
2036  *
2037  * @param mbuf          Mode buffer
2038  * @param mode          MODE_ADD or MODE_DEL OR'd with MODE_PRIVATE etc.
2039  */
2040 void
2041 modebuf_mode(struct ModeBuf *mbuf, ulong64 mode)
2042 {
2043   assert(0 != mbuf);
2044   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2045
2046   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
2047            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS | MODE_REGONLY |
2048            MODE_DELJOINS | MODE_WASDELJOINS | MODE_REGISTERED | MODE_PERSIST |
2049            MODE_NOCOLOUR | MODE_NOCTCP | MODE_NOAMSGS | MODE_NONOTICE | 
2050                    MODE_QUARANTINE | MODE_AUDITORIUM);
2051
2052   if (!(mode & ~(MODE_ADD | MODE_DEL))) /* don't add empty modes... */
2053     return;
2054
2055   if (mode & MODE_ADD) {
2056     mbuf->mb_rem &= ~mode;
2057     mbuf->mb_add |= mode;
2058   } else {
2059     mbuf->mb_add &= ~mode;
2060     mbuf->mb_rem |= mode;
2061   }
2062 }
2063
2064 /** Append a mode that takes an ulong64 argument to the modebuf
2065  *
2066  * This routine adds a mode to be added or deleted that takes a unsigned
2067  * ulong64 parameter; mode may *only* be the relevant mode flag ORed with one
2068  * of MODE_ADD or MODE_DEL
2069  *
2070  * @param mbuf          The mode buffer to append to.
2071  * @param mode          The mode to append.
2072  * @param uint          The argument to the mode.
2073  */
2074 void
2075 modebuf_mode_uint(struct ModeBuf *mbuf, ulong64 mode, unsigned int uint)
2076 {
2077   assert(0 != mbuf);
2078   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2079
2080   if (mode == (MODE_LIMIT | MODE_DEL)) {
2081       mbuf->mb_rem |= mode;
2082       return;
2083   }
2084   if (mode == (MODE_ACCESS | MODE_DEL)) {
2085       mbuf->mb_rem |= mode;
2086       return;
2087   }
2088   MB_TYPE(mbuf, mbuf->mb_count) = mode;
2089   MB_UINT(mbuf, mbuf->mb_count) = uint;
2090
2091   /* when we've reached the maximal count, flush the buffer */
2092   if (++mbuf->mb_count >=
2093       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
2094     modebuf_flush_int(mbuf, 0);
2095 }
2096
2097 /** append a string mode
2098  * This routine adds a mode to be added or deleted that takes a string
2099  * parameter; mode may *only* be the relevant mode flag ORed with one of
2100  * MODE_ADD or MODE_DEL
2101  *
2102  * @param mbuf          The mode buffer to append to.
2103  * @param mode          The mode to append.
2104  * @param string        The string parameter to append.
2105  * @param free          If the string should be free'd later.
2106  */
2107 void
2108 modebuf_mode_string(struct ModeBuf *mbuf, ulong64 mode, char *string,
2109                     int free)
2110 {
2111   assert(0 != mbuf);
2112   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2113
2114   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
2115   MB_STRING(mbuf, mbuf->mb_count) = string;
2116
2117   /* when we've reached the maximal count, flush the buffer */
2118   if (++mbuf->mb_count >=
2119       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
2120     modebuf_flush_int(mbuf, 0);
2121 }
2122
2123 /** Append a mode on a client to a modebuf.
2124  * This routine adds a mode to be added or deleted that takes a client
2125  * parameter; mode may *only* be the relevant mode flag ORed with one of
2126  * MODE_ADD or MODE_DEL
2127  *
2128  * @param mbuf          The modebuf to append the mode to.
2129  * @param mode          The mode to append.
2130  * @param client        The client argument to append.
2131  * @param oplevel       The oplevel the user had or will have
2132  */
2133 void
2134 modebuf_mode_client(struct ModeBuf *mbuf, ulong64 mode,
2135                     struct Client *client, int oplevel)
2136 {
2137   assert(0 != mbuf);
2138   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2139
2140   MB_TYPE(mbuf, mbuf->mb_count) = mode;
2141   MB_CLIENT(mbuf, mbuf->mb_count) = client;
2142   MB_OPLEVEL(mbuf, mbuf->mb_count) = oplevel;
2143
2144   /* when we've reached the maximal count, flush the buffer */
2145   if (++mbuf->mb_count >=
2146       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
2147     modebuf_flush_int(mbuf, 0);
2148 }
2149
2150 /** Check a channel for join-delayed members.
2151  * @param[in] chan Channel to search.
2152  * @return Non-zero if any members are join-delayed; false if none are.
2153  */
2154 static int
2155 find_delayed_joins(const struct Channel *chan)
2156 {
2157   const struct Membership *memb;
2158   for (memb = chan->members; memb; memb = memb->next_member)
2159     if (IsDelayedJoin(memb) && !IsInvisibleJoin(memb))
2160       return 1;
2161   return 0;
2162 }
2163
2164 /** The exported binding for modebuf_flush()
2165  *
2166  * @param mbuf  The mode buffer to flush.
2167  * 
2168  * @see modebuf_flush_int()
2169  */
2170 int
2171 modebuf_flush(struct ModeBuf *mbuf)
2172 {
2173   /* Check if MODE_WASDELJOINS should be set: */
2174   /* Must be set if going -D and some clients are hidden */
2175   if ((mbuf->mb_rem & MODE_DELJOINS)
2176       && !(mbuf->mb_channel->mode.mode & (MODE_DELJOINS | MODE_WASDELJOINS))
2177       && find_delayed_joins(mbuf->mb_channel)) {
2178     mbuf->mb_channel->mode.mode |= MODE_WASDELJOINS;
2179     mbuf->mb_add |= MODE_WASDELJOINS;
2180     mbuf->mb_rem &= ~MODE_WASDELJOINS;
2181   }
2182   /* Must be cleared if +D is set */
2183   if ((mbuf->mb_add & MODE_DELJOINS)
2184       && ((mbuf->mb_channel->mode.mode & (MODE_WASDELJOINS | MODE_WASDELJOINS))
2185           == (MODE_WASDELJOINS | MODE_WASDELJOINS))) {
2186     mbuf->mb_channel->mode.mode &= ~MODE_WASDELJOINS;
2187     mbuf->mb_add &= ~MODE_WASDELJOINS;
2188     mbuf->mb_rem |= MODE_WASDELJOINS;
2189   }
2190
2191   return modebuf_flush_int(mbuf, 1);
2192 }
2193
2194 /* This extracts the simple modes contained in mbuf
2195  *
2196  * @param mbuf          The mode buffer to extract the modes from.
2197  * @param buf           The string buffer to write the modes into.
2198  */
2199 void
2200 modebuf_extract(struct ModeBuf *mbuf, char *buf)
2201 {
2202   static ulong64 flags[] = {
2203 /*  MODE_CHANOP,        'o', */
2204 /*  MODE_VOICE,         'v', */
2205     MODE_PRIVATE,       'p',
2206     MODE_SECRET,        's',
2207     MODE_MODERATED,     'm',
2208     MODE_TOPICLIMIT,    't',
2209     MODE_INVITEONLY,    'i',
2210     MODE_NOPRIVMSGS,    'n',
2211     MODE_KEY,           'k',
2212     MODE_APASS,         'A',
2213     MODE_UPASS,         'U',
2214     MODE_REGISTERED,    'R',
2215 /*  MODE_BAN,           'b', */
2216     MODE_LIMIT,         'l',
2217     MODE_REGONLY,       'r',
2218     MODE_DELJOINS,      'D',
2219     MODE_PERSIST,       'z',
2220     MODE_NOCOLOUR,  'c',
2221     MODE_NOCTCP,    'C',
2222     MODE_NOAMSGS,   'M',
2223         MODE_NONOTICE,  'N',
2224         MODE_QUARANTINE,  'Q',
2225         MODE_ALTCHAN,    'F',
2226         MODE_ACCESS,    'a',
2227         MODE_AUDITORIUM, 'u',
2228         MODE_NOFLOOD,   'f',
2229     0x0, 0x0
2230   };
2231   ulong64 add;
2232   int i, bufpos = 0, len;
2233   ulong64 *flag_p;
2234   char *key = 0, limitbuf[20], accessbuf[20];
2235   char *apass = 0, *upass = 0, *altchan = 0, *noflood = 0;
2236
2237   assert(0 != mbuf);
2238   assert(0 != buf);
2239
2240   buf[0] = '\0';
2241
2242   add = mbuf->mb_add;
2243
2244   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
2245     if (MB_TYPE(mbuf, i) & MODE_ADD) {
2246       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT | MODE_APASS | MODE_UPASS | MODE_ALTCHAN | MODE_ACCESS | MODE_NOFLOOD);
2247
2248       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
2249         key = MB_STRING(mbuf, i);
2250       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
2251         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
2252           else if (MB_TYPE(mbuf, i) & MODE_ACCESS)
2253         ircd_snprintf(0, accessbuf, sizeof(accessbuf), "%u", MB_UINT(mbuf, i));
2254       else if (MB_TYPE(mbuf, i) & MODE_UPASS)
2255         upass = MB_STRING(mbuf, i);
2256       else if (MB_TYPE(mbuf, i) & MODE_APASS)
2257         apass = MB_STRING(mbuf, i);
2258       else if (MB_TYPE(mbuf, i) & MODE_ALTCHAN)
2259         altchan = MB_STRING(mbuf, i);
2260           else if (MB_TYPE(mbuf, i) & MODE_NOFLOOD)
2261         noflood = MB_STRING(mbuf, i);
2262     }
2263   }
2264
2265   if (!add)
2266     return;
2267
2268   buf[bufpos++] = '+'; /* start building buffer */
2269
2270   for (flag_p = flags; flag_p[0]; flag_p += 2)
2271     if (*flag_p & add)
2272       buf[bufpos++] = flag_p[1];
2273
2274   for (i = 0, len = bufpos; i < len; i++) {
2275     if (buf[i] == 'k')
2276       build_string(buf, &bufpos, key, 0, ' ');
2277     else if (buf[i] == 'l')
2278       build_string(buf, &bufpos, limitbuf, 0, ' ');
2279     else if (buf[i] == 'a')
2280       build_string(buf, &bufpos, accessbuf, 0, ' ');
2281     else if (buf[i] == 'U')
2282       build_string(buf, &bufpos, upass, 0, ' ');
2283     else if (buf[i] == 'A')
2284       build_string(buf, &bufpos, apass, 0, ' ');
2285         else if (buf[i] == 'F')
2286       build_string(buf, &bufpos, altchan, 0, ' ');
2287         else if (buf[i] == 'f')
2288       build_string(buf, &bufpos, noflood, 0, ' ');
2289   }
2290
2291   buf[bufpos] = '\0';
2292
2293   return;
2294 }
2295
2296 /** Simple function to invalidate a channel's ban cache.
2297  *
2298  * This function marks all members of the channel as being neither
2299  * banned nor banned.
2300  *
2301  * @param chan  The channel to operate on.
2302  */
2303 void
2304 mode_ban_invalidate(struct Channel *chan)
2305 {
2306   struct Membership *member;
2307
2308   for (member = chan->members; member; member = member->next_member)
2309     ClearBanValid(member);
2310 }
2311
2312 /** Simple function to drop invite structures
2313  *
2314  * Remove all the invites on the channel.
2315  *
2316  * @param chan          Channel to remove invites from.
2317  *
2318  */
2319 void
2320 mode_invite_clear(struct Channel *chan)
2321 {
2322   while (chan->invites)
2323     del_invite(chan->invites->value.cptr, chan);
2324 }
2325
2326 /* What we've done for mode_parse so far... */
2327 #define DONE_LIMIT      0x01    /**< We've set the limit */
2328 #define DONE_KEY_ADD    0x02    /**< We've set the key */
2329 #define DONE_BANLIST    0x04    /**< We've sent the ban list */
2330 #define DONE_NOTOPER    0x08    /**< We've sent a "Not oper" error */
2331 #define DONE_BANCLEAN   0x10    /**< We've cleaned bans... */
2332 #define DONE_UPASS_ADD  0x20    /**< We've set user pass */
2333 #define DONE_APASS_ADD  0x40    /**< We've set admin pass */
2334 #define DONE_KEY_DEL    0x80    /**< We've removed the key */
2335 #define DONE_UPASS_DEL  0x100   /**< We've removed the user pass */
2336 #define DONE_APASS_DEL  0x200   /**< We've removed the admin pass */
2337 #define DONE_ALTCHAN    0x800   /**< We've set the altchan */
2338 #define DONE_ACCESS     0x1000  /**< We've set the access */
2339 #define DONE_NOFLOOD    0x2000  /**< We've set the noflood options */
2340
2341 struct ParseState {
2342   struct ModeBuf *mbuf;
2343   struct Client *cptr;
2344   struct Client *sptr;
2345   struct Channel *chptr;
2346   struct Membership *member;
2347   int parc;
2348   char **parv;
2349   ulong64 flags;
2350   ulong64 dir;
2351   ulong64 done;
2352   ulong64 add;
2353   ulong64 del;
2354   int args_used;
2355   int max_args;
2356   int numbans;
2357   struct Ban banlist[MAXPARA];
2358   struct {
2359     ulong64 flag;
2360     unsigned short oplevel;
2361     struct Client *client;
2362   } cli_change[MAXPARA];
2363 };
2364
2365 /** Helper function to send "Not oper" or "Not member" messages
2366  * Here's a helper function to deal with sending along "Not oper" or
2367  * "Not member" messages
2368  *
2369  * @param state         Parsing State object
2370  */
2371 static void
2372 send_notoper(struct ParseState *state)
2373 {
2374   if (state->done & DONE_NOTOPER)
2375     return;
2376
2377   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
2378              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
2379
2380   state->done |= DONE_NOTOPER;
2381 }
2382
2383 /** Parse a limit
2384  * Helper function to convert limits
2385  *
2386  * @param state         Parsing state object.
2387  * @param flag_p        ?
2388  */
2389 static void
2390 mode_parse_limit(struct ParseState *state, ulong64 *flag_p)
2391 {
2392   unsigned int t_limit;
2393
2394   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
2395     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
2396       return;
2397
2398     if (state->parc <= 0) { /* warn if not enough args */
2399       if (MyUser(state->sptr))
2400         need_more_params(state->sptr, "MODE +l");
2401       return;
2402     }
2403
2404     t_limit = strtoul(state->parv[state->args_used++], 0, 10); /* grab arg */
2405     state->parc--;
2406     state->max_args--;
2407
2408     if ((int)t_limit<0) /* don't permit a negative limit */
2409       return;
2410
2411     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
2412         (!t_limit || t_limit == state->chptr->mode.limit))
2413       return;
2414   } else
2415     t_limit = state->chptr->mode.limit;
2416
2417   /* If they're not an oper, they can't change modes */
2418   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2419     send_notoper(state);
2420     return;
2421   }
2422
2423   /* Can't remove a limit that's not there */
2424   if (state->dir == MODE_DEL && !state->chptr->mode.limit)
2425     return;
2426     
2427   /* Skip if this is a burst and a lower limit than this is set already */
2428   if ((state->flags & MODE_PARSE_BURST) &&
2429       (state->chptr->mode.mode & flag_p[0]) &&
2430       (state->chptr->mode.limit < t_limit))
2431     return;
2432
2433   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
2434     return;
2435   state->done |= DONE_LIMIT;
2436
2437   if (!state->mbuf)
2438     return;
2439
2440   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
2441
2442   if (state->flags & MODE_PARSE_SET) { /* set the limit */
2443     if (state->dir & MODE_ADD) {
2444       state->chptr->mode.mode |= flag_p[0];
2445       state->chptr->mode.limit = t_limit;
2446     } else {
2447       state->chptr->mode.mode &= ~flag_p[0];
2448       state->chptr->mode.limit = 0;
2449     }
2450   }
2451 }
2452
2453
2454 static void
2455 mode_parse_access(struct ParseState *state, ulong64 *flag_p)
2456 {
2457   unsigned int t_access;
2458
2459   if (state->dir == MODE_ADD) { /* convert arg only if adding access */
2460     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
2461       return;
2462
2463     if (state->parc <= 0) { /* warn if not enough args */
2464       if (MyUser(state->sptr))
2465         need_more_params(state->sptr, "MODE +a");
2466       return;
2467     }
2468
2469     t_access = strtoul(state->parv[state->args_used++], 0, 10); /* grab arg */
2470     state->parc--;
2471     state->max_args--;
2472
2473     if ((int)t_access<1 || (int)t_access>500) /* don't permit a negative access or an access over 500 */
2474       return;
2475     
2476     if (!feature_bool(FEAT_CHMODE_A_ENABLE)) { /* don't parse MODE_ACCESS if it's disabled */
2477         if (MyUser(state->sptr)) {
2478             char mode[1] = "a";
2479             send_reply(state->sptr, ERR_UNKNOWNMODE, mode[0]);
2480         }
2481         return;
2482     }
2483     
2484     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
2485         (!t_access || t_access == state->chptr->mode.access))
2486       return;
2487   } else
2488     t_access = state->chptr->mode.access;
2489
2490   /* If they're not an oper, they can't change modes */
2491   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2492     send_notoper(state);
2493     return;
2494   }
2495
2496   /* Can't remove an access that's not there */
2497   if (state->dir == MODE_DEL && !state->chptr->mode.access)
2498     return;
2499     
2500   /* Skip if this is a burst and a higher access than this is set already */
2501   if ((state->flags & MODE_PARSE_BURST) &&
2502       (state->chptr->mode.mode & flag_p[0]) &&
2503       (state->chptr->mode.access > t_access))
2504     return;
2505
2506   if (state->done & DONE_ACCESS) /* allow access to be set only once */
2507     return;
2508   state->done |= DONE_ACCESS;
2509
2510   if (!state->mbuf)
2511     return;
2512
2513   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_access);
2514
2515   if (state->flags & MODE_PARSE_SET) { /* set the access */
2516     if (state->dir & MODE_ADD) {
2517       state->chptr->mode.mode |= flag_p[0];
2518       state->chptr->mode.access = t_access;
2519     } else {
2520       state->chptr->mode.mode &= ~flag_p[0];
2521       state->chptr->mode.access = 0;
2522     }
2523   }
2524 }
2525
2526
2527 static void
2528 mode_parse_altchan(struct ParseState *state, ulong64 *flag_p)
2529 {
2530   char *t_str;
2531
2532   if (state->dir == MODE_ADD) { /* convert arg only if adding altchan */
2533     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
2534       return;
2535     
2536     if (!feature_bool(FEAT_CHMODE_F_ENABLE))
2537         return;
2538     
2539     if (state->parc <= 0) { /* warn if not enough args */
2540       if (MyUser(state->sptr))
2541         need_more_params(state->sptr, "MODE +F");
2542       return;
2543     }
2544
2545     t_str = state->parv[state->args_used++]; /* grab arg */
2546     state->parc--;
2547     state->max_args--;
2548
2549     if (!IsChannelName(t_str) || !strIsIrcCh(t_str) || strlen(t_str) > IRCD_MIN(CHANNELLEN, feature_int(FEAT_CHANNELLEN)) || t_str[0] == '&') /* only parse it if it's a valid channel name! */
2550       return;
2551     
2552     if(!(state->flags & MODE_PARSE_FORCE)) {
2553       struct Channel *chptr;
2554       struct Membership *member;
2555       if (!(chptr = FindChannel(t_str)))
2556         return;
2557       if(!(member = find_member_link(chptr, state->sptr)))
2558         return;
2559       if(!IsChanOp(member)) {
2560         send_notoper(state);
2561         return;
2562       }
2563     }
2564     
2565     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
2566         (!t_str || t_str == state->chptr->mode.altchan))
2567       return;
2568   } else
2569     t_str = state->chptr->mode.altchan;
2570
2571   /* If they're not an oper, they can't change modes */
2572   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2573     send_notoper(state);
2574     return;
2575   }
2576
2577   /* Can't remove a altchan that's not there */
2578   if (state->dir == MODE_DEL && !*state->chptr->mode.altchan)
2579     return;
2580     
2581   /* Skip if this is a burst and a lower altchan than this is set already */
2582   if ((state->flags & MODE_PARSE_BURST) &&
2583       *(state->chptr->mode.altchan))
2584     return;
2585
2586   if (state->done & DONE_ALTCHAN) /* allow altchan to be set only once */
2587     return;
2588   state->done |= DONE_ALTCHAN;
2589
2590   if (!state->mbuf)
2591     return;
2592
2593   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2594       !ircd_strcmp(state->chptr->mode.altchan, t_str))
2595     return; /* no change */
2596
2597   if (state->flags & MODE_PARSE_BOUNCE) {
2598     if (*state->chptr->mode.altchan) /* reset old altchan */
2599       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0], state->chptr->mode.altchan, 0);
2600     else /* remove new bogus altchan */
2601       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2602   } else /* send new altchan */
2603     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2604
2605   if (state->flags & MODE_PARSE_SET) {
2606     if (state->dir == MODE_DEL) { /* remove the old altchan */
2607       *state->chptr->mode.altchan = '\0';
2608       state->chptr->mode.mode &= ~flag_p[0];
2609     } else {
2610       ircd_strncpy(state->chptr->mode.altchan, t_str, CHANNELLEN);
2611       state->chptr->mode.mode |= flag_p[0];
2612     }
2613   }
2614 }
2615
2616 static void
2617 mode_parse_noflood(struct ParseState *state, ulong64 *flag_p)
2618 {
2619   char *t_str;
2620   char *tmp;
2621   unsigned int count = 0, time = 0, flags = 0;
2622
2623   if (state->dir == MODE_ADD) { /* convert arg only if adding noflood */
2624     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
2625       return;
2626     
2627     if (state->parc <= 0) { /* warn if not enough args */
2628       if (MyUser(state->sptr))
2629         need_more_params(state->sptr, "MODE +f");
2630       return;
2631     }
2632
2633     t_str = state->parv[state->args_used++]; /* grab arg */
2634     state->parc--;
2635     state->max_args--;
2636
2637     tmp = t_str;
2638     
2639     if(tmp[0] == '!') {
2640         if(state->flags & MODE_PARSE_FORCE) flags |= FLFL_NOFLOOD;
2641         else t_str++; //simply ignore if it's not an opmode
2642         tmp++;
2643     }
2644     if(tmp[0] == '+' || tmp[0] == '@') {
2645         if(tmp[0] == '+') flags |= FLFL_VOICE;
2646         if(tmp[0] == '@') flags |= FLFL_CHANOP;
2647         tmp++;
2648     }
2649     char *p;
2650     for(p = tmp; p[0]; p++) {
2651       if(p[0] == ':') {
2652         char tmpchar = p[0];
2653         p[0] = '\0';
2654         count = strtoul(tmp,0,10);
2655         p[0] = tmpchar;
2656         p++;
2657         time = strtoul(p,0,10);
2658         break;
2659       }
2660     }
2661     if(count <= 0 || time <= 0 || count > 100 || time > 600) return;
2662     
2663     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
2664         (!t_str || t_str == state->chptr->mode.noflood))
2665       return;
2666   } else
2667     t_str = state->chptr->mode.noflood;
2668
2669   /* If they're not an oper, they can't change modes */
2670   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2671     send_notoper(state);
2672     return;
2673   }
2674
2675   /* Can't remove a noflood that's not there */
2676   if (state->dir == MODE_DEL && !*state->chptr->mode.noflood)
2677     return;
2678     
2679   /* Skip if this is a burst and a lower noflood than this is set already */
2680   if ((state->flags & MODE_PARSE_BURST) &&
2681       *(state->chptr->mode.noflood))
2682     return;
2683
2684   if (state->done & DONE_NOFLOOD) /* allow noflood to be set only once */
2685     return;
2686   state->done |= DONE_NOFLOOD;
2687
2688   if (!state->mbuf)
2689     return;
2690
2691   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2692       !ircd_strcmp(state->chptr->mode.noflood, t_str))
2693     return; /* no change */
2694
2695   if (state->flags & MODE_PARSE_BOUNCE) {
2696     if (*state->chptr->mode.noflood) /* reset old noflood */
2697       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0], state->chptr->mode.noflood, 0);
2698     else /* remove new bogus noflood */
2699       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2700   } else /* send new noflood */
2701     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2702
2703   if (state->flags & MODE_PARSE_SET) {
2704     if (state->dir == MODE_DEL) { /* remove the old noflood */
2705       *state->chptr->mode.noflood = '\0';
2706       state->chptr->mode.mode &= ~flag_p[0];
2707     } else {
2708       ircd_strncpy(state->chptr->mode.noflood, t_str, CHANNELLEN);
2709       state->chptr->mode.mode |= flag_p[0];
2710     }
2711   }
2712   
2713   if (state->dir == MODE_ADD) {
2714     unsigned int noflood_value = time;
2715     noflood_value <<= 10;
2716     noflood_value |= count;
2717     noflood_value <<= 3;
2718     noflood_value |= flags;
2719     state->chptr->mode.noflood_value = noflood_value;
2720   } else {
2721     //removed the mode so free all flood objects
2722     state->chptr->mode.noflood_value = 0;
2723     struct Membership *member;
2724     for(member = state->chptr->members; member; member = member->next_member) {
2725         struct MemberFlood *floodnode;
2726         for(floodnode = member->flood;floodnode ; floodnode = floodnode->next_memberflood) {
2727           if(floodnode->next_memberflood == NULL) break;
2728         } //simply walk to the end
2729         if(!floodnode) continue;
2730         floodnode->next_memberflood = free_MemberFlood;
2731         free_MemberFlood  = floodnode;
2732         member->flood = NULL;
2733     }
2734   }
2735 }
2736
2737 static void
2738 mode_parse_quarantine(struct ParseState *state, ulong64 *flag_p)
2739 {
2740     
2741 }
2742
2743 /** Helper function to validate key-like parameters.
2744  *
2745  * @param[in] state Parse state for feedback to user.
2746  * @param[in] s Key to validate.
2747  * @param[in] command String to pass for need_more_params() command.
2748  * @return Zero on an invalid key, non-zero if the key was okay.
2749  */
2750 static int
2751 is_clean_key(struct ParseState *state, char *s, char *command)
2752 {
2753   int ii;
2754
2755   if (s[0] == '\0') {
2756     if (MyUser(state->sptr))
2757       need_more_params(state->sptr, command);
2758     return 0;
2759   }
2760   else if (s[0] == ':') {
2761     if (MyUser(state->sptr))
2762       send_reply(state->sptr, ERR_INVALIDKEY, state->chptr->chname);
2763     return 0;
2764   }
2765   for (ii = 0; (ii <= KEYLEN) && (s[ii] != '\0'); ++ii) {
2766     if ((unsigned char)s[ii] <= ' ' || s[ii] == ',') {
2767       if (MyUser(state->sptr))
2768         send_reply(state->sptr, ERR_INVALIDKEY, state->chptr->chname);
2769       return 0;
2770     }
2771   }
2772   if (ii > KEYLEN) {
2773     if (MyUser(state->sptr))
2774       send_reply(state->sptr, ERR_INVALIDKEY, state->chptr->chname);
2775     return 0;
2776   }
2777   return 1;
2778 }
2779
2780 /*
2781  * Helper function to convert keys
2782  */
2783 static void
2784 mode_parse_key(struct ParseState *state, ulong64 *flag_p)
2785 {
2786   char *t_str;
2787
2788   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2789     return;
2790
2791   if (state->parc <= 0) { /* warn if not enough args */
2792     if (MyUser(state->sptr))
2793       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2794                        "MODE -k");
2795     return;
2796   }
2797
2798   t_str = state->parv[state->args_used++]; /* grab arg */
2799   state->parc--;
2800   state->max_args--;
2801
2802   /* If they're not an oper, they can't change modes */
2803   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2804     send_notoper(state);
2805     return;
2806   }
2807
2808   /* allow removing and then adding key, but not adding and then removing */
2809   if (state->dir == MODE_ADD)
2810   {
2811     if (state->done & DONE_KEY_ADD)
2812       return;
2813     state->done |= DONE_KEY_ADD;
2814   }
2815   else
2816   {
2817     if (state->done & (DONE_KEY_ADD | DONE_KEY_DEL))
2818       return;
2819     state->done |= DONE_KEY_DEL;
2820   }
2821
2822   /* If the key is invalid, tell the user and bail. */
2823   if (!is_clean_key(state, t_str, state->dir == MODE_ADD ? "MODE +k" :
2824                     "MODE -k"))
2825     return;
2826
2827   if (!state->mbuf)
2828     return;
2829
2830   /* Skip if this is a burst, we have a key already and the new key is 
2831    * after the old one alphabetically */
2832   if ((state->flags & MODE_PARSE_BURST) &&
2833       *(state->chptr->mode.key) &&
2834       ircd_strcmp(state->chptr->mode.key, t_str) <= 0)
2835     return;
2836
2837   /* can't add a key if one is set, nor can one remove the wrong key */
2838   if (!(state->flags & MODE_PARSE_FORCE))
2839     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
2840         (state->dir == MODE_DEL &&
2841          ircd_strcmp(state->chptr->mode.key, t_str))) {
2842       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2843       return;
2844     }
2845
2846   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2847       !ircd_strcmp(state->chptr->mode.key, t_str))
2848     return; /* no key change */
2849
2850   if (state->flags & MODE_PARSE_BOUNCE) {
2851     if (*state->chptr->mode.key) /* reset old key */
2852       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2853                           state->chptr->mode.key, 0);
2854     else /* remove new bogus key */
2855       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2856   } else /* send new key */
2857     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2858
2859   if (state->flags & MODE_PARSE_SET) {
2860     if (state->dir == MODE_DEL) /* remove the old key */
2861       *state->chptr->mode.key = '\0';
2862     else
2863       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
2864   }
2865 }
2866
2867 /*
2868  * Helper function to convert user passes
2869  */
2870 static void
2871 mode_parse_upass(struct ParseState *state, ulong64 *flag_p)
2872 {
2873   char *t_str;
2874
2875   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2876     return;
2877
2878   if (state->parc <= 0) { /* warn if not enough args */
2879     if (MyUser(state->sptr))
2880       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
2881                        "MODE -U");
2882     return;
2883   }
2884
2885   t_str = state->parv[state->args_used++]; /* grab arg */
2886   state->parc--;
2887   state->max_args--;
2888
2889   /* If they're not an oper, they can't change modes */
2890   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2891     send_notoper(state);
2892     return;
2893   }
2894
2895   /* If a non-service user is trying to force it, refuse. */
2896   if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
2897       && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
2898     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2899                state->chptr->chname);
2900     return;
2901   }
2902
2903   /* If they are not the channel manager, they are not allowed to change it */
2904   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
2905     if (*state->chptr->mode.apass) {
2906       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2907                  state->chptr->chname);
2908     } else {
2909       send_reply(state->sptr, ERR_NOMANAGER, state->chptr->chname,
2910           (TStime() - state->chptr->creationtime < 172800) ?
2911           "approximately 4-5 minutes" : "approximately 48 hours");
2912     }
2913     return;
2914   }
2915
2916   /* allow removing and then adding upass, but not adding and then removing */
2917   if (state->dir == MODE_ADD)
2918   {
2919     if (state->done & DONE_UPASS_ADD)
2920       return;
2921     state->done |= DONE_UPASS_ADD;
2922   }
2923   else
2924   {
2925     if (state->done & (DONE_UPASS_ADD | DONE_UPASS_DEL))
2926       return;
2927     state->done |= DONE_UPASS_DEL;
2928   }
2929
2930   /* If the Upass is invalid, tell the user and bail. */
2931   if (!is_clean_key(state, t_str, state->dir == MODE_ADD ? "MODE +U" :
2932                     "MODE -U"))
2933     return;
2934
2935   if (!state->mbuf)
2936     return;
2937
2938   if (!(state->flags & MODE_PARSE_FORCE)) {
2939     /* can't add the upass while apass is not set */
2940     if (state->dir == MODE_ADD && !*state->chptr->mode.apass) {
2941       send_reply(state->sptr, ERR_UPASSNOTSET, state->chptr->chname, state->chptr->chname);
2942       return;
2943     }
2944     /* cannot set a +U password that is the same as +A */
2945     if (state->dir == MODE_ADD && !ircd_strcmp(state->chptr->mode.apass, t_str)) {
2946       send_reply(state->sptr, ERR_UPASS_SAME_APASS, state->chptr->chname);
2947       return;
2948     }
2949     /* can't add a upass if one is set, nor can one remove the wrong upass */
2950     if ((state->dir == MODE_ADD && *state->chptr->mode.upass) ||
2951         (state->dir == MODE_DEL &&
2952          ircd_strcmp(state->chptr->mode.upass, t_str))) {
2953       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2954       return;
2955     }
2956   }
2957
2958   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2959       !ircd_strcmp(state->chptr->mode.upass, t_str))
2960     return; /* no upass change */
2961
2962   /* Skip if this is a burst, we have a Upass already and the new Upass is
2963    * after the old one alphabetically */
2964   if ((state->flags & MODE_PARSE_BURST) &&
2965       *(state->chptr->mode.upass) &&
2966       ircd_strcmp(state->chptr->mode.upass, t_str) <= 0)
2967     return;
2968
2969   if (state->flags & MODE_PARSE_BOUNCE) {
2970     if (*state->chptr->mode.upass) /* reset old upass */
2971       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2972                           state->chptr->mode.upass, 0);
2973     else /* remove new bogus upass */
2974       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2975   } else /* send new upass */
2976     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2977
2978   if (state->flags & MODE_PARSE_SET) {
2979     if (state->dir == MODE_DEL) /* remove the old upass */
2980       *state->chptr->mode.upass = '\0';
2981     else
2982       ircd_strncpy(state->chptr->mode.upass, t_str, KEYLEN);
2983   }
2984 }
2985
2986 /*
2987  * Helper function to convert admin passes
2988  */
2989 static void
2990 mode_parse_apass(struct ParseState *state, ulong64 *flag_p)
2991 {
2992   struct Membership *memb;
2993   char *t_str;
2994
2995   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2996     return;
2997
2998   if (state->parc <= 0) { /* warn if not enough args */
2999     if (MyUser(state->sptr))
3000       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
3001                        "MODE -A");
3002     return;
3003   }
3004
3005   t_str = state->parv[state->args_used++]; /* grab arg */
3006   state->parc--;
3007   state->max_args--;
3008
3009   /* If they're not an oper, they can't change modes */
3010   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3011     send_notoper(state);
3012     return;
3013   }
3014
3015   if (MyUser(state->sptr)) {
3016     if (state->flags & MODE_PARSE_FORCE) {
3017       /* If an unprivileged oper is trying to force it, refuse. */
3018       if (!HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
3019         send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
3020                    state->chptr->chname);
3021         return;
3022       }
3023     } else {
3024       /* If they are not the channel manager, they are not allowed to change it. */
3025       if (!IsChannelManager(state->member)) {
3026         if (*state->chptr->mode.apass) {
3027           send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
3028                      state->chptr->chname);
3029         } else {
3030           send_reply(state->sptr, ERR_NOMANAGER, state->chptr->chname,
3031                      (TStime() - state->chptr->creationtime < 172800) ?
3032                      "approximately 4-5 minutes" : "approximately 48 hours");
3033         }
3034         return;
3035       }
3036       /* Can't remove the Apass while Upass is still set. */
3037       if (state->dir == MODE_DEL && *state->chptr->mode.upass) {
3038         send_reply(state->sptr, ERR_UPASSSET, state->chptr->chname, state->chptr->chname);
3039         return;
3040       }
3041       /* Can't add an Apass if one is set, nor can one remove the wrong Apass. */
3042       if ((state->dir == MODE_ADD && *state->chptr->mode.apass) ||
3043           (state->dir == MODE_DEL && ircd_strcmp(state->chptr->mode.apass, t_str))) {
3044         send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
3045         return;
3046       }
3047     }
3048
3049     /* Forbid removing the Apass if the channel is older than 48 hours
3050      * unless an oper is doing it. */
3051     if (TStime() - state->chptr->creationtime >= 172800
3052         && state->dir == MODE_DEL
3053         && !IsAnOper(state->sptr)) {
3054       send_reply(state->sptr, ERR_CHANSECURED, state->chptr->chname);
3055       return;
3056     }
3057   }
3058
3059   /* allow removing and then adding apass, but not adding and then removing */
3060   if (state->dir == MODE_ADD)
3061   {
3062     if (state->done & DONE_APASS_ADD)
3063       return;
3064     state->done |= DONE_APASS_ADD;
3065   }
3066   else
3067   {
3068     if (state->done & (DONE_APASS_ADD | DONE_APASS_DEL))
3069       return;
3070     state->done |= DONE_APASS_DEL;
3071   }
3072
3073   /* If the Apass is invalid, tell the user and bail. */
3074   if (!is_clean_key(state, t_str, state->dir == MODE_ADD ? "MODE +A" :
3075                     "MODE -A"))
3076     return;
3077
3078   if (!state->mbuf)
3079     return;
3080
3081   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
3082       !ircd_strcmp(state->chptr->mode.apass, t_str))
3083     return; /* no apass change */
3084
3085   /* Skip if this is a burst, we have an Apass already and the new Apass is
3086    * after the old one alphabetically */
3087   if ((state->flags & MODE_PARSE_BURST) &&
3088       *(state->chptr->mode.apass) &&
3089       ircd_strcmp(state->chptr->mode.apass, t_str) <= 0)
3090     return;
3091
3092   if (state->flags & MODE_PARSE_BOUNCE) {
3093     if (*state->chptr->mode.apass) /* reset old apass */
3094       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
3095                           state->chptr->mode.apass, 0);
3096     else /* remove new bogus apass */
3097       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
3098   } else /* send new apass */
3099     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
3100
3101   if (state->flags & MODE_PARSE_SET) {
3102     if (state->dir == MODE_ADD) { /* set the new apass */
3103       /* Only accept the new apass if there is no current apass or
3104        * this is a BURST. */
3105       if (state->chptr->mode.apass[0] == '\0' ||
3106           (state->flags & MODE_PARSE_BURST))
3107         ircd_strncpy(state->chptr->mode.apass, t_str, KEYLEN);
3108       /* Make it VERY clear to the user that this is a one-time password */
3109       if (MyUser(state->sptr)) {
3110         send_reply(state->sptr, RPL_APASSWARN_SET, state->chptr->mode.apass);
3111         send_reply(state->sptr, RPL_APASSWARN_SECRET, state->chptr->chname,
3112                    state->chptr->mode.apass);
3113       }
3114       /* Give the channel manager level 0 ops.
3115          There should not be tested for IsChannelManager here because
3116          on the local server it is impossible to set the apass if one
3117          isn't a channel manager and remote servers might need to sync
3118          the oplevel here: when someone creates a channel (and becomes
3119          channel manager) during a net.break, and only sets the Apass
3120          after the net rejoined, they will have oplevel MAXOPLEVEL on
3121          all remote servers. */
3122       if (state->member)
3123         SetOpLevel(state->member, 0);
3124     } else { /* remove the old apass */
3125       *state->chptr->mode.apass = '\0';
3126       /* Clear Upass so that there is never a Upass set when a zannel is burst. */
3127       *state->chptr->mode.upass = '\0';
3128       if (MyUser(state->sptr))
3129         send_reply(state->sptr, RPL_APASSWARN_CLEAR);
3130       /* Revert everyone to MAXOPLEVEL. */
3131       for (memb = state->chptr->members; memb; memb = memb->next_member) {
3132         if (memb->status & MODE_CHANOP)
3133           SetOpLevel(memb, MAXOPLEVEL);
3134       }
3135     }
3136   }
3137 }
3138
3139 /** Compare one ban's extent to another.
3140  * This works very similarly to mmatch() but it knows about CIDR masks
3141  * and ban exceptions.  If both bans are CIDR-based, compare their
3142  * address bits; otherwise, use mmatch().
3143  * @param[in] old_ban One ban.
3144  * @param[in] new_ban Another ban.
3145  * @return Zero if \a old_ban is a superset of \a new_ban, non-zero otherwise.
3146  */
3147 static int
3148 bmatch(struct Ban *old_ban, struct Ban *new_ban)
3149 {
3150   int res;
3151   assert(old_ban != NULL);
3152   assert(new_ban != NULL);
3153   /* A ban is never treated as a superset of an exception and vice versa. */
3154   if(((old_ban->flags & BAN_EXCEPTION) && !(new_ban->flags & BAN_EXCEPTION))
3155      || (!(old_ban->flags & BAN_EXCEPTION) && (new_ban->flags & BAN_EXCEPTION)))
3156     return 1;
3157   /* If either is not an address mask, match the text masks. */
3158   if ((old_ban->flags & new_ban->flags & BAN_IPMASK) == 0)
3159     return mmatch(old_ban->banstr, new_ban->banstr);
3160   /* If the old ban has a longer prefix than new, it cannot be a superset. */
3161   if (old_ban->addrbits > new_ban->addrbits)
3162     return 1;
3163   /* Compare the masks before the hostname part.  */
3164   old_ban->banstr[old_ban->nu_len] = new_ban->banstr[new_ban->nu_len] = '\0';
3165   res = mmatch(old_ban->banstr, new_ban->banstr);
3166   old_ban->banstr[old_ban->nu_len] = new_ban->banstr[new_ban->nu_len] = '@';
3167   if (res)
3168     return res;
3169   /* If the old ban's mask mismatches, cannot be a superset. */
3170   if (!ipmask_check(&new_ban->address, &old_ban->address, old_ban->addrbits))
3171     return 1;
3172   /* Otherwise it depends on whether the old ban's text is a superset
3173    * of the new. */
3174   return mmatch(old_ban->banstr, new_ban->banstr);
3175 }
3176
3177 /** Add a ban from a ban list and mark bans that should be removed
3178  * because they overlap.
3179  *
3180  * There are three invariants for a ban list.  First, no ban may be
3181  * more specific than another ban.  Second, no exception may be more
3182  * specific than another exception.  Finally, no ban may be more
3183  * specific than any exception.
3184  *
3185  * @param[in,out] banlist Pointer to head of list.
3186  * @param[in] newban Ban (or exception) to add (or remove).
3187  * @param[in] do_free If non-zero, free \a newban on failure.
3188  * @return Zero if \a newban could be applied, non-zero if not.
3189  */
3190 int apply_ban(struct Ban **banlist, struct Ban *newban, int do_free)
3191 {
3192   struct Ban *ban;
3193   size_t count = 0;
3194
3195   assert(newban->flags & (BAN_ADD|BAN_DEL));
3196   if (newban->flags & BAN_ADD) {
3197     size_t totlen = 0;
3198     /* If a less specific *active* entry is found, fail.  */
3199     for (ban = *banlist; ban; ban = ban->next) {
3200       if (!bmatch(ban, newban) && !(ban->flags & BAN_DEL)) {
3201         if (do_free)
3202           free_ban(newban);
3203         return 1;
3204       }
3205       if (!(ban->flags & (BAN_OVERLAPPED|BAN_DEL))) {
3206         count++;
3207         totlen += strlen(ban->banstr);
3208       }
3209     }
3210     /* Mark more specific entries and add this one to the end of the list. */
3211     while ((ban = *banlist) != NULL) {
3212       if (!bmatch(newban, ban)) {
3213         ban->flags |= BAN_OVERLAPPED | BAN_DEL;
3214       }
3215       banlist = &ban->next;
3216     }
3217     *banlist = newban;
3218     return 0;
3219   } else if (newban->flags & BAN_DEL) {
3220     size_t remove_count = 0;
3221     /* Mark more specific entries. */
3222     for (ban = *banlist; ban; ban = ban->next) {
3223       if (!bmatch(newban, ban)) {
3224         ban->flags |= BAN_OVERLAPPED | BAN_DEL;
3225         remove_count++;
3226       }
3227     }
3228     if (remove_count)
3229         return 0;
3230     /* If no matches were found, fail. */
3231     if (do_free)
3232       free_ban(newban);
3233     return 3;
3234   }
3235   if (do_free)
3236     free_ban(newban);
3237   return 4;
3238 }
3239
3240 /* Removes MODE_WASDELJOINS in a channel.
3241  * Reveals all hidden users.
3242  */
3243 static void reveal_hidden_chan_users(struct ParseState *state, ulong64 *flag_p) {
3244     struct Membership *member;
3245
3246     /* If the channel is not +d, do nothing. */
3247     if(!(state->chptr->mode.mode & MODE_WASDELJOINS)) return;
3248
3249     /* Iterate through all members and reveal them if they are hidden. */
3250     for(member = state->chptr->members; member; member = member->next_member) {
3251         if(IsDelayedJoin(member) && !IsInvisibleJoin(member)) {
3252             RevealDelayedJoin(member);
3253         }
3254     }
3255 }
3256
3257 /* Handle MODE_AUDITORIUM changes 
3258  * set Delayed for all hidden users on MODE_DEL
3259  * part all nonoped users on MODE_ADD
3260  */
3261 static void audit_chan_users(struct ParseState *state, ulong64 *flag_p) {
3262         struct Membership *member;
3263         if (state->dir == MODE_ADD) {
3264                 for(member = state->chptr->members; member; member = member->next_member) {
3265                         if(!IsChanOp(member) && !HasVoice(member)) {
3266                                 sendcmdto_channel_butserv_butone(member->user, CMD_PART, member->channel, member->user, SKIP_OPS, "%H :%s", member->channel, "mode +u set.");
3267                         }
3268                 }
3269         } else {
3270                 for(member = state->chptr->members; member; member = member->next_member) {
3271                         if(!IsChanOp(member) && !HasVoice(member)) {
3272                                 sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, SKIP_OPS, ":%H", member->channel);
3273                         }
3274                 }
3275         }
3276 }
3277
3278
3279 /*
3280  * Helper function to convert bans
3281  */
3282 static void
3283 mode_parse_ban(struct ParseState *state, ulong64 *flag_p)
3284 {
3285   char *t_str, *s;
3286   struct Ban *ban, *newban;
3287
3288   if (state->parc <= 0) { /* Not enough args, send ban list */
3289     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
3290       send_ban_list(state->sptr, state->chptr);
3291       state->done |= DONE_BANLIST;
3292     }
3293     return;
3294   }
3295
3296   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3297     return;
3298
3299   t_str = state->parv[state->args_used++]; /* grab arg */
3300   state->parc--;
3301   state->max_args--;
3302
3303   /* If they're not an oper, they can't change modes */
3304   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3305     send_notoper(state);
3306     return;
3307   }
3308
3309   if ((s = strchr(t_str, ' ')))
3310     *s = '\0';
3311
3312   if (!*t_str || *t_str == ':') { /* warn if empty */
3313     if (MyUser(state->sptr))
3314       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
3315                        "MODE -b");
3316     return;
3317   }
3318
3319   /* Clear all ADD/DEL/OVERLAPPED flags from ban list. */
3320   if (!(state->done & DONE_BANCLEAN)) {
3321     for (ban = state->chptr->banlist; ban; ban = ban->next)
3322       ban->flags &= ~(BAN_ADD | BAN_DEL | BAN_OVERLAPPED);
3323     state->done |= DONE_BANCLEAN;
3324   }
3325
3326   /* remember the ban for the moment... */
3327   newban = state->banlist + (state->numbans++);
3328   newban->next = 0;
3329   newban->flags = ((state->dir == MODE_ADD) ? BAN_ADD : BAN_DEL)
3330       | (*flag_p == MODE_BAN ? 0 : BAN_EXCEPTION);
3331   set_ban_mask(newban, collapse(pretty_mask(t_str)));
3332   ircd_strncpy(newban->who, IsUser(state->sptr) ? cli_name(state->sptr) : "*", NICKLEN);
3333   newban->when = TStime();
3334   apply_ban(&state->chptr->banlist, newban, 0);
3335 }
3336
3337 /*
3338  * This is the bottom half of the ban processor
3339  */
3340 static void
3341 mode_process_bans(struct ParseState *state)
3342 {
3343   struct Ban *ban, *newban, *prevban, *nextban;
3344   int count = 0;
3345   int len = 0;
3346   int banlen;
3347   int changed = 0;
3348
3349   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
3350     count++;
3351     banlen = strlen(ban->banstr);
3352     len += banlen;
3353     nextban = ban->next;
3354
3355     if ((ban->flags & (BAN_DEL | BAN_ADD)) == (BAN_DEL | BAN_ADD)) {
3356       if (prevban)
3357         prevban->next = 0; /* Break the list; ban isn't a real ban */
3358       else
3359         state->chptr->banlist = 0;
3360
3361       count--;
3362       len -= banlen;
3363
3364       continue;
3365     } else if (ban->flags & BAN_DEL) { /* Deleted a ban? */
3366       char *bandup;
3367       DupString(bandup, ban->banstr);
3368       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN, bandup, 1);
3369
3370       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
3371         if (prevban) /* clip it out of the list... */
3372           prevban->next = ban->next;
3373         else
3374           state->chptr->banlist = ban->next;
3375
3376         count--;
3377         len -= banlen;
3378         free_ban(ban);
3379
3380         changed++;
3381         continue; /* next ban; keep prevban like it is */
3382       } else
3383         ban->flags &= BAN_IPMASK; /* unset other flags */
3384     } else if (ban->flags & BAN_ADD) { /* adding a ban? */
3385       if (prevban)
3386         prevban->next = 0; /* Break the list; ban isn't a real ban */
3387       else
3388         state->chptr->banlist = 0;
3389
3390       /* If we're supposed to ignore it, do so. */
3391       if (ban->flags & BAN_OVERLAPPED &&
3392           !(state->flags & MODE_PARSE_BOUNCE)) {
3393         count--;
3394         len -= banlen;
3395       } else {
3396         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
3397             (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
3398              count > feature_int(FEAT_MAXBANS))) {
3399           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
3400                      ban->banstr);
3401           count--;
3402           len -= banlen;
3403         } else {
3404           char *bandup;
3405           /* add the ban to the buffer */
3406           DupString(bandup, ban->banstr);
3407           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN, bandup, 1);
3408
3409           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
3410             newban = make_ban(ban->banstr);
3411             strcpy(newban->who, ban->who);
3412             newban->when = ban->when;
3413             newban->flags = ban->flags & BAN_IPMASK;
3414
3415             newban->next = state->chptr->banlist; /* and link it in */
3416             state->chptr->banlist = newban;
3417
3418             changed++;
3419           }
3420         }
3421       }
3422     }
3423
3424     prevban = ban;
3425   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
3426
3427   if (changed) /* if we changed the ban list, we must invalidate the bans */
3428     mode_ban_invalidate(state->chptr);
3429 }
3430
3431 /*
3432  * Helper function to process client changes
3433  */
3434 static void
3435 mode_parse_client(struct ParseState *state, ulong64 *flag_p)
3436 {
3437   char *t_str;
3438   char *colon;
3439   struct Client *acptr;
3440   struct Membership *member;
3441   int oplevel = MAXOPLEVEL + 1;
3442   int req_oplevel;
3443   int i;
3444
3445   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3446     return;
3447
3448   if (state->parc <= 0) /* return if not enough args */
3449     return;
3450
3451   t_str = state->parv[state->args_used++]; /* grab arg */
3452   state->parc--;
3453   state->max_args--;
3454
3455   /* If they're not an oper, they can't change modes */
3456   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3457     send_notoper(state);
3458     return;
3459   }
3460
3461   if (MyUser(state->sptr)) {
3462     colon = strchr(t_str, ':');
3463     if (colon != NULL) {
3464       *colon++ = '\0';
3465       req_oplevel = atoi(colon);
3466       if (*flag_p == CHFL_VOICE || state->dir == MODE_DEL) {
3467         /* Ignore the colon and its argument. */
3468       } else if (!(state->flags & MODE_PARSE_FORCE)
3469           && state->member
3470           && (req_oplevel < OpLevel(state->member)
3471               || (req_oplevel == OpLevel(state->member)
3472                   && OpLevel(state->member) < MAXOPLEVEL)
3473               || req_oplevel > MAXOPLEVEL)) {
3474         send_reply(state->sptr, ERR_NOTLOWEROPLEVEL,
3475                    t_str, state->chptr->chname,
3476                    OpLevel(state->member), req_oplevel, "op",
3477                    OpLevel(state->member) == req_oplevel ? "the same" : "a higher");
3478       } else if (req_oplevel <= MAXOPLEVEL)
3479         oplevel = req_oplevel;
3480     }
3481     /* find client we're manipulating */
3482     acptr = find_chasing(state->sptr, t_str, NULL);
3483   } else {
3484     if (t_str[5] == ':') {
3485       t_str[5] = '\0';
3486       oplevel = atoi(t_str + 6);
3487     }
3488     acptr = findNUser(t_str);
3489   }
3490
3491   if (!acptr)
3492     return; /* find_chasing() already reported an error to the user */
3493
3494   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
3495     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
3496                                        state->cli_change[i].flag & flag_p[0]))
3497       break; /* found a slot */
3498
3499   /* If we are going to bounce this deop, mark the correct oplevel. */
3500   if (state->flags & MODE_PARSE_BOUNCE
3501       && state->dir == MODE_DEL
3502       && flag_p[0] == MODE_CHANOP
3503       && (member = find_member_link(state->chptr, acptr)))
3504       oplevel = OpLevel(member);
3505
3506   /* Store what we're doing to them */
3507   state->cli_change[i].flag = state->dir | flag_p[0];
3508   state->cli_change[i].oplevel = oplevel;
3509   state->cli_change[i].client = acptr;
3510 }
3511
3512 /*
3513  * Helper function to process the changed client list
3514  */
3515 static void
3516 mode_process_clients(struct ParseState *state)
3517 {
3518   int i;
3519   struct Membership *member;
3520
3521   for (i = 0; state->cli_change[i].flag; i++) {
3522     assert(0 != state->cli_change[i].client);
3523
3524     /* look up member link */
3525     if (!(member = find_member_link(state->chptr,
3526                                     state->cli_change[i].client)) ||
3527         (MyUser(state->sptr) && IsZombie(member))) {
3528       if (MyUser(state->sptr))
3529         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
3530                    cli_name(state->cli_change[i].client),
3531                    state->chptr->chname);
3532       continue;
3533     }
3534         if (member && (IsInvisibleJoin(member) &&  state->cli_change[i].client != state->sptr) && IsDelayedJoin(member)) {
3535         if (MyUser(state->sptr))
3536         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
3537                    cli_name(state->cli_change[i].client),
3538                    state->chptr->chname);
3539       continue;
3540         }
3541
3542     if ((state->cli_change[i].flag & MODE_ADD &&
3543          (state->cli_change[i].flag & member->status)) ||
3544         (state->cli_change[i].flag & MODE_DEL &&
3545          !(state->cli_change[i].flag & member->status)))
3546       continue; /* no change made, don't do anything */
3547
3548     /* see if the deop is allowed */
3549     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
3550         (MODE_DEL | MODE_CHANOP)) {
3551       /* Prevent +k users from being deopped, but allow extra ops to deop
3552        * +k users. We do not prevent deopping _REAL_ services because /opmode
3553        * will always allow this.
3554        */
3555       if(IsChannelService(state->cli_change[i].client) && !IsXtraOp(state->sptr) && state->sptr != state->cli_change[i].client) {
3556         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
3557           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
3558                                state->chptr,
3559                                (IsServer(state->sptr) ? cli_name(state->sptr) :
3560                                 cli_name((cli_user(state->sptr))->server)));
3561
3562         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
3563           send_reply(state->sptr, ERR_ISCHANSERVICE,
3564                      cli_name(state->cli_change[i].client),
3565                      state->chptr->chname);
3566           continue;
3567         }
3568       }
3569
3570       /* check deop for local user */
3571       if (MyUser(state->sptr)) {
3572
3573         /* don't allow local opers to be deopped on local channels */
3574         if (state->cli_change[i].client != state->sptr &&
3575             IsLocalChannel(state->chptr->chname) &&
3576             HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
3577           send_reply(state->sptr, ERR_ISOPERLCHAN,
3578                      cli_name(state->cli_change[i].client),
3579                      state->chptr->chname);
3580           continue;
3581         }
3582
3583         /* Forbid deopping other members with an oplevel less than
3584          * one's own level, and other members with an oplevel the same
3585          * as one's own unless both are at MAXOPLEVEL. */
3586         if (state->sptr != state->cli_change[i].client
3587             && state->member
3588             && ((OpLevel(member) < OpLevel(state->member))
3589                 || (OpLevel(member) == OpLevel(state->member)
3590                     && OpLevel(member) < MAXOPLEVEL))) {
3591             int equal = (OpLevel(member) == OpLevel(state->member));
3592             send_reply(state->sptr, ERR_NOTLOWEROPLEVEL,
3593                        cli_name(state->cli_change[i].client),
3594                        state->chptr->chname,
3595                        OpLevel(state->member), OpLevel(member),
3596                        "deop", equal ? "the same" : "a higher");
3597           continue;
3598         }
3599       }
3600     }
3601
3602     /* set op-level of member being opped */
3603     if ((state->cli_change[i].flag & (MODE_ADD | MODE_CHANOP)) ==
3604         (MODE_ADD | MODE_CHANOP)) {
3605       /* If a valid oplevel was specified, use it.
3606        * Otherwise, if being opped by an outsider, get MAXOPLEVEL.
3607        * Otherwise, if not an apass channel, or state->member has
3608        *   MAXOPLEVEL, get oplevel MAXOPLEVEL.
3609        * Otherwise, get state->member's oplevel+1.
3610        */
3611       if (state->cli_change[i].oplevel <= MAXOPLEVEL)
3612         SetOpLevel(member, state->cli_change[i].oplevel);
3613       else if (!state->member)
3614         SetOpLevel(member, MAXOPLEVEL);
3615       else if (OpLevel(state->member) >= MAXOPLEVEL)
3616           SetOpLevel(member, OpLevel(state->member));
3617       else
3618         SetOpLevel(member, OpLevel(state->member) + 1);
3619     }
3620         
3621         int user_visible = (member->status & CHFL_VOICED_OR_OPPED);
3622         
3623     /* actually effect the change */
3624     if (state->flags & MODE_PARSE_SET) {
3625       if (state->cli_change[i].flag & MODE_ADD) {
3626         if (IsDelayedJoin(member) && !IsZombie(member))
3627           RevealDelayedJoin(member);
3628         member->status |= (state->cli_change[i].flag &
3629                            (MODE_CHANOP | MODE_VOICE));
3630         if (state->cli_change[i].flag & MODE_CHANOP)
3631           ClearDeopped(member);
3632       } else
3633         member->status &= ~(state->cli_change[i].flag &
3634                             (MODE_CHANOP | MODE_VOICE));
3635     }
3636
3637     /* accumulate the change */
3638     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
3639                         state->cli_change[i].client,
3640                         state->cli_change[i].oplevel);
3641         
3642         if((member->channel->mode.mode & MODE_AUDITORIUM)) {
3643                 //join or part the user
3644                 if((member->status & CHFL_VOICED_OR_OPPED) && !user_visible) {
3645                         sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, SKIP_OPS, ":%H", member->channel);
3646                 } else if(!(member->status & CHFL_VOICED_OR_OPPED) && user_visible) {
3647                         sendcmdto_channel_butserv_butone(member->user, CMD_PART, member->channel, member->user, SKIP_OPS, "%H :%s", member->channel, "user deoped/devoiced on a +u channel.");
3648                 }
3649                 if(MyUser(member->user) && (state->cli_change[i].flag & MODE_CHANOP)) {
3650                         //do_names(member->user, member->channel, NAMES_ALL|NAMES_EON|((member->status & MODE_CHANOP) ? 0 : NAMES_OPS));
3651                         //this is not working for all users :(  so we have to send join/part events
3652                         struct Membership *member2;
3653                         if (state->cli_change[i].flag & MODE_ADD) {
3654                                 //JOIN events
3655                                 for(member2 = state->chptr->members; member2; member2 = member2->next_member) {
3656                                         if(!IsChanOp(member2) && !HasVoice(member2)) {
3657                                                 sendcmdto_one(member2->user, CMD_JOIN, member->user, ":%H", member->channel);
3658                                         }
3659                                 }
3660                         } else {
3661                                 //PART events
3662                                 for(member2 = state->chptr->members; member2; member2 = member2->next_member) {
3663                                         if(!IsChanOp(member2) && !HasVoice(member2) && member != member2) {
3664                                                 sendcmdto_one(member2->user, CMD_PART, member->user, "%H :%s", member->channel, "invisible user on +u channel.");
3665                                         }
3666                                 }
3667                         }
3668                 }
3669         }
3670   } /* for (i = 0; state->cli_change[i].flags; i++) */
3671 }
3672
3673 /*
3674  * Helper function to process the simple modes
3675  */
3676 static void
3677 mode_parse_mode(struct ParseState *state, ulong64 *flag_p)
3678 {
3679   /* If they're not an oper, they can't change modes */
3680   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3681     send_notoper(state);
3682     return;
3683   }
3684
3685   if (!state->mbuf)
3686     return;
3687
3688   /* Local users are not permitted to change registration status */
3689   if (flag_p[0] == MODE_REGISTERED && !(state->flags & MODE_PARSE_FORCE) && MyUser(state->sptr))
3690     return;
3691         
3692   if(flag_p[0] == MODE_AUDITORIUM)
3693     audit_chan_users(state, flag_p);
3694
3695   if (state->dir == MODE_ADD) {
3696     state->add |= flag_p[0];
3697     state->del &= ~flag_p[0];
3698
3699     if (flag_p[0] & MODE_SECRET) {
3700       state->add &= ~MODE_PRIVATE;
3701       state->del |= MODE_PRIVATE;
3702     } else if (flag_p[0] & MODE_PRIVATE) {
3703       state->add &= ~MODE_SECRET;
3704       state->del |= MODE_SECRET;
3705     }
3706   } else {
3707     state->add &= ~flag_p[0];
3708     state->del |= flag_p[0];
3709   }
3710
3711   assert(0 == (state->add & state->del));
3712   assert((MODE_SECRET | MODE_PRIVATE) !=
3713          (state->add & (MODE_SECRET | MODE_PRIVATE)));
3714 }
3715
3716 /**
3717  * This routine is intended to parse MODE or OPMODE commands and effect the
3718  * changes (or just build the bounce buffer).
3719  *
3720  * \param[out] mbuf Receives parsed representation of mode change.
3721  * \param[in] cptr Connection that sent the message to this server.
3722  * \param[in] sptr Original source of the message.
3723  * \param[in] chptr Channel whose modes are being changed.
3724  * \param[in] parc Number of valid strings in \a parv.
3725  * \param[in] parv Text arguments representing mode change, with the
3726  *   zero'th element containing a string like "+m" or "-o".
3727  * \param[in] flags Set of bitwise MODE_PARSE_* flags.
3728  * \param[in] member If non-null, the channel member attempting to change the modes.
3729  */
3730 int
3731 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
3732            struct Channel *chptr, int parc, char *parv[], unsigned int flags,
3733            struct Membership* member)
3734 {
3735   static ulong64 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_APASS,         'A',
3746     MODE_UPASS,         'U',
3747     MODE_REGISTERED,    'R',
3748     MODE_BAN,           'b',
3749     MODE_LIMIT,         'l',
3750     MODE_REGONLY,       'r',
3751     MODE_DELJOINS,      'D',
3752     MODE_WASDELJOINS,   'd',
3753     MODE_PERSIST,       'z',
3754     MODE_NOCOLOUR,      'c',
3755     MODE_NOCTCP,        'C',
3756     MODE_NOAMSGS,       'M',
3757         MODE_NONOTICE,      'N',
3758         MODE_QUARANTINE,      'Q',
3759         MODE_ALTCHAN,        'F',
3760     MODE_ACCESS,        'a',
3761         MODE_AUDITORIUM,    'u',
3762         MODE_NOFLOOD,       'f',
3763     MODE_ADD,           '+',
3764     MODE_DEL,           '-',
3765     0x0, 0x0
3766   };
3767   int i;
3768   ulong64 *flag_p;
3769   ulong64 t_mode;
3770   char *modestr;
3771   struct ParseState state;
3772
3773   assert(0 != cptr);
3774   assert(0 != sptr);
3775   assert(0 != chptr);
3776   assert(0 != parc);
3777   assert(0 != parv);
3778
3779   state.mbuf = mbuf;
3780   state.cptr = cptr;
3781   state.sptr = sptr;
3782   state.chptr = chptr;
3783   state.member = member;
3784   state.parc = parc;
3785   state.parv = parv;
3786   state.flags = flags;
3787   state.dir = MODE_ADD;
3788   state.done = 0;
3789   state.add = 0;
3790   state.del = 0;
3791   state.args_used = 0;
3792   state.max_args = MAXMODEPARAMS;
3793   state.numbans = 0;
3794
3795   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
3796     state.banlist[i].next = 0;
3797     state.banlist[i].who[0] = '\0';
3798     state.banlist[i].when = 0;
3799     state.banlist[i].flags = 0;
3800     state.cli_change[i].flag = 0;
3801     state.cli_change[i].client = 0;
3802   }
3803
3804   modestr = state.parv[state.args_used++];
3805   state.parc--;
3806
3807   while (*modestr) {
3808     for (; *modestr; modestr++) {
3809       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
3810         if (flag_p[1] == *modestr)
3811           break;
3812
3813       if (!flag_p[0]) { /* didn't find it?  complain and continue */
3814         if (MyUser(state.sptr))
3815           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
3816         continue;
3817       }
3818
3819       switch (*modestr) {
3820       case '+': /* switch direction to MODE_ADD */
3821       case '-': /* switch direction to MODE_DEL */
3822         state.dir = flag_p[0];
3823         break;
3824
3825       case 'l': /* deal with limits */
3826         mode_parse_limit(&state, flag_p);
3827         break;
3828       case 'a': /* deal with limits */
3829         mode_parse_access(&state, flag_p);
3830         break;
3831           case 'F':
3832         mode_parse_altchan(&state, flag_p);
3833         break;
3834           case 'f':
3835         mode_parse_noflood(&state, flag_p);
3836         break;
3837       case 'Q':
3838       if(IsNetServ(state.sptr) && IsSecurityServ(state.sptr))
3839         mode_parse_mode(&state, flag_p);
3840         break;
3841       case 'k': /* deal with keys */
3842         mode_parse_key(&state, flag_p);
3843         break;
3844       case 'A': /* deal with Admin passes */
3845         if (IsServer(cptr) || feature_bool(FEAT_OPLEVELS))
3846         mode_parse_apass(&state, flag_p);
3847         break;
3848       case 'U': /* deal with user passes */
3849         if (IsServer(cptr) || feature_bool(FEAT_OPLEVELS))
3850         mode_parse_upass(&state, flag_p);
3851         break;
3852       case 'b': /* deal with bans */
3853         mode_parse_ban(&state, flag_p);
3854         break;
3855
3856       case 'd': /* deal with hidden members */
3857         reveal_hidden_chan_users(&state, flag_p);
3858         break;
3859
3860       case 'o': /* deal with ops/voice */
3861       case 'v':
3862         mode_parse_client(&state, flag_p);
3863         break;
3864
3865       case 'z': /* remote clients are allowed to change +z */
3866         if(!MyUser(state.sptr) || (state.flags & MODE_PARSE_FORCE))
3867           mode_parse_mode(&state, flag_p);
3868         break;
3869           case 'O': /* remote clients are allowed to change +z */
3870             //struct User* user = cli_user(cptr);
3871                 //|| (chptr.chanowner && IsAccount(cptr) && chptr.chanowner == user->account)
3872         if(!MyUser(state.sptr) || (state.flags & MODE_PARSE_FORCE) )
3873           mode_parse_mode(&state, flag_p);
3874         break;
3875
3876       default: /* deal with other modes */
3877         mode_parse_mode(&state, flag_p);
3878         break;
3879       } /* switch (*modestr) */
3880     } /* for (; *modestr; modestr++) */
3881
3882     if (state.flags & MODE_PARSE_BURST)
3883       break; /* don't interpret any more arguments */
3884
3885     if (state.parc > 0) { /* process next argument in string */
3886       modestr = state.parv[state.args_used++];
3887       state.parc--;
3888
3889       /* is it a TS? */
3890       if (IsServer(state.cptr) && !state.parc && IsDigit(*modestr)) {
3891         time_t recv_ts;
3892
3893         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
3894           break;                     /* we're then going to bounce the mode! */
3895
3896         recv_ts = atoi(modestr);
3897
3898         if (recv_ts && recv_ts < state.chptr->creationtime)
3899           state.chptr->creationtime = recv_ts; /* respect earlier TS */
3900         else if (recv_ts > state.chptr->creationtime) {
3901           struct Client *sserv;
3902
3903           /* Check whether the originating server has fully processed
3904            * the burst to it. */
3905           sserv = state.cptr;
3906           if (!IsServer(sserv))
3907               sserv = cli_user(sserv)->server;
3908           if (IsBurstOrBurstAck(sserv)) {
3909             /* This is a legal but unusual case; the source server
3910              * probably just has not processed the BURST for this
3911              * channel.  It SHOULD wipe out all its modes soon, so
3912              * silently ignore the mode change rather than send a
3913              * bounce that could desync modes from our side (that
3914              * have already been sent).
3915              */
3916             state.mbuf->mb_add = 0;
3917             state.mbuf->mb_rem = 0;
3918             state.mbuf->mb_count = 0;
3919             return state.args_used;
3920           } else {
3921             /* Server is desynced; bounce the mode and deop the source
3922              * to fix it. */
3923             state.flags &= ~MODE_PARSE_SET;
3924             state.flags |= MODE_PARSE_BOUNCE;
3925             state.mbuf->mb_dest &= ~(MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK4);
3926             state.mbuf->mb_dest |= MODEBUF_DEST_BOUNCE | MODEBUF_DEST_HACK2;
3927             if (!IsServer(state.cptr))
3928               state.mbuf->mb_dest |= MODEBUF_DEST_DEOP;
3929           }
3930         }
3931
3932         break; /* break out of while loop */
3933       } else if (state.flags & MODE_PARSE_STRICT ||
3934                  (MyUser(state.sptr) && state.max_args <= 0)) {
3935         state.parc++; /* we didn't actually gobble the argument */
3936         state.args_used--;
3937         break; /* break out of while loop */
3938       }
3939     }
3940   } /* while (*modestr) */
3941
3942   /*
3943    * the rest of the function finishes building resultant MODEs; if the
3944    * origin isn't a member or an oper, skip it.
3945    */
3946   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
3947     return state.args_used; /* tell our parent how many args we gobbled */
3948
3949   t_mode = state.chptr->mode.mode;
3950
3951   if (state.del & t_mode) { /* delete any modes to be deleted... */
3952     modebuf_mode(state.mbuf, MODE_DEL | (state.del & t_mode));
3953
3954     t_mode &= ~state.del;
3955   }
3956   if (state.add & ~t_mode) { /* add any modes to be added... */
3957     modebuf_mode(state.mbuf, MODE_ADD | (state.add & ~t_mode));
3958
3959     t_mode |= state.add;
3960   }
3961
3962   if (state.flags & MODE_PARSE_SET) { /* set the channel modes */
3963     if ((state.chptr->mode.mode & MODE_INVITEONLY) &&
3964         !(t_mode & MODE_INVITEONLY))
3965       mode_invite_clear(state.chptr);
3966
3967     state.chptr->mode.mode = t_mode;
3968   }
3969
3970   if (state.flags & MODE_PARSE_WIPEOUT) {
3971     if (state.chptr->mode.limit && !(state.done & DONE_LIMIT))
3972       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
3973                         state.chptr->mode.limit);
3974     if (state.chptr->mode.access && !(state.done & DONE_ACCESS))
3975       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_ACCESS,
3976                         state.chptr->mode.access);
3977     if (state.chptr->mode.altchan && !(state.done & DONE_ALTCHAN))
3978       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_ALTCHAN,
3979                         state.chptr->mode.altchan, 0);
3980         if (state.chptr->mode.noflood && !(state.done & DONE_NOFLOOD))
3981       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_NOFLOOD,
3982                         state.chptr->mode.noflood, 0);
3983     if (*state.chptr->mode.key && !(state.done & DONE_KEY_DEL))
3984       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
3985                           state.chptr->mode.key, 0);
3986     if (*state.chptr->mode.upass && !(state.done & DONE_UPASS_DEL))
3987       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_UPASS,
3988                           state.chptr->mode.upass, 0);
3989     if (*state.chptr->mode.apass && !(state.done & DONE_APASS_DEL))
3990       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_APASS,
3991                           state.chptr->mode.apass, 0);
3992   }
3993
3994   if (state.done & DONE_BANCLEAN) /* process bans */
3995     mode_process_bans(&state);
3996
3997   /* process client changes */
3998   if (state.cli_change[0].flag)
3999     mode_process_clients(&state);
4000
4001   return state.args_used; /* tell our parent how many args we gobbled */
4002 }
4003
4004 /*
4005  * Initialize a join buffer
4006  */
4007 void
4008 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
4009              struct Client *connect, unsigned int type, char *comment,
4010              time_t create)
4011 {
4012   int i;
4013
4014   assert(0 != jbuf);
4015   assert(0 != source);
4016   assert(0 != connect);
4017
4018   jbuf->jb_source = source; /* just initialize struct JoinBuf */
4019   jbuf->jb_connect = connect;
4020   jbuf->jb_type = type;
4021   jbuf->jb_comment = comment;
4022   jbuf->jb_create = create;
4023   jbuf->jb_count = 0;
4024   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
4025                        type == JOINBUF_TYPE_PART ||
4026                        type == JOINBUF_TYPE_PARTALL) ?
4027                       STARTJOINLEN : STARTCREATELEN) +
4028                      (comment ? strlen(comment) + 2 : 0));
4029
4030   for (i = 0; i < MAXJOINARGS; i++)
4031     jbuf->jb_channels[i] = 0;
4032 }
4033
4034 /*
4035  * Add a channel to the join buffer
4036  */
4037 void
4038 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
4039 {
4040   unsigned int len;
4041   int is_local;
4042
4043   assert(0 != jbuf);
4044
4045   if (!chan) {
4046     sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect, "0");
4047     return;
4048   }
4049
4050   is_local = IsLocalChannel(chan->chname);
4051
4052   if (jbuf->jb_type == JOINBUF_TYPE_PART ||
4053       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
4054     struct Membership *member = find_member_link(chan, jbuf->jb_source);
4055     if (IsUserParting(member))
4056       return;
4057     SetUserParting(member);
4058
4059     /* Send notification to channel */
4060         if((chan->mode.mode & MODE_AUDITORIUM) && !(member->status & CHFL_VOICED_OR_OPPED)) {
4061           //send part to ops only
4062           sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_PART, chan, NULL, SKIP_NONOPS, "%H :%s", chan, jbuf->jb_comment);
4063           if(MyUser(jbuf->jb_source))
4064                   sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source, "%H :%s", chan, jbuf->jb_comment);
4065     } else if (!(flags & (CHFL_ZOMBIE | CHFL_DELAYED)))
4066       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_PART, chan, NULL, 0,
4067                                 (flags & CHFL_BANNED || !jbuf->jb_comment) ?
4068                                 ":%H" : "%H :%s", chan, jbuf->jb_comment);
4069     else if (MyUser(jbuf->jb_source))
4070       sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
4071                     (flags & CHFL_BANNED || !jbuf->jb_comment) ?
4072                     ":%H" : "%H :%s", chan, jbuf->jb_comment);
4073     /* XXX: Shouldn't we send a PART here anyway? */
4074     /* to users on the channel?  Why?  From their POV, the user isn't on
4075      * the channel anymore anyway.  We don't send to servers until below,
4076      * when we gang all the channel parts together.  Note that this is
4077      * exactly the same logic, albeit somewhat more concise, as was in
4078      * the original m_part.c */
4079
4080     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
4081         is_local) /* got to remove user here */
4082       remove_user_from_channel(jbuf->jb_source, chan);
4083   } else {
4084     int oplevel = !chan->mode.apass[0] ? MAXOPLEVEL
4085         : (flags & CHFL_CHANNEL_MANAGER) ? 0
4086         : 1;
4087     /* Add user to channel */
4088     if (((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED)) || ((flags & CHFL_INVISIBLE) && !(flags & CHFL_VOICED_OR_OPPED))) {
4089       add_user_to_channel(chan, jbuf->jb_source, flags | CHFL_DELAYED, oplevel);
4090     } else
4091       add_user_to_channel(chan, jbuf->jb_source, flags, oplevel);
4092
4093     /* send JOIN notification to all servers (CREATE is sent later). */
4094     if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !is_local) {
4095          if ((flags & CHFL_INVISIBLE) && !(flags & CHFL_VOICED_OR_OPPED)) {
4096       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
4097                             "%H %Tu %i", chan, chan->creationtime, 1);
4098           } else {
4099           sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
4100                             "%H %Tu %i", chan, chan->creationtime, 0);
4101           }
4102         }
4103         
4104         if((chan->mode.mode & MODE_AUDITORIUM) && !(flags & CHFL_VOICED_OR_OPPED)) {
4105                 //we have to send this JOIN event to ops only...                  
4106                 sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_JOIN, chan, NULL, SKIP_NONOPS, "%H", chan);
4107                 if(MyUser(jbuf->jb_source))
4108                   sendcmdto_one(jbuf->jb_source, CMD_JOIN, jbuf->jb_source, ":%H", chan);
4109         }
4110     else if (!((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED)) && !((flags & CHFL_INVISIBLE) && !(flags & CHFL_VOICED_OR_OPPED))) {
4111       /* Send the notification to the channel */
4112       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_JOIN, chan, NULL, 0, "%H", chan);
4113
4114       /* send an op, too, if needed */
4115       if (flags & CHFL_CHANOP && (oplevel < MAXOPLEVEL || !MyUser(jbuf->jb_source)))
4116         sendcmdto_channel_butserv_butone((chan->mode.apass[0] ? &his : jbuf->jb_source),
4117                                          CMD_MODE, chan, NULL, 0, "%H +o %C",
4118                                          chan, jbuf->jb_source);
4119     } else if (MyUser(jbuf->jb_source)) {
4120       sendcmdto_one(jbuf->jb_source, CMD_JOIN, jbuf->jb_source, ":%H", chan);
4121         }
4122   }
4123
4124   if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
4125       jbuf->jb_type == JOINBUF_TYPE_JOIN || is_local)
4126     return; /* don't send to remote */
4127
4128   /* figure out if channel name will cause buffer to be overflowed */
4129   len = chan ? strlen(chan->chname) + 1 : 2;
4130   if (jbuf->jb_strlen + len > BUFSIZE)
4131     joinbuf_flush(jbuf);
4132
4133   /* add channel to list of channels to send and update counts */
4134   jbuf->jb_channels[jbuf->jb_count++] = chan;
4135   jbuf->jb_strlen += len;
4136
4137   /* if we've used up all slots, flush */
4138   if (jbuf->jb_count >= MAXJOINARGS)
4139     joinbuf_flush(jbuf);
4140 }
4141
4142 /*
4143  * Flush the channel list to remote servers
4144  */
4145 int
4146 joinbuf_flush(struct JoinBuf *jbuf)
4147 {
4148   char chanlist[BUFSIZE];
4149   int chanlist_i = 0;
4150   int i;
4151
4152   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
4153       jbuf->jb_type == JOINBUF_TYPE_JOIN)
4154     return 0; /* no joins to process */
4155
4156   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
4157     build_string(chanlist, &chanlist_i,
4158                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
4159                  i == 0 ? '\0' : ',');
4160     if (JOINBUF_TYPE_PART == jbuf->jb_type)
4161       /* Remove user from channel */
4162       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
4163
4164     jbuf->jb_channels[i] = 0; /* mark slot empty */
4165   }
4166
4167   jbuf->jb_count = 0; /* reset base counters */
4168   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_PART ?
4169                       STARTJOINLEN : STARTCREATELEN) +
4170                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
4171
4172   /* and send the appropriate command */
4173   switch (jbuf->jb_type) {
4174   case JOINBUF_TYPE_CREATE:
4175     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
4176                           "%s %Tu", chanlist, jbuf->jb_create);
4177     break;
4178
4179   case JOINBUF_TYPE_PART:
4180     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
4181                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
4182                           jbuf->jb_comment);
4183     break;
4184   }
4185
4186   return 0;
4187 }
4188
4189 /* Returns TRUE (1) if client is invited, FALSE (0) if not */
4190 int IsInvited(struct Client* cptr, const void* chptr)
4191 {
4192   struct SLink *lp;
4193
4194   for (lp = (cli_user(cptr))->invited; lp; lp = lp->next)
4195     if (lp->value.chptr == chptr)
4196       return 1;
4197   return 0;
4198 }
4199
4200 /* RevealDelayedJoin: sends a join for a hidden user */
4201
4202 void RevealDelayedJoin(struct Membership *member)
4203 {
4204   ClearDelayedJoin(member);
4205   sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, 0, ":%H",
4206                                    member->channel);
4207   CheckDelayedJoins(member->channel);
4208 }
4209
4210 /* CheckDelayedJoins: checks and clear +d if necessary */
4211
4212 void CheckDelayedJoins(struct Channel *chan)
4213 {
4214   if ((chan->mode.mode & MODE_WASDELJOINS) && !find_delayed_joins(chan)) {
4215     chan->mode.mode &= ~MODE_WASDELJOINS;
4216     sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan, NULL, 0,
4217                                      "%H -d", chan);
4218     sendcmdto_channel_servers_butone(&me, CMD_MODE, chan, NULL, 0,
4219                                      "%H -d", chan);
4220   }
4221 }
4222
4223 void CheckEnableDelayedJoins(struct Channel *chan) {
4224   if (!(chan->mode.mode & MODE_WASDELJOINS) && find_delayed_joins(chan)) {
4225         chan->mode.mode |= MODE_WASDELJOINS;
4226         sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan, NULL, 0,
4227                                      "%H +d", chan);
4228     sendcmdto_channel_servers_butone(&me, CMD_MODE, chan, NULL, 0,
4229                                      "%H +d", chan);
4230   }
4231 }
4232
4233 /* checks whether a channel is nonpersistent with no users and deletes it
4234  * returns 1 if deleted, otherwise 0
4235  */
4236 signed int destruct_nonpers_channel(struct Channel *chptr) {
4237   if(!(chptr->mode.mode & MODE_PERSIST) && chptr->users == 0) {
4238     if(chptr->destruct_event)
4239       remove_destruct_event(chptr);
4240     destruct_channel(chptr);
4241     return 1;
4242   }
4243   return 0;
4244 }
4245
4246 /** Send a join for the user if (s)he is a hidden member of the channel.
4247  */
4248 void RevealDelayedJoinIfNeeded(struct Client *sptr, struct Channel *chptr)
4249 {
4250   struct Membership *member = find_member_link(chptr, sptr);
4251   if (member && IsDelayedJoin(member) && !IsInvisibleJoin(member))
4252     RevealDelayedJoin(member);
4253 }
4254
4255 /** Extended multi target message block check.
4256  * The channelmode MODE_NOAMSGS prevents multi-target messages from being sent
4257  * to the channel. Since many clients sent these so called AMSGS manually with
4258  * one PRIVMSG per channel, we have this extended check which prevents messages
4259  * from being sent to multiple channels.
4260  *
4261  * The check is quite simple: We save the last sent message of every client.
4262  * When the client sends a new PRIVMSG to another channel, we compare the
4263  * message to the previously sent message and if they equal we may drop the new
4264  * message instead of broadcasting it.
4265  * There are several additional checks. That is, the new message must be sent in
4266  * a specific amount of time in which this check works. If the ducplicate
4267  * message is delayed for too long then it will pass this check. Furthermore,
4268  * there is a specific number a message must be already sent to different
4269  * channels until it is blocked.
4270  * Both numbers can be configured by the FEATURES subsystem.
4271  *
4272  * This function returns 0 if the message may pass and 1 if the message should
4273  * be blocked.
4274  * For this function to work properly it must be called on every PRIVMSG which
4275  * is sent by any user.
4276  *
4277  * Since users are creative and sometimes smart (damnit!) this function can be
4278  * outsourced into a dynamic library so we can adjust this function to protect
4279  * against any user scripts on-the-fly.
4280  *
4281  * --gix 2009/11/19
4282  */
4283 int ext_amsg_block(struct Client *cptr, struct Channel *chptr, const char *msg)
4284 {
4285   int amsg_time;
4286   
4287   /* First on every message we check whether the mechanism is enabled.
4288    * If it is enabled, we check:
4289    *  - whether the channel has MODE_NOAMSGS
4290    *  - whether it was sent in between the configured time span
4291    *  - whether it matches the previous message
4292    * in exactly this order. If at least one test fails, we do not block the
4293    * message.
4294    * If at least one test failed we copy the message into the users buffer so
4295    * it will be checked the next time he sends a message. We also update the
4296    * timestamp of the user.
4297    */
4298   amsg_time = feature_int(FEAT_NOAMSG_TIME);
4299   if(amsg_time > 0) {
4300     /* first of all strip the message (filter out invisible content) */
4301     char *stripped_message = MyMalloc(BUFSIZE + 1);
4302     strcpy(stripped_message, msg);
4303     char p = stripped_message[0];
4304     int p_pos = 0;
4305     int is_visible = 1, is_ccode = 0, i = 0, j = 0;
4306     char codes[5];
4307     for(i = 0; p != '\n'; p = stripped_message[++i]) {
4308       if(p == 3) {
4309         j = 0;
4310         is_ccode = 1;
4311       } else if(is_ccode) {
4312         if((p >= 48 && p <= 57) || p == 44) {
4313           if(is_ccode == 1) {
4314             if(p == 44) {
4315               is_ccode = 2;
4316               codes[j++] = 0;
4317               j = 0;
4318             } else
4319               codes[j++] = p;
4320           } else {
4321             //compare
4322             if(p != codes[j++]) {
4323              is_ccode = 3;
4324             }
4325           }
4326         } else {
4327           //END of color code...
4328           is_ccode = 0;
4329           if(is_ccode != 1 && codes[j] != 0) is_ccode = 3;
4330           if(is_ccode == 1) {
4331             codes[j] = 0;
4332             int k;
4333             for(k = 0; k < j-1; k++) {
4334               if(codes[k] != 48) {
4335                 is_visible = 1;
4336                 goto normalchar;
4337               }
4338             }
4339             is_visible = 0;
4340           } else if(is_ccode == 2) {
4341             is_visible = 0;
4342           } else if(is_ccode == 3) {
4343             is_visible = 1;
4344             goto normalchar;
4345           }
4346         }
4347       } else {
4348         normalchar:
4349         if(is_visible)
4350           stripped_message[p_pos++] = p;
4351       }
4352     }
4353     stripped_message[p_pos++] = 0;
4354     /* Allocate a new buffer if there is none, yet. */
4355     if(!cli_user(cptr)->lastmsg) {
4356       cli_user(cptr)->lastmsg = MyMalloc(BUFSIZE + 1);
4357       memset(cli_user(cptr)->lastmsg, 0, BUFSIZE + 1);
4358     }
4359     if((chptr->mode.mode & MODE_NOAMSGS) &&
4360        ((cli_user(cptr)->lastmsg_time + amsg_time) >= CurrentTime) &&
4361        (strcmp(cli_user(cptr)->lastmsg, stripped_message) == 0)) {
4362       cli_user(cptr)->lastmsg_time = CurrentTime;
4363       cli_user(cptr)->lastmsg_num++;
4364       MyFree(stripped_message);
4365       if(cli_user(cptr)->lastmsg_num >= feature_int(FEAT_NOAMSG_NUM)) return 1;
4366       else return 0;
4367     }
4368     /* Message did not match so update the data. */
4369     cli_user(cptr)->lastmsg_time = CurrentTime;
4370     cli_user(cptr)->lastmsg_num = 0;
4371     strcpy(cli_user(cptr)->lastmsg, stripped_message);
4372     MyFree(stripped_message);
4373   }
4374   return 0;
4375 }
4376
4377 /** Extended flood check.
4378  * The channelmode MODE_NOFLOOD prevents users from flooding the channel.
4379  * 
4380  * This function returns 0 if the message may pass and 1 if the message should
4381  * be blocked.
4382  * For this function to work properly it must be called on every PRIVMSG which
4383  * is sent by any user.
4384  *
4385  * --pk910 2011/7/1
4386  */
4387 int ext_noflood_block(struct Client *cptr, struct Channel *chptr) {
4388   if(!*chptr->mode.noflood) return 0;
4389   struct Membership *member = find_member_link(chptr, cptr);
4390   if(!member) return 0; //TODO: we've no check for -n channels implemented, yet
4391   //check if this user is really affected by +f
4392   unsigned int flags = (chptr->mode.noflood_value & 0x00000007);        //0000 0000 0000 0000 0000 0000 0000 0111 = 0x00000007 >> 0
4393   unsigned int count = (chptr->mode.noflood_value & 0x00001ff8) >> 3;   //0000 0000 0000 0000 0001 1111 1111 1000 = 0x00001ff8 >> 3
4394   int time           = (chptr->mode.noflood_value & 0x07ffe000) >> 13;  //0000 0111 1111 1111 1110 0000 0000 0000 = 0x07ffe000 >> 13
4395   if(count == 0 || time == 0) return 0;
4396   if(!(flags & FLFL_NOFLOOD) && HasPriv(cptr, PRIV_FLOOD))
4397     return 0;
4398   if(!(flags & FLFL_CHANOP) && (member->status & CHFL_CHANOP)) 
4399     return 0;
4400   if(!(flags & (FLFL_CHANOP | FLFL_VOICE)) && (member->status & CHFL_VOICE)) 
4401     return 0;
4402   int floodcount = 0;
4403   struct MemberFlood *floodnode, *prev_floodnode;
4404   for (floodnode = member->flood; floodnode; floodnode = floodnode->next_memberflood) {
4405     if(floodnode->time + time > CurrentTime) {
4406       if(floodcount == 0 && floodnode != member->flood) {
4407         //free all before
4408         prev_floodnode->next_memberflood = free_MemberFlood;
4409         free_MemberFlood  = prev_floodnode;
4410         member->flood = floodnode;
4411       }
4412       floodcount++;
4413     }
4414     prev_floodnode = floodnode;
4415   }
4416   Debug((DEBUG_INFO, "floodcount: %i", floodcount));
4417   if(floodcount >= count) return 1; //blocked!
4418   //add a new floodnode :)
4419   if(free_MemberFlood) {
4420     floodnode = free_MemberFlood;
4421     free_MemberFlood = floodnode->next_memberflood;
4422   } else
4423     floodnode = (struct MemberFlood*) MyMalloc(sizeof(struct MemberFlood));
4424   floodnode->time = CurrentTime;
4425   floodnode->next_memberflood = NULL;
4426   if(floodcount > 0)
4427     prev_floodnode->next_memberflood = floodnode;
4428   else
4429     member->flood = floodnode;
4430   return 0;
4431 }
4432