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