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