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