Fix the irregular IP ban bug harder.
[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 == '.')
1113     {
1114       /* Case 2: Found last '.' (without finding a '!' or '@' yet) */
1115       last_dot = ptr;
1116       continue;
1117     }
1118     else
1119       continue;
1120     for (; *ptr; ++ptr)
1121     {
1122       if (*ptr == '@')
1123       {
1124         /* Case 4 or 5: Found last '@' */
1125         host = ptr + 1;
1126       }
1127     }
1128     break;
1129   }
1130   if (user == star && last_dot)
1131   {
1132     /* Case 2: */
1133     nick = star;
1134     user = star;
1135     host = mask;
1136   }
1137   /* Check lengths */
1138   if (nick != star)
1139   {
1140     char *nick_end = (user != star) ? user - 1 : ptr;
1141     if (nick_end - nick > NICKLEN)
1142       nick[NICKLEN] = 0;
1143     *nick_end = 0;
1144   }
1145   if (user != star)
1146   {
1147     char *user_end = (host != star) ? host - 1 : ptr;
1148     if (user_end - user > USERLEN)
1149     {
1150       user = user_end - USERLEN;
1151       *user = '*';
1152     }
1153     *user_end = 0;
1154   }
1155   if (host != star && ptr - host > HOSTLEN)
1156   {
1157     host = ptr - HOSTLEN;
1158     *host = '*';
1159   }
1160   ircd_snprintf(0, retmask, sizeof(retmask), "%s!%s@%s", nick, user, host);
1161   return retmask;
1162 }
1163
1164 /** send a banlist to a client for a channel
1165  *
1166  * @param cptr  Client to send the banlist to.
1167  * @param chptr Channel whose banlist to send.
1168  */
1169 static void send_ban_list(struct Client* cptr, struct Channel* chptr)
1170 {
1171   struct Ban* lp;
1172
1173   assert(0 != cptr);
1174   assert(0 != chptr);
1175
1176   for (lp = chptr->banlist; lp; lp = lp->next)
1177     send_reply(cptr, RPL_BANLIST, chptr->chname, lp->banstr,
1178                lp->who, lp->when);
1179
1180   send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
1181 }
1182
1183 /** Check a key against a keyring.
1184  * We are now treating the key part of /join channellist key as a key
1185  * ring; that is, we try one key against the actual channel key, and if that
1186  * doesn't work, we try the next one, and so on. -Kev -Texaco
1187  * Returns: 0 on match, 1 otherwise
1188  * This version contributed by SeKs \<intru@info.polymtl.ca\>
1189  *
1190  * @param key           Key to check
1191  * @param keyring       Comma separated list of keys
1192  *
1193  * @returns True if the key was found and matches, false otherwise.
1194  */
1195 static int compall(char *key, char *keyring)
1196 {
1197   char *p1;
1198
1199 top:
1200   p1 = key;                     /* point to the key... */
1201   while (*p1 && *p1 == *keyring)
1202   {                             /* step through the key and ring until they
1203                                    don't match... */
1204     p1++;
1205     keyring++;
1206   }
1207
1208   if (!*p1 && (!*keyring || *keyring == ','))
1209     /* ok, if we're at the end of the and also at the end of one of the keys
1210        in the keyring, we have a match */
1211     return 0;
1212
1213   if (!*keyring)                /* if we're at the end of the key ring, there
1214                                    weren't any matches, so we return 1 */
1215     return 1;
1216
1217   /* Not at the end of the key ring, so step
1218      through to the next key in the ring: */
1219   while (*keyring && *(keyring++) != ',');
1220
1221   goto top;                     /* and check it against the key */
1222 }
1223
1224 /** Returns if a user can join a channel with a specific key.
1225  *
1226  * @param sptr  The client trying to join
1227  * @param chptr The channel to join
1228  * @param key   The key to use
1229  *
1230  * @returns any error that occurred bit-wise OR'd with MAGIC_OPER_OVERRIDE
1231  *          if the oper used the magic key, 0 if no error occurred.
1232  */
1233 int can_join(struct Client *sptr, struct Channel *chptr, char *key)
1234 {
1235   int overrideJoin = 0;  
1236   
1237   /*
1238    * Now a banned user CAN join if invited -- Nemesi
1239    * Now a user CAN escape channel limit if invited -- bfriendly
1240    * Now a user CAN escape anything if invited -- Isomer
1241    */
1242
1243   if (IsInvited(sptr, chptr))
1244     return 0;
1245   
1246   /* An oper can force a join on a local channel using "OVERRIDE" as the key. 
1247      a HACK(4) notice will be sent if he would not have been supposed
1248      to join normally. */ 
1249   if (IsLocalChannel(chptr->chname) && HasPriv(sptr, PRIV_WALK_LCHAN) &&
1250       !BadPtr(key) && compall("OVERRIDE",chptr->mode.key) != 0 &&
1251       compall("OVERRIDE",key) == 0)
1252     overrideJoin = MAGIC_OPER_OVERRIDE;
1253
1254   if (chptr->mode.mode & MODE_INVITEONLY)
1255         return overrideJoin + ERR_INVITEONLYCHAN;
1256         
1257   if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
1258         return overrideJoin + ERR_CHANNELISFULL;
1259
1260   if ((chptr->mode.mode & MODE_REGONLY) && !IsAccount(sptr))
1261         return overrideJoin + ERR_NEEDREGGEDNICK;
1262         
1263   if (find_ban(sptr, chptr->banlist))
1264         return overrideJoin + ERR_BANNEDFROMCHAN;
1265   
1266   /*
1267    * now using compall (above) to test against a whole key ring -Kev
1268    */
1269   if (*chptr->mode.key && (EmptyString(key) || compall(chptr->mode.key, key)))
1270     return overrideJoin + ERR_BADCHANNELKEY;
1271
1272   if (overrideJoin)     
1273         return ERR_DONTCHEAT;
1274         
1275   return 0;
1276 }
1277
1278 /** Remove bells and commas from channel name
1279  *
1280  * @param cn    Channel name to clean, modified in place.
1281  */
1282 void clean_channelname(char *cn)
1283 {
1284   int i;
1285
1286   for (i = 0; cn[i]; i++) {
1287     if (i >= IRCD_MIN(CHANNELLEN, feature_int(FEAT_CHANNELLEN))
1288         || !IsChannelChar(cn[i])) {
1289       cn[i] = '\0';
1290       return;
1291     }
1292     if (IsChannelLower(cn[i])) {
1293       cn[i] = ToLower(cn[i]);
1294 #ifndef FIXME
1295       /*
1296        * Remove for .08+
1297        * toupper(0xd0)
1298        */
1299       if ((unsigned char)(cn[i]) == 0xd0)
1300         cn[i] = (char) 0xf0;
1301 #endif
1302     }
1303   }
1304 }
1305
1306 /** Get a channel block, creating if necessary.
1307  *  Get Channel block for chname (and allocate a new channel
1308  *  block, if it didn't exists before).
1309  *
1310  * @param cptr          Client joining the channel.
1311  * @param chname        The name of the channel to join.
1312  * @param flag          set to CGT_CREATE to create the channel if it doesn't 
1313  *                      exist
1314  *
1315  * @returns NULL if the channel is invalid, doesn't exist and CGT_CREATE 
1316  *      wasn't specified or a pointer to the channel structure
1317  */
1318 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
1319 {
1320   struct Channel *chptr;
1321   int len;
1322
1323   if (EmptyString(chname))
1324     return NULL;
1325
1326   len = strlen(chname);
1327   if (MyUser(cptr) && len > CHANNELLEN)
1328   {
1329     len = CHANNELLEN;
1330     *(chname + CHANNELLEN) = '\0';
1331   }
1332   if ((chptr = FindChannel(chname)))
1333     return (chptr);
1334   if (flag == CGT_CREATE)
1335   {
1336     chptr = (struct Channel*) MyMalloc(sizeof(struct Channel) + len);
1337     assert(0 != chptr);
1338     ++UserStats.channels;
1339     memset(chptr, 0, sizeof(struct Channel));
1340     strcpy(chptr->chname, chname);
1341     if (GlobalChannelList)
1342       GlobalChannelList->prev = chptr;
1343     chptr->prev = NULL;
1344     chptr->next = GlobalChannelList;
1345     chptr->creationtime = MyUser(cptr) ? TStime() : (time_t) 0;
1346     GlobalChannelList = chptr;
1347     hAddChannel(chptr);
1348   }
1349   return chptr;
1350 }
1351
1352 /** invite a user to a channel.
1353  *
1354  * Adds an invite for a user to a channel.  Limits the number of invites
1355  * to FEAT_MAXCHANNELSPERUSER.  Does not sent notification to the user.
1356  *
1357  * @param cptr  The client to be invited.
1358  * @param chptr The channel to be invited to.
1359  */
1360 void add_invite(struct Client *cptr, struct Channel *chptr)
1361 {
1362   struct SLink *inv, **tmp;
1363
1364   del_invite(cptr, chptr);
1365   /*
1366    * Delete last link in chain if the list is max length
1367    */
1368   assert(list_length((cli_user(cptr))->invited) == (cli_user(cptr))->invites);
1369   if ((cli_user(cptr))->invites >= feature_int(FEAT_MAXCHANNELSPERUSER))
1370     del_invite(cptr, (cli_user(cptr))->invited->value.chptr);
1371   /*
1372    * Add client to channel invite list
1373    */
1374   inv = make_link();
1375   inv->value.cptr = cptr;
1376   inv->next = chptr->invites;
1377   chptr->invites = inv;
1378   /*
1379    * Add channel to the end of the client invite list
1380    */
1381   for (tmp = &((cli_user(cptr))->invited); *tmp; tmp = &((*tmp)->next));
1382   inv = make_link();
1383   inv->value.chptr = chptr;
1384   inv->next = NULL;
1385   (*tmp) = inv;
1386   (cli_user(cptr))->invites++;
1387 }
1388
1389 /** Delete an invite
1390  * Delete Invite block from channel invite list and client invite list
1391  *
1392  * @param cptr  Client pointer
1393  * @param chptr Channel pointer
1394  */
1395 void del_invite(struct Client *cptr, struct Channel *chptr)
1396 {
1397   struct SLink **inv, *tmp;
1398
1399   for (inv = &(chptr->invites); (tmp = *inv); inv = &tmp->next)
1400     if (tmp->value.cptr == cptr)
1401     {
1402       *inv = tmp->next;
1403       free_link(tmp);
1404       tmp = 0;
1405       (cli_user(cptr))->invites--;
1406       break;
1407     }
1408
1409   for (inv = &((cli_user(cptr))->invited); (tmp = *inv); inv = &tmp->next)
1410     if (tmp->value.chptr == chptr)
1411     {
1412       *inv = tmp->next;
1413       free_link(tmp);
1414       tmp = 0;
1415       break;
1416     }
1417 }
1418
1419 /** @page zombie Explanation of Zombies
1420  *
1421  * Synopsis:
1422  *
1423  * A channel member is turned into a zombie when he is kicked from a
1424  * channel but his server has not acknowledged the kick.  Servers that
1425  * see the member as a zombie can accept actions he performed before
1426  * being kicked, without allowing chanop operations from outsiders or
1427  * desyncing the network.
1428  *
1429  * Consider:
1430  * <pre>
1431  *                     client
1432  *                       |
1433  *                       c
1434  *                       |
1435  *     X --a--> A --b--> B --d--> D
1436  *                       |
1437  *                      who
1438  * </pre>
1439  *
1440  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
1441  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
1442  *
1443  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
1444  *    Remove the user immediately when no users are left on the channel.
1445  * b) On server B : remove the user (who/lp) from the channel, send a
1446  *    PART upstream (to A) and pass on the KICK.
1447  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
1448  *    channel, and pass on the KICK.
1449  * d) On server D : remove the user (who/lp) from the channel, and pass on
1450  *    the KICK.
1451  *
1452  * Note:
1453  * - Setting the ZOMBIE flag never hurts, we either remove the
1454  *   client after that or we don't.
1455  * - The KICK message was already passed on, as should be in all cases.
1456  * - `who' is removed in all cases except case a) when users are left.
1457  * - A PART is only sent upstream in case b).
1458  *
1459  * 2 aug 97:
1460  * <pre>
1461  *              6
1462  *              |
1463  *  1 --- 2 --- 3 --- 4 --- 5
1464  *        |           |
1465  *      kicker       who
1466  * </pre>
1467  *
1468  * We also need to turn 'who' into a zombie on servers 1 and 6,
1469  * because a KICK from 'who' (kicking someone else in that direction)
1470  * can arrive there afterward - which should not be bounced itself.
1471  * Therefore case a) also applies for servers 1 and 6.
1472  *
1473  * --Run
1474  */
1475
1476 /** Turn a user on a channel into a zombie
1477  * This function turns a user into a zombie (see \ref zombie)
1478  *
1479  * @param member  The structure representing this user on this channel.
1480  * @param who     The client that is being kicked.
1481  * @param cptr    The connection the kick came from.
1482  * @param sptr    The client that is doing the kicking.
1483  * @param chptr   The channel the user is being kicked from.
1484  */
1485 void make_zombie(struct Membership* member, struct Client* who, 
1486                 struct Client* cptr, struct Client* sptr, struct Channel* chptr)
1487 {
1488   assert(0 != member);
1489   assert(0 != who);
1490   assert(0 != cptr);
1491   assert(0 != chptr);
1492
1493   /* Default for case a): */
1494   SetZombie(member);
1495
1496   /* Case b) or c) ?: */
1497   if (MyUser(who))      /* server 4 */
1498   {
1499     if (IsServer(cptr)) /* Case b) ? */
1500       sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
1501     remove_user_from_channel(who, chptr);
1502     return;
1503   }
1504   if (cli_from(who) == cptr)        /* True on servers 1, 5 and 6 */
1505   {
1506     struct Client *acptr = IsServer(sptr) ? sptr : (cli_user(sptr))->server;
1507     for (; acptr != &me; acptr = (cli_serv(acptr))->up)
1508       if (acptr == (cli_user(who))->server)   /* Case d) (server 5) */
1509       {
1510         remove_user_from_channel(who, chptr);
1511         return;
1512       }
1513   }
1514
1515   /* Case a) (servers 1, 2, 3 and 6) */
1516   if (channel_all_zombies(chptr))
1517     remove_user_from_channel(who, chptr);
1518
1519   /* XXX Can't actually call Debug here; if the channel is all zombies,
1520    * chptr will no longer exist when we get here.
1521   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
1522   */
1523 }
1524
1525 /** returns the number of zombies on a channel
1526  * @param chptr Channel to count zombies in.
1527  *
1528  * @returns The number of zombies on the channel.
1529  */
1530 int number_of_zombies(struct Channel *chptr)
1531 {
1532   struct Membership* member;
1533   int                count = 0;
1534
1535   assert(0 != chptr);
1536   for (member = chptr->members; member; member = member->next_member) {
1537     if (IsZombie(member))
1538       ++count;
1539   }
1540   return count;
1541 }
1542
1543 /** Concatenate some strings together.
1544  * This helper function builds an argument string in strptr, consisting
1545  * of the original string, a space, and str1 and str2 concatenated (if,
1546  * of course, str2 is not NULL)
1547  *
1548  * @param strptr        The buffer to concatenate into
1549  * @param strptr_i      modified offset to the position to modify
1550  * @param str1          The string to concatenate from.
1551  * @param str2          The second string to contatenate from.
1552  * @param c             Charactor to separate the string from str1 and str2.
1553  */
1554 static void
1555 build_string(char *strptr, int *strptr_i, const char *str1,
1556              const char *str2, char c)
1557 {
1558   if (c)
1559     strptr[(*strptr_i)++] = c;
1560
1561   while (*str1)
1562     strptr[(*strptr_i)++] = *(str1++);
1563
1564   if (str2)
1565     while (*str2)
1566       strptr[(*strptr_i)++] = *(str2++);
1567
1568   strptr[(*strptr_i)] = '\0';
1569 }
1570
1571 /** Flush out the modes
1572  * This is the workhorse of our ModeBuf suite; this actually generates the
1573  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
1574  *
1575  * @param mbuf  The mode buffer to flush
1576  * @param all   If true, flush all modes, otherwise leave partial modes in the
1577  *              buffer.
1578  *
1579  * @returns 0
1580  */
1581 static int
1582 modebuf_flush_int(struct ModeBuf *mbuf, int all)
1583 {
1584   /* we only need the flags that don't take args right now */
1585   static int flags[] = {
1586 /*  MODE_CHANOP,        'o', */
1587 /*  MODE_VOICE,         'v', */
1588     MODE_PRIVATE,       'p',
1589     MODE_SECRET,        's',
1590     MODE_MODERATED,     'm',
1591     MODE_TOPICLIMIT,    't',
1592     MODE_INVITEONLY,    'i',
1593     MODE_NOPRIVMSGS,    'n',
1594     MODE_REGONLY,       'r',
1595     MODE_DELJOINS,      'D',
1596     MODE_WASDELJOINS,   'd',
1597 /*  MODE_KEY,           'k', */
1598 /*  MODE_BAN,           'b', */
1599     MODE_LIMIT,         'l',
1600 /*  MODE_APASS,         'A', */
1601 /*  MODE_UPASS,         'U', */
1602     0x0, 0x0
1603   };
1604   int i;
1605   int *flag_p;
1606
1607   struct Client *app_source; /* where the MODE appears to come from */
1608
1609   char addbuf[20]; /* accumulates +psmtin, etc. */
1610   int addbuf_i = 0;
1611   char rembuf[20]; /* accumulates -psmtin, etc. */
1612   int rembuf_i = 0;
1613   char *bufptr; /* we make use of indirection to simplify the code */
1614   int *bufptr_i;
1615
1616   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
1617   int addstr_i;
1618   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
1619   int remstr_i;
1620   char *strptr; /* more indirection to simplify the code */
1621   int *strptr_i;
1622
1623   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
1624   int tmp;
1625
1626   char limitbuf[20]; /* convert limits to strings */
1627
1628   unsigned int limitdel = MODE_LIMIT;
1629
1630   assert(0 != mbuf);
1631
1632   /* If the ModeBuf is empty, we have nothing to do */
1633   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
1634     return 0;
1635
1636   /* Ok, if we were given the OPMODE flag, or its a server, hide the source.
1637    */
1638   if (mbuf->mb_dest & MODEBUF_DEST_OPMODE || IsServer(mbuf->mb_source) || IsMe(mbuf->mb_source))
1639     app_source = &his;
1640   else
1641     app_source = mbuf->mb_source;
1642
1643   /*
1644    * Account for user we're bouncing; we have to get it in on the first
1645    * bounced MODE, or we could have problems
1646    */
1647   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
1648     totalbuflen -= 6; /* numeric nick == 5, plus one space */
1649
1650   /* Calculate the simple flags */
1651   for (flag_p = flags; flag_p[0]; flag_p += 2) {
1652     if (*flag_p & mbuf->mb_add)
1653       addbuf[addbuf_i++] = flag_p[1];
1654     else if (*flag_p & mbuf->mb_rem)
1655       rembuf[rembuf_i++] = flag_p[1];
1656   }
1657
1658   /* Now go through the modes with arguments... */
1659   for (i = 0; i < mbuf->mb_count; i++) {
1660     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1661       bufptr = addbuf;
1662       bufptr_i = &addbuf_i;
1663     } else {
1664       bufptr = rembuf;
1665       bufptr_i = &rembuf_i;
1666     }
1667
1668     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
1669       tmp = strlen(cli_name(MB_CLIENT(mbuf, i)));
1670
1671       if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
1672         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1673       else {
1674         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
1675         totalbuflen -= IRCD_MAX(5, tmp) + 1;
1676       }
1677     } else if (MB_TYPE(mbuf, i) & (MODE_BAN | MODE_APASS | MODE_UPASS)) {
1678       tmp = strlen(MB_STRING(mbuf, i));
1679
1680       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1681         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1682       else {
1683         char mode_char;
1684         switch(MB_TYPE(mbuf, i) & (MODE_BAN | MODE_APASS | MODE_UPASS))
1685         {
1686           case MODE_APASS:
1687             mode_char = 'A';
1688             break;
1689           case MODE_UPASS:
1690             mode_char = 'U';
1691             break;
1692           default:
1693             mode_char = 'b';
1694             break;
1695         }
1696         bufptr[(*bufptr_i)++] = mode_char;
1697         totalbuflen -= tmp + 1;
1698       }
1699     } else if (MB_TYPE(mbuf, i) & MODE_KEY) {
1700       tmp = (mbuf->mb_dest & MODEBUF_DEST_NOKEY ? 1 :
1701              strlen(MB_STRING(mbuf, i)));
1702
1703       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1704         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1705       else {
1706         bufptr[(*bufptr_i)++] = 'k';
1707         totalbuflen -= tmp + 1;
1708       }
1709     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
1710       /* if it's a limit, we also format the number */
1711       ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
1712
1713       tmp = strlen(limitbuf);
1714
1715       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
1716         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
1717       else {
1718         bufptr[(*bufptr_i)++] = 'l';
1719         totalbuflen -= tmp + 1;
1720       }
1721     }
1722   }
1723
1724   /* terminate the mode strings */
1725   addbuf[addbuf_i] = '\0';
1726   rembuf[rembuf_i] = '\0';
1727
1728   /* If we're building a user visible MODE or HACK... */
1729   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
1730                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
1731                        MODEBUF_DEST_LOG)) {
1732     /* Set up the parameter strings */
1733     addstr[0] = '\0';
1734     addstr_i = 0;
1735     remstr[0] = '\0';
1736     remstr_i = 0;
1737
1738     for (i = 0; i < mbuf->mb_count; i++) {
1739       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1740         continue;
1741
1742       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1743         strptr = addstr;
1744         strptr_i = &addstr_i;
1745       } else {
1746         strptr = remstr;
1747         strptr_i = &remstr_i;
1748       }
1749
1750       /* deal with clients... */
1751       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1752         build_string(strptr, strptr_i, cli_name(MB_CLIENT(mbuf, i)), 0, ' ');
1753
1754       /* deal with bans... */
1755       else if (MB_TYPE(mbuf, i) & MODE_BAN)
1756         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1757
1758       /* deal with keys... */
1759       else if (MB_TYPE(mbuf, i) & MODE_KEY)
1760         build_string(strptr, strptr_i, mbuf->mb_dest & MODEBUF_DEST_NOKEY ?
1761                      "*" : MB_STRING(mbuf, i), 0, ' ');
1762
1763       /* deal with invisible passwords */
1764       else if (MB_TYPE(mbuf, i) & (MODE_APASS | MODE_UPASS))
1765         build_string(strptr, strptr_i, "*", 0, ' ');
1766
1767       /*
1768        * deal with limit; note we cannot include the limit parameter if we're
1769        * removing it
1770        */
1771       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
1772                (MODE_ADD | MODE_LIMIT))
1773         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1774     }
1775
1776     /* send the messages off to their destination */
1777     if (mbuf->mb_dest & MODEBUF_DEST_HACK2)
1778       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
1779                            "[%Tu]",
1780                            cli_name(feature_bool(FEAT_HIS_SNOTICES) ?
1781                                     mbuf->mb_source : app_source),
1782                            mbuf->mb_channel->chname,
1783                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1784                            addbuf, remstr, addstr,
1785                            mbuf->mb_channel->creationtime);
1786
1787     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
1788       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
1789                            "%s%s%s%s%s%s [%Tu]",
1790                            cli_name(feature_bool(FEAT_HIS_SNOTICES) ? 
1791                                     mbuf->mb_source : app_source),
1792                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
1793                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
1794                            mbuf->mb_channel->creationtime);
1795
1796     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
1797       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
1798                            "[%Tu]",
1799                            cli_name(feature_bool(FEAT_HIS_SNOTICES) ?
1800                                     mbuf->mb_source : app_source),
1801                            mbuf->mb_channel->chname,
1802                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1803                            addbuf, remstr, addstr,
1804                            mbuf->mb_channel->creationtime);
1805
1806     if (mbuf->mb_dest & MODEBUF_DEST_LOG)
1807       log_write(LS_OPERMODE, L_INFO, LOG_NOSNOTICE,
1808                 "%#C OPMODE %H %s%s%s%s%s%s", mbuf->mb_source,
1809                 mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
1810                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1811
1812     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
1813       sendcmdto_channel_butserv_butone(app_source, CMD_MODE, mbuf->mb_channel, NULL, 0,
1814                                 "%H %s%s%s%s%s%s", mbuf->mb_channel,
1815                                 rembuf_i ? "-" : "", rembuf,
1816                                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
1817   }
1818
1819   /* Now are we supposed to propagate to other servers? */
1820   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
1821     /* set up parameter string */
1822     addstr[0] = '\0';
1823     addstr_i = 0;
1824     remstr[0] = '\0';
1825     remstr_i = 0;
1826
1827     /*
1828      * limit is supressed if we're removing it; we have to figure out which
1829      * direction is the direction for it to be removed, though...
1830      */
1831     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
1832
1833     for (i = 0; i < mbuf->mb_count; i++) {
1834       if (MB_TYPE(mbuf, i) & MODE_SAVE)
1835         continue;
1836
1837       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
1838         strptr = addstr;
1839         strptr_i = &addstr_i;
1840       } else {
1841         strptr = remstr;
1842         strptr_i = &remstr_i;
1843       }
1844
1845       /* deal with modes that take clients */
1846       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1847         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
1848
1849       /* deal with modes that take strings */
1850       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN | MODE_APASS | MODE_UPASS))
1851         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1852
1853       /*
1854        * deal with the limit.  Logic here is complicated; if HACK2 is set,
1855        * we're bouncing the mode, so sense is reversed, and we have to
1856        * include the original limit if it looks like it's being removed
1857        */
1858       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
1859         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1860     }
1861
1862     /* we were told to deop the source */
1863     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
1864       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
1865       addbuf[addbuf_i] = '\0'; /* terminate the string... */
1866       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
1867
1868       /* mark that we've done this, so we don't do it again */
1869       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
1870     }
1871
1872     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
1873       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
1874       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
1875                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
1876                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1877                             addbuf, remstr, addstr);
1878     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
1879       /*
1880        * If HACK2 was set, we're bouncing; we send the MODE back to the
1881        * connection we got it from with the senses reversed and a TS of 0;
1882        * origin is us
1883        */
1884       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
1885                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
1886                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
1887                     mbuf->mb_channel->creationtime);
1888     } else {
1889       /*
1890        * We're propagating a normal MODE command to the rest of the network;
1891        * we send the actual channel TS unless this is a HACK3 or a HACK4
1892        */
1893       if (IsServer(mbuf->mb_source))
1894         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1895                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
1896                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1897                               addbuf, remstr, addstr,
1898                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
1899                               mbuf->mb_channel->creationtime);
1900       else
1901         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1902                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
1903                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1904                               addbuf, remstr, addstr);
1905     }
1906   }
1907
1908   /* We've drained the ModeBuf... */
1909   mbuf->mb_add = 0;
1910   mbuf->mb_rem = 0;
1911   mbuf->mb_count = 0;
1912
1913   /* reinitialize the mode-with-arg slots */
1914   for (i = 0; i < MAXMODEPARAMS; i++) {
1915     /* If we saved any, pack them down */
1916     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
1917       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
1918       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
1919
1920       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
1921         continue;
1922     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
1923       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
1924
1925     MB_TYPE(mbuf, i) = 0;
1926     MB_UINT(mbuf, i) = 0;
1927   }
1928
1929   /* If we're supposed to flush it all, do so--all hail tail recursion */
1930   if (all && mbuf->mb_count)
1931     return modebuf_flush_int(mbuf, 1);
1932
1933   return 0;
1934 }
1935
1936 /** Initialise a modebuf
1937  * This routine just initializes a ModeBuf structure with the information
1938  * needed and the options given.
1939  *
1940  * @param mbuf          The mode buffer to initialise.
1941  * @param source        The client that is performing the mode.
1942  * @param connect       ?
1943  * @param chan          The channel that the mode is being performed upon.
1944  * @param dest          ?
1945  */
1946 void
1947 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
1948              struct Client *connect, struct Channel *chan, unsigned int dest)
1949 {
1950   int i;
1951
1952   assert(0 != mbuf);
1953   assert(0 != source);
1954   assert(0 != chan);
1955   assert(0 != dest);
1956
1957   if (IsLocalChannel(chan->chname)) dest &= ~MODEBUF_DEST_SERVER;
1958
1959   mbuf->mb_add = 0;
1960   mbuf->mb_rem = 0;
1961   mbuf->mb_source = source;
1962   mbuf->mb_connect = connect;
1963   mbuf->mb_channel = chan;
1964   mbuf->mb_dest = dest;
1965   mbuf->mb_count = 0;
1966
1967   /* clear each mode-with-parameter slot */
1968   for (i = 0; i < MAXMODEPARAMS; i++) {
1969     MB_TYPE(mbuf, i) = 0;
1970     MB_UINT(mbuf, i) = 0;
1971   }
1972 }
1973
1974 /** Append a new mode to a modebuf
1975  * This routine simply adds modes to be added or deleted; do a binary OR
1976  * with either MODE_ADD or MODE_DEL
1977  *
1978  * @param mbuf          Mode buffer
1979  * @param mode          MODE_ADD or MODE_DEL OR'd with MODE_PRIVATE etc.
1980  */
1981 void
1982 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
1983 {
1984   assert(0 != mbuf);
1985   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1986
1987   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
1988            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS | MODE_REGONLY |
1989            MODE_DELJOINS | MODE_WASDELJOINS);
1990
1991   if (!(mode & ~(MODE_ADD | MODE_DEL))) /* don't add empty modes... */
1992     return;
1993
1994   if (mode & MODE_ADD) {
1995     mbuf->mb_rem &= ~mode;
1996     mbuf->mb_add |= mode;
1997   } else {
1998     mbuf->mb_add &= ~mode;
1999     mbuf->mb_rem |= mode;
2000   }
2001 }
2002
2003 /** Append a mode that takes an int argument to the modebuf
2004  *
2005  * This routine adds a mode to be added or deleted that takes a unsigned
2006  * int parameter; mode may *only* be the relevant mode flag ORed with one
2007  * of MODE_ADD or MODE_DEL
2008  *
2009  * @param mbuf          The mode buffer to append to.
2010  * @param mode          The mode to append.
2011  * @param uint          The argument to the mode.
2012  */
2013 void
2014 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
2015 {
2016   assert(0 != mbuf);
2017   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2018
2019   if (mode == (MODE_LIMIT | MODE_DEL)) {
2020       mbuf->mb_rem |= mode;
2021       return;
2022   }
2023   MB_TYPE(mbuf, mbuf->mb_count) = mode;
2024   MB_UINT(mbuf, mbuf->mb_count) = uint;
2025
2026   /* when we've reached the maximal count, flush the buffer */
2027   if (++mbuf->mb_count >=
2028       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
2029     modebuf_flush_int(mbuf, 0);
2030 }
2031
2032 /** append a string mode
2033  * This routine adds a mode to be added or deleted that takes a string
2034  * parameter; mode may *only* be the relevant mode flag ORed with one of
2035  * MODE_ADD or MODE_DEL
2036  *
2037  * @param mbuf          The mode buffer to append to.
2038  * @param mode          The mode to append.
2039  * @param string        The string parameter to append.
2040  * @param free          If the string should be free'd later.
2041  */
2042 void
2043 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
2044                     int free)
2045 {
2046   assert(0 != mbuf);
2047   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2048
2049   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
2050   MB_STRING(mbuf, mbuf->mb_count) = string;
2051
2052   /* when we've reached the maximal count, flush the buffer */
2053   if (++mbuf->mb_count >=
2054       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
2055     modebuf_flush_int(mbuf, 0);
2056 }
2057
2058 /** Append a mode on a client to a modebuf.
2059  * This routine adds a mode to be added or deleted that takes a client
2060  * parameter; mode may *only* be the relevant mode flag ORed with one of
2061  * MODE_ADD or MODE_DEL
2062  *
2063  * @param mbuf          The modebuf to append the mode to.
2064  * @param mode          The mode to append.
2065  * @param client        The client argument to append.
2066  */
2067 void
2068 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
2069                     struct Client *client)
2070 {
2071   assert(0 != mbuf);
2072   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2073
2074   MB_TYPE(mbuf, mbuf->mb_count) = mode;
2075   MB_CLIENT(mbuf, mbuf->mb_count) = client;
2076
2077   /* when we've reached the maximal count, flush the buffer */
2078   if (++mbuf->mb_count >=
2079       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
2080     modebuf_flush_int(mbuf, 0);
2081 }
2082
2083 /** The exported binding for modebuf_flush()
2084  *
2085  * @param mbuf  The mode buffer to flush.
2086  * 
2087  * @see modebuf_flush_int()
2088  */
2089 int
2090 modebuf_flush(struct ModeBuf *mbuf)
2091 {
2092   struct Membership *memb;
2093
2094   /* Check if MODE_WASDELJOINS should be set */
2095   if (!(mbuf->mb_channel->mode.mode & (MODE_DELJOINS | MODE_WASDELJOINS))
2096       && (mbuf->mb_rem & MODE_DELJOINS)) {
2097     for (memb = mbuf->mb_channel->members; memb; memb = memb->next_member) {
2098       if (IsDelayedJoin(memb)) {
2099           mbuf->mb_channel->mode.mode |= MODE_WASDELJOINS;
2100           mbuf->mb_add |= MODE_WASDELJOINS;
2101           mbuf->mb_rem &= ~MODE_WASDELJOINS;
2102           break;
2103       }
2104     }
2105   }
2106
2107   return modebuf_flush_int(mbuf, 1);
2108 }
2109
2110 /* This extracts the simple modes contained in mbuf
2111  *
2112  * @param mbuf          The mode buffer to extract the modes from.
2113  * @param buf           The string buffer to write the modes into.
2114  */
2115 void
2116 modebuf_extract(struct ModeBuf *mbuf, char *buf)
2117 {
2118   static int flags[] = {
2119 /*  MODE_CHANOP,        'o', */
2120 /*  MODE_VOICE,         'v', */
2121     MODE_PRIVATE,       'p',
2122     MODE_SECRET,        's',
2123     MODE_MODERATED,     'm',
2124     MODE_TOPICLIMIT,    't',
2125     MODE_INVITEONLY,    'i',
2126     MODE_NOPRIVMSGS,    'n',
2127     MODE_KEY,           'k',
2128     MODE_APASS,         'A',
2129     MODE_UPASS,         'U',
2130 /*  MODE_BAN,           'b', */
2131     MODE_LIMIT,         'l',
2132     MODE_REGONLY,       'r',
2133     MODE_DELJOINS,      'D',
2134     0x0, 0x0
2135   };
2136   unsigned int add;
2137   int i, bufpos = 0, len;
2138   int *flag_p;
2139   char *key = 0, limitbuf[20];
2140   char *apass = 0, *upass = 0;
2141
2142   assert(0 != mbuf);
2143   assert(0 != buf);
2144
2145   buf[0] = '\0';
2146
2147   add = mbuf->mb_add;
2148
2149   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
2150     if (MB_TYPE(mbuf, i) & MODE_ADD) {
2151       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT | MODE_APASS | MODE_UPASS);
2152
2153       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
2154         key = MB_STRING(mbuf, i);
2155       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
2156         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
2157       else if (MB_TYPE(mbuf, i) & MODE_UPASS)
2158         upass = MB_STRING(mbuf, i);
2159       else if (MB_TYPE(mbuf, i) & MODE_APASS)
2160         apass = MB_STRING(mbuf, i);
2161     }
2162   }
2163
2164   if (!add)
2165     return;
2166
2167   buf[bufpos++] = '+'; /* start building buffer */
2168
2169   for (flag_p = flags; flag_p[0]; flag_p += 2)
2170     if (*flag_p & add)
2171       buf[bufpos++] = flag_p[1];
2172
2173   for (i = 0, len = bufpos; i < len; i++) {
2174     if (buf[i] == 'k')
2175       build_string(buf, &bufpos, key, 0, ' ');
2176     else if (buf[i] == 'l')
2177       build_string(buf, &bufpos, limitbuf, 0, ' ');
2178     else if (buf[i] == 'U')
2179       build_string(buf, &bufpos, upass, 0, ' ');
2180     else if (buf[i] == 'A')
2181       build_string(buf, &bufpos, apass, 0, ' ');
2182   }
2183
2184   buf[bufpos] = '\0';
2185
2186   return;
2187 }
2188
2189 /** Simple function to invalidate bans
2190  *
2191  * This function sets all bans as being valid.
2192  *
2193  * @param chan  The channel to operate on.
2194  */
2195 void
2196 mode_ban_invalidate(struct Channel *chan)
2197 {
2198   struct Membership *member;
2199
2200   for (member = chan->members; member; member = member->next_member)
2201     ClearBanValid(member);
2202 }
2203
2204 /** Simple function to drop invite structures
2205  *
2206  * Remove all the invites on the channel.
2207  *
2208  * @param chan          Channel to remove invites from.
2209  *
2210  */
2211 void
2212 mode_invite_clear(struct Channel *chan)
2213 {
2214   while (chan->invites)
2215     del_invite(chan->invites->value.cptr, chan);
2216 }
2217
2218 /* What we've done for mode_parse so far... */
2219 #define DONE_LIMIT      0x01    /**< We've set the limit */
2220 #define DONE_KEY        0x02    /**< We've set the key */
2221 #define DONE_BANLIST    0x04    /**< We've sent the ban list */
2222 #define DONE_NOTOPER    0x08    /**< We've sent a "Not oper" error */
2223 #define DONE_BANCLEAN   0x10    /**< We've cleaned bans... */
2224 #define DONE_UPASS      0x20    /**< We've set user pass */
2225 #define DONE_APASS      0x40    /**< We've set admin pass */
2226
2227 struct ParseState {
2228   struct ModeBuf *mbuf;
2229   struct Client *cptr;
2230   struct Client *sptr;
2231   struct Channel *chptr;
2232   struct Membership *member;
2233   int parc;
2234   char **parv;
2235   unsigned int flags;
2236   unsigned int dir;
2237   unsigned int done;
2238   unsigned int add;
2239   unsigned int del;
2240   int args_used;
2241   int max_args;
2242   int numbans;
2243   struct Ban banlist[MAXPARA];
2244   struct {
2245     unsigned int flag;
2246     struct Client *client;
2247   } cli_change[MAXPARA];
2248 };
2249
2250 /** Helper function to send "Not oper" or "Not member" messages
2251  * Here's a helper function to deal with sending along "Not oper" or
2252  * "Not member" messages
2253  *
2254  * @param state         Parsing State object
2255  */
2256 static void
2257 send_notoper(struct ParseState *state)
2258 {
2259   if (state->done & DONE_NOTOPER)
2260     return;
2261
2262   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
2263              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
2264
2265   state->done |= DONE_NOTOPER;
2266 }
2267
2268 /** Parse a limit
2269  * Helper function to convert limits
2270  *
2271  * @param state         Parsing state object.
2272  * @param flag_p        ?
2273  */
2274 static void
2275 mode_parse_limit(struct ParseState *state, int *flag_p)
2276 {
2277   unsigned int t_limit;
2278
2279   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
2280     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
2281       return;
2282
2283     if (state->parc <= 0) { /* warn if not enough args */
2284       if (MyUser(state->sptr))
2285         need_more_params(state->sptr, "MODE +l");
2286       return;
2287     }
2288
2289     t_limit = strtoul(state->parv[state->args_used++], 0, 10); /* grab arg */
2290     state->parc--;
2291     state->max_args--;
2292
2293     if ((int)t_limit<0) /* don't permit a negative limit */
2294       return;
2295
2296     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
2297         (!t_limit || t_limit == state->chptr->mode.limit))
2298       return;
2299   } else
2300     t_limit = state->chptr->mode.limit;
2301
2302   /* If they're not an oper, they can't change modes */
2303   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2304     send_notoper(state);
2305     return;
2306   }
2307
2308   /* Can't remove a limit that's not there */
2309   if (state->dir == MODE_DEL && !state->chptr->mode.limit)
2310     return;
2311     
2312   /* Skip if this is a burst and a lower limit than this is set already */
2313   if ((state->flags & MODE_PARSE_BURST) &&
2314       (state->chptr->mode.mode & flag_p[0]) &&
2315       (state->chptr->mode.limit < t_limit))
2316     return;
2317
2318   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
2319     return;
2320   state->done |= DONE_LIMIT;
2321
2322   if (!state->mbuf)
2323     return;
2324
2325   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
2326
2327   if (state->flags & MODE_PARSE_SET) { /* set the limit */
2328     if (state->dir & MODE_ADD) {
2329       state->chptr->mode.mode |= flag_p[0];
2330       state->chptr->mode.limit = t_limit;
2331     } else {
2332       state->chptr->mode.mode &= ~flag_p[0];
2333       state->chptr->mode.limit = 0;
2334     }
2335   }
2336 }
2337
2338 /*
2339  * Helper function to convert keys
2340  */
2341 static void
2342 mode_parse_key(struct ParseState *state, int *flag_p)
2343 {
2344   char *t_str, *s;
2345   int t_len;
2346
2347   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2348     return;
2349
2350   if (state->parc <= 0) { /* warn if not enough args */
2351     if (MyUser(state->sptr))
2352       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2353                        "MODE -k");
2354     return;
2355   }
2356
2357   t_str = state->parv[state->args_used++]; /* grab arg */
2358   state->parc--;
2359   state->max_args--;
2360
2361   /* If they're not an oper, they can't change modes */
2362   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2363     send_notoper(state);
2364     return;
2365   }
2366
2367   if (state->done & DONE_KEY) /* allow key to be set only once */
2368     return;
2369   state->done |= DONE_KEY;
2370
2371   t_len = KEYLEN;
2372
2373   /* clean up the key string */
2374   s = t_str;
2375   while (*s > ' ' && *s != ':' && *s != ',' && t_len--)
2376     s++;
2377   *s = '\0';
2378
2379   if (!*t_str) { /* warn if empty */
2380     if (MyUser(state->sptr))
2381       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2382                        "MODE -k");
2383     return;
2384   }
2385
2386   if (!state->mbuf)
2387     return;
2388
2389   /* Skip if this is a burst, we have a key already and the new key is 
2390    * after the old one alphabetically */
2391   if ((state->flags & MODE_PARSE_BURST) &&
2392       *(state->chptr->mode.key) &&
2393       ircd_strcmp(state->chptr->mode.key, t_str) <= 0)
2394     return;
2395
2396   /* can't add a key if one is set, nor can one remove the wrong key */
2397   if (!(state->flags & MODE_PARSE_FORCE))
2398     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
2399         (state->dir == MODE_DEL &&
2400          ircd_strcmp(state->chptr->mode.key, t_str))) {
2401       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2402       return;
2403     }
2404
2405   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2406       !ircd_strcmp(state->chptr->mode.key, t_str))
2407     return; /* no key change */
2408
2409   if (state->flags & MODE_PARSE_BOUNCE) {
2410     if (*state->chptr->mode.key) /* reset old key */
2411       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2412                           state->chptr->mode.key, 0);
2413     else /* remove new bogus key */
2414       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2415   } else /* send new key */
2416     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2417
2418   if (state->flags & MODE_PARSE_SET) {
2419     if (state->dir == MODE_ADD) /* set the new key */
2420       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
2421     else /* remove the old key */
2422       *state->chptr->mode.key = '\0';
2423   }
2424 }
2425
2426 /*
2427  * Helper function to convert user passes
2428  */
2429 static void
2430 mode_parse_upass(struct ParseState *state, int *flag_p)
2431 {
2432   char *t_str, *s;
2433   int t_len;
2434
2435   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2436     return;
2437
2438   if (state->parc <= 0) { /* warn if not enough args */
2439     if (MyUser(state->sptr))
2440       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
2441                        "MODE -U");
2442     return;
2443   }
2444
2445   t_str = state->parv[state->args_used++]; /* grab arg */
2446   state->parc--;
2447   state->max_args--;
2448
2449   /* If they're not an oper, they can't change modes */
2450   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2451     send_notoper(state);
2452     return;
2453   }
2454
2455   /* If a non-service user is trying to force it, refuse. */
2456   if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
2457       && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
2458     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2459                state->chptr->chname);
2460     return;
2461   }
2462
2463   /* If they are not the channel manager, they are not allowed to change it */
2464   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
2465     if (*state->chptr->mode.apass) {
2466       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2467                  state->chptr->chname);
2468     } else if (TStime() - state->chptr->creationtime >= 171000) {
2469       send_reply(state->sptr, ERR_NOMANAGER_LONG, state->chptr->chname);
2470     } else {
2471       send_reply(state->sptr, ERR_NOMANAGER_SHORT, state->chptr->chname);
2472     }
2473     return;
2474   }
2475
2476   if (state->done & DONE_UPASS) /* allow upass to be set only once */
2477     return;
2478   state->done |= DONE_UPASS;
2479
2480   t_len = PASSLEN + 1;
2481
2482   /* clean up the upass string */
2483   s = t_str;
2484   while (*++s > ' ' && *s != ':' && --t_len)
2485     ;
2486   *s = '\0';
2487
2488   if (!*t_str) { /* warn if empty */
2489     if (MyUser(state->sptr))
2490       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
2491                        "MODE -U");
2492     return;
2493   }
2494
2495   if (!state->mbuf)
2496     return;
2497
2498   if (!(state->flags & MODE_PARSE_FORCE)) {
2499     /* can't add the upass while apass is not set */
2500     if (state->dir == MODE_ADD && !*state->chptr->mode.apass) {
2501       send_reply(state->sptr, ERR_UPASSNOTSET, state->chptr->chname, state->chptr->chname);
2502       return;
2503     }
2504     /* cannot set a +U password that is the same as +A */
2505     if (state->dir == MODE_ADD && !ircd_strcmp(state->chptr->mode.apass, t_str)) {
2506       send_reply(state->sptr, ERR_UPASS_SAME_APASS, state->chptr->chname);
2507       return;
2508     }
2509     /* can't add a upass if one is set, nor can one remove the wrong upass */
2510     if ((state->dir == MODE_ADD && *state->chptr->mode.upass) ||
2511         (state->dir == MODE_DEL &&
2512          ircd_strcmp(state->chptr->mode.upass, t_str))) {
2513       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2514       return;
2515     }
2516   }
2517
2518   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2519       !ircd_strcmp(state->chptr->mode.upass, t_str))
2520     return; /* no upass change */
2521
2522   if (state->flags & MODE_PARSE_BOUNCE) {
2523     if (*state->chptr->mode.upass) /* reset old upass */
2524       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2525                           state->chptr->mode.upass, 0);
2526     else /* remove new bogus upass */
2527       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2528   } else /* send new upass */
2529     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2530
2531   if (state->flags & MODE_PARSE_SET) {
2532     if (state->dir == MODE_ADD) /* set the new upass */
2533       ircd_strncpy(state->chptr->mode.upass, t_str, PASSLEN);
2534     else /* remove the old upass */
2535       *state->chptr->mode.upass = '\0';
2536   }
2537 }
2538
2539 /*
2540  * Helper function to convert admin passes
2541  */
2542 static void
2543 mode_parse_apass(struct ParseState *state, int *flag_p)
2544 {
2545   struct Membership *memb;
2546   char *t_str, *s;
2547   int t_len;
2548
2549   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2550     return;
2551
2552   if (state->parc <= 0) { /* warn if not enough args */
2553     if (MyUser(state->sptr))
2554       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
2555                        "MODE -A");
2556     return;
2557   }
2558
2559   t_str = state->parv[state->args_used++]; /* grab arg */
2560   state->parc--;
2561   state->max_args--;
2562
2563   /* If they're not an oper, they can't change modes */
2564   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2565     send_notoper(state);
2566     return;
2567   }
2568
2569   /* If a non-service user is trying to force it, refuse. */
2570   if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
2571       && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
2572     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2573                state->chptr->chname);
2574     return;
2575   }
2576
2577   /* Don't allow to change the Apass if the channel is older than 48 hours. */
2578   if (TStime() - state->chptr->creationtime >= 172800 && !IsAnOper(state->sptr)) {
2579     send_reply(state->sptr, ERR_CHANSECURED, state->chptr->chname);
2580     return;
2581   }
2582
2583   /* If they are not the channel manager, they are not allowed to change it */
2584   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
2585     if (*state->chptr->mode.apass) {
2586       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2587                  state->chptr->chname);
2588     } else if (TStime() - state->chptr->creationtime >= 171000) {
2589       send_reply(state->sptr, ERR_NOMANAGER_LONG, state->chptr->chname);
2590     } else {
2591       send_reply(state->sptr, ERR_NOMANAGER_SHORT, state->chptr->chname);
2592     }
2593     return;
2594   }
2595
2596   if (state->done & DONE_APASS) /* allow apass to be set only once */
2597     return;
2598   state->done |= DONE_APASS;
2599
2600   t_len = PASSLEN + 1;
2601
2602   /* clean up the apass string */
2603   s = t_str;
2604   while (*++s > ' ' && *s != ':' && --t_len)
2605     ;
2606   *s = '\0';
2607
2608   if (!*t_str) { /* warn if empty */
2609     if (MyUser(state->sptr))
2610       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
2611                        "MODE -A");
2612     return;
2613   }
2614
2615   if (!state->mbuf)
2616     return;
2617
2618   if (!(state->flags & MODE_PARSE_FORCE)) {
2619     /* can't remove the apass while upass is still set */
2620     if (state->dir == MODE_DEL && *state->chptr->mode.upass) {
2621       send_reply(state->sptr, ERR_UPASSSET, state->chptr->chname, state->chptr->chname);
2622       return;
2623     }
2624     /* can't add an apass if one is set, nor can one remove the wrong apass */
2625     if ((state->dir == MODE_ADD && *state->chptr->mode.apass) ||
2626         (state->dir == MODE_DEL && ircd_strcmp(state->chptr->mode.apass, t_str))) {
2627       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2628       return;
2629     }
2630   }
2631
2632   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2633       !ircd_strcmp(state->chptr->mode.apass, t_str))
2634     return; /* no apass change */
2635
2636   if (state->flags & MODE_PARSE_BOUNCE) {
2637     if (*state->chptr->mode.apass) /* reset old apass */
2638       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2639                           state->chptr->mode.apass, 0);
2640     else /* remove new bogus apass */
2641       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2642   } else /* send new apass */
2643     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2644
2645   if (state->flags & MODE_PARSE_SET) {
2646     if (state->dir == MODE_ADD) { /* set the new apass */
2647       /* Make it VERY clear to the user that this is a one-time password */
2648       ircd_strncpy(state->chptr->mode.apass, t_str, PASSLEN);
2649       if (MyUser(state->sptr)) {
2650         send_reply(state->sptr, RPL_APASSWARN_SET, state->chptr->mode.apass);
2651         send_reply(state->sptr, RPL_APASSWARN_SECRET, state->chptr->chname,
2652                    state->chptr->mode.apass);
2653       }
2654       /* Give the channel manager level 0 ops. */
2655       if (!(state->flags & MODE_PARSE_FORCE) && IsChannelManager(state->member))
2656         SetOpLevel(state->member, 0);
2657     } else { /* remove the old apass */
2658       *state->chptr->mode.apass = '\0';
2659       if (MyUser(state->sptr))
2660         send_reply(state->sptr, RPL_APASSWARN_CLEAR);
2661       /* Revert everyone to MAXOPLEVEL. */
2662       for (memb = state->chptr->members; memb; memb = memb->next_member) {
2663         if (memb->status & MODE_CHANOP)
2664           memb->oplevel = MAXOPLEVEL;
2665       }
2666     }
2667   }
2668 }
2669
2670 /** Compare one ban's extent to another.
2671  * This works very similarly to mmatch() but it knows about CIDR masks
2672  * and ban exceptions.  If both bans are CIDR-based, compare their
2673  * address bits; otherwise, use mmatch().
2674  * @param[in] old_ban One ban.
2675  * @param[in] new_ban Another ban.
2676  * @return Zero if \a old_ban is a superset of \a new_ban, non-zero otherwise.
2677  */
2678 static int
2679 bmatch(struct Ban *old_ban, struct Ban *new_ban)
2680 {
2681   int res;
2682   assert(old_ban != NULL);
2683   assert(new_ban != NULL);
2684   /* A ban is never treated as a superset of an exception. */
2685   if (!(old_ban->flags & BAN_EXCEPTION)
2686       && (new_ban->flags & BAN_EXCEPTION))
2687     return 1;
2688   /* If either is not an address mask, match the text masks. */
2689   if ((old_ban->flags & new_ban->flags & BAN_IPMASK) == 0)
2690     return mmatch(old_ban->banstr, new_ban->banstr);
2691   /* If the old ban has a longer prefix than new, it cannot be a superset. */
2692   if (old_ban->addrbits > new_ban->addrbits)
2693     return 1;
2694   /* Compare the masks before the hostname part.  */
2695   old_ban->banstr[old_ban->nu_len] = new_ban->banstr[new_ban->nu_len] = '\0';
2696   res = mmatch(old_ban->banstr, new_ban->banstr);
2697   old_ban->banstr[old_ban->nu_len] = new_ban->banstr[new_ban->nu_len] = '@';
2698   if (res)
2699     return res;
2700   /* Compare the addresses. */
2701   return !ipmask_check(&new_ban->address, &old_ban->address, old_ban->addrbits);
2702 }
2703
2704 /** Add a ban from a ban list and mark bans that should be removed
2705  * because they overlap.
2706  *
2707  * There are three invariants for a ban list.  First, no ban may be
2708  * more specific than another ban.  Second, no exception may be more
2709  * specific than another exception.  Finally, no ban may be more
2710  * specific than any exception.
2711  *
2712  * @param[in,out] banlist Pointer to head of list.
2713  * @param[in] newban Ban (or exception) to add (or remove).
2714  * @param[in] do_free If non-zero, free \a newban on failure.
2715  * @return Zero if \a newban could be applied, non-zero if not.
2716  */
2717 int apply_ban(struct Ban **banlist, struct Ban *newban, int do_free)
2718 {
2719   struct Ban *ban;
2720   size_t count = 0;
2721
2722   assert(newban->flags & (BAN_ADD|BAN_DEL));
2723   if (newban->flags & BAN_ADD) {
2724     size_t totlen = 0;
2725     /* If a less specific entry is found, fail.  */
2726     for (ban = *banlist; ban; ban = ban->next) {
2727       if (!bmatch(ban, newban)) {
2728         if (do_free)
2729           free_ban(newban);
2730         return 1;
2731       }
2732       if (!(ban->flags & (BAN_OVERLAPPED|BAN_DEL))) {
2733         count++;
2734         totlen += strlen(ban->banstr);
2735       }
2736     }
2737     /* Mark more specific entries and add this one to the end of the list. */
2738     while ((ban = *banlist) != NULL) {
2739       if (!bmatch(newban, ban)) {
2740         ban->flags |= BAN_OVERLAPPED | BAN_DEL;
2741       }
2742       banlist = &ban->next;
2743     }
2744     *banlist = newban;
2745     return 0;
2746   } else if (newban->flags & BAN_DEL) {
2747     size_t remove_count = 0;
2748     /* Mark more specific entries. */
2749     for (ban = *banlist; ban; ban = ban->next) {
2750       if (!bmatch(newban, ban)) {
2751         ban->flags |= BAN_OVERLAPPED | BAN_DEL;
2752         remove_count++;
2753       }
2754     }
2755     if (remove_count)
2756         return 0;
2757     /* If no matches were found, fail. */
2758     if (do_free)
2759       free_ban(newban);
2760     return 3;
2761   }
2762   if (do_free)
2763     free_ban(newban);
2764   return 4;
2765 }
2766
2767 /*
2768  * Helper function to convert bans
2769  */
2770 static void
2771 mode_parse_ban(struct ParseState *state, int *flag_p)
2772 {
2773   char *t_str, *s;
2774   struct Ban *ban, *newban;
2775
2776   if (state->parc <= 0) { /* Not enough args, send ban list */
2777     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
2778       send_ban_list(state->sptr, state->chptr);
2779       state->done |= DONE_BANLIST;
2780     }
2781
2782     return;
2783   }
2784
2785   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2786     return;
2787
2788   t_str = state->parv[state->args_used++]; /* grab arg */
2789   state->parc--;
2790   state->max_args--;
2791
2792   /* If they're not an oper, they can't change modes */
2793   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2794     send_notoper(state);
2795     return;
2796   }
2797
2798   if ((s = strchr(t_str, ' ')))
2799     *s = '\0';
2800
2801   if (!*t_str || *t_str == ':') { /* warn if empty */
2802     if (MyUser(state->sptr))
2803       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
2804                        "MODE -b");
2805     return;
2806   }
2807
2808   /* Clear all ADD/DEL/OVERLAPPED flags from ban list. */
2809   if (!(state->done & DONE_BANCLEAN)) {
2810     for (ban = state->chptr->banlist; ban; ban = ban->next)
2811       ban->flags &= ~(BAN_ADD | BAN_DEL | BAN_OVERLAPPED);
2812     state->done |= DONE_BANCLEAN;
2813   }
2814
2815   /* remember the ban for the moment... */
2816   newban = state->banlist + (state->numbans++);
2817   newban->next = 0;
2818   newban->flags = ((state->dir == MODE_ADD) ? BAN_ADD : BAN_DEL)
2819       | (*flag_p == MODE_BAN ? 0 : BAN_EXCEPTION);
2820   set_ban_mask(newban, collapse(pretty_mask(t_str)));
2821   ircd_strncpy(newban->who, cli_name(state->sptr), HOSTLEN);
2822   newban->when = TStime();
2823   apply_ban(&state->chptr->banlist, newban, 0);
2824 }
2825
2826 /*
2827  * This is the bottom half of the ban processor
2828  */
2829 static void
2830 mode_process_bans(struct ParseState *state)
2831 {
2832   struct Ban *ban, *newban, *prevban, *nextban;
2833   int count = 0;
2834   int len = 0;
2835   int banlen;
2836   int changed = 0;
2837
2838   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
2839     count++;
2840     banlen = strlen(ban->banstr);
2841     len += banlen;
2842     nextban = ban->next;
2843
2844     if ((ban->flags & (BAN_DEL | BAN_ADD)) == (BAN_DEL | BAN_ADD)) {
2845       if (prevban)
2846         prevban->next = 0; /* Break the list; ban isn't a real ban */
2847       else
2848         state->chptr->banlist = 0;
2849
2850       count--;
2851       len -= banlen;
2852
2853       continue;
2854     } else if (ban->flags & BAN_DEL) { /* Deleted a ban? */
2855       char *bandup;
2856       DupString(bandup, ban->banstr);
2857       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
2858                           bandup, 1);
2859
2860       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
2861         if (prevban) /* clip it out of the list... */
2862           prevban->next = ban->next;
2863         else
2864           state->chptr->banlist = ban->next;
2865
2866         count--;
2867         len -= banlen;
2868         free_ban(ban);
2869
2870         changed++;
2871         continue; /* next ban; keep prevban like it is */
2872       } else
2873         ban->flags &= BAN_IPMASK; /* unset other flags */
2874     } else if (ban->flags & BAN_ADD) { /* adding a ban? */
2875       if (prevban)
2876         prevban->next = 0; /* Break the list; ban isn't a real ban */
2877       else
2878         state->chptr->banlist = 0;
2879
2880       /* If we're supposed to ignore it, do so. */
2881       if (ban->flags & BAN_OVERLAPPED &&
2882           !(state->flags & MODE_PARSE_BOUNCE)) {
2883         count--;
2884         len -= banlen;
2885       } else {
2886         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
2887             (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
2888              count > feature_int(FEAT_MAXBANS))) {
2889           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
2890                      ban->banstr);
2891           count--;
2892           len -= banlen;
2893         } else {
2894           char *bandup;
2895           /* add the ban to the buffer */
2896           DupString(bandup, ban->banstr);
2897           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
2898                               bandup, 1);
2899
2900           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
2901             newban = make_ban(ban->banstr);
2902             strcpy(newban->who, ban->who);
2903             newban->when = ban->when;
2904             newban->flags = ban->flags & BAN_IPMASK;
2905
2906             newban->next = state->chptr->banlist; /* and link it in */
2907             state->chptr->banlist = newban;
2908
2909             changed++;
2910           }
2911         }
2912       }
2913     }
2914
2915     prevban = ban;
2916   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
2917
2918   if (changed) /* if we changed the ban list, we must invalidate the bans */
2919     mode_ban_invalidate(state->chptr);
2920 }
2921
2922 /*
2923  * Helper function to process client changes
2924  */
2925 static void
2926 mode_parse_client(struct ParseState *state, int *flag_p)
2927 {
2928   char *t_str;
2929   struct Client *acptr;
2930   int i;
2931
2932   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2933     return;
2934
2935   if (state->parc <= 0) /* return if not enough args */
2936     return;
2937
2938   t_str = state->parv[state->args_used++]; /* grab arg */
2939   state->parc--;
2940   state->max_args--;
2941
2942   /* If they're not an oper, they can't change modes */
2943   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2944     send_notoper(state);
2945     return;
2946   }
2947
2948   if (MyUser(state->sptr)) /* find client we're manipulating */
2949     acptr = find_chasing(state->sptr, t_str, NULL);
2950   else
2951     acptr = findNUser(t_str);
2952
2953   if (!acptr)
2954     return; /* find_chasing() already reported an error to the user */
2955
2956   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
2957     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
2958                                        state->cli_change[i].flag & flag_p[0]))
2959       break; /* found a slot */
2960
2961   /* Store what we're doing to them */
2962   state->cli_change[i].flag = state->dir | flag_p[0];
2963   state->cli_change[i].client = acptr;
2964 }
2965
2966 /*
2967  * Helper function to process the changed client list
2968  */
2969 static void
2970 mode_process_clients(struct ParseState *state)
2971 {
2972   int i;
2973   struct Membership *member;
2974
2975   for (i = 0; state->cli_change[i].flag; i++) {
2976     assert(0 != state->cli_change[i].client);
2977
2978     /* look up member link */
2979     if (!(member = find_member_link(state->chptr,
2980                                     state->cli_change[i].client)) ||
2981         (MyUser(state->sptr) && IsZombie(member))) {
2982       if (MyUser(state->sptr))
2983         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
2984                    cli_name(state->cli_change[i].client),
2985                    state->chptr->chname);
2986       continue;
2987     }
2988
2989     if ((state->cli_change[i].flag & MODE_ADD &&
2990          (state->cli_change[i].flag & member->status)) ||
2991         (state->cli_change[i].flag & MODE_DEL &&
2992          !(state->cli_change[i].flag & member->status)))
2993       continue; /* no change made, don't do anything */
2994
2995     /* see if the deop is allowed */
2996     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
2997         (MODE_DEL | MODE_CHANOP)) {
2998       /* prevent +k users from being deopped */
2999       if (IsChannelService(state->cli_change[i].client)) {
3000         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
3001           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
3002                                state->chptr,
3003                                (IsServer(state->sptr) ? cli_name(state->sptr) :
3004                                 cli_name((cli_user(state->sptr))->server)));
3005
3006         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
3007           send_reply(state->sptr, ERR_ISCHANSERVICE,
3008                      cli_name(state->cli_change[i].client),
3009                      state->chptr->chname);
3010           continue;
3011         }
3012       }
3013
3014       /* check deop for local user */
3015       if (MyUser(state->sptr)) {
3016
3017         /* don't allow local opers to be deopped on local channels */
3018         if (state->cli_change[i].client != state->sptr &&
3019             IsLocalChannel(state->chptr->chname) &&
3020             HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
3021           send_reply(state->sptr, ERR_ISOPERLCHAN,
3022                      cli_name(state->cli_change[i].client),
3023                      state->chptr->chname);
3024           continue;
3025         }
3026
3027         /* don't allow to deop members with an op level that is <= our own level */
3028         if (state->sptr != state->cli_change[i].client          /* but allow to deop oneself */
3029             && state->chptr->mode.apass[0]
3030             && state->member
3031             && OpLevel(member) <= OpLevel(state->member)) {
3032             int equal = (OpLevel(member) == OpLevel(state->member));
3033             send_reply(state->sptr, ERR_NOTLOWEROPLEVEL,
3034                        cli_name(state->cli_change[i].client),
3035                        state->chptr->chname,
3036                        OpLevel(state->member), OpLevel(member),
3037                        "deop", equal ? "the same" : "a higher");
3038           continue;
3039         }
3040     }
3041     }
3042
3043     /* set op-level of member being opped */
3044     if ((state->cli_change[i].flag & (MODE_ADD | MODE_CHANOP)) ==
3045         (MODE_ADD | MODE_CHANOP)) {
3046       /* If being opped by an outsider, get oplevel 0 for an apass
3047        *   channel, else MAXOPLEVEL.
3048        * Otherwise, if not an apass channel, or state->member has
3049        *   MAXOPLEVEL, get oplevel MAXOPLEVEL.
3050        * Otherwise, get state->member's oplevel+1.
3051        */
3052       if (!state->member)
3053         SetOpLevel(member, state->chptr->mode.apass[0] ? 0 : MAXOPLEVEL);
3054       else if (!state->chptr->mode.apass[0] || OpLevel(state->member) == MAXOPLEVEL)
3055         SetOpLevel(member, MAXOPLEVEL);
3056       else
3057         SetOpLevel(member, OpLevel(state->member) + 1);
3058     }
3059
3060     /* actually effect the change */
3061     if (state->flags & MODE_PARSE_SET) {
3062       if (state->cli_change[i].flag & MODE_ADD) {
3063         if (IsDelayedJoin(member))
3064           RevealDelayedJoin(member);
3065         member->status |= (state->cli_change[i].flag &
3066                            (MODE_CHANOP | MODE_VOICE));
3067         if (state->cli_change[i].flag & MODE_CHANOP)
3068           ClearDeopped(member);
3069       } else
3070         member->status &= ~(state->cli_change[i].flag &
3071                             (MODE_CHANOP | MODE_VOICE));
3072     }
3073
3074     /* accumulate the change */
3075     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
3076                         state->cli_change[i].client);
3077   } /* for (i = 0; state->cli_change[i].flags; i++) */
3078 }
3079
3080 /*
3081  * Helper function to process the simple modes
3082  */
3083 static void
3084 mode_parse_mode(struct ParseState *state, int *flag_p)
3085 {
3086   /* If they're not an oper, they can't change modes */
3087   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3088     send_notoper(state);
3089     return;
3090   }
3091
3092   if (!state->mbuf)
3093     return;
3094
3095   if (state->dir == MODE_ADD) {
3096     state->add |= flag_p[0];
3097     state->del &= ~flag_p[0];
3098
3099     if (flag_p[0] & MODE_SECRET) {
3100       state->add &= ~MODE_PRIVATE;
3101       state->del |= MODE_PRIVATE;
3102     } else if (flag_p[0] & MODE_PRIVATE) {
3103       state->add &= ~MODE_SECRET;
3104       state->del |= MODE_SECRET;
3105     }
3106     if (flag_p[0] & MODE_DELJOINS) {
3107       state->add &= ~MODE_WASDELJOINS;
3108       state->del |= MODE_WASDELJOINS;
3109     }
3110   } else {
3111     state->add &= ~flag_p[0];
3112     state->del |= flag_p[0];
3113   }
3114
3115   assert(0 == (state->add & state->del));
3116   assert((MODE_SECRET | MODE_PRIVATE) !=
3117          (state->add & (MODE_SECRET | MODE_PRIVATE)));
3118 }
3119
3120 /*
3121  * This routine is intended to parse MODE or OPMODE commands and effect the
3122  * changes (or just build the bounce buffer).  We pass the starting offset
3123  * as a 
3124  */
3125 int
3126 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
3127            struct Channel *chptr, int parc, char *parv[], unsigned int flags,
3128            struct Membership* member)
3129 {
3130   static int chan_flags[] = {
3131     MODE_CHANOP,        'o',
3132     MODE_VOICE,         'v',
3133     MODE_PRIVATE,       'p',
3134     MODE_SECRET,        's',
3135     MODE_MODERATED,     'm',
3136     MODE_TOPICLIMIT,    't',
3137     MODE_INVITEONLY,    'i',
3138     MODE_NOPRIVMSGS,    'n',
3139     MODE_KEY,           'k',
3140     MODE_APASS,         'A',
3141     MODE_UPASS,         'U',
3142     MODE_BAN,           'b',
3143     MODE_LIMIT,         'l',
3144     MODE_REGONLY,       'r',
3145     MODE_DELJOINS,      'D',
3146     MODE_ADD,           '+',
3147     MODE_DEL,           '-',
3148     0x0, 0x0
3149   };
3150   int i;
3151   int *flag_p;
3152   unsigned int t_mode;
3153   char *modestr;
3154   struct ParseState state;
3155
3156   assert(0 != cptr);
3157   assert(0 != sptr);
3158   assert(0 != chptr);
3159   assert(0 != parc);
3160   assert(0 != parv);
3161
3162   state.mbuf = mbuf;
3163   state.cptr = cptr;
3164   state.sptr = sptr;
3165   state.chptr = chptr;
3166   state.member = member;
3167   state.parc = parc;
3168   state.parv = parv;
3169   state.flags = flags;
3170   state.dir = MODE_ADD;
3171   state.done = 0;
3172   state.add = 0;
3173   state.del = 0;
3174   state.args_used = 0;
3175   state.max_args = MAXMODEPARAMS;
3176   state.numbans = 0;
3177
3178   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
3179     state.banlist[i].next = 0;
3180     state.banlist[i].who[0] = '\0';
3181     state.banlist[i].when = 0;
3182     state.banlist[i].flags = 0;
3183     state.cli_change[i].flag = 0;
3184     state.cli_change[i].client = 0;
3185   }
3186
3187   modestr = state.parv[state.args_used++];
3188   state.parc--;
3189
3190   while (*modestr) {
3191     for (; *modestr; modestr++) {
3192       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
3193         if (flag_p[1] == *modestr)
3194           break;
3195
3196       if (!flag_p[0]) { /* didn't find it?  complain and continue */
3197         if (MyUser(state.sptr))
3198           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
3199         continue;
3200       }
3201
3202       switch (*modestr) {
3203       case '+': /* switch direction to MODE_ADD */
3204       case '-': /* switch direction to MODE_DEL */
3205         state.dir = flag_p[0];
3206         break;
3207
3208       case 'l': /* deal with limits */
3209         mode_parse_limit(&state, flag_p);
3210         break;
3211
3212       case 'k': /* deal with keys */
3213         mode_parse_key(&state, flag_p);
3214         break;
3215
3216       case 'A': /* deal with Admin passes */
3217         if (feature_bool(FEAT_OPLEVELS))
3218         mode_parse_apass(&state, flag_p);
3219         break;
3220
3221       case 'U': /* deal with user passes */
3222         if (feature_bool(FEAT_OPLEVELS))
3223         mode_parse_upass(&state, flag_p);
3224         break;
3225
3226       case 'b': /* deal with bans */
3227         mode_parse_ban(&state, flag_p);
3228         break;
3229
3230       case 'o': /* deal with ops/voice */
3231       case 'v':
3232         mode_parse_client(&state, flag_p);
3233         break;
3234
3235       default: /* deal with other modes */
3236         mode_parse_mode(&state, flag_p);
3237         break;
3238       } /* switch (*modestr) */
3239     } /* for (; *modestr; modestr++) */
3240
3241     if (state.flags & MODE_PARSE_BURST)
3242       break; /* don't interpret any more arguments */
3243
3244     if (state.parc > 0) { /* process next argument in string */
3245       modestr = state.parv[state.args_used++];
3246       state.parc--;
3247
3248       /* is it a TS? */
3249       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
3250         time_t recv_ts;
3251
3252         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
3253           break;                     /* we're then going to bounce the mode! */
3254
3255         recv_ts = atoi(modestr);
3256
3257         if (recv_ts && recv_ts < state.chptr->creationtime)
3258           state.chptr->creationtime = recv_ts; /* respect earlier TS */
3259
3260         break; /* break out of while loop */
3261       } else if (state.flags & MODE_PARSE_STRICT ||
3262                  (MyUser(state.sptr) && state.max_args <= 0)) {
3263         state.parc++; /* we didn't actually gobble the argument */
3264         state.args_used--;
3265         break; /* break out of while loop */
3266       }
3267     }
3268   } /* while (*modestr) */
3269
3270   /*
3271    * the rest of the function finishes building resultant MODEs; if the
3272    * origin isn't a member or an oper, skip it.
3273    */
3274   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
3275     return state.args_used; /* tell our parent how many args we gobbled */
3276
3277   t_mode = state.chptr->mode.mode;
3278
3279   if (state.del & t_mode) { /* delete any modes to be deleted... */
3280     modebuf_mode(state.mbuf, MODE_DEL | (state.del & t_mode));
3281
3282     t_mode &= ~state.del;
3283   }
3284   if (state.add & ~t_mode) { /* add any modes to be added... */
3285     modebuf_mode(state.mbuf, MODE_ADD | (state.add & ~t_mode));
3286
3287     t_mode |= state.add;
3288   }
3289
3290   if (state.flags & MODE_PARSE_SET) { /* set the channel modes */
3291     if ((state.chptr->mode.mode & MODE_INVITEONLY) &&
3292         !(t_mode & MODE_INVITEONLY))
3293       mode_invite_clear(state.chptr);
3294
3295     state.chptr->mode.mode = t_mode;
3296   }
3297
3298   if (state.flags & MODE_PARSE_WIPEOUT) {
3299     if (state.chptr->mode.limit && !(state.done & DONE_LIMIT))
3300       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
3301                         state.chptr->mode.limit);
3302     if (*state.chptr->mode.key && !(state.done & DONE_KEY))
3303       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
3304                           state.chptr->mode.key, 0);
3305     if (*state.chptr->mode.upass && !(state.done & DONE_UPASS))
3306       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_UPASS,
3307                           state.chptr->mode.upass, 0);
3308     if (*state.chptr->mode.apass && !(state.done & DONE_APASS))
3309       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_APASS,
3310                           state.chptr->mode.apass, 0);
3311   }
3312
3313   if (state.done & DONE_BANCLEAN) /* process bans */
3314     mode_process_bans(&state);
3315
3316   /* process client changes */
3317   if (state.cli_change[0].flag)
3318     mode_process_clients(&state);
3319
3320   return state.args_used; /* tell our parent how many args we gobbled */
3321 }
3322
3323 /*
3324  * Initialize a join buffer
3325  */
3326 void
3327 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
3328              struct Client *connect, unsigned int type, char *comment,
3329              time_t create)
3330 {
3331   int i;
3332
3333   assert(0 != jbuf);
3334   assert(0 != source);
3335   assert(0 != connect);
3336
3337   jbuf->jb_source = source; /* just initialize struct JoinBuf */
3338   jbuf->jb_connect = connect;
3339   jbuf->jb_type = type;
3340   jbuf->jb_comment = comment;
3341   jbuf->jb_create = create;
3342   jbuf->jb_count = 0;
3343   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
3344                        type == JOINBUF_TYPE_PART ||
3345                        type == JOINBUF_TYPE_PARTALL) ?
3346                       STARTJOINLEN : STARTCREATELEN) +
3347                      (comment ? strlen(comment) + 2 : 0));
3348
3349   for (i = 0; i < MAXJOINARGS; i++)
3350     jbuf->jb_channels[i] = 0;
3351 }
3352
3353 /*
3354  * Add a channel to the join buffer
3355  */
3356 void
3357 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
3358 {
3359   unsigned int len;
3360   int is_local;
3361
3362   assert(0 != jbuf);
3363
3364   if (!chan) {
3365     if (jbuf->jb_type == JOINBUF_TYPE_JOIN)
3366       sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect, "0");
3367
3368     return;
3369   }
3370
3371   is_local = IsLocalChannel(chan->chname);
3372
3373   if (jbuf->jb_type == JOINBUF_TYPE_PART ||
3374       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
3375     struct Membership *member = find_member_link(chan, jbuf->jb_source);
3376     if (IsUserParting(member))
3377       return;
3378     SetUserParting(member);
3379
3380     /* Send notification to channel */
3381     if (!(flags & (CHFL_ZOMBIE | CHFL_DELAYED)))
3382       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_PART, chan, NULL, 0,
3383                                 (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3384                                 ":%H" : "%H :%s", chan, jbuf->jb_comment);
3385     else if (MyUser(jbuf->jb_source))
3386       sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
3387                     (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3388                     ":%H" : "%H :%s", chan, jbuf->jb_comment);
3389     /* XXX: Shouldn't we send a PART here anyway? */
3390     /* to users on the channel?  Why?  From their POV, the user isn't on
3391      * the channel anymore anyway.  We don't send to servers until below,
3392      * when we gang all the channel parts together.  Note that this is
3393      * exactly the same logic, albeit somewhat more concise, as was in
3394      * the original m_part.c */
3395
3396     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3397         is_local) /* got to remove user here */
3398       remove_user_from_channel(jbuf->jb_source, chan);
3399   } else {
3400     int oplevel = !chan->mode.apass[0] ? MAXOPLEVEL
3401         : (flags & CHFL_CHANNEL_MANAGER) ? 0
3402         : 1;
3403     /* Add user to channel */
3404     if ((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))
3405       add_user_to_channel(chan, jbuf->jb_source, flags | CHFL_DELAYED, oplevel);
3406     else
3407       add_user_to_channel(chan, jbuf->jb_source, flags, oplevel);
3408
3409     /* send notification to all servers */
3410     if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !is_local)
3411     {
3412       if (flags & CHFL_CHANOP)
3413         sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
3414                               "%u:%H %Tu", oplevel, chan, chan->creationtime);
3415       else
3416         sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
3417                               "%H %Tu", chan, chan->creationtime);
3418     }
3419
3420     if (!((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))) {
3421       /* Send the notification to the channel */
3422       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_JOIN, chan, NULL, 0, "%H", chan);
3423
3424       /* send an op, too, if needed */
3425       if (flags & CHFL_CHANOP && (oplevel < MAXOPLEVEL || !MyUser(jbuf->jb_source)))
3426         sendcmdto_channel_butserv_butone((chan->mode.apass[0] ? &me : jbuf->jb_source),
3427                                          CMD_MODE, chan, NULL, 0, "%H +o %C",
3428                                          chan, jbuf->jb_source);
3429     } else if (MyUser(jbuf->jb_source))
3430       sendcmdto_one(jbuf->jb_source, CMD_JOIN, jbuf->jb_source, ":%H", chan);
3431   }
3432
3433   if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3434       jbuf->jb_type == JOINBUF_TYPE_JOIN || is_local)
3435     return; /* don't send to remote */
3436
3437   /* figure out if channel name will cause buffer to be overflowed */
3438   len = chan ? strlen(chan->chname) + 1 : 2;
3439   if (jbuf->jb_strlen + len > BUFSIZE)
3440     joinbuf_flush(jbuf);
3441
3442   /* add channel to list of channels to send and update counts */
3443   jbuf->jb_channels[jbuf->jb_count++] = chan;
3444   jbuf->jb_strlen += len;
3445
3446   /* if we've used up all slots, flush */
3447   if (jbuf->jb_count >= MAXJOINARGS)
3448     joinbuf_flush(jbuf);
3449 }
3450
3451 /*
3452  * Flush the channel list to remote servers
3453  */
3454 int
3455 joinbuf_flush(struct JoinBuf *jbuf)
3456 {
3457   char chanlist[BUFSIZE];
3458   int chanlist_i = 0;
3459   int i;
3460
3461   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3462       jbuf->jb_type == JOINBUF_TYPE_JOIN)
3463     return 0; /* no joins to process */
3464
3465   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
3466     build_string(chanlist, &chanlist_i,
3467                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
3468                  i == 0 ? '\0' : ',');
3469     if (JOINBUF_TYPE_PART == jbuf->jb_type)
3470       /* Remove user from channel */
3471       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
3472
3473     jbuf->jb_channels[i] = 0; /* mark slot empty */
3474   }
3475
3476   jbuf->jb_count = 0; /* reset base counters */
3477   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_PART ?
3478                       STARTJOINLEN : STARTCREATELEN) +
3479                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
3480
3481   /* and send the appropriate command */
3482   switch (jbuf->jb_type) {
3483   case JOINBUF_TYPE_CREATE:
3484     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
3485                           "%s %Tu", chanlist, jbuf->jb_create);
3486     break;
3487
3488   case JOINBUF_TYPE_PART:
3489     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
3490                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
3491                           jbuf->jb_comment);
3492     break;
3493   }
3494
3495   return 0;
3496 }
3497
3498 /* Returns TRUE (1) if client is invited, FALSE (0) if not */
3499 int IsInvited(struct Client* cptr, const void* chptr)
3500 {
3501   struct SLink *lp;
3502
3503   for (lp = (cli_user(cptr))->invited; lp; lp = lp->next)
3504     if (lp->value.chptr == chptr)
3505       return 1;
3506   return 0;
3507 }
3508
3509 /* RevealDelayedJoin: sends a join for a hidden user */
3510
3511 void RevealDelayedJoin(struct Membership *member)
3512 {
3513   ClearDelayedJoin(member);
3514   sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, 0, ":%H",
3515                                    member->channel);
3516   CheckDelayedJoins(member->channel);
3517 }
3518
3519 /* CheckDelayedJoins: checks and clear +d if necessary */
3520
3521 void CheckDelayedJoins(struct Channel *chan)
3522 {
3523   struct Membership *memb2;
3524
3525   if (chan->mode.mode & MODE_WASDELJOINS) {
3526     for (memb2=chan->members;memb2;memb2=memb2->next_member)
3527       if (IsDelayedJoin(memb2))
3528         break;
3529
3530     if (!memb2) {
3531       /* clear +d */
3532       chan->mode.mode &= ~MODE_WASDELJOINS;
3533       sendcmdto_channel_butserv_butone(&me, CMD_MODE, chan, NULL, 0,
3534                                        "%H -d", chan);
3535     }
3536   }
3537 }