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