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