Fix bug #1298149 and a similar desynch for channel keys.
[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(5, 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(5, 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       /* deal with modes that take clients */
1752       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
1753         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
1754
1755       /* deal with modes that take strings */
1756       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN | MODE_APASS | MODE_UPASS))
1757         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
1758
1759       /*
1760        * deal with the limit.  Logic here is complicated; if HACK2 is set,
1761        * we're bouncing the mode, so sense is reversed, and we have to
1762        * include the original limit if it looks like it's being removed
1763        */
1764       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
1765         build_string(strptr, strptr_i, limitbuf, 0, ' ');
1766     }
1767
1768     /* we were told to deop the source */
1769     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
1770       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
1771       addbuf[addbuf_i] = '\0'; /* terminate the string... */
1772       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
1773
1774       /* mark that we've done this, so we don't do it again */
1775       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
1776     }
1777
1778     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
1779       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
1780       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
1781                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
1782                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1783                             addbuf, remstr, addstr);
1784     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
1785       /*
1786        * If HACK2 was set, we're bouncing; we send the MODE back to the
1787        * connection we got it from with the senses reversed and a TS of 0;
1788        * origin is us
1789        */
1790       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
1791                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
1792                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
1793                     mbuf->mb_channel->creationtime);
1794     } else {
1795       /*
1796        * We're propagating a normal MODE command to the rest of the network;
1797        * we send the actual channel TS unless this is a HACK3 or a HACK4
1798        */
1799       if (IsServer(mbuf->mb_source))
1800         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1801                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
1802                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1803                               addbuf, remstr, addstr,
1804                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
1805                               mbuf->mb_channel->creationtime);
1806       else
1807         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
1808                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
1809                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
1810                               addbuf, remstr, addstr);
1811     }
1812   }
1813
1814   /* We've drained the ModeBuf... */
1815   mbuf->mb_add = 0;
1816   mbuf->mb_rem = 0;
1817   mbuf->mb_count = 0;
1818
1819   /* reinitialize the mode-with-arg slots */
1820   for (i = 0; i < MAXMODEPARAMS; i++) {
1821     /* If we saved any, pack them down */
1822     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
1823       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
1824       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
1825
1826       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
1827         continue;
1828     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
1829       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
1830
1831     MB_TYPE(mbuf, i) = 0;
1832     MB_UINT(mbuf, i) = 0;
1833   }
1834
1835   /* If we're supposed to flush it all, do so--all hail tail recursion */
1836   if (all && mbuf->mb_count)
1837     return modebuf_flush_int(mbuf, 1);
1838
1839   return 0;
1840 }
1841
1842 /** Initialise a modebuf
1843  * This routine just initializes a ModeBuf structure with the information
1844  * needed and the options given.
1845  *
1846  * @param mbuf          The mode buffer to initialise.
1847  * @param source        The client that is performing the mode.
1848  * @param connect       ?
1849  * @param chan          The channel that the mode is being performed upon.
1850  * @param dest          ?
1851  */
1852 void
1853 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
1854              struct Client *connect, struct Channel *chan, unsigned int dest)
1855 {
1856   int i;
1857
1858   assert(0 != mbuf);
1859   assert(0 != source);
1860   assert(0 != chan);
1861   assert(0 != dest);
1862
1863   if (IsLocalChannel(chan->chname)) dest &= ~MODEBUF_DEST_SERVER;
1864
1865   mbuf->mb_add = 0;
1866   mbuf->mb_rem = 0;
1867   mbuf->mb_source = source;
1868   mbuf->mb_connect = connect;
1869   mbuf->mb_channel = chan;
1870   mbuf->mb_dest = dest;
1871   mbuf->mb_count = 0;
1872
1873   /* clear each mode-with-parameter slot */
1874   for (i = 0; i < MAXMODEPARAMS; i++) {
1875     MB_TYPE(mbuf, i) = 0;
1876     MB_UINT(mbuf, i) = 0;
1877   }
1878 }
1879
1880 /** Append a new mode to a modebuf
1881  * This routine simply adds modes to be added or deleted; do a binary OR
1882  * with either MODE_ADD or MODE_DEL
1883  *
1884  * @param mbuf          Mode buffer
1885  * @param mode          MODE_ADD or MODE_DEL OR'd with MODE_PRIVATE etc.
1886  */
1887 void
1888 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
1889 {
1890   assert(0 != mbuf);
1891   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1892
1893   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
1894            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS | MODE_REGONLY |
1895            MODE_DELJOINS | MODE_WASDELJOINS);
1896
1897   if (!(mode & ~(MODE_ADD | MODE_DEL))) /* don't add empty modes... */
1898     return;
1899
1900   if (mode & MODE_ADD) {
1901     mbuf->mb_rem &= ~mode;
1902     mbuf->mb_add |= mode;
1903   } else {
1904     mbuf->mb_add &= ~mode;
1905     mbuf->mb_rem |= mode;
1906   }
1907 }
1908
1909 /** Append a mode that takes an int argument to the modebuf
1910  *
1911  * This routine adds a mode to be added or deleted that takes a unsigned
1912  * int parameter; mode may *only* be the relevant mode flag ORed with one
1913  * of MODE_ADD or MODE_DEL
1914  *
1915  * @param mbuf          The mode buffer to append to.
1916  * @param mode          The mode to append.
1917  * @param uint          The argument to the mode.
1918  */
1919 void
1920 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
1921 {
1922   assert(0 != mbuf);
1923   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1924
1925   if (mode == (MODE_LIMIT | MODE_DEL)) {
1926       mbuf->mb_rem |= mode;
1927       return;
1928   }
1929   MB_TYPE(mbuf, mbuf->mb_count) = mode;
1930   MB_UINT(mbuf, mbuf->mb_count) = uint;
1931
1932   /* when we've reached the maximal count, flush the buffer */
1933   if (++mbuf->mb_count >=
1934       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1935     modebuf_flush_int(mbuf, 0);
1936 }
1937
1938 /** append a string mode
1939  * This routine adds a mode to be added or deleted that takes a string
1940  * parameter; mode may *only* be the relevant mode flag ORed with one of
1941  * MODE_ADD or MODE_DEL
1942  *
1943  * @param mbuf          The mode buffer to append to.
1944  * @param mode          The mode to append.
1945  * @param string        The string parameter to append.
1946  * @param free          If the string should be free'd later.
1947  */
1948 void
1949 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
1950                     int free)
1951 {
1952   assert(0 != mbuf);
1953   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1954
1955   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
1956   MB_STRING(mbuf, mbuf->mb_count) = string;
1957
1958   /* when we've reached the maximal count, flush the buffer */
1959   if (++mbuf->mb_count >=
1960       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1961     modebuf_flush_int(mbuf, 0);
1962 }
1963
1964 /** Append a mode on a client to a modebuf.
1965  * This routine adds a mode to be added or deleted that takes a client
1966  * parameter; mode may *only* be the relevant mode flag ORed with one of
1967  * MODE_ADD or MODE_DEL
1968  *
1969  * @param mbuf          The modebuf to append the mode to.
1970  * @param mode          The mode to append.
1971  * @param client        The client argument to append.
1972  */
1973 void
1974 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
1975                     struct Client *client)
1976 {
1977   assert(0 != mbuf);
1978   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
1979
1980   MB_TYPE(mbuf, mbuf->mb_count) = mode;
1981   MB_CLIENT(mbuf, mbuf->mb_count) = client;
1982
1983   /* when we've reached the maximal count, flush the buffer */
1984   if (++mbuf->mb_count >=
1985       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
1986     modebuf_flush_int(mbuf, 0);
1987 }
1988
1989 /** The exported binding for modebuf_flush()
1990  *
1991  * @param mbuf  The mode buffer to flush.
1992  * 
1993  * @see modebuf_flush_int()
1994  */
1995 int
1996 modebuf_flush(struct ModeBuf *mbuf)
1997 {
1998   struct Membership *memb;
1999
2000   /* Check if MODE_WASDELJOINS should be set */
2001   if (!(mbuf->mb_channel->mode.mode & (MODE_DELJOINS | MODE_WASDELJOINS))
2002       && (mbuf->mb_rem & MODE_DELJOINS)) {
2003     for (memb = mbuf->mb_channel->members; memb; memb = memb->next_member) {
2004       if (IsDelayedJoin(memb)) {
2005           mbuf->mb_channel->mode.mode |= MODE_WASDELJOINS;
2006           mbuf->mb_add |= MODE_WASDELJOINS;
2007           mbuf->mb_rem &= ~MODE_WASDELJOINS;
2008           break;
2009       }
2010     }
2011   }
2012
2013   return modebuf_flush_int(mbuf, 1);
2014 }
2015
2016 /* This extracts the simple modes contained in mbuf
2017  *
2018  * @param mbuf          The mode buffer to extract the modes from.
2019  * @param buf           The string buffer to write the modes into.
2020  */
2021 void
2022 modebuf_extract(struct ModeBuf *mbuf, char *buf)
2023 {
2024   static int flags[] = {
2025 /*  MODE_CHANOP,        'o', */
2026 /*  MODE_VOICE,         'v', */
2027     MODE_PRIVATE,       'p',
2028     MODE_SECRET,        's',
2029     MODE_MODERATED,     'm',
2030     MODE_TOPICLIMIT,    't',
2031     MODE_INVITEONLY,    'i',
2032     MODE_NOPRIVMSGS,    'n',
2033     MODE_KEY,           'k',
2034     MODE_APASS,         'A',
2035     MODE_UPASS,         'U',
2036 /*  MODE_BAN,           'b', */
2037     MODE_LIMIT,         'l',
2038     MODE_REGONLY,       'r',
2039     MODE_DELJOINS,      'D',
2040     0x0, 0x0
2041   };
2042   unsigned int add;
2043   int i, bufpos = 0, len;
2044   int *flag_p;
2045   char *key = 0, limitbuf[20];
2046   char *apass = 0, *upass = 0;
2047
2048   assert(0 != mbuf);
2049   assert(0 != buf);
2050
2051   buf[0] = '\0';
2052
2053   add = mbuf->mb_add;
2054
2055   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
2056     if (MB_TYPE(mbuf, i) & MODE_ADD) {
2057       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT | MODE_APASS | MODE_UPASS);
2058
2059       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
2060         key = MB_STRING(mbuf, i);
2061       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
2062         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%u", MB_UINT(mbuf, i));
2063       else if (MB_TYPE(mbuf, i) & MODE_UPASS)
2064         upass = MB_STRING(mbuf, i);
2065       else if (MB_TYPE(mbuf, i) & MODE_APASS)
2066         apass = MB_STRING(mbuf, i);
2067     }
2068   }
2069
2070   if (!add)
2071     return;
2072
2073   buf[bufpos++] = '+'; /* start building buffer */
2074
2075   for (flag_p = flags; flag_p[0]; flag_p += 2)
2076     if (*flag_p & add)
2077       buf[bufpos++] = flag_p[1];
2078
2079   for (i = 0, len = bufpos; i < len; i++) {
2080     if (buf[i] == 'k')
2081       build_string(buf, &bufpos, key, 0, ' ');
2082     else if (buf[i] == 'l')
2083       build_string(buf, &bufpos, limitbuf, 0, ' ');
2084     else if (buf[i] == 'U')
2085       build_string(buf, &bufpos, upass, 0, ' ');
2086     else if (buf[i] == 'A')
2087       build_string(buf, &bufpos, apass, 0, ' ');
2088   }
2089
2090   buf[bufpos] = '\0';
2091
2092   return;
2093 }
2094
2095 /** Simple function to invalidate bans
2096  *
2097  * This function sets all bans as being valid.
2098  *
2099  * @param chan  The channel to operate on.
2100  */
2101 void
2102 mode_ban_invalidate(struct Channel *chan)
2103 {
2104   struct Membership *member;
2105
2106   for (member = chan->members; member; member = member->next_member)
2107     ClearBanValid(member);
2108 }
2109
2110 /** Simple function to drop invite structures
2111  *
2112  * Remove all the invites on the channel.
2113  *
2114  * @param chan          Channel to remove invites from.
2115  *
2116  */
2117 void
2118 mode_invite_clear(struct Channel *chan)
2119 {
2120   while (chan->invites)
2121     del_invite(chan->invites->value.cptr, chan);
2122 }
2123
2124 /* What we've done for mode_parse so far... */
2125 #define DONE_LIMIT      0x01    /**< We've set the limit */
2126 #define DONE_KEY        0x02    /**< We've set the key */
2127 #define DONE_BANLIST    0x04    /**< We've sent the ban list */
2128 #define DONE_NOTOPER    0x08    /**< We've sent a "Not oper" error */
2129 #define DONE_BANCLEAN   0x10    /**< We've cleaned bans... */
2130 #define DONE_UPASS      0x20    /**< We've set user pass */
2131 #define DONE_APASS      0x40    /**< We've set admin pass */
2132
2133 struct ParseState {
2134   struct ModeBuf *mbuf;
2135   struct Client *cptr;
2136   struct Client *sptr;
2137   struct Channel *chptr;
2138   struct Membership *member;
2139   int parc;
2140   char **parv;
2141   unsigned int flags;
2142   unsigned int dir;
2143   unsigned int done;
2144   unsigned int add;
2145   unsigned int del;
2146   int args_used;
2147   int max_args;
2148   int numbans;
2149   struct Ban banlist[MAXPARA];
2150   struct {
2151     unsigned int flag;
2152     struct Client *client;
2153   } cli_change[MAXPARA];
2154 };
2155
2156 /** Helper function to send "Not oper" or "Not member" messages
2157  * Here's a helper function to deal with sending along "Not oper" or
2158  * "Not member" messages
2159  *
2160  * @param state         Parsing State object
2161  */
2162 static void
2163 send_notoper(struct ParseState *state)
2164 {
2165   if (state->done & DONE_NOTOPER)
2166     return;
2167
2168   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
2169              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
2170
2171   state->done |= DONE_NOTOPER;
2172 }
2173
2174 /** Parse a limit
2175  * Helper function to convert limits
2176  *
2177  * @param state         Parsing state object.
2178  * @param flag_p        ?
2179  */
2180 static void
2181 mode_parse_limit(struct ParseState *state, int *flag_p)
2182 {
2183   unsigned int t_limit;
2184
2185   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
2186     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
2187       return;
2188
2189     if (state->parc <= 0) { /* warn if not enough args */
2190       if (MyUser(state->sptr))
2191         need_more_params(state->sptr, "MODE +l");
2192       return;
2193     }
2194
2195     t_limit = strtoul(state->parv[state->args_used++], 0, 10); /* grab arg */
2196     state->parc--;
2197     state->max_args--;
2198
2199     if ((int)t_limit<0) /* don't permit a negative limit */
2200       return;
2201
2202     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
2203         (!t_limit || t_limit == state->chptr->mode.limit))
2204       return;
2205   } else
2206     t_limit = state->chptr->mode.limit;
2207
2208   /* If they're not an oper, they can't change modes */
2209   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2210     send_notoper(state);
2211     return;
2212   }
2213
2214   /* Can't remove a limit that's not there */
2215   if (state->dir == MODE_DEL && !state->chptr->mode.limit)
2216     return;
2217     
2218   /* Skip if this is a burst and a lower limit than this is set already */
2219   if ((state->flags & MODE_PARSE_BURST) &&
2220       (state->chptr->mode.mode & flag_p[0]) &&
2221       (state->chptr->mode.limit < t_limit))
2222     return;
2223
2224   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
2225     return;
2226   state->done |= DONE_LIMIT;
2227
2228   if (!state->mbuf)
2229     return;
2230
2231   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
2232
2233   if (state->flags & MODE_PARSE_SET) { /* set the limit */
2234     if (state->dir & MODE_ADD) {
2235       state->chptr->mode.mode |= flag_p[0];
2236       state->chptr->mode.limit = t_limit;
2237     } else {
2238       state->chptr->mode.mode &= ~flag_p[0];
2239       state->chptr->mode.limit = 0;
2240     }
2241   }
2242 }
2243
2244 /** Helper function to clean key-like parameters. */
2245 static void
2246 clean_key(char *s)
2247 {
2248   int t_len = KEYLEN;
2249
2250   while (*s > ' ' && *s != ':' && *s != ',' && t_len--)
2251     s++;
2252   *s = '\0';
2253 }
2254
2255 /*
2256  * Helper function to convert keys
2257  */
2258 static void
2259 mode_parse_key(struct ParseState *state, int *flag_p)
2260 {
2261   char *t_str;
2262
2263   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2264     return;
2265
2266   if (state->parc <= 0) { /* warn if not enough args */
2267     if (MyUser(state->sptr))
2268       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2269                        "MODE -k");
2270     return;
2271   }
2272
2273   t_str = state->parv[state->args_used++]; /* grab arg */
2274   state->parc--;
2275   state->max_args--;
2276
2277   /* If they're not an oper, they can't change modes */
2278   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2279     send_notoper(state);
2280     return;
2281   }
2282
2283   if (state->done & DONE_KEY) /* allow key to be set only once */
2284     return;
2285   state->done |= DONE_KEY;
2286
2287   /* clean up the key string */
2288   clean_key(t_str);
2289   if (!*t_str || *t_str == ':') { /* warn if empty */
2290     if (MyUser(state->sptr))
2291       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
2292                        "MODE -k");
2293     return;
2294   }
2295
2296   if (!state->mbuf)
2297     return;
2298
2299   /* Skip if this is a burst, we have a key already and the new key is 
2300    * after the old one alphabetically */
2301   if ((state->flags & MODE_PARSE_BURST) &&
2302       *(state->chptr->mode.key) &&
2303       ircd_strcmp(state->chptr->mode.key, t_str) <= 0)
2304     return;
2305
2306   /* can't add a key if one is set, nor can one remove the wrong key */
2307   if (!(state->flags & MODE_PARSE_FORCE))
2308     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
2309         (state->dir == MODE_DEL &&
2310          ircd_strcmp(state->chptr->mode.key, t_str))) {
2311       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2312       return;
2313     }
2314
2315   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2316       !ircd_strcmp(state->chptr->mode.key, t_str))
2317     return; /* no key change */
2318
2319   if (state->flags & MODE_PARSE_BOUNCE) {
2320     if (*state->chptr->mode.key) /* reset old key */
2321       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2322                           state->chptr->mode.key, 0);
2323     else /* remove new bogus key */
2324       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2325   } else /* send new key */
2326     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2327
2328   if (state->flags & MODE_PARSE_SET) {
2329     if (state->dir == MODE_DEL) /* remove the old key */
2330       *state->chptr->mode.key = '\0';
2331     else if (!state->chptr->mode.key[0]
2332              || ircd_strcmp(t_str, state->chptr->mode.key) < 0)
2333       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
2334   }
2335 }
2336
2337 /*
2338  * Helper function to convert user passes
2339  */
2340 static void
2341 mode_parse_upass(struct ParseState *state, int *flag_p)
2342 {
2343   char *t_str;
2344
2345   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2346     return;
2347
2348   if (state->parc <= 0) { /* warn if not enough args */
2349     if (MyUser(state->sptr))
2350       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
2351                        "MODE -U");
2352     return;
2353   }
2354
2355   t_str = state->parv[state->args_used++]; /* grab arg */
2356   state->parc--;
2357   state->max_args--;
2358
2359   /* If they're not an oper, they can't change modes */
2360   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2361     send_notoper(state);
2362     return;
2363   }
2364
2365   /* If a non-service user is trying to force it, refuse. */
2366   if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
2367       && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
2368     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2369                state->chptr->chname);
2370     return;
2371   }
2372
2373   /* If they are not the channel manager, they are not allowed to change it */
2374   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
2375     if (*state->chptr->mode.apass) {
2376       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2377                  state->chptr->chname);
2378     } else {
2379       send_reply(state->sptr, ERR_NOMANAGER, state->chptr->chname);
2380     }
2381     return;
2382   }
2383
2384   if (state->done & DONE_UPASS) /* allow upass to be set only once */
2385     return;
2386   state->done |= DONE_UPASS;
2387
2388   /* clean up the upass string */
2389   clean_key(t_str);
2390   if (!*t_str || *t_str == ':') { /* warn if empty */
2391     if (MyUser(state->sptr))
2392       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +U" :
2393                        "MODE -U");
2394     return;
2395   }
2396
2397   if (!state->mbuf)
2398     return;
2399
2400   if (!(state->flags & MODE_PARSE_FORCE)) {
2401     /* can't add the upass while apass is not set */
2402     if (state->dir == MODE_ADD && !*state->chptr->mode.apass) {
2403       send_reply(state->sptr, ERR_UPASSNOTSET, state->chptr->chname, state->chptr->chname);
2404       return;
2405     }
2406     /* cannot set a +U password that is the same as +A */
2407     if (state->dir == MODE_ADD && !ircd_strcmp(state->chptr->mode.apass, t_str)) {
2408       send_reply(state->sptr, ERR_UPASS_SAME_APASS, state->chptr->chname);
2409       return;
2410     }
2411     /* can't add a upass if one is set, nor can one remove the wrong upass */
2412     if ((state->dir == MODE_ADD && *state->chptr->mode.upass) ||
2413         (state->dir == MODE_DEL &&
2414          ircd_strcmp(state->chptr->mode.upass, t_str))) {
2415       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2416       return;
2417     }
2418   }
2419
2420   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2421       !ircd_strcmp(state->chptr->mode.upass, t_str))
2422     return; /* no upass change */
2423
2424   if (state->flags & MODE_PARSE_BOUNCE) {
2425     if (*state->chptr->mode.upass) /* reset old upass */
2426       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2427                           state->chptr->mode.upass, 0);
2428     else /* remove new bogus upass */
2429       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2430   } else /* send new upass */
2431     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2432
2433   if (state->flags & MODE_PARSE_SET) {
2434     if (state->dir == MODE_DEL) /* remove the old upass */
2435       *state->chptr->mode.upass = '\0';
2436     else if (state->chptr->mode.upass[0] == '\0'
2437              || ircd_strcmp(t_str, state->chptr->mode.upass) < 0)
2438       ircd_strncpy(state->chptr->mode.upass, t_str, KEYLEN);
2439   }
2440 }
2441
2442 /*
2443  * Helper function to convert admin passes
2444  */
2445 static void
2446 mode_parse_apass(struct ParseState *state, int *flag_p)
2447 {
2448   struct Membership *memb;
2449   char *t_str;
2450
2451   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2452     return;
2453
2454   if (state->parc <= 0) { /* warn if not enough args */
2455     if (MyUser(state->sptr))
2456       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
2457                        "MODE -A");
2458     return;
2459   }
2460
2461   t_str = state->parv[state->args_used++]; /* grab arg */
2462   state->parc--;
2463   state->max_args--;
2464
2465   /* If they're not an oper, they can't change modes */
2466   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2467     send_notoper(state);
2468     return;
2469   }
2470
2471   /* If a non-service user is trying to force it, refuse. */
2472   if (state->flags & MODE_PARSE_FORCE && MyUser(state->sptr)
2473       && !HasPriv(state->sptr, PRIV_APASS_OPMODE)) {
2474     send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2475                state->chptr->chname);
2476     return;
2477   }
2478
2479   /* Don't allow to change the Apass if the channel is older than 48 hours. */
2480   if (MyUser(state->sptr)
2481       && TStime() - state->chptr->creationtime >= 172800
2482       && !IsAnOper(state->sptr)) {
2483     send_reply(state->sptr, ERR_CHANSECURED, state->chptr->chname);
2484     return;
2485   }
2486
2487   /* If they are not the channel manager, they are not allowed to change it */
2488   if (MyUser(state->sptr) && !(state->flags & MODE_PARSE_FORCE || IsChannelManager(state->member))) {
2489     if (*state->chptr->mode.apass) {
2490       send_reply(state->sptr, ERR_NOTMANAGER, state->chptr->chname,
2491                  state->chptr->chname);
2492     } else {
2493       send_reply(state->sptr, ERR_NOMANAGER, state->chptr->chname);
2494     }
2495     return;
2496   }
2497
2498   if (state->done & DONE_APASS) /* allow apass to be set only once */
2499     return;
2500   state->done |= DONE_APASS;
2501
2502   /* clean up the apass string */
2503   clean_key(t_str);
2504   if (!*t_str || *t_str == ':') { /* warn if empty */
2505     if (MyUser(state->sptr))
2506       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +A" :
2507                        "MODE -A");
2508     return;
2509   }
2510
2511   if (!state->mbuf)
2512     return;
2513
2514   if (!(state->flags & MODE_PARSE_FORCE)) {
2515     /* can't remove the apass while upass is still set */
2516     if (state->dir == MODE_DEL && *state->chptr->mode.upass) {
2517       send_reply(state->sptr, ERR_UPASSSET, state->chptr->chname, state->chptr->chname);
2518       return;
2519     }
2520     /* can't add an apass if one is set, nor can one remove the wrong apass */
2521     if ((state->dir == MODE_ADD && *state->chptr->mode.apass) ||
2522         (state->dir == MODE_DEL && ircd_strcmp(state->chptr->mode.apass, t_str))) {
2523       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
2524       return;
2525     }
2526   }
2527
2528   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
2529       !ircd_strcmp(state->chptr->mode.apass, t_str))
2530     return; /* no apass change */
2531
2532   if (state->flags & MODE_PARSE_BOUNCE) {
2533     if (*state->chptr->mode.apass) /* reset old apass */
2534       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
2535                           state->chptr->mode.apass, 0);
2536     else /* remove new bogus apass */
2537       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
2538   } else /* send new apass */
2539     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
2540
2541   if (state->flags & MODE_PARSE_SET) {
2542     if (state->dir == MODE_ADD) { /* set the new apass */
2543       /* Only accept the new apass if there is no current apass
2544        * (e.g. when a user sets it) or the new one is "less" than the
2545        * old (for resolving conflicts during burst).
2546        */
2547       if (state->chptr->mode.apass[0] == '\0'
2548           || ircd_strcmp(t_str, state->chptr->mode.apass) < 0)
2549         ircd_strncpy(state->chptr->mode.apass, t_str, KEYLEN);
2550       /* Make it VERY clear to the user that this is a one-time password */
2551       if (MyUser(state->sptr)) {
2552         send_reply(state->sptr, RPL_APASSWARN_SET, state->chptr->mode.apass);
2553         send_reply(state->sptr, RPL_APASSWARN_SECRET, state->chptr->chname,
2554                    state->chptr->mode.apass);
2555       }
2556       /* Give the channel manager level 0 ops. */
2557       if (!(state->flags & MODE_PARSE_FORCE) && IsChannelManager(state->member))
2558         SetOpLevel(state->member, 0);
2559     } else { /* remove the old apass */
2560       *state->chptr->mode.apass = '\0';
2561       if (MyUser(state->sptr))
2562         send_reply(state->sptr, RPL_APASSWARN_CLEAR);
2563       /* Revert everyone to MAXOPLEVEL. */
2564       for (memb = state->chptr->members; memb; memb = memb->next_member) {
2565         if (memb->status & MODE_CHANOP)
2566           SetOpLevel(memb, MAXOPLEVEL);
2567       }
2568     }
2569   }
2570 }
2571
2572 /** Compare one ban's extent to another.
2573  * This works very similarly to mmatch() but it knows about CIDR masks
2574  * and ban exceptions.  If both bans are CIDR-based, compare their
2575  * address bits; otherwise, use mmatch().
2576  * @param[in] old_ban One ban.
2577  * @param[in] new_ban Another ban.
2578  * @return Zero if \a old_ban is a superset of \a new_ban, non-zero otherwise.
2579  */
2580 static int
2581 bmatch(struct Ban *old_ban, struct Ban *new_ban)
2582 {
2583   int res;
2584   assert(old_ban != NULL);
2585   assert(new_ban != NULL);
2586   /* A ban is never treated as a superset of an exception. */
2587   if (!(old_ban->flags & BAN_EXCEPTION)
2588       && (new_ban->flags & BAN_EXCEPTION))
2589     return 1;
2590   /* If either is not an address mask, match the text masks. */
2591   if ((old_ban->flags & new_ban->flags & BAN_IPMASK) == 0)
2592     return mmatch(old_ban->banstr, new_ban->banstr);
2593   /* If the old ban has a longer prefix than new, it cannot be a superset. */
2594   if (old_ban->addrbits > new_ban->addrbits)
2595     return 1;
2596   /* Compare the masks before the hostname part.  */
2597   old_ban->banstr[old_ban->nu_len] = new_ban->banstr[new_ban->nu_len] = '\0';
2598   res = mmatch(old_ban->banstr, new_ban->banstr);
2599   old_ban->banstr[old_ban->nu_len] = new_ban->banstr[new_ban->nu_len] = '@';
2600   if (res)
2601     return res;
2602   /* Compare the addresses. */
2603   return !ipmask_check(&new_ban->address, &old_ban->address, old_ban->addrbits);
2604 }
2605
2606 /** Add a ban from a ban list and mark bans that should be removed
2607  * because they overlap.
2608  *
2609  * There are three invariants for a ban list.  First, no ban may be
2610  * more specific than another ban.  Second, no exception may be more
2611  * specific than another exception.  Finally, no ban may be more
2612  * specific than any exception.
2613  *
2614  * @param[in,out] banlist Pointer to head of list.
2615  * @param[in] newban Ban (or exception) to add (or remove).
2616  * @param[in] do_free If non-zero, free \a newban on failure.
2617  * @return Zero if \a newban could be applied, non-zero if not.
2618  */
2619 int apply_ban(struct Ban **banlist, struct Ban *newban, int do_free)
2620 {
2621   struct Ban *ban;
2622   size_t count = 0;
2623
2624   assert(newban->flags & (BAN_ADD|BAN_DEL));
2625   if (newban->flags & BAN_ADD) {
2626     size_t totlen = 0;
2627     /* If a less specific entry is found, fail.  */
2628     for (ban = *banlist; ban; ban = ban->next) {
2629       if (!bmatch(ban, newban)) {
2630         if (do_free)
2631           free_ban(newban);
2632         return 1;
2633       }
2634       if (!(ban->flags & (BAN_OVERLAPPED|BAN_DEL))) {
2635         count++;
2636         totlen += strlen(ban->banstr);
2637       }
2638     }
2639     /* Mark more specific entries and add this one to the end of the list. */
2640     while ((ban = *banlist) != NULL) {
2641       if (!bmatch(newban, ban)) {
2642         ban->flags |= BAN_OVERLAPPED | BAN_DEL;
2643       }
2644       banlist = &ban->next;
2645     }
2646     *banlist = newban;
2647     return 0;
2648   } else if (newban->flags & BAN_DEL) {
2649     size_t remove_count = 0;
2650     /* Mark more specific entries. */
2651     for (ban = *banlist; ban; ban = ban->next) {
2652       if (!bmatch(newban, ban)) {
2653         ban->flags |= BAN_OVERLAPPED | BAN_DEL;
2654         remove_count++;
2655       }
2656     }
2657     if (remove_count)
2658         return 0;
2659     /* If no matches were found, fail. */
2660     if (do_free)
2661       free_ban(newban);
2662     return 3;
2663   }
2664   if (do_free)
2665     free_ban(newban);
2666   return 4;
2667 }
2668
2669 /*
2670  * Helper function to convert bans
2671  */
2672 static void
2673 mode_parse_ban(struct ParseState *state, int *flag_p)
2674 {
2675   char *t_str, *s;
2676   struct Ban *ban, *newban;
2677
2678   if (state->parc <= 0) { /* Not enough args, send ban list */
2679     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
2680       send_ban_list(state->sptr, state->chptr);
2681       state->done |= DONE_BANLIST;
2682     }
2683
2684     return;
2685   }
2686
2687   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2688     return;
2689
2690   t_str = state->parv[state->args_used++]; /* grab arg */
2691   state->parc--;
2692   state->max_args--;
2693
2694   /* If they're not an oper, they can't change modes */
2695   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2696     send_notoper(state);
2697     return;
2698   }
2699
2700   if ((s = strchr(t_str, ' ')))
2701     *s = '\0';
2702
2703   if (!*t_str || *t_str == ':') { /* warn if empty */
2704     if (MyUser(state->sptr))
2705       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
2706                        "MODE -b");
2707     return;
2708   }
2709
2710   /* Clear all ADD/DEL/OVERLAPPED flags from ban list. */
2711   if (!(state->done & DONE_BANCLEAN)) {
2712     for (ban = state->chptr->banlist; ban; ban = ban->next)
2713       ban->flags &= ~(BAN_ADD | BAN_DEL | BAN_OVERLAPPED);
2714     state->done |= DONE_BANCLEAN;
2715   }
2716
2717   /* remember the ban for the moment... */
2718   newban = state->banlist + (state->numbans++);
2719   newban->next = 0;
2720   newban->flags = ((state->dir == MODE_ADD) ? BAN_ADD : BAN_DEL)
2721       | (*flag_p == MODE_BAN ? 0 : BAN_EXCEPTION);
2722   set_ban_mask(newban, collapse(pretty_mask(t_str)));
2723   ircd_strncpy(newban->who, IsUser(state->sptr) ? cli_name(state->sptr) : "*", NICKLEN);
2724   newban->when = TStime();
2725   apply_ban(&state->chptr->banlist, newban, 0);
2726 }
2727
2728 /*
2729  * This is the bottom half of the ban processor
2730  */
2731 static void
2732 mode_process_bans(struct ParseState *state)
2733 {
2734   struct Ban *ban, *newban, *prevban, *nextban;
2735   int count = 0;
2736   int len = 0;
2737   int banlen;
2738   int changed = 0;
2739
2740   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
2741     count++;
2742     banlen = strlen(ban->banstr);
2743     len += banlen;
2744     nextban = ban->next;
2745
2746     if ((ban->flags & (BAN_DEL | BAN_ADD)) == (BAN_DEL | BAN_ADD)) {
2747       if (prevban)
2748         prevban->next = 0; /* Break the list; ban isn't a real ban */
2749       else
2750         state->chptr->banlist = 0;
2751
2752       count--;
2753       len -= banlen;
2754
2755       continue;
2756     } else if (ban->flags & BAN_DEL) { /* Deleted a ban? */
2757       char *bandup;
2758       DupString(bandup, ban->banstr);
2759       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
2760                           bandup, 1);
2761
2762       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
2763         if (prevban) /* clip it out of the list... */
2764           prevban->next = ban->next;
2765         else
2766           state->chptr->banlist = ban->next;
2767
2768         count--;
2769         len -= banlen;
2770         free_ban(ban);
2771
2772         changed++;
2773         continue; /* next ban; keep prevban like it is */
2774       } else
2775         ban->flags &= BAN_IPMASK; /* unset other flags */
2776     } else if (ban->flags & BAN_ADD) { /* adding a ban? */
2777       if (prevban)
2778         prevban->next = 0; /* Break the list; ban isn't a real ban */
2779       else
2780         state->chptr->banlist = 0;
2781
2782       /* If we're supposed to ignore it, do so. */
2783       if (ban->flags & BAN_OVERLAPPED &&
2784           !(state->flags & MODE_PARSE_BOUNCE)) {
2785         count--;
2786         len -= banlen;
2787       } else {
2788         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
2789             (len > (feature_int(FEAT_AVBANLEN) * feature_int(FEAT_MAXBANS)) ||
2790              count > feature_int(FEAT_MAXBANS))) {
2791           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
2792                      ban->banstr);
2793           count--;
2794           len -= banlen;
2795         } else {
2796           char *bandup;
2797           /* add the ban to the buffer */
2798           DupString(bandup, ban->banstr);
2799           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
2800                               bandup, 1);
2801
2802           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
2803             newban = make_ban(ban->banstr);
2804             strcpy(newban->who, ban->who);
2805             newban->when = ban->when;
2806             newban->flags = ban->flags & BAN_IPMASK;
2807
2808             newban->next = state->chptr->banlist; /* and link it in */
2809             state->chptr->banlist = newban;
2810
2811             changed++;
2812           }
2813         }
2814       }
2815     }
2816
2817     prevban = ban;
2818   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
2819
2820   if (changed) /* if we changed the ban list, we must invalidate the bans */
2821     mode_ban_invalidate(state->chptr);
2822 }
2823
2824 /*
2825  * Helper function to process client changes
2826  */
2827 static void
2828 mode_parse_client(struct ParseState *state, int *flag_p)
2829 {
2830   char *t_str;
2831   struct Client *acptr;
2832   int i;
2833
2834   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
2835     return;
2836
2837   if (state->parc <= 0) /* return if not enough args */
2838     return;
2839
2840   t_str = state->parv[state->args_used++]; /* grab arg */
2841   state->parc--;
2842   state->max_args--;
2843
2844   /* If they're not an oper, they can't change modes */
2845   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2846     send_notoper(state);
2847     return;
2848   }
2849
2850   if (MyUser(state->sptr)) /* find client we're manipulating */
2851     acptr = find_chasing(state->sptr, t_str, NULL);
2852   else
2853     acptr = findNUser(t_str);
2854
2855   if (!acptr)
2856     return; /* find_chasing() already reported an error to the user */
2857
2858   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
2859     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
2860                                        state->cli_change[i].flag & flag_p[0]))
2861       break; /* found a slot */
2862
2863   /* Store what we're doing to them */
2864   state->cli_change[i].flag = state->dir | flag_p[0];
2865   state->cli_change[i].client = acptr;
2866 }
2867
2868 /*
2869  * Helper function to process the changed client list
2870  */
2871 static void
2872 mode_process_clients(struct ParseState *state)
2873 {
2874   int i;
2875   struct Membership *member;
2876
2877   for (i = 0; state->cli_change[i].flag; i++) {
2878     assert(0 != state->cli_change[i].client);
2879
2880     /* look up member link */
2881     if (!(member = find_member_link(state->chptr,
2882                                     state->cli_change[i].client)) ||
2883         (MyUser(state->sptr) && IsZombie(member))) {
2884       if (MyUser(state->sptr))
2885         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
2886                    cli_name(state->cli_change[i].client),
2887                    state->chptr->chname);
2888       continue;
2889     }
2890
2891     if ((state->cli_change[i].flag & MODE_ADD &&
2892          (state->cli_change[i].flag & member->status)) ||
2893         (state->cli_change[i].flag & MODE_DEL &&
2894          !(state->cli_change[i].flag & member->status)))
2895       continue; /* no change made, don't do anything */
2896
2897     /* see if the deop is allowed */
2898     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
2899         (MODE_DEL | MODE_CHANOP)) {
2900       /* prevent +k users from being deopped */
2901       if (IsChannelService(state->cli_change[i].client)) {
2902         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
2903           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
2904                                state->chptr,
2905                                (IsServer(state->sptr) ? cli_name(state->sptr) :
2906                                 cli_name((cli_user(state->sptr))->server)));
2907
2908         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
2909           send_reply(state->sptr, ERR_ISCHANSERVICE,
2910                      cli_name(state->cli_change[i].client),
2911                      state->chptr->chname);
2912           continue;
2913         }
2914       }
2915
2916       /* check deop for local user */
2917       if (MyUser(state->sptr)) {
2918
2919         /* don't allow local opers to be deopped on local channels */
2920         if (state->cli_change[i].client != state->sptr &&
2921             IsLocalChannel(state->chptr->chname) &&
2922             HasPriv(state->cli_change[i].client, PRIV_DEOP_LCHAN)) {
2923           send_reply(state->sptr, ERR_ISOPERLCHAN,
2924                      cli_name(state->cli_change[i].client),
2925                      state->chptr->chname);
2926           continue;
2927         }
2928
2929         /* don't allow to deop members with an op level that is <= our own level */
2930         if (state->sptr != state->cli_change[i].client          /* but allow to deop oneself */
2931             && state->chptr->mode.apass[0]
2932             && state->member
2933             && OpLevel(member) <= OpLevel(state->member)) {
2934             int equal = (OpLevel(member) == OpLevel(state->member));
2935             send_reply(state->sptr, ERR_NOTLOWEROPLEVEL,
2936                        cli_name(state->cli_change[i].client),
2937                        state->chptr->chname,
2938                        OpLevel(state->member), OpLevel(member),
2939                        "deop", equal ? "the same" : "a higher");
2940           continue;
2941         }
2942     }
2943     }
2944
2945     /* set op-level of member being opped */
2946     if ((state->cli_change[i].flag & (MODE_ADD | MODE_CHANOP)) ==
2947         (MODE_ADD | MODE_CHANOP)) {
2948       /* If being opped by an outsider, get oplevel 1 for an apass
2949        *   channel, else MAXOPLEVEL.
2950        * Otherwise, if not an apass channel, or state->member has
2951        *   MAXOPLEVEL, get oplevel MAXOPLEVEL.
2952        * Otherwise, get state->member's oplevel+1.
2953        */
2954       if (!state->member)
2955         SetOpLevel(member, state->chptr->mode.apass[0] ? 1 : MAXOPLEVEL);
2956       else if (!state->chptr->mode.apass[0] || OpLevel(state->member) == MAXOPLEVEL)
2957         SetOpLevel(member, MAXOPLEVEL);
2958       else
2959         SetOpLevel(member, OpLevel(state->member) + 1);
2960     }
2961
2962     /* actually effect the change */
2963     if (state->flags & MODE_PARSE_SET) {
2964       if (state->cli_change[i].flag & MODE_ADD) {
2965         if (IsDelayedJoin(member))
2966           RevealDelayedJoin(member);
2967         member->status |= (state->cli_change[i].flag &
2968                            (MODE_CHANOP | MODE_VOICE));
2969         if (state->cli_change[i].flag & MODE_CHANOP)
2970           ClearDeopped(member);
2971       } else
2972         member->status &= ~(state->cli_change[i].flag &
2973                             (MODE_CHANOP | MODE_VOICE));
2974     }
2975
2976     /* accumulate the change */
2977     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
2978                         state->cli_change[i].client);
2979   } /* for (i = 0; state->cli_change[i].flags; i++) */
2980 }
2981
2982 /*
2983  * Helper function to process the simple modes
2984  */
2985 static void
2986 mode_parse_mode(struct ParseState *state, int *flag_p)
2987 {
2988   /* If they're not an oper, they can't change modes */
2989   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
2990     send_notoper(state);
2991     return;
2992   }
2993
2994   if (!state->mbuf)
2995     return;
2996
2997   if (state->dir == MODE_ADD) {
2998     state->add |= flag_p[0];
2999     state->del &= ~flag_p[0];
3000
3001     if (flag_p[0] & MODE_SECRET) {
3002       state->add &= ~MODE_PRIVATE;
3003       state->del |= MODE_PRIVATE;
3004     } else if (flag_p[0] & MODE_PRIVATE) {
3005       state->add &= ~MODE_SECRET;
3006       state->del |= MODE_SECRET;
3007     }
3008     if (flag_p[0] & MODE_DELJOINS) {
3009       state->add &= ~MODE_WASDELJOINS;
3010       state->del |= MODE_WASDELJOINS;
3011     }
3012   } else {
3013     state->add &= ~flag_p[0];
3014     state->del |= flag_p[0];
3015   }
3016
3017   assert(0 == (state->add & state->del));
3018   assert((MODE_SECRET | MODE_PRIVATE) !=
3019          (state->add & (MODE_SECRET | MODE_PRIVATE)));
3020 }
3021
3022 /*
3023  * This routine is intended to parse MODE or OPMODE commands and effect the
3024  * changes (or just build the bounce buffer).  We pass the starting offset
3025  * as a 
3026  */
3027 int
3028 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
3029            struct Channel *chptr, int parc, char *parv[], unsigned int flags,
3030            struct Membership* member)
3031 {
3032   static int chan_flags[] = {
3033     MODE_CHANOP,        'o',
3034     MODE_VOICE,         'v',
3035     MODE_PRIVATE,       'p',
3036     MODE_SECRET,        's',
3037     MODE_MODERATED,     'm',
3038     MODE_TOPICLIMIT,    't',
3039     MODE_INVITEONLY,    'i',
3040     MODE_NOPRIVMSGS,    'n',
3041     MODE_KEY,           'k',
3042     MODE_APASS,         'A',
3043     MODE_UPASS,         'U',
3044     MODE_BAN,           'b',
3045     MODE_LIMIT,         'l',
3046     MODE_REGONLY,       'r',
3047     MODE_DELJOINS,      'D',
3048     MODE_ADD,           '+',
3049     MODE_DEL,           '-',
3050     0x0, 0x0
3051   };
3052   int i;
3053   int *flag_p;
3054   unsigned int t_mode;
3055   char *modestr;
3056   struct ParseState state;
3057
3058   assert(0 != cptr);
3059   assert(0 != sptr);
3060   assert(0 != chptr);
3061   assert(0 != parc);
3062   assert(0 != parv);
3063
3064   state.mbuf = mbuf;
3065   state.cptr = cptr;
3066   state.sptr = sptr;
3067   state.chptr = chptr;
3068   state.member = member;
3069   state.parc = parc;
3070   state.parv = parv;
3071   state.flags = flags;
3072   state.dir = MODE_ADD;
3073   state.done = 0;
3074   state.add = 0;
3075   state.del = 0;
3076   state.args_used = 0;
3077   state.max_args = MAXMODEPARAMS;
3078   state.numbans = 0;
3079
3080   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
3081     state.banlist[i].next = 0;
3082     state.banlist[i].who[0] = '\0';
3083     state.banlist[i].when = 0;
3084     state.banlist[i].flags = 0;
3085     state.cli_change[i].flag = 0;
3086     state.cli_change[i].client = 0;
3087   }
3088
3089   modestr = state.parv[state.args_used++];
3090   state.parc--;
3091
3092   while (*modestr) {
3093     for (; *modestr; modestr++) {
3094       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
3095         if (flag_p[1] == *modestr)
3096           break;
3097
3098       if (!flag_p[0]) { /* didn't find it?  complain and continue */
3099         if (MyUser(state.sptr))
3100           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
3101         continue;
3102       }
3103
3104       switch (*modestr) {
3105       case '+': /* switch direction to MODE_ADD */
3106       case '-': /* switch direction to MODE_DEL */
3107         state.dir = flag_p[0];
3108         break;
3109
3110       case 'l': /* deal with limits */
3111         mode_parse_limit(&state, flag_p);
3112         break;
3113
3114       case 'k': /* deal with keys */
3115         mode_parse_key(&state, flag_p);
3116         break;
3117
3118       case 'A': /* deal with Admin passes */
3119         if (IsServer(cptr) || feature_bool(FEAT_OPLEVELS))
3120         mode_parse_apass(&state, flag_p);
3121         break;
3122
3123       case 'U': /* deal with user passes */
3124         if (IsServer(cptr) || feature_bool(FEAT_OPLEVELS))
3125         mode_parse_upass(&state, flag_p);
3126         break;
3127
3128       case 'b': /* deal with bans */
3129         mode_parse_ban(&state, flag_p);
3130         break;
3131
3132       case 'o': /* deal with ops/voice */
3133       case 'v':
3134         mode_parse_client(&state, flag_p);
3135         break;
3136
3137       default: /* deal with other modes */
3138         mode_parse_mode(&state, flag_p);
3139         break;
3140       } /* switch (*modestr) */
3141     } /* for (; *modestr; modestr++) */
3142
3143     if (state.flags & MODE_PARSE_BURST)
3144       break; /* don't interpret any more arguments */
3145
3146     if (state.parc > 0) { /* process next argument in string */
3147       modestr = state.parv[state.args_used++];
3148       state.parc--;
3149
3150       /* is it a TS? */
3151       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
3152         time_t recv_ts;
3153
3154         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
3155           break;                     /* we're then going to bounce the mode! */
3156
3157         recv_ts = atoi(modestr);
3158
3159         if (recv_ts && recv_ts < state.chptr->creationtime)
3160           state.chptr->creationtime = recv_ts; /* respect earlier TS */
3161
3162         break; /* break out of while loop */
3163       } else if (state.flags & MODE_PARSE_STRICT ||
3164                  (MyUser(state.sptr) && state.max_args <= 0)) {
3165         state.parc++; /* we didn't actually gobble the argument */
3166         state.args_used--;
3167         break; /* break out of while loop */
3168       }
3169     }
3170   } /* while (*modestr) */
3171
3172   /*
3173    * the rest of the function finishes building resultant MODEs; if the
3174    * origin isn't a member or an oper, skip it.
3175    */
3176   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
3177     return state.args_used; /* tell our parent how many args we gobbled */
3178
3179   t_mode = state.chptr->mode.mode;
3180
3181   if (state.del & t_mode) { /* delete any modes to be deleted... */
3182     modebuf_mode(state.mbuf, MODE_DEL | (state.del & t_mode));
3183
3184     t_mode &= ~state.del;
3185   }
3186   if (state.add & ~t_mode) { /* add any modes to be added... */
3187     modebuf_mode(state.mbuf, MODE_ADD | (state.add & ~t_mode));
3188
3189     t_mode |= state.add;
3190   }
3191
3192   if (state.flags & MODE_PARSE_SET) { /* set the channel modes */
3193     if ((state.chptr->mode.mode & MODE_INVITEONLY) &&
3194         !(t_mode & MODE_INVITEONLY))
3195       mode_invite_clear(state.chptr);
3196
3197     state.chptr->mode.mode = t_mode;
3198   }
3199
3200   if (state.flags & MODE_PARSE_WIPEOUT) {
3201     if (state.chptr->mode.limit && !(state.done & DONE_LIMIT))
3202       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
3203                         state.chptr->mode.limit);
3204     if (*state.chptr->mode.key && !(state.done & DONE_KEY))
3205       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
3206                           state.chptr->mode.key, 0);
3207     if (*state.chptr->mode.upass && !(state.done & DONE_UPASS))
3208       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_UPASS,
3209                           state.chptr->mode.upass, 0);
3210     if (*state.chptr->mode.apass && !(state.done & DONE_APASS))
3211       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_APASS,
3212                           state.chptr->mode.apass, 0);
3213   }
3214
3215   if (state.done & DONE_BANCLEAN) /* process bans */
3216     mode_process_bans(&state);
3217
3218   /* process client changes */
3219   if (state.cli_change[0].flag)
3220     mode_process_clients(&state);
3221
3222   return state.args_used; /* tell our parent how many args we gobbled */
3223 }
3224
3225 /*
3226  * Initialize a join buffer
3227  */
3228 void
3229 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
3230              struct Client *connect, unsigned int type, char *comment,
3231              time_t create)
3232 {
3233   int i;
3234
3235   assert(0 != jbuf);
3236   assert(0 != source);
3237   assert(0 != connect);
3238
3239   jbuf->jb_source = source; /* just initialize struct JoinBuf */
3240   jbuf->jb_connect = connect;
3241   jbuf->jb_type = type;
3242   jbuf->jb_comment = comment;
3243   jbuf->jb_create = create;
3244   jbuf->jb_count = 0;
3245   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
3246                        type == JOINBUF_TYPE_PART ||
3247                        type == JOINBUF_TYPE_PARTALL) ?
3248                       STARTJOINLEN : STARTCREATELEN) +
3249                      (comment ? strlen(comment) + 2 : 0));
3250
3251   for (i = 0; i < MAXJOINARGS; i++)
3252     jbuf->jb_channels[i] = 0;
3253 }
3254
3255 /*
3256  * Add a channel to the join buffer
3257  */
3258 void
3259 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
3260 {
3261   unsigned int len;
3262   int is_local;
3263
3264   assert(0 != jbuf);
3265
3266   if (!chan) {
3267     sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect, "0");
3268     return;
3269   }
3270
3271   is_local = IsLocalChannel(chan->chname);
3272
3273   if (jbuf->jb_type == JOINBUF_TYPE_PART ||
3274       jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
3275     struct Membership *member = find_member_link(chan, jbuf->jb_source);
3276     if (IsUserParting(member))
3277       return;
3278     SetUserParting(member);
3279
3280     /* Send notification to channel */
3281     if (!(flags & (CHFL_ZOMBIE | CHFL_DELAYED)))
3282       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_PART, chan, NULL, 0,
3283                                 (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3284                                 ":%H" : "%H :%s", chan, jbuf->jb_comment);
3285     else if (MyUser(jbuf->jb_source))
3286       sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
3287                     (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3288                     ":%H" : "%H :%s", chan, jbuf->jb_comment);
3289     /* XXX: Shouldn't we send a PART here anyway? */
3290     /* to users on the channel?  Why?  From their POV, the user isn't on
3291      * the channel anymore anyway.  We don't send to servers until below,
3292      * when we gang all the channel parts together.  Note that this is
3293      * exactly the same logic, albeit somewhat more concise, as was in
3294      * the original m_part.c */
3295
3296     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3297         is_local) /* got to remove user here */
3298       remove_user_from_channel(jbuf->jb_source, chan);
3299   } else {
3300     int oplevel = !chan->mode.apass[0] ? MAXOPLEVEL
3301         : (flags & CHFL_CHANNEL_MANAGER) ? 0
3302         : 1;
3303     /* Add user to channel */
3304     if ((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))
3305       add_user_to_channel(chan, jbuf->jb_source, flags | CHFL_DELAYED, oplevel);
3306     else
3307       add_user_to_channel(chan, jbuf->jb_source, flags, oplevel);
3308
3309     /* send notification to all servers */
3310     if (jbuf->jb_type != JOINBUF_TYPE_CREATE && !is_local)
3311     {
3312       if (flags & CHFL_CHANOP) {
3313         assert(oplevel == 0 || oplevel == 1);
3314         sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
3315                               "%u:%H %Tu", oplevel, chan, chan->creationtime);
3316       } else
3317         sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
3318                               "%H %Tu", chan, chan->creationtime);
3319     }
3320
3321     if (!((chan->mode.mode & MODE_DELJOINS) && !(flags & CHFL_VOICED_OR_OPPED))) {
3322       /* Send the notification to the channel */
3323       sendcmdto_channel_butserv_butone(jbuf->jb_source, CMD_JOIN, chan, NULL, 0, "%H", chan);
3324
3325       /* send an op, too, if needed */
3326       if (flags & CHFL_CHANOP && (oplevel < MAXOPLEVEL || !MyUser(jbuf->jb_source)))
3327         sendcmdto_channel_butserv_butone((chan->mode.apass[0] ? &his : jbuf->jb_source),
3328                                          CMD_MODE, chan, NULL, 0, "%H +o %C",
3329                                          chan, jbuf->jb_source);
3330     } else if (MyUser(jbuf->jb_source))
3331       sendcmdto_one(jbuf->jb_source, CMD_JOIN, jbuf->jb_source, ":%H", chan);
3332   }
3333
3334   if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3335       jbuf->jb_type == JOINBUF_TYPE_JOIN || is_local)
3336     return; /* don't send to remote */
3337
3338   /* figure out if channel name will cause buffer to be overflowed */
3339   len = chan ? strlen(chan->chname) + 1 : 2;
3340   if (jbuf->jb_strlen + len > BUFSIZE)
3341     joinbuf_flush(jbuf);
3342
3343   /* add channel to list of channels to send and update counts */
3344   jbuf->jb_channels[jbuf->jb_count++] = chan;
3345   jbuf->jb_strlen += len;
3346
3347   /* if we've used up all slots, flush */
3348   if (jbuf->jb_count >= MAXJOINARGS)
3349     joinbuf_flush(jbuf);
3350 }
3351
3352 /*
3353  * Flush the channel list to remote servers
3354  */
3355 int
3356 joinbuf_flush(struct JoinBuf *jbuf)
3357 {
3358   char chanlist[BUFSIZE];
3359   int chanlist_i = 0;
3360   int i;
3361
3362   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3363       jbuf->jb_type == JOINBUF_TYPE_JOIN)
3364     return 0; /* no joins to process */
3365
3366   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
3367     build_string(chanlist, &chanlist_i,
3368                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
3369                  i == 0 ? '\0' : ',');
3370     if (JOINBUF_TYPE_PART == jbuf->jb_type)
3371       /* Remove user from channel */
3372       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
3373
3374     jbuf->jb_channels[i] = 0; /* mark slot empty */
3375   }
3376
3377   jbuf->jb_count = 0; /* reset base counters */
3378   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_PART ?
3379                       STARTJOINLEN : STARTCREATELEN) +
3380                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
3381
3382   /* and send the appropriate command */
3383   switch (jbuf->jb_type) {
3384   case JOINBUF_TYPE_CREATE:
3385     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
3386                           "%s %Tu", chanlist, jbuf->jb_create);
3387     break;
3388
3389   case JOINBUF_TYPE_PART:
3390     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
3391                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
3392                           jbuf->jb_comment);
3393     break;
3394   }
3395
3396   return 0;
3397 }
3398
3399 /* Returns TRUE (1) if client is invited, FALSE (0) if not */
3400 int IsInvited(struct Client* cptr, const void* chptr)
3401 {
3402   struct SLink *lp;
3403
3404   for (lp = (cli_user(cptr))->invited; lp; lp = lp->next)
3405     if (lp->value.chptr == chptr)
3406       return 1;
3407   return 0;
3408 }
3409
3410 /* RevealDelayedJoin: sends a join for a hidden user */
3411
3412 void RevealDelayedJoin(struct Membership *member)
3413 {
3414   ClearDelayedJoin(member);
3415   sendcmdto_channel_butserv_butone(member->user, CMD_JOIN, member->channel, member->user, 0, ":%H",
3416                                    member->channel);
3417   CheckDelayedJoins(member->channel);
3418 }
3419
3420 /* CheckDelayedJoins: checks and clear +d if necessary */
3421
3422 void CheckDelayedJoins(struct Channel *chan)
3423 {
3424   struct Membership *memb2;
3425
3426   if (chan->mode.mode & MODE_WASDELJOINS) {
3427     for (memb2=chan->members;memb2;memb2=memb2->next_member)
3428       if (IsDelayedJoin(memb2))
3429         break;
3430
3431     if (!memb2) {
3432       /* clear +d */
3433       chan->mode.mode &= ~MODE_WASDELJOINS;
3434       sendcmdto_channel_butserv_butone(&his, CMD_MODE, chan, NULL, 0,
3435                                        "%H -d", chan);
3436     }
3437   }
3438 }