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