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