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