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