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