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