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