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