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