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