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