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