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