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