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