560bcadb8ca93432ba34d3fa649dc3b26410b2b5
[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  * $Id$
21  */
22 #include "channel.h"
23 #include "client.h"
24 #include "hash.h"
25 #include "ircd.h"
26 #include "ircd_alloc.h"
27 #include "ircd_chattr.h"
28 #include "ircd_reply.h"
29 #include "ircd_snprintf.h"
30 #include "ircd_string.h"
31 #include "list.h"
32 #include "match.h"
33 #include "msg.h"
34 #include "numeric.h"
35 #include "numnicks.h"
36 #include "querycmds.h"
37 #include "s_bsd.h"
38 #include "s_conf.h"
39 #include "s_debug.h"
40 #include "s_misc.h"
41 #include "s_user.h"
42 #include "send.h"
43 #include "sprintf_irc.h"
44 #include "struct.h"
45 #include "support.h"
46 #include "sys.h"
47 #include "whowas.h"
48
49 #include <assert.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53
54 struct Channel* GlobalChannelList = 0;
55
56 static struct SLink *next_overlapped_ban(void);
57 static int del_banid(struct Channel *, char *, int);
58 void del_invite(struct Client *, struct Channel *);
59
60 const char* const PartFmt1     = ":%s " MSG_PART " %s";
61 const char* const PartFmt2     = ":%s " MSG_PART " %s :%s";
62 const char* const PartFmt1serv = "%s%s " TOK_PART " %s";
63 const char* const PartFmt2serv = "%s%s " TOK_PART " %s :%s";
64
65
66 static struct SLink* next_ban;
67 static struct SLink* prev_ban;
68 static struct SLink* removed_bans_list;
69
70 /*
71  * Use a global variable to remember if an oper set a mode on a local channel. Ugly,
72  * but the only way to do it without changing set_mode intensively.
73  */
74 int LocalChanOperMode = 0;
75
76 #if !defined(NDEBUG)
77 /*
78  * return the length (>=0) of a chain of links.
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 struct Membership* find_member_link(struct Channel* chptr, const struct Client* cptr)
91 {
92   struct Membership *m;
93   assert(0 != cptr);
94   assert(0 != chptr);
95   
96   /* Servers don't have member links */
97   if (IsServer(cptr))
98      return 0;
99   
100   /* +k users are typically on a LOT of channels.  So we iterate over who
101    * is in the channel.  X/W are +k and are in about 5800 channels each.
102    * however there are typically no more than 1000 people in a channel
103    * at a time.
104    */
105   if (IsChannelService(cptr)) {
106     m = chptr->members;
107     while (m) {
108       assert(m->channel == chptr);
109       if (m->user == cptr)
110         return m;
111       m = m->next_member;
112     }
113   }
114   /* Users on the other hand aren't allowed on more than 15 channels.  50%
115    * of users that are on channels are on 2 or less, 95% are on 7 or less,
116    * and 99% are on 10 or less.
117    */
118   else {
119    m = cptr->user->channel;
120    while (m) {
121      assert(m->user == cptr);
122      if (m->channel == chptr)
123        return m;
124      m = m->next_channel;
125    }
126   }
127   return 0;
128 }
129
130 /*
131  * find_chasing - Find the client structure for a nick name (user)
132  * using history mechanism if necessary. If the client is not found, an error
133  * message (NO SUCH NICK) is generated. If the client was found
134  * through the history, chasing will be 1 and otherwise 0.
135  */
136 struct Client* find_chasing(struct Client* sptr, const char* user, int* chasing)
137 {
138   struct Client* who = FindClient(user);
139
140   if (chasing)
141     *chasing = 0;
142   if (who)
143     return who;
144
145   if (!(who = get_history(user, KILLCHASETIMELIMIT))) {
146     send_reply(sptr, ERR_NOSUCHNICK, user);
147     return 0;
148   }
149   if (chasing)
150     *chasing = 1;
151   return who;
152 }
153
154 /*
155  * Create a string of form "foo!bar@fubar" given foo, bar and fubar
156  * as the parameters.  If NULL, they become "*".
157  */
158 static char *make_nick_user_host(const char *nick, const char *name,
159                                  const char *host)
160 {
161   static char namebuf[NICKLEN + USERLEN + HOSTLEN + 3];
162   sprintf_irc(namebuf, "%s!%s@%s", nick, name, host);
163   return namebuf;
164 }
165
166 /*
167  * Create a string of form "foo!bar@123.456.789.123" given foo, bar and the
168  * IP-number as the parameters.  If NULL, they become "*".
169  */
170 static char *make_nick_user_ip(char *nick, char *name, struct in_addr ip)
171 {
172   static char ipbuf[NICKLEN + USERLEN + 16 + 3];
173   sprintf_irc(ipbuf, "%s!%s@%s", nick, name, ircd_ntoa((const char*) &ip));
174   return ipbuf;
175 }
176
177 #if 0
178 static int DoesOp(const char* modebuf)
179 {
180   assert(0 != modebuf);
181   while (*modebuf) {
182     if (*modebuf == 'o' || *modebuf == 'v')
183       return 1;
184     ++modebuf;
185   }
186   return 0;
187 }
188
189 /*
190  * This function should be removed when all servers are 2.10
191  */
192 static void sendmodeto_one(struct Client* cptr, const char* from,
193                            const char* name, const char* mode,
194                            const char* param, time_t creationtime)
195 {
196   if (IsServer(cptr) && DoesOp(mode) && creationtime)
197     sendto_one(cptr, ":%s MODE %s %s %s " TIME_T_FMT, /* XXX DEAD */
198                from, name, mode, param, creationtime);
199   else
200     sendto_one(cptr, ":%s MODE %s %s %s", from, name, mode, param); /* XXX DEAD */
201 }
202 #endif /* 0 */
203
204 /*
205  * Subtract one user from channel i (and free channel
206  * block, if channel became empty).
207  * Returns: true  (1) if channel still exists
208  *          false (0) if the channel was destroyed
209  */
210 int sub1_from_channel(struct Channel* chptr)
211 {
212   struct SLink *tmp;
213   struct SLink *obtmp;
214
215   if (chptr->users > 1)         /* Can be 0, called for an empty channel too */
216   {
217     assert(0 != chptr->members);
218     --chptr->users;
219     return 1;
220   }
221
222   assert(0 == chptr->members);
223
224   /* Channel became (or was) empty: Remove channel */
225   if (is_listed(chptr))
226   {
227     int i;
228     for (i = 0; i <= HighestFd; i++)
229     {
230       struct Client *acptr;
231       if ((acptr = LocalClientArray[i]) && acptr->listing &&
232           acptr->listing->chptr == chptr)
233       {
234         list_next_channels(acptr, 1);
235         break;                  /* Only one client can list a channel */
236       }
237     }
238   }
239   /*
240    * Now, find all invite links from channel structure
241    */
242   while ((tmp = chptr->invites))
243     del_invite(tmp->value.cptr, chptr);
244
245   tmp = chptr->banlist;
246   while (tmp)
247   {
248     obtmp = tmp;
249     tmp = tmp->next;
250     MyFree(obtmp->value.ban.banstr);
251     MyFree(obtmp->value.ban.who);
252     free_link(obtmp);
253   }
254   if (chptr->prev)
255     chptr->prev->next = chptr->next;
256   else
257     GlobalChannelList = chptr->next;
258   if (chptr->next)
259     chptr->next->prev = chptr->prev;
260   hRemChannel(chptr);
261   --UserStats.channels;
262   /*
263    * make sure that channel actually got removed from hash table
264    */
265   assert(chptr->hnext == chptr);
266   MyFree(chptr);
267   return 0;
268 }
269
270 /*
271  * add_banid
272  *
273  * `cptr' must be the client adding the ban.
274  *
275  * If `change' is true then add `banid' to channel `chptr'.
276  * Returns 0 if the ban was added.
277  * Returns -2 if the ban already existed and was marked CHFL_BURST_BAN_WIPEOUT.
278  * Return -1 otherwise.
279  *
280  * Those bans that overlapped with `banid' are flagged with CHFL_BAN_OVERLAPPED
281  * when `change' is false, otherwise they will be removed from the banlist.
282  * Subsequently calls to next_overlapped_ban() or next_removed_overlapped_ban()
283  * respectively will return these bans until NULL is returned.
284  *
285  * If `firsttime' is true, the ban list as returned by next_overlapped_ban()
286  * is reset (unless a non-zero value is returned, in which case the
287  * CHFL_BAN_OVERLAPPED flag might not have been reset!).
288  *
289  * --Run
290  */
291 int add_banid(struct Client *cptr, struct Channel *chptr, char *banid,
292                      int change, int firsttime)
293 {
294   struct SLink*  ban;
295   struct SLink** banp;
296   int            cnt = 0;
297   int            removed_bans = 0;
298   int            len = strlen(banid);
299
300   if (firsttime)
301   {
302     next_ban = NULL;
303     assert(0 == prev_ban);
304     assert(0 == removed_bans_list);
305   }
306   if (MyUser(cptr))
307     collapse(banid);
308   for (banp = &chptr->banlist; *banp;)
309   {
310     len += strlen((*banp)->value.ban.banstr);
311     ++cnt;
312     if (((*banp)->flags & CHFL_BURST_BAN_WIPEOUT))
313     {
314       if (!strcmp((*banp)->value.ban.banstr, banid))
315       {
316         (*banp)->flags &= ~CHFL_BURST_BAN_WIPEOUT;
317         return -2;
318       }
319     }
320     else if (!mmatch((*banp)->value.ban.banstr, banid))
321       return -1;
322     if (!mmatch(banid, (*banp)->value.ban.banstr))
323     {
324       struct SLink *tmp = *banp;
325       if (change)
326       {
327         if (MyUser(cptr))
328         {
329           cnt--;
330           len -= strlen(tmp->value.ban.banstr);
331         }
332         *banp = tmp->next;
333 #if 0
334         /* Silently remove overlapping bans */
335         MyFree(tmp->value.ban.banstr);
336         MyFree(tmp->value.ban.who);
337         free_link(tmp);
338         tmp = 0;
339 #else
340         /* These will be sent to the user later as -b */
341         tmp->next = removed_bans_list;
342         removed_bans_list = tmp;
343         removed_bans = 1;
344 #endif
345       }
346       else if (!(tmp->flags & CHFL_BURST_BAN_WIPEOUT))
347       {
348         tmp->flags |= CHFL_BAN_OVERLAPPED;
349         if (!next_ban)
350           next_ban = tmp;
351         banp = &tmp->next;
352       }
353       else
354         banp = &tmp->next;
355     }
356     else
357     {
358       if (firsttime)
359         (*banp)->flags &= ~CHFL_BAN_OVERLAPPED;
360       banp = &(*banp)->next;
361     }
362   }
363   if (MyUser(cptr) && !removed_bans && (len > MAXBANLENGTH || (cnt >= MAXBANS)))
364   {
365     send_reply(cptr, ERR_BANLISTFULL, chptr->chname, banid);
366     return -1;
367   }
368   if (change)
369   {
370     char*              ip_start;
371     struct Membership* member;
372     ban = make_link();
373     ban->next = chptr->banlist;
374
375     ban->value.ban.banstr = (char*) MyMalloc(strlen(banid) + 1);
376     assert(0 != ban->value.ban.banstr);
377     strcpy(ban->value.ban.banstr, banid);
378
379     ban->value.ban.who = (char*) MyMalloc(strlen(cptr->name) + 1);
380     assert(0 != ban->value.ban.who);
381     strcpy(ban->value.ban.who, cptr->name);
382
383     ban->value.ban.when = TStime();
384     ban->flags = CHFL_BAN;      /* This bit is never used I think... */
385     if ((ip_start = strrchr(banid, '@')) && check_if_ipmask(ip_start + 1))
386       ban->flags |= CHFL_BAN_IPMASK;
387     chptr->banlist = ban;
388
389     /*
390      * Erase ban-valid-bit
391      */
392     for (member = chptr->members; member; member = member->next_member)
393       ClearBanValid(member);     /* `ban' == channel member ! */
394   }
395   return 0;
396 }
397
398 static struct SLink *next_overlapped_ban(void)
399 {
400   struct SLink *tmp = next_ban;
401   if (tmp)
402   {
403     struct SLink *ban;
404     for (ban = tmp->next; ban; ban = ban->next)
405       if ((ban->flags & CHFL_BAN_OVERLAPPED))
406         break;
407     next_ban = ban;
408   }
409   return tmp;
410 }
411
412 struct SLink *next_removed_overlapped_ban(void)
413 {
414   struct SLink *tmp = removed_bans_list;
415   if (prev_ban)
416   {
417     if (prev_ban->value.ban.banstr)     /* Can be set to NULL in set_mode() */
418       MyFree(prev_ban->value.ban.banstr);
419     MyFree(prev_ban->value.ban.who);
420     free_link(prev_ban);
421     prev_ban = 0;
422   }
423   if (tmp)
424     removed_bans_list = removed_bans_list->next;
425   prev_ban = tmp;
426   return tmp;
427 }
428
429 /*
430  * del_banid
431  *
432  * If `change' is true, delete `banid' from channel `chptr'.
433  * Returns `false' if removal was (or would have been) successful.
434  */
435 static int del_banid(struct Channel *chptr, char *banid, int change)
436 {
437   struct SLink **ban;
438   struct SLink *tmp;
439
440   if (!banid)
441     return -1;
442   for (ban = &(chptr->banlist); *ban; ban = &((*ban)->next)) {
443     if (0 == ircd_strcmp(banid, (*ban)->value.ban.banstr))
444     {
445       tmp = *ban;
446       if (change)
447       {
448         struct Membership* member;
449         *ban = tmp->next;
450         MyFree(tmp->value.ban.banstr);
451         MyFree(tmp->value.ban.who);
452         free_link(tmp);
453         /*
454          * Erase ban-valid-bit, for channel members that are banned
455          */
456         for (member = chptr->members; member; member = member->next_member)
457           if (CHFL_BANVALIDMASK == (member->status & CHFL_BANVALIDMASK))
458             ClearBanValid(member);       /* `tmp' == channel member */
459       }
460       return 0;
461     }
462   }
463   return -1;
464 }
465
466 /*
467  * find_channel_member - returns Membership * if a person is joined and not a zombie
468  */
469 struct Membership* find_channel_member(struct Client* cptr, struct Channel* chptr)
470 {
471   struct Membership* member;
472   assert(0 != chptr);
473
474   member = find_member_link(chptr, cptr);
475   return (member && !IsZombie(member)) ? member : 0;
476 }
477
478 /*
479  * is_banned - a non-zero value if banned else 0.
480  */
481 static int is_banned(struct Client *cptr, struct Channel *chptr,
482                      struct Membership* member)
483 {
484   struct SLink* tmp;
485   char*         s;
486   char*         ip_s = NULL;
487
488   if (!IsUser(cptr))
489     return 0;
490
491   if (member && IsBanValid(member))
492     return IsBanned(member);
493
494   s = make_nick_user_host(cptr->name, cptr->user->username, cptr->user->host);
495
496   for (tmp = chptr->banlist; tmp; tmp = tmp->next) {
497     if ((tmp->flags & CHFL_BAN_IPMASK)) {
498       if (!ip_s)
499         ip_s = make_nick_user_ip(cptr->name, cptr->user->username, cptr->ip);
500       if (match(tmp->value.ban.banstr, ip_s) == 0)
501         break;
502     }
503     else if (match(tmp->value.ban.banstr, s) == 0)
504       break;
505   }
506
507   if (member) {
508     SetBanValid(member);
509     if (tmp) {
510       SetBanned(member);
511       return 1;
512     }
513     else {
514       ClearBanned(member);
515       return 0;
516     }
517   }
518
519   return (tmp != NULL);
520 }
521
522 /*
523  * adds a user to a channel by adding another link to the channels member
524  * chain.
525  */
526 void add_user_to_channel(struct Channel* chptr, struct Client* who,
527                                 unsigned int flags)
528 {
529   assert(0 != chptr);
530   assert(0 != who);
531
532   if (who->user) {
533     struct Membership* member = 
534             (struct Membership*) MyMalloc(sizeof(struct Membership));
535     assert(0 != member);
536     member->user         = who;
537     member->channel      = chptr;
538     member->status       = flags;
539
540     member->next_member  = chptr->members;
541     if (member->next_member)
542       member->next_member->prev_member = member;
543     member->prev_member  = 0; 
544     chptr->members       = member;
545
546     member->next_channel = who->user->channel;
547     if (member->next_channel)
548       member->next_channel->prev_channel = member;
549     member->prev_channel = 0;
550     who->user->channel = member;
551
552     ++chptr->users;
553     ++who->user->joined;
554   }
555 }
556
557 static int remove_member_from_channel(struct Membership* member)
558 {
559   struct Channel* chptr;
560   assert(0 != member);
561   chptr = member->channel;
562   /*
563    * unlink channel member list
564    */
565   if (member->next_member)
566     member->next_member->prev_member = member->prev_member;
567   if (member->prev_member)
568     member->prev_member->next_member = member->next_member;
569   else
570     member->channel->members = member->next_member; 
571       
572   /*
573    * unlink client channel list
574    */
575   if (member->next_channel)
576     member->next_channel->prev_channel = member->prev_channel;
577   if (member->prev_channel)
578     member->prev_channel->next_channel = member->next_channel;
579   else
580     member->user->user->channel = member->next_channel;
581
582   --member->user->user->joined;
583   MyFree(member);
584
585   return sub1_from_channel(chptr);
586 }
587
588 static int channel_all_zombies(struct Channel* chptr)
589 {
590   struct Membership* member;
591
592   for (member = chptr->members; member; member = member->next_member) {
593     if (!IsZombie(member))
594       return 0;
595   }
596   return 1;
597 }
598       
599
600 void remove_user_from_channel(struct Client* cptr, struct Channel* chptr)
601 {
602   
603   struct Membership* member;
604   assert(0 != chptr);
605
606   if ((member = find_member_link(chptr, cptr))) {
607     if (remove_member_from_channel(member)) {
608       if (channel_all_zombies(chptr)) {
609         /*
610          * XXX - this looks dangerous but isn't if we got the referential
611          * integrity right for channels
612          */
613         while (remove_member_from_channel(chptr->members))
614           ;
615       }
616     }
617   }
618 }
619
620 void remove_user_from_all_channels(struct Client* cptr)
621 {
622   struct Membership* chan;
623   assert(0 != cptr);
624   assert(0 != cptr->user);
625
626   while ((chan = cptr->user->channel))
627     remove_user_from_channel(cptr, chan->channel);
628 }
629
630 int is_chan_op(struct Client *cptr, struct Channel *chptr)
631 {
632   struct Membership* member;
633   assert(chptr);
634   if ((member = find_member_link(chptr, cptr)))
635     return (!IsZombie(member) && IsChanOp(member));
636
637   return 0;
638 }
639
640 static int is_deopped(struct Client *cptr, struct Channel *chptr)
641 {
642   struct Membership* member;
643
644   assert(0 != chptr);
645   if ((member = find_member_link(chptr, cptr)))
646     return IsDeopped(member);
647
648   return (IsUser(cptr) ? 1 : 0);
649 }
650
651 int is_zombie(struct Client *cptr, struct Channel *chptr)
652 {
653   struct Membership* member;
654
655   assert(0 != chptr);
656
657   if ((member = find_member_link(chptr, cptr)))
658       return IsZombie(member);
659   return 0;
660 }
661
662 int has_voice(struct Client* cptr, struct Channel* chptr)
663 {
664   struct Membership* member;
665
666   assert(0 != chptr);
667   if ((member = find_member_link(chptr, cptr)))
668     return (!IsZombie(member) && HasVoice(member));
669
670   return 0;
671 }
672
673 int member_can_send_to_channel(struct Membership* member)
674 {
675   assert(0 != member);
676
677   if (IsVoicedOrOpped(member))
678     return 1;
679   /*
680    * If it's moderated, and you aren't a priviledged user, you can't
681    * speak.  
682    */
683   if (member->channel->mode.mode & MODE_MODERATED)
684     return 0;
685   /*
686    * If you're banned then you can't speak either.
687    * but because of the amount of CPU time that is_banned chews
688    * we only check it for our clients.
689    */
690   if (MyUser(member->user) && is_banned(member->user, member->channel, member))
691     return 0;
692   return 1;
693 }
694
695 int client_can_send_to_channel(struct Client *cptr, struct Channel *chptr)
696 {
697   struct Membership *member;
698   assert(0 != cptr); 
699   /*
700    * Servers can always speak on channels.
701    */
702   if (IsServer(cptr))
703     return 1;
704
705   member = find_channel_member(cptr, chptr);
706
707   /*
708    * You can't speak if your off channel, if the channel is modeless, or
709    * +n.(no external messages)
710    */
711   if (!member) {
712     if ((chptr->mode.mode & MODE_NOPRIVMSGS) || IsModelessChannel(chptr->chname)) 
713       return 0;
714     else
715       return 1;
716   }
717   return member_can_send_to_channel(member); 
718 }
719
720 /*
721  * find_no_nickchange_channel
722  * if a member and not opped or voiced and banned
723  * return the name of the first channel banned on
724  */
725 const char* find_no_nickchange_channel(struct Client* cptr)
726 {
727   if (MyUser(cptr)) {
728     struct Membership* member;
729     for (member = cptr->user->channel; member; member = member->next_channel) {
730       if (!IsVoicedOrOpped(member) && is_banned(cptr, member->channel, member))
731         return member->channel->chname;
732     }
733   }
734   return 0;
735 }
736
737
738 /*
739  * write the "simple" list of channel modes for channel chptr onto buffer mbuf
740  * with the parameters in pbuf.
741  */
742 void channel_modes(struct Client *cptr, char *mbuf, char *pbuf,
743                           struct Channel *chptr)
744 {
745   assert(0 != mbuf);
746   assert(0 != pbuf);
747   assert(0 != chptr);
748
749   *mbuf++ = '+';
750   if (chptr->mode.mode & MODE_SECRET)
751     *mbuf++ = 's';
752   else if (chptr->mode.mode & MODE_PRIVATE)
753     *mbuf++ = 'p';
754   if (chptr->mode.mode & MODE_MODERATED)
755     *mbuf++ = 'm';
756   if (chptr->mode.mode & MODE_TOPICLIMIT)
757     *mbuf++ = 't';
758   if (chptr->mode.mode & MODE_INVITEONLY)
759     *mbuf++ = 'i';
760   if (chptr->mode.mode & MODE_NOPRIVMSGS)
761     *mbuf++ = 'n';
762   if (chptr->mode.limit) {
763     *mbuf++ = 'l';
764     sprintf_irc(pbuf, "%d", chptr->mode.limit);
765   }
766
767   if (*chptr->mode.key) {
768     *mbuf++ = 'k';
769     if (is_chan_op(cptr, chptr) || IsServer(cptr)) {
770       if (chptr->mode.limit)
771         strcat(pbuf, " ");
772       strcat(pbuf, chptr->mode.key);
773     }
774   }
775   *mbuf = '\0';
776 }
777
778 #if 0
779 static int send_mode_list(struct Client *cptr, char *chname,
780                           time_t creationtime, struct SLink *top,
781                           int mask, char flag)
782 {
783   struct SLink* lp;
784   char*         cp;
785   char*         name;
786   int           count = 0;
787   int           send = 0;
788   int           sent = 0;
789
790   cp = modebuf + strlen(modebuf);
791   if (*parabuf)                 /* mode +l or +k xx */
792     count = 1;
793   for (lp = top; lp; lp = lp->next)
794   {
795     if (!(lp->flags & mask))
796       continue;
797     if (mask == CHFL_BAN)
798       name = lp->value.ban.banstr;
799     else
800       name = lp->value.cptr->name;
801     if (strlen(parabuf) + strlen(name) + 11 < MODEBUFLEN)
802     {
803       strcat(parabuf, " ");
804       strcat(parabuf, name);
805       count++;
806       *cp++ = flag;
807       *cp = '\0';
808     }
809     else if (*parabuf)
810       send = 1;
811     if (count == 6)
812       send = 1;
813     if (send)
814     {
815       /* cptr is always a server! So we send creationtimes */
816       sendmodeto_one(cptr, me.name, chname, modebuf, parabuf, creationtime);
817       sent = 1;
818       send = 0;
819       *parabuf = '\0';
820       cp = modebuf;
821       *cp++ = '+';
822       if (count != 6)
823       {
824         strcpy(parabuf, name);
825         *cp++ = flag;
826       }
827       count = 0;
828       *cp = '\0';
829     }
830   }
831   return sent;
832 }
833
834 #endif /* 0 */
835
836 /*
837  * send "cptr" a full list of the modes for channel chptr.
838  */
839 void send_channel_modes(struct Client *cptr, struct Channel *chptr)
840 {
841   static unsigned int current_flags[4] =
842       { 0, CHFL_CHANOP | CHFL_VOICE, CHFL_VOICE, CHFL_CHANOP };
843   int                first = 1;
844   int                full  = 1;
845   int                flag_cnt = 0;
846   int                new_mode = 0;
847   size_t             len;
848   size_t             sblen;
849   struct Membership* member;
850   struct SLink*      lp2;
851   char modebuf[MODEBUFLEN];
852   char parabuf[MODEBUFLEN];
853   char sndbuf[IRC_BUFSIZE];
854
855   assert(0 != cptr);
856   assert(0 != chptr); 
857
858   if (IsLocalChannel(chptr->chname))
859     return;
860
861   member = chptr->members;
862   lp2 = chptr->banlist;
863
864   *modebuf = *parabuf = '\0';
865   channel_modes(cptr, modebuf, parabuf, chptr);
866
867   for (first = 1; full; first = 0)      /* Loop for multiple messages */
868   {
869     full = 0;                   /* Assume by default we get it
870                                  all in one message */
871
872     /* (Continued) prefix: "<Y> B <channel> <TS>" */
873     /* is there any better way we can do this? */
874     sblen = ircd_snprintf(&me, sndbuf, sizeof(sndbuf), "%C " TOK_BURST
875                           " %H %Tu", &me, chptr, chptr->creationtime);
876
877     if (first && modebuf[1])    /* Add simple modes (iklmnpst)
878                                  if first message */
879     {
880       /* prefix: "<Y> B <channel> <TS>[ <modes>[ <params>]]" */
881       sndbuf[sblen++] = ' ';
882       strcpy(sndbuf + sblen, modebuf);
883       sblen += strlen(modebuf);
884       if (*parabuf)
885       {
886         sndbuf[sblen++] = ' ';
887         strcpy(sndbuf + sblen, parabuf);
888         sblen += strlen(parabuf);
889       }
890     }
891
892     /*
893      * Attach nicks, comma seperated " nick[:modes],nick[:modes],..."
894      *
895      * Run 4 times over all members, to group the members with the
896      * same mode together
897      */
898     for (first = 1; flag_cnt < 4;
899          member = chptr->members, new_mode = 1, flag_cnt++)
900     {
901       for (; member; member = member->next_member)
902       {
903         if ((member->status & CHFL_VOICED_OR_OPPED) !=
904             current_flags[flag_cnt])
905           continue;             /* Skip members with different flags */
906         if (sblen + NUMNICKLEN + 4 > BUFSIZE - 3)
907           /* The 4 is a possible ",:ov"
908              The -3 is for the "\r\n\0" that is added in send.c */
909         {
910           full = 1;           /* Make sure we continue after
911                                  sending it so far */
912           new_mode = 1;       /* Ensure the new BURST line contains the current
913                                  mode. --Gte */
914           break;              /* Do not add this member to this message */
915         }
916         sndbuf[sblen++] = first ? ' ' : ',';
917         first = 0;              /* From now on, us comma's to add new nicks */
918
919         sblen += ircd_snprintf(&me, sndbuf + sblen, sizeof(sndbuf) - sblen,
920                                "%C", member->user);
921         /*
922          * Do we have a nick with a new mode ?
923          * Or are we starting a new BURST line?
924          */
925         if (new_mode)
926         {
927           new_mode = 0;
928           if (IsVoicedOrOpped(member)) {
929             sndbuf[sblen++] = ':';
930             if (IsChanOp(member))
931               sndbuf[sblen++] = 'o';
932             if (HasVoice(member))
933               sndbuf[sblen++] = 'v';
934           }
935         }
936       }
937       if (full)
938         break;
939     }
940
941     if (!full)
942     {
943       /* Attach all bans, space seperated " :%ban ban ..." */
944       for (first = 2; lp2; lp2 = lp2->next)
945       {
946         len = strlen(lp2->value.ban.banstr);
947         if (sblen + len + 1 + first > BUFSIZE - 3)
948           /* The +1 stands for the added ' '.
949            * The +first stands for the added ":%".
950            * The -3 is for the "\r\n\0" that is added in send.c
951            */
952         {
953           full = 1;
954           break;
955         }
956         if (first)
957         {
958           first = 0;
959           sndbuf[sblen++] = ' ';
960           sndbuf[sblen++] = ':';       /* Will be last parameter */
961           sndbuf[sblen++] = '%';       /* To tell bans apart */
962         }
963         else
964           sndbuf[sblen++] = ' ';
965         strcpy(sndbuf + sblen, lp2->value.ban.banstr);
966         sblen += len;
967       }
968     }
969
970     sndbuf[sblen] = '\0';
971     send_buffer(cptr, sndbuf);  /* Send this message */
972   }                             /* Continue when there was something
973                                  that didn't fit (full==1) */
974 }
975
976 /*
977  * pretty_mask
978  *
979  * by Carlo Wood (Run), 05 Oct 1998.
980  *
981  * Canonify a mask.
982  *
983  * When the nick is longer then NICKLEN, it is cut off (its an error of course).
984  * When the user name or host name are too long (USERLEN and HOSTLEN
985  * respectively) then they are cut off at the start with a '*'.
986  *
987  * The following transformations are made:
988  *
989  * 1)   xxx             -> nick!*@*
990  * 2)   xxx.xxx         -> *!*@host
991  * 3)   xxx!yyy         -> nick!user@*
992  * 4)   xxx@yyy         -> *!user@host
993  * 5)   xxx!yyy@zzz     -> nick!user@host
994  */
995 char *pretty_mask(char *mask)
996 {
997   static char star[2] = { '*', 0 };
998   char *last_dot = NULL;
999   char *ptr;
1000
1001   /* Case 1: default */
1002   char *nick = mask;
1003   char *user = star;
1004   char *host = star;
1005
1006   /* Do a _single_ pass through the characters of the mask: */
1007   for (ptr = mask; *ptr; ++ptr)
1008   {
1009     if (*ptr == '!')
1010     {
1011       /* Case 3 or 5: Found first '!' (without finding a '@' yet) */
1012       user = ++ptr;
1013       host = star;
1014     }
1015     else if (*ptr == '@')
1016     {
1017       /* Case 4: Found last '@' (without finding a '!' yet) */
1018       nick = star;
1019       user = mask;
1020       host = ++ptr;
1021     }
1022     else if (*ptr == '.')
1023     {
1024       /* Case 2: Found last '.' (without finding a '!' or '@' yet) */
1025       last_dot = ptr;
1026       continue;
1027     }
1028     else
1029       continue;
1030     for (; *ptr; ++ptr)
1031     {
1032       if (*ptr == '@')
1033       {
1034         /* Case 4 or 5: Found last '@' */
1035         host = ptr + 1;
1036       }
1037     }
1038     break;
1039   }
1040   if (user == star && last_dot)
1041   {
1042     /* Case 2: */
1043     nick = star;
1044     user = star;
1045     host = mask;
1046   }
1047   /* Check lengths */
1048   if (nick != star)
1049   {
1050     char *nick_end = (user != star) ? user - 1 : ptr;
1051     if (nick_end - nick > NICKLEN)
1052       nick[NICKLEN] = 0;
1053     *nick_end = 0;
1054   }
1055   if (user != star)
1056   {
1057     char *user_end = (host != star) ? host - 1 : ptr;
1058     if (user_end - user > USERLEN)
1059     {
1060       user = user_end - USERLEN;
1061       *user = '*';
1062     }
1063     *user_end = 0;
1064   }
1065   if (host != star && ptr - host > HOSTLEN)
1066   {
1067     host = ptr - HOSTLEN;
1068     *host = '*';
1069   }
1070   return make_nick_user_host(nick, user, host);
1071 }
1072
1073 static void send_ban_list(struct Client* cptr, struct Channel* chptr)
1074 {
1075   struct SLink* lp;
1076
1077   assert(0 != cptr);
1078   assert(0 != chptr);
1079
1080   for (lp = chptr->banlist; lp; lp = lp->next)
1081     send_reply(cptr, RPL_BANLIST, chptr->chname, lp->value.ban.banstr,
1082                lp->value.ban.who, lp->value.ban.when);
1083
1084   send_reply(cptr, RPL_ENDOFBANLIST, chptr->chname);
1085 }
1086
1087 /*
1088  * Check and try to apply the channel modes passed in the parv array for
1089  * the client ccptr to channel chptr.  The resultant changes are printed
1090  * into mbuf and pbuf (if any) and applied to the channel.
1091  */
1092 int set_mode(struct Client* cptr, struct Client* sptr,
1093                     struct Channel* chptr, int parc, char* parv[],
1094                     char* mbuf, char* pbuf, char* npbuf, int* badop)
1095
1096   /* 
1097    * This size is only needed when a broken
1098    * server sends more then MAXMODEPARAMS
1099    * parameters
1100    */
1101   static struct SLink chops[MAXPARA - 2];
1102   static int flags[] = {
1103     MODE_PRIVATE,    'p',
1104     MODE_SECRET,     's',
1105     MODE_MODERATED,  'm',
1106     MODE_NOPRIVMSGS, 'n',
1107     MODE_TOPICLIMIT, 't',
1108     MODE_INVITEONLY, 'i',
1109     MODE_VOICE,      'v',
1110     MODE_KEY,        'k',
1111     0x0, 0x0
1112   };
1113
1114   char bmodebuf[MODEBUFLEN];
1115   char bparambuf[MODEBUFLEN];
1116   char nbparambuf[MODEBUFLEN];     /* "Numeric" Bounce Parameter Buffer */
1117   struct SLink*      lp;
1118   char*              curr = parv[0];
1119   char*              cp = NULL;
1120   int*               ip;
1121   struct Membership* member_x;
1122   struct Membership* member_y;
1123   unsigned int       whatt = MODE_ADD;
1124   unsigned int       bwhatt = 0;
1125   int                limitset = 0;
1126   int                bounce;
1127   int                add_banid_called = 0;
1128   size_t             len;
1129   size_t             nlen;
1130   size_t             blen;
1131   size_t             nblen;
1132   int                keychange = 0;
1133   unsigned int       nusers = 0;
1134   unsigned int       newmode;
1135   int                opcnt = 0;
1136   int                banlsent = 0;
1137   int                doesdeop = 0;
1138   int                doesop = 0;
1139   int                hacknotice = 0;
1140   int                change;
1141   int                gotts = 0;
1142   struct Client*     who;
1143   struct Mode*       mode;
1144   struct Mode        oldm;
1145   static char        numeric[16];
1146   char*              bmbuf = bmodebuf;
1147   char*              bpbuf = bparambuf;
1148   char*              nbpbuf = nbparambuf;
1149   time_t             newtime = 0;
1150   struct ConfItem*   aconf;
1151
1152   *mbuf = *pbuf = *npbuf = *bmbuf = *bpbuf = *nbpbuf = '\0';
1153   *badop = 0;
1154   if (parc < 1)
1155     return 0;
1156   /*
1157    * Mode is accepted when sptr is a channel operator
1158    * but also when the mode is received from a server.
1159    * At this point, let any member pass, so they are allowed
1160    * to see the bans.
1161    */
1162   member_y = find_channel_member(sptr, chptr);
1163   if (!(IsServer(cptr) || member_y))
1164     return 0;
1165
1166 #ifdef OPER_MODE_LCHAN
1167   if (IsOperOnLocalChannel(sptr, chptr->chname) && !IsChanOp(member_y))
1168     LocalChanOperMode = 1;
1169 #endif
1170
1171   mode = &(chptr->mode);
1172   memcpy(&oldm, mode, sizeof(struct Mode));
1173
1174   newmode = mode->mode;
1175
1176   while (curr && *curr) {
1177     switch (*curr) {
1178       case '+':
1179         whatt = MODE_ADD;
1180         break;
1181       case '-':
1182         whatt = MODE_DEL;
1183         break;
1184       case 'o':
1185       case 'v':
1186         if (--parc <= 0)
1187           break;
1188         parv++;
1189         if (MyUser(sptr) && opcnt >= MAXMODEPARAMS)
1190           break;
1191         /*
1192          * Check for nickname changes and try to follow these
1193          * to make sure the right client is affected by the
1194          * mode change.
1195          * Even if we find a nick with find_chasing() there
1196          * is still a reason to ignore in a special case.
1197          * We need to ignore the mode when:
1198          * - It is part of a net.burst (from a server and
1199          *   a MODE_ADD). Ofcourse we don't ignore mode
1200          *   changes from Uworld.
1201          * - The found nick is not on the right side off
1202          *   the net.junction.
1203          * This fixes the bug that when someone (tries to)
1204          * ride a net.break and does so with the nick of
1205          * someone on the otherside, that he is nick collided
1206          * (killed) but his +o still ops the other person.
1207          */
1208         if (MyUser(sptr))
1209         {
1210           if (!(who = find_chasing(sptr, parv[0], NULL)))
1211             break;
1212         }
1213         else
1214         {
1215           if (!(who = findNUser(parv[0])))
1216             break;
1217         }
1218         if (whatt == MODE_ADD && IsServer(sptr) && who->from != sptr->from &&
1219             !find_conf_byhost(cptr->confs, sptr->name, CONF_UWORLD))
1220           break;
1221
1222         if (!(member_x = find_member_link(chptr, who)) ||
1223             (MyUser(sptr) && IsZombie(member_x)))
1224         {
1225           send_reply(cptr, ERR_USERNOTINCHANNEL, who->name, chptr->chname);
1226           break;
1227         }
1228         /*
1229          * if the user is +k, prevent a deop from local user
1230          */
1231         if (whatt == MODE_DEL && IsChannelService(who) && *curr == 'o') {
1232           /*
1233            * XXX - CHECKME
1234            */
1235           if (MyUser(cptr)) {
1236             send_reply(cptr, ERR_ISCHANSERVICE, parv[0], chptr->chname);
1237             break;
1238            }
1239            else {
1240              sprintf_irc(sendbuf,":%s NOTICE * :*** Notice -- Deop of +k user on %s by %s", /* XXX set_mode only called by old m_mode */
1241                          me.name,chptr->chname,cptr->name);             
1242            }
1243         }
1244 #ifdef NO_OPER_DEOP_LCHAN
1245         /*
1246          * if the user is an oper on a local channel, prevent him
1247          * from being deoped. that oper can deop himself though.
1248          */
1249         if (whatt == MODE_DEL && IsOperOnLocalChannel(who, chptr->chname) &&
1250             (who != sptr) && MyUser(cptr) && *curr == 'o')
1251         {
1252           send_reply(cptr, ERR_ISOPERLCHAN, parv[0], chptr->chname);
1253           break;
1254         }
1255 #endif
1256         if (whatt == MODE_ADD)
1257         {
1258           lp = &chops[opcnt++];
1259           lp->value.cptr = who;
1260           if (IsServer(sptr) && (!(who->flags & FLAGS_TS8) || ((*curr == 'o') &&
1261               !(member_x->status & (CHFL_SERVOPOK | CHFL_CHANOP)))))
1262             *badop = ((member_x->status & CHFL_DEOPPED) && (*curr == 'o')) ? 2 : 3;
1263           lp->flags = (*curr == 'o') ? MODE_CHANOP : MODE_VOICE;
1264           lp->flags |= MODE_ADD;
1265         }
1266         else if (whatt == MODE_DEL)
1267         {
1268           lp = &chops[opcnt++];
1269           lp->value.cptr = who;
1270           doesdeop = 1;         /* Also when -v */
1271           lp->flags = (*curr == 'o') ? MODE_CHANOP : MODE_VOICE;
1272           lp->flags |= MODE_DEL;
1273         }
1274         if (*curr == 'o')
1275           doesop = 1;
1276         break;
1277       case 'k':
1278         if (--parc <= 0)
1279           break;
1280         parv++;
1281         /* check now so we eat the parameter if present */
1282         if (keychange)
1283           break;
1284         else
1285         {
1286           char *s = &(*parv)[-1];
1287           unsigned short count = KEYLEN + 1;
1288
1289           while (*++s > ' ' && *s != ':' && --count);
1290           *s = '\0';
1291           if (!**parv)          /* nothing left in key */
1292             break;
1293         }
1294         if (MyUser(sptr) && opcnt >= MAXMODEPARAMS)
1295           break;
1296         if (whatt == MODE_ADD)
1297         {
1298           if (*mode->key && !IsServer(cptr))
1299             send_reply(cptr, ERR_KEYSET, chptr->chname);
1300           else if (!*mode->key || IsServer(cptr))
1301           {
1302             lp = &chops[opcnt++];
1303             lp->value.cp = *parv;
1304             if (strlen(lp->value.cp) > KEYLEN)
1305               lp->value.cp[KEYLEN] = '\0';
1306             lp->flags = MODE_KEY | MODE_ADD;
1307             keychange = 1;
1308           }
1309         }
1310         else if (whatt == MODE_DEL)
1311         {
1312           /* Debug((DEBUG_INFO, "removing key: mode->key: >%s< *parv: >%s<", mode->key, *parv)); */
1313           if (0 == ircd_strcmp(mode->key, *parv) || IsServer(cptr))
1314           {
1315             /* Debug((DEBUG_INFO, "key matched")); */
1316             lp = &chops[opcnt++];
1317             lp->value.cp = mode->key;
1318             lp->flags = MODE_KEY | MODE_DEL;
1319             keychange = 1;
1320           }
1321         }
1322         break;
1323       case 'b':
1324         if (--parc <= 0) {
1325           if (0 == banlsent) {
1326             /*
1327              * Only send it once
1328              */
1329             send_ban_list(cptr, chptr);
1330             banlsent = 1;
1331           }
1332           break;
1333         }
1334         parv++;
1335         if (EmptyString(*parv))
1336           break;
1337         if (MyUser(sptr))
1338         {
1339           if ((cp = strchr(*parv, ' ')))
1340             *cp = 0;
1341           if (opcnt >= MAXMODEPARAMS || **parv == ':' || **parv == '\0')
1342             break;
1343         }
1344         if (whatt == MODE_ADD)
1345         {
1346           lp = &chops[opcnt++];
1347           lp->value.cp = *parv;
1348           lp->flags = MODE_ADD | MODE_BAN;
1349         }
1350         else if (whatt == MODE_DEL)
1351         {
1352           lp = &chops[opcnt++];
1353           lp->value.cp = *parv;
1354           lp->flags = MODE_DEL | MODE_BAN;
1355         }
1356         break;
1357       case 'l':
1358         /*
1359          * limit 'l' to only *1* change per mode command but
1360          * eat up others.
1361          */
1362         if (limitset)
1363         {
1364           if (whatt == MODE_ADD && --parc > 0)
1365             parv++;
1366           break;
1367         }
1368         if (whatt == MODE_DEL)
1369         {
1370           limitset = 1;
1371           nusers = 0;
1372           break;
1373         }
1374         if (--parc > 0)
1375         {
1376           if (EmptyString(*parv))
1377             break;
1378           if (MyUser(sptr) && opcnt >= MAXMODEPARAMS)
1379             break;
1380           if (!(nusers = atoi(*++parv)))
1381             continue;
1382           lp = &chops[opcnt++];
1383           lp->flags = MODE_ADD | MODE_LIMIT;
1384           limitset = 1;
1385           break;
1386         }
1387         need_more_params(cptr, "MODE +l");
1388         break;
1389       case 'i':         /* falls through for default case */
1390         if (whatt == MODE_DEL)
1391           while ((lp = chptr->invites))
1392             del_invite(lp->value.cptr, chptr);
1393       default:
1394         for (ip = flags; *ip; ip += 2)
1395           if (*(ip + 1) == *curr)
1396             break;
1397
1398         if (*ip)
1399         {
1400           if (whatt == MODE_ADD)
1401           {
1402             if (*ip == MODE_PRIVATE)
1403               newmode &= ~MODE_SECRET;
1404             else if (*ip == MODE_SECRET)
1405               newmode &= ~MODE_PRIVATE;
1406             newmode |= *ip;
1407           }
1408           else
1409             newmode &= ~*ip;
1410         }
1411         else if (!IsServer(cptr))
1412           send_reply(cptr, ERR_UNKNOWNMODE, *curr);
1413         break;
1414     }
1415     curr++;
1416     /*
1417      * Make sure mode strings such as "+m +t +p +i" are parsed
1418      * fully.
1419      */
1420     if (!*curr && parc > 0)
1421     {
1422       curr = *++parv;
1423       parc--;
1424       /* If this was from a server, and it is the last
1425        * parameter and it starts with a digit, it must
1426        * be the creationtime.  --Run
1427        */
1428       if (IsServer(sptr))
1429       {
1430         if (parc == 1 && IsDigit(*curr))
1431         {
1432           newtime = atoi(curr);
1433           if (newtime && chptr->creationtime == MAGIC_REMOTE_JOIN_TS)
1434           {
1435             chptr->creationtime = newtime;
1436             *badop = 0;
1437           }
1438           gotts = 1;
1439           if (newtime == 0)
1440           {
1441             *badop = 2;
1442             hacknotice = 1;
1443           }
1444           else if (newtime > chptr->creationtime)
1445           {                     /* It is a net-break ride if we have ops.
1446                                    bounce modes if we have ops.  --Run */
1447             if (doesdeop)
1448               *badop = 2;
1449             else if (chptr->creationtime == 0)
1450             {
1451               if (chptr->creationtime == 0 || doesop)
1452                 chptr->creationtime = newtime;
1453               *badop = 0;
1454             }
1455             /* Bounce: */
1456             else
1457               *badop = 1;
1458           }
1459           /*
1460            * A legal *badop can occur when two
1461            * people join simultaneously a channel,
1462            * Allow for 10 min of lag (and thus hacking
1463            * on channels younger then 10 min) --Run
1464            */
1465           else if (*badop == 0 ||
1466               chptr->creationtime > (TStime() - TS_LAG_TIME))
1467           {
1468             if (newtime < chptr->creationtime)
1469               chptr->creationtime = newtime;
1470             *badop = 0;
1471           }
1472           break;
1473         }
1474       }
1475       else
1476         *badop = 0;
1477     }
1478   }                             /* end of while loop for MODE processing */
1479
1480 #ifdef OPER_MODE_LCHAN
1481   /*
1482    * Now reject non chan ops. Accept modes from opers on local channels
1483    * even if they are deopped
1484    */
1485   if (!IsServer(cptr) &&
1486       (!member_y || !(IsChanOp(member_y) ||
1487                  IsOperOnLocalChannel(sptr, chptr->chname))))
1488 #else
1489   if (!IsServer(cptr) && (!member_y || !IsChanOp(member_y)))
1490 #endif
1491   {
1492     *badop = 0;
1493     return (opcnt || newmode != mode->mode || limitset || keychange) ? 0 : -1;
1494   }
1495
1496   if (doesop && newtime == 0 && IsServer(sptr))
1497     *badop = 2;
1498
1499   if (*badop >= 2 &&
1500       (aconf = find_conf_byhost(cptr->confs, sptr->name, CONF_UWORLD)))
1501     *badop = 4;
1502
1503 #ifdef OPER_MODE_LCHAN
1504   bounce = (*badop == 1 || *badop == 2 ||
1505             (is_deopped(sptr, chptr) &&
1506              !IsOperOnLocalChannel(sptr, chptr->chname))) ? 1 : 0;
1507 #else
1508   bounce = (*badop == 1 || *badop == 2 || is_deopped(sptr, chptr)) ? 1 : 0;
1509 #endif
1510
1511   whatt = 0;
1512   for (ip = flags; *ip; ip += 2) {
1513     if ((*ip & newmode) && !(*ip & oldm.mode))
1514     {
1515       if (bounce)
1516       {
1517         if (bwhatt != MODE_DEL)
1518         {
1519           *bmbuf++ = '-';
1520           bwhatt = MODE_DEL;
1521         }
1522         *bmbuf++ = *(ip + 1);
1523       }
1524       else
1525       {
1526         if (whatt != MODE_ADD)
1527         {
1528           *mbuf++ = '+';
1529           whatt = MODE_ADD;
1530         }
1531         mode->mode |= *ip;
1532         *mbuf++ = *(ip + 1);
1533       }
1534     }
1535   }
1536   for (ip = flags; *ip; ip += 2) {
1537     if ((*ip & oldm.mode) && !(*ip & newmode))
1538     {
1539       if (bounce)
1540       {
1541         if (bwhatt != MODE_ADD)
1542         {
1543           *bmbuf++ = '+';
1544           bwhatt = MODE_ADD;
1545         }
1546         *bmbuf++ = *(ip + 1);
1547       }
1548       else
1549       {
1550         if (whatt != MODE_DEL)
1551         {
1552           *mbuf++ = '-';
1553           whatt = MODE_DEL;
1554         }
1555         mode->mode &= ~*ip;
1556         *mbuf++ = *(ip + 1);
1557       }
1558     }
1559   }
1560   blen = nblen = 0;
1561   if (limitset && !nusers && mode->limit)
1562   {
1563     if (bounce)
1564     {
1565       if (bwhatt != MODE_ADD)
1566       {
1567         *bmbuf++ = '+';
1568         bwhatt = MODE_ADD;
1569       }
1570       *bmbuf++ = 'l';
1571       sprintf(numeric, "%-15d", mode->limit);
1572       if ((cp = strchr(numeric, ' ')))
1573         *cp = '\0';
1574       strcat(bpbuf, numeric);
1575       blen += strlen(numeric);
1576       strcat(bpbuf, " ");
1577       strcat(nbpbuf, numeric);
1578       nblen += strlen(numeric);
1579       strcat(nbpbuf, " ");
1580     }
1581     else
1582     {
1583       if (whatt != MODE_DEL)
1584       {
1585         *mbuf++ = '-';
1586         whatt = MODE_DEL;
1587       }
1588       mode->mode &= ~MODE_LIMIT;
1589       mode->limit = 0;
1590       *mbuf++ = 'l';
1591     }
1592   }
1593   /*
1594    * Reconstruct "+bkov" chain.
1595    */
1596   if (opcnt)
1597   {
1598     int i = 0;
1599     char c = 0;
1600     unsigned int prev_whatt = 0;
1601
1602     for (; i < opcnt; i++)
1603     {
1604       lp = &chops[i];
1605       /*
1606        * make sure we have correct mode change sign
1607        */
1608       if (whatt != (lp->flags & (MODE_ADD | MODE_DEL)))
1609       {
1610         if (lp->flags & MODE_ADD)
1611         {
1612           *mbuf++ = '+';
1613           prev_whatt = whatt;
1614           whatt = MODE_ADD;
1615         }
1616         else
1617         {
1618           *mbuf++ = '-';
1619           prev_whatt = whatt;
1620           whatt = MODE_DEL;
1621         }
1622       }
1623       len = strlen(pbuf);
1624       nlen = strlen(npbuf);
1625       /*
1626        * get c as the mode char and tmp as a pointer to
1627        * the parameter for this mode change.
1628        */
1629       switch (lp->flags & MODE_WPARAS)
1630       {
1631         case MODE_CHANOP:
1632           c = 'o';
1633           cp = lp->value.cptr->name;
1634           break;
1635         case MODE_VOICE:
1636           c = 'v';
1637           cp = lp->value.cptr->name;
1638           break;
1639         case MODE_BAN:
1640           /*
1641            * I made this a bit more user-friendly (tm):
1642            * nick = nick!*@*
1643            * nick!user = nick!user@*
1644            * user@host = *!user@host
1645            * host.name = *!*@host.name    --Run
1646            */
1647           c = 'b';
1648           cp = pretty_mask(lp->value.cp);
1649           break;
1650         case MODE_KEY:
1651           c = 'k';
1652           cp = lp->value.cp;
1653           break;
1654         case MODE_LIMIT:
1655           c = 'l';
1656           sprintf(numeric, "%-15d", nusers);
1657           if ((cp = strchr(numeric, ' ')))
1658             *cp = '\0';
1659           cp = numeric;
1660           break;
1661       }
1662
1663       /* What could be added: cp+' '+' '+<TS>+'\0' */
1664       if (len + strlen(cp) + 13 > MODEBUFLEN ||
1665           nlen + strlen(cp) + NUMNICKLEN + 12 > MODEBUFLEN)
1666         break;
1667
1668       switch (lp->flags & MODE_WPARAS)
1669       {
1670         case MODE_KEY:
1671           if (strlen(cp) > KEYLEN)
1672             *(cp + KEYLEN) = '\0';
1673           if ((whatt == MODE_ADD && (*mode->key == '\0' ||
1674                0 != ircd_strcmp(mode->key, cp))) ||
1675               (whatt == MODE_DEL && (*mode->key != '\0')))
1676           {
1677             if (bounce)
1678             {
1679               if (*mode->key == '\0')
1680               {
1681                 if (bwhatt != MODE_DEL)
1682                 {
1683                   *bmbuf++ = '-';
1684                   bwhatt = MODE_DEL;
1685                 }
1686                 strcat(bpbuf, cp);
1687                 blen += strlen(cp);
1688                 strcat(bpbuf, " ");
1689                 blen++;
1690                 strcat(nbpbuf, cp);
1691                 nblen += strlen(cp);
1692                 strcat(nbpbuf, " ");
1693                 nblen++;
1694               }
1695               else
1696               {
1697                 if (bwhatt != MODE_ADD)
1698                 {
1699                   *bmbuf++ = '+';
1700                   bwhatt = MODE_ADD;
1701                 }
1702                 strcat(bpbuf, mode->key);
1703                 blen += strlen(mode->key);
1704                 strcat(bpbuf, " ");
1705                 blen++;
1706                 strcat(nbpbuf, mode->key);
1707                 nblen += strlen(mode->key);
1708                 strcat(nbpbuf, " ");
1709                 nblen++;
1710               }
1711               *bmbuf++ = c;
1712               mbuf--;
1713               if (*mbuf != '+' && *mbuf != '-')
1714                 mbuf++;
1715               else
1716                 whatt = prev_whatt;
1717             }
1718             else
1719             {
1720               *mbuf++ = c;
1721               strcat(pbuf, cp);
1722               len += strlen(cp);
1723               strcat(pbuf, " ");
1724               len++;
1725               strcat(npbuf, cp);
1726               nlen += strlen(cp);
1727               strcat(npbuf, " ");
1728               nlen++;
1729               if (whatt == MODE_ADD)
1730                 ircd_strncpy(mode->key, cp, KEYLEN);
1731               else
1732                 *mode->key = '\0';
1733             }
1734           }
1735           break;
1736         case MODE_LIMIT:
1737           if (nusers && nusers != mode->limit)
1738           {
1739             if (bounce)
1740             {
1741               if (mode->limit == 0)
1742               {
1743                 if (bwhatt != MODE_DEL)
1744                 {
1745                   *bmbuf++ = '-';
1746                   bwhatt = MODE_DEL;
1747                 }
1748               }
1749               else
1750               {
1751                 if (bwhatt != MODE_ADD)
1752                 {
1753                   *bmbuf++ = '+';
1754                   bwhatt = MODE_ADD;
1755                 }
1756                 sprintf(numeric, "%-15d", mode->limit);
1757                 if ((cp = strchr(numeric, ' ')))
1758                   *cp = '\0';
1759                 strcat(bpbuf, numeric);
1760                 blen += strlen(numeric);
1761                 strcat(bpbuf, " ");
1762                 blen++;
1763                 strcat(nbpbuf, numeric);
1764                 nblen += strlen(numeric);
1765                 strcat(nbpbuf, " ");
1766                 nblen++;
1767               }
1768               *bmbuf++ = c;
1769               mbuf--;
1770               if (*mbuf != '+' && *mbuf != '-')
1771                 mbuf++;
1772               else
1773                 whatt = prev_whatt;
1774             }
1775             else
1776             {
1777               *mbuf++ = c;
1778               strcat(pbuf, cp);
1779               len += strlen(cp);
1780               strcat(pbuf, " ");
1781               len++;
1782               strcat(npbuf, cp);
1783               nlen += strlen(cp);
1784               strcat(npbuf, " ");
1785               nlen++;
1786               mode->limit = nusers;
1787             }
1788           }
1789           break;
1790         case MODE_CHANOP:
1791         case MODE_VOICE:
1792           member_y = find_member_link(chptr, lp->value.cptr);
1793           if (lp->flags & MODE_ADD)
1794           {
1795             change = (~member_y->status) & CHFL_VOICED_OR_OPPED & lp->flags;
1796             if (change && bounce)
1797             {
1798               if (lp->flags & MODE_CHANOP)
1799                 SetDeopped(member_y);
1800
1801               if (bwhatt != MODE_DEL)
1802               {
1803                 *bmbuf++ = '-';
1804                 bwhatt = MODE_DEL;
1805               }
1806               *bmbuf++ = c;
1807               strcat(bpbuf, lp->value.cptr->name);
1808               blen += strlen(lp->value.cptr->name);
1809               strcat(bpbuf, " ");
1810               blen++;
1811               sprintf_irc(nbpbuf + nblen, "%s%s ", NumNick(lp->value.cptr));
1812               nblen += strlen(nbpbuf + nblen);
1813               change = 0;
1814             }
1815             else if (change)
1816             {
1817               member_y->status |= lp->flags & CHFL_VOICED_OR_OPPED;
1818               if (IsChanOp(member_y))
1819               {
1820                 ClearDeopped(member_y);
1821                 if (IsServer(sptr))
1822                   ClearServOpOk(member_y);
1823               }
1824             }
1825           }
1826           else
1827           {
1828             change = member_y->status & CHFL_VOICED_OR_OPPED & lp->flags;
1829             if (change && bounce)
1830             {
1831               if (lp->flags & MODE_CHANOP)
1832                 ClearDeopped(member_y);
1833               if (bwhatt != MODE_ADD)
1834               {
1835                 *bmbuf++ = '+';
1836                 bwhatt = MODE_ADD;
1837               }
1838               *bmbuf++ = c;
1839               strcat(bpbuf, lp->value.cptr->name);
1840               blen += strlen(lp->value.cptr->name);
1841               strcat(bpbuf, " ");
1842               blen++;
1843               sprintf_irc(nbpbuf + nblen, "%s%s ", NumNick(lp->value.cptr));
1844               blen += strlen(bpbuf + blen);
1845               change = 0;
1846             }
1847             else
1848             {
1849               member_y->status &= ~change;
1850               if ((change & MODE_CHANOP) && IsServer(sptr))
1851                 SetDeopped(member_y);
1852             }
1853           }
1854           if (change || *badop == 2 || *badop == 4)
1855           {
1856             *mbuf++ = c;
1857             strcat(pbuf, cp);
1858             len += strlen(cp);
1859             strcat(pbuf, " ");
1860             len++;
1861             sprintf_irc(npbuf + nlen, "%s%s ", NumNick(lp->value.cptr));
1862             nlen += strlen(npbuf + nlen);
1863             npbuf[nlen++] = ' ';
1864             npbuf[nlen] = 0;
1865           }
1866           else
1867           {
1868             mbuf--;
1869             if (*mbuf != '+' && *mbuf != '-')
1870               mbuf++;
1871             else
1872               whatt = prev_whatt;
1873           }
1874           break;
1875         case MODE_BAN:
1876 /*
1877  * Only bans aren't bounced, it makes no sense to bounce last second
1878  * bans while propagating bans done before the net.rejoin. The reason
1879  * why I don't bounce net.rejoin bans is because it is too much
1880  * work to take care of too long strings adding the necessary TS to
1881  * net.burst bans -- RunLazy
1882  * We do have to check for *badop==2 now, we don't want HACKs to take
1883  * effect.
1884  *
1885  * Since BURST - I *did* implement net.rejoin ban bouncing. So now it
1886  * certainly makes sense to also bounce 'last second' bans (bans done
1887  * after the net.junction). -- RunHardWorker
1888  */
1889           if ((change = (whatt & MODE_ADD) &&
1890               !add_banid(sptr, chptr, cp, !bounce, !add_banid_called)))
1891             add_banid_called = 1;
1892           else
1893             change = (whatt & MODE_DEL) && !del_banid(chptr, cp, !bounce);
1894
1895           if (bounce && change)
1896           {
1897             change = 0;
1898             if ((whatt & MODE_ADD))
1899             {
1900               if (bwhatt != MODE_DEL)
1901               {
1902                 *bmbuf++ = '-';
1903                 bwhatt = MODE_DEL;
1904               }
1905             }
1906             else if ((whatt & MODE_DEL))
1907             {
1908               if (bwhatt != MODE_ADD)
1909               {
1910                 *bmbuf++ = '+';
1911                 bwhatt = MODE_ADD;
1912               }
1913             }
1914             *bmbuf++ = c;
1915             strcat(bpbuf, cp);
1916             blen += strlen(cp);
1917             strcat(bpbuf, " ");
1918             blen++;
1919             strcat(nbpbuf, cp);
1920             nblen += strlen(cp);
1921             strcat(nbpbuf, " ");
1922             nblen++;
1923           }
1924           if (change)
1925           {
1926             *mbuf++ = c;
1927             strcat(pbuf, cp);
1928             len += strlen(cp);
1929             strcat(pbuf, " ");
1930             len++;
1931             strcat(npbuf, cp);
1932             nlen += strlen(cp);
1933             strcat(npbuf, " ");
1934             nlen++;
1935           }
1936           else
1937           {
1938             mbuf--;
1939             if (*mbuf != '+' && *mbuf != '-')
1940               mbuf++;
1941             else
1942               whatt = prev_whatt;
1943           }
1944           break;
1945       }
1946     }                           /* for (; i < opcnt; i++) */
1947   }                             /* if (opcnt) */
1948
1949   *mbuf++ = '\0';
1950   *bmbuf++ = '\0';
1951
1952   /* Bounce here */
1953   if (!hacknotice && *bmodebuf && chptr->creationtime)
1954   {
1955     sendcmdto_one(&me, CMD_MODE, cptr, "%H %s %s %Tu", chptr, bmodebuf,
1956                   nbparambuf, *badop == 2 ? (time_t) 0 : chptr->creationtime);
1957   }
1958   /* If there are possibly bans to re-add, bounce them now */
1959   if (add_banid_called && bounce)
1960   {
1961     struct SLink *ban[6];               /* Max 6 bans at a time */
1962     size_t len[6], sblen, total_len;
1963     int cnt, delayed = 0;
1964     while (delayed || (ban[0] = next_overlapped_ban()))
1965     {
1966       len[0] = strlen(ban[0]->value.ban.banstr);
1967       cnt = 1;                  /* We already got one ban :) */
1968       /* XXX sendbuf used to send ban bounces! */
1969       sblen = sprintf_irc(sendbuf, ":%s MODE %s +b", /* XXX set_mode only called by old m_mode */
1970           me.name, chptr->chname) - sendbuf; /* XXX set_mode only called by old m_mode */
1971       total_len = sblen + 1 + len[0];   /* 1 = ' ' */
1972       /* Find more bans: */
1973       delayed = 0;
1974       while (cnt < 6 && (ban[cnt] = next_overlapped_ban()))
1975       {
1976         len[cnt] = strlen(ban[cnt]->value.ban.banstr);
1977         if (total_len + 5 + len[cnt] > BUFSIZE) /* 5 = "b \r\n\0" */
1978         {
1979           delayed = cnt + 1;    /* != 0 */
1980           break;                /* Flush */
1981         }
1982         sendbuf[sblen++] = 'b'; /* XXX set_mode only called by old m_mode */
1983         total_len += 2 + len[cnt++];    /* 2 = "b " */
1984       }
1985       while (cnt--)
1986       {
1987         sendbuf[sblen++] = ' '; /* XXX set_mode only called by old m_mode */
1988         strcpy(sendbuf + sblen, ban[cnt]->value.ban.banstr); /* XXX set_mode only called by old m_mode */
1989         sblen += len[cnt];
1990       }
1991       sendbufto_one(cptr);      /* Send bounce to uplink */ /* XXX set_mode only called by old m_mode */
1992       if (delayed)
1993         ban[0] = ban[delayed - 1];
1994     }
1995   }
1996   /* Send -b's of overlapped bans to clients to keep them synchronized */
1997   if (add_banid_called && !bounce)
1998   {
1999     struct SLink *ban;
2000     char *banstr[6];            /* Max 6 bans at a time */
2001     size_t len[6], sblen, psblen, total_len;
2002     int cnt, delayed = 0;
2003     struct Membership* member_z;
2004     struct Client *acptr;
2005     if (IsServer(sptr))
2006       /* XXX sendbuf used to send ban bounces! */
2007       psblen = sprintf_irc(sendbuf, ":%s MODE %s -b", /* XXX set_mode only called by old m_mode */
2008           sptr->name, chptr->chname) - sendbuf; /* XXX set_mode only called by old m_mode */
2009     else                        /* We rely on IsRegistered(sptr) being true for MODE */
2010       psblen = sprintf_irc(sendbuf, ":%s!%s@%s MODE %s -b", sptr->name, /* XXX set_mode only called by old m_mode */
2011           sptr->user->username, sptr->user->host, chptr->chname) - sendbuf; /* XXX set_mode only called by old m_mode */
2012     while (delayed || (ban = next_removed_overlapped_ban()))
2013     {
2014       if (!delayed)
2015       {
2016         len[0] = strlen((banstr[0] = ban->value.ban.banstr));
2017         ban->value.ban.banstr = NULL;
2018       }
2019       cnt = 1;                  /* We already got one ban :) */
2020       sblen = psblen;
2021       total_len = sblen + 1 + len[0];   /* 1 = ' ' */
2022       /* Find more bans: */
2023       delayed = 0;
2024       while (cnt < 6 && (ban = next_removed_overlapped_ban()))
2025       {
2026         len[cnt] = strlen((banstr[cnt] = ban->value.ban.banstr));
2027         ban->value.ban.banstr = NULL;
2028         if (total_len + 5 + len[cnt] > BUFSIZE) /* 5 = "b \r\n\0" */
2029         {
2030           delayed = cnt + 1;    /* != 0 */
2031           break;                /* Flush */
2032         }
2033         sendbuf[sblen++] = 'b'; /* XXX set_mode only called by old m_mode */
2034         total_len += 2 + len[cnt++];    /* 2 = "b " */
2035       }
2036       while (cnt--)
2037       {
2038         sendbuf[sblen++] = ' '; /* XXX set_mode only called by old m_mode */
2039         strcpy(sendbuf + sblen, banstr[cnt]); /* XXX set_mode only called by old m_mode */
2040         MyFree(banstr[cnt]);
2041         sblen += len[cnt];
2042       }
2043       for (member_z = chptr->members; member_z; member_z = member_z->next_member) {
2044         acptr = member_z->user;
2045         if (MyConnect(acptr) && !IsZombie(member_z))
2046           sendbufto_one(acptr); /* XXX set_mode only called by old m_mode */
2047       }
2048       if (delayed)
2049       {
2050         banstr[0] = banstr[delayed - 1];
2051         len[0] = len[delayed - 1];
2052       }
2053     }
2054   }
2055
2056   return gotts ? 1 : -1;
2057 }
2058
2059 /* We are now treating the <key> part of /join <channel list> <key> as a key
2060  * ring; that is, we try one key against the actual channel key, and if that
2061  * doesn't work, we try the next one, and so on. -Kev -Texaco
2062  * Returns: 0 on match, 1 otherwise
2063  * This version contributed by SeKs <intru@info.polymtl.ca>
2064  */
2065 static int compall(char *key, char *keyring)
2066 {
2067   char *p1;
2068
2069 top:
2070   p1 = key;                     /* point to the key... */
2071   while (*p1 && *p1 == *keyring)
2072   {                             /* step through the key and ring until they
2073                                    don't match... */
2074     p1++;
2075     keyring++;
2076   }
2077
2078   if (!*p1 && (!*keyring || *keyring == ','))
2079     /* ok, if we're at the end of the and also at the end of one of the keys
2080        in the keyring, we have a match */
2081     return 0;
2082
2083   if (!*keyring)                /* if we're at the end of the key ring, there
2084                                    weren't any matches, so we return 1 */
2085     return 1;
2086
2087   /* Not at the end of the key ring, so step
2088      through to the next key in the ring: */
2089   while (*keyring && *(keyring++) != ',');
2090
2091   goto top;                     /* and check it against the key */
2092 }
2093
2094 int can_join(struct Client *sptr, struct Channel *chptr, char *key)
2095 {
2096   struct SLink *lp;
2097   int overrideJoin = 0;  
2098   
2099   /*
2100    * Now a banned user CAN join if invited -- Nemesi
2101    * Now a user CAN escape channel limit if invited -- bfriendly
2102    * Now a user CAN escape anything if invited -- Isomer
2103    */
2104
2105   for (lp = sptr->user->invited; lp; lp = lp->next)
2106     if (lp->value.chptr == chptr)
2107       return 0;
2108   
2109 #ifdef OPER_WALK_THROUGH_LMODES
2110   /* An oper can force a join on a local channel using "OVERRIDE" as the key. 
2111      a HACK(4) notice will be sent if he would not have been supposed
2112      to join normally. */ 
2113   if (IsOperOnLocalChannel(sptr,chptr->chname) && !BadPtr(key) && compall("OVERRIDE",key) == 0)
2114   {
2115     overrideJoin = MAGIC_OPER_OVERRIDE;
2116   }
2117 #endif
2118
2119   if (chptr->mode.mode & MODE_INVITEONLY)
2120         return overrideJoin + ERR_INVITEONLYCHAN;
2121         
2122   if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
2123         return overrideJoin + ERR_CHANNELISFULL;
2124         
2125   if (is_banned(sptr, chptr, NULL))
2126         return overrideJoin + ERR_BANNEDFROMCHAN;
2127   
2128   /*
2129    * now using compall (above) to test against a whole key ring -Kev
2130    */
2131   if (*chptr->mode.key && (EmptyString(key) || compall(chptr->mode.key, key)))
2132     return overrideJoin + ERR_BADCHANNELKEY;
2133
2134   if (overrideJoin)     
2135         return ERR_DONTCHEAT;
2136         
2137   return 0;
2138 }
2139
2140 /*
2141  * Remove bells and commas from channel name
2142  */
2143 void clean_channelname(char *cn)
2144 {
2145   int i;
2146
2147   for (i = 0; cn[i]; i++) {
2148     if (i >= CHANNELLEN || !IsChannelChar(cn[i])) {
2149       cn[i] = '\0';
2150       return;
2151     }
2152     if (IsChannelLower(cn[i])) {
2153       cn[i] = ToLower(cn[i]);
2154 #ifndef FIXME
2155       /*
2156        * Remove for .08+
2157        * toupper(0xd0)
2158        */
2159       if ((unsigned char)(cn[i]) == 0xd0)
2160         cn[i] = (char) 0xf0;
2161 #endif
2162     }
2163   }
2164 }
2165
2166 /*
2167  *  Get Channel block for i (and allocate a new channel
2168  *  block, if it didn't exists before).
2169  */
2170 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
2171 {
2172   struct Channel *chptr;
2173   int len;
2174
2175   if (EmptyString(chname))
2176     return NULL;
2177
2178   len = strlen(chname);
2179   if (MyUser(cptr) && len > CHANNELLEN)
2180   {
2181     len = CHANNELLEN;
2182     *(chname + CHANNELLEN) = '\0';
2183   }
2184   if ((chptr = FindChannel(chname)))
2185     return (chptr);
2186   if (flag == CGT_CREATE)
2187   {
2188     chptr = (struct Channel*) MyMalloc(sizeof(struct Channel) + len);
2189     assert(0 != chptr);
2190     ++UserStats.channels;
2191     memset(chptr, 0, sizeof(struct Channel));
2192     strcpy(chptr->chname, chname);
2193     if (GlobalChannelList)
2194       GlobalChannelList->prev = chptr;
2195     chptr->prev = NULL;
2196     chptr->next = GlobalChannelList;
2197     chptr->creationtime = MyUser(cptr) ? TStime() : (time_t) 0;
2198     GlobalChannelList = chptr;
2199     hAddChannel(chptr);
2200   }
2201   return chptr;
2202 }
2203
2204 void add_invite(struct Client *cptr, struct Channel *chptr)
2205 {
2206   struct SLink *inv, **tmp;
2207
2208   del_invite(cptr, chptr);
2209   /*
2210    * Delete last link in chain if the list is max length
2211    */
2212   assert(list_length(cptr->user->invited) == cptr->user->invites);
2213   if (cptr->user->invites>=MAXCHANNELSPERUSER)
2214     del_invite(cptr, cptr->user->invited->value.chptr);
2215   /*
2216    * Add client to channel invite list
2217    */
2218   inv = make_link();
2219   inv->value.cptr = cptr;
2220   inv->next = chptr->invites;
2221   chptr->invites = inv;
2222   /*
2223    * Add channel to the end of the client invite list
2224    */
2225   for (tmp = &(cptr->user->invited); *tmp; tmp = &((*tmp)->next));
2226   inv = make_link();
2227   inv->value.chptr = chptr;
2228   inv->next = NULL;
2229   (*tmp) = inv;
2230   cptr->user->invites++;
2231 }
2232
2233 /*
2234  * Delete Invite block from channel invite list and client invite list
2235  */
2236 void del_invite(struct Client *cptr, struct Channel *chptr)
2237 {
2238   struct SLink **inv, *tmp;
2239
2240   for (inv = &(chptr->invites); (tmp = *inv); inv = &tmp->next)
2241     if (tmp->value.cptr == cptr)
2242     {
2243       *inv = tmp->next;
2244       free_link(tmp);
2245       tmp = 0;
2246       cptr->user->invites--;
2247       break;
2248     }
2249
2250   for (inv = &(cptr->user->invited); (tmp = *inv); inv = &tmp->next)
2251     if (tmp->value.chptr == chptr)
2252     {
2253       *inv = tmp->next;
2254       free_link(tmp);
2255       tmp = 0;
2256       break;
2257     }
2258 }
2259
2260 /* List and skip all channels that are listen */
2261 void list_next_channels(struct Client *cptr, int nr)
2262 {
2263   struct ListingArgs *args = cptr->listing;
2264   struct Channel *chptr = args->chptr;
2265   chptr->mode.mode &= ~MODE_LISTED;
2266   while (is_listed(chptr) || --nr >= 0)
2267   {
2268     for (; chptr; chptr = chptr->next)
2269     {
2270       if (!cptr->user || (SecretChannel(chptr) && !find_channel_member(cptr, chptr)))
2271         continue;
2272       if (chptr->users > args->min_users && chptr->users < args->max_users &&
2273           chptr->creationtime > args->min_time &&
2274           chptr->creationtime < args->max_time &&
2275           (!args->topic_limits || (*chptr->topic &&
2276           chptr->topic_time > args->min_topic_time &&
2277           chptr->topic_time < args->max_topic_time)))
2278       {
2279         if (ShowChannel(cptr,chptr))
2280           send_reply(cptr, RPL_LIST, chptr->chname, chptr->users,
2281                      chptr->topic);
2282         chptr = chptr->next;
2283         break;
2284       }
2285     }
2286     if (!chptr)
2287     {
2288       MyFree(cptr->listing);
2289       cptr->listing = NULL;
2290       send_reply(cptr, RPL_LISTEND);
2291       break;
2292     }
2293   }
2294   if (chptr)
2295   {
2296     cptr->listing->chptr = chptr;
2297     chptr->mode.mode |= MODE_LISTED;
2298   }
2299 }
2300
2301 /* XXX AIEEEE! sendbuf is an institution here :( */
2302 void add_token_to_sendbuf(char *token, size_t *sblenp, int *firstp,
2303     int *send_itp, char is_a_ban, int mode)
2304 {
2305   int first = *firstp;
2306
2307   /*
2308    * Heh - we do not need to test if it still fits in the buffer, because
2309    * this BURST message is reconstructed from another BURST message, and
2310    * it only can become smaller. --Run
2311    */
2312
2313   if (*firstp)                  /* First token in this parameter ? */
2314   {
2315     *firstp = 0;
2316     if (*send_itp == 0)
2317       *send_itp = 1;            /* Buffer contains data to be sent */
2318     sendbuf[(*sblenp)++] = ' '; /* XXX add_token_to_sendbuf only called by old m_burst */
2319     if (is_a_ban)
2320     {
2321       sendbuf[(*sblenp)++] = ':';       /* Bans are always the last "parv" */ /* XXX add_token_to_sendbuf only called by old m_burst */
2322       sendbuf[(*sblenp)++] = is_a_ban; /* XXX add_token_to_sendbuf only called by old m_burst */
2323     }
2324   }
2325   else                          /* Of course, 'send_it' is already set here */
2326     /* Seperate banmasks with a space because
2327        they can contain commas themselfs: */
2328     sendbuf[(*sblenp)++] = is_a_ban ? ' ' : ','; /* XXX add_token_to_sendbuf only called by old m_burst */
2329   strcpy(sendbuf + *sblenp, token); /* XXX add_token_to_sendbuf only called by old m_burst */
2330   *sblenp += strlen(token);
2331   if (!is_a_ban)                /* nick list ? Need to take care
2332                                    of modes for nicks: */
2333   {
2334     static int last_mode = 0;
2335     mode &= CHFL_CHANOP | CHFL_VOICE;
2336     if (first)
2337       last_mode = 0;
2338     if (last_mode != mode)      /* Append mode like ':ov' if changed */
2339     {
2340       last_mode = mode;
2341       sendbuf[(*sblenp)++] = ':'; /* XXX add_token_to_sendbuf only called by old m_burst */
2342       if (mode & CHFL_CHANOP)
2343         sendbuf[(*sblenp)++] = 'o'; /* XXX add_token_to_sendbuf only called by old m_burst */
2344       if (mode & CHFL_VOICE)
2345         sendbuf[(*sblenp)++] = 'v'; /* XXX add_token_to_sendbuf only called by old m_burst */
2346     }
2347     sendbuf[*sblenp] = '\0'; /* XXX add_token_to_sendbuf only called by old m_burst */
2348   }
2349 }
2350
2351 void cancel_mode(struct Client *sptr, struct Channel *chptr, char m,
2352                         const char *param, int *count)
2353 {
2354   static char* pb;
2355   static char* sbp;
2356   static char* sbpi;
2357   int          paramdoesntfit = 0;
2358   char parabuf[MODEBUFLEN];
2359
2360   assert(0 != sptr);
2361   assert(0 != chptr);
2362   assert(0 != count);
2363   
2364   if (*count == -1)             /* initialize ? */
2365   {
2366     /* XXX sendbuf used! */
2367     sbp = sbpi =
2368         sprintf_irc(sendbuf, ":%s MODE %s -", sptr->name, chptr->chname); /* XXX cancel_mode only called from old ms_burst */
2369     pb = parabuf;
2370     *count = 0;
2371   }
2372   /* m == 0 means flush */
2373   if (m)
2374   {
2375     if (param)
2376     {
2377       size_t nplen = strlen(param);
2378       if (pb - parabuf + nplen + 23 > MODEBUFLEN)
2379         paramdoesntfit = 1;
2380       else
2381       {
2382         *sbp++ = m;
2383         *pb++ = ' ';
2384         strcpy(pb, param);
2385         pb += nplen;
2386         ++*count;
2387       }
2388     }
2389     else
2390       *sbp++ = m;
2391   }
2392   else if (*count == 0)
2393     return;
2394   if (*count == 6 || !m || paramdoesntfit)
2395   {
2396     struct Membership* member;
2397     strcpy(sbp, parabuf);
2398     for (member = chptr->members; member; member = member->next_member)
2399       if (MyUser(member->user))
2400         sendbufto_one(member->user); /* XXX cancel_mode only called from old ms_burst */
2401     sbp = sbpi;
2402     pb = parabuf;
2403     *count = 0;
2404   }
2405   if (paramdoesntfit)
2406   {
2407     *sbp++ = m;
2408     *pb++ = ' ';
2409     strcpy(pb, param);
2410     pb += strlen(param);
2411     ++*count;
2412   }
2413 }
2414
2415
2416 /*
2417  * Consider:
2418  *
2419  *                     client
2420  *                       |
2421  *                       c
2422  *                       |
2423  *     X --a--> A --b--> B --d--> D
2424  *                       |
2425  *                      who
2426  *
2427  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
2428  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
2429  *
2430  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
2431  *    Remove the user immedeately when no users are left on the channel.
2432  * b) On server B : remove the user (who/lp) from the channel, send a
2433  *    PART upstream (to A) and pass on the KICK.
2434  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
2435  *    channel, and pass on the KICK.
2436  * d) On server D : remove the user (who/lp) from the channel, and pass on
2437  *    the KICK.
2438  *
2439  * Note:
2440  * - Setting the ZOMBIE flag never hurts, we either remove the
2441  *   client after that or we don't.
2442  * - The KICK message was already passed on, as should be in all cases.
2443  * - `who' is removed in all cases except case a) when users are left.
2444  * - A PART is only sent upstream in case b).
2445  *
2446  * 2 aug 97:
2447  *
2448  *              6
2449  *              |
2450  *  1 --- 2 --- 3 --- 4 --- 5
2451  *        |           |
2452  *      kicker       who
2453  *
2454  * We also need to turn 'who' into a zombie on servers 1 and 6,
2455  * because a KICK from 'who' (kicking someone else in that direction)
2456  * can arrive there afterwards - which should not be bounced itself.
2457  * Therefore case a) also applies for servers 1 and 6.
2458  *
2459  * --Run
2460  */
2461 void make_zombie(struct Membership* member, struct Client* who, struct Client* cptr,
2462                  struct Client* sptr, struct Channel* chptr)
2463 {
2464   assert(0 != member);
2465   assert(0 != who);
2466   assert(0 != cptr);
2467   assert(0 != chptr);
2468
2469   /* Default for case a): */
2470   SetZombie(member);
2471
2472   /* Case b) or c) ?: */
2473   if (MyUser(who))      /* server 4 */
2474   {
2475     if (IsServer(cptr)) /* Case b) ? */
2476       sendcmdto_one(who, CMD_PART, cptr, "%H", chptr);
2477     remove_user_from_channel(who, chptr);
2478     return;
2479   }
2480   if (who->from == cptr)        /* True on servers 1, 5 and 6 */
2481   {
2482     struct Client *acptr = IsServer(sptr) ? sptr : sptr->user->server;
2483     for (; acptr != &me; acptr = acptr->serv->up)
2484       if (acptr == who->user->server)   /* Case d) (server 5) */
2485       {
2486         remove_user_from_channel(who, chptr);
2487         return;
2488       }
2489   }
2490
2491   /* Case a) (servers 1, 2, 3 and 6) */
2492   if (channel_all_zombies(chptr))
2493     remove_user_from_channel(who, chptr);
2494
2495   /* XXX Can't actually call Debug here; if the channel is all zombies,
2496    * chptr will no longer exist when we get here.
2497   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
2498   */
2499 }
2500
2501 int number_of_zombies(struct Channel *chptr)
2502 {
2503   struct Membership* member;
2504   int                count = 0;
2505
2506   assert(0 != chptr);
2507   for (member = chptr->members; member; member = member->next_member) {
2508     if (IsZombie(member))
2509       ++count;
2510   }
2511   return count;
2512 }
2513
2514 /*
2515  * send_hack_notice()
2516  *
2517  * parc & parv[] are the same as that of the calling function:
2518  *   mtype == 1 is from m_mode, 2 is from m_create, 3 is from m_kick.
2519  *
2520  * This function prepares sendbuf with the server notices and wallops
2521  *   to be sent for all hacks.  -Ghostwolf 18-May-97
2522  */
2523 /* XXX let's get rid of this if we can */
2524 void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
2525                       char *parv[], int badop, int mtype)
2526 {
2527   struct Channel *chptr;
2528   static char params[MODEBUFLEN];
2529   int i = 3;
2530   chptr = FindChannel(parv[1]);
2531   *params = '\0';
2532
2533   /* P10 servers require numeric nick conversion before sending. */
2534   switch (mtype)
2535   {
2536     case 1:                     /* Convert nicks for MODE HACKs here  */
2537     {
2538       char *mode = parv[2];
2539       while (i < parc)
2540       {
2541         while (*mode && *mode != 'o' && *mode != 'v')
2542           ++mode;
2543         strcat(params, " ");
2544         if (*mode == 'o' || *mode == 'v')
2545         {
2546           /*
2547            * blindly stumble through parameter list hoping one of them
2548            * might turn out to be a numeric nick
2549            * NOTE: this should not cause a problem but _may_ end up finding
2550            * something we aren't looking for. findNUser should be able to
2551            * handle any garbage that is thrown at it, but may return a client
2552            * if we happen to get lucky with a mode string or a timestamp
2553            */
2554           struct Client *acptr;
2555           if ((acptr = findNUser(parv[i])) != NULL)     /* Convert nicks here */
2556             strcat(params, acptr->name);
2557           else
2558           {
2559             strcat(params, "<");
2560             strcat(params, parv[i]);
2561             strcat(params, ">");
2562           }
2563         }
2564         else                    /* If it isn't a numnick, send it 'as is' */
2565           strcat(params, parv[i]);
2566         i++;
2567       }
2568       sprintf_irc(sendbuf, /* XXX send_hack_notice only called from old m_mode */
2569           ":%s NOTICE * :*** Notice -- %sHACK(%d): %s MODE %s %s%s ["
2570           TIME_T_FMT "]", me.name, (badop == 3) ? "BOUNCE or " : "", badop,
2571           parv[0], parv[1], parv[2], params, chptr->creationtime);
2572       sendbufto_op_mask((badop == 3) ? SNO_HACK3 : (badop == /* XXX DYING */ /* XXX send_hack_notice only called from old m_mode */
2573           4) ? SNO_HACK4 : SNO_HACK2);
2574
2575       if ((IsServer(sptr)) && (badop == 2))
2576       {
2577         sprintf_irc(sendbuf, ":%s DESYNCH :HACK: %s MODE %s %s%s", /* XXX send_hack_notice only called from old m_mode */
2578             me.name, parv[0], parv[1], parv[2], params);
2579         sendbufto_serv_butone(cptr); /* XXX DYING */ /* XXX send_hack_notice only called from old m_mode */
2580       }
2581       break;
2582     }
2583     case 2:                     /* No conversion is needed for CREATE; the only numnick is sptr */
2584     {
2585       sendto_serv_butone(cptr, ":%s DESYNCH :HACK: %s CREATE %s %s", /* XXX DYING */
2586           me.name, sptr->name, chptr->chname, parv[2]);
2587       sendto_op_mask(SNO_HACK2, "HACK(2): %s CREATE %s %s", /* XXX DYING */
2588           sptr->name, chptr->chname, parv[2]);
2589       break;
2590     }
2591     case 3:                     /* Convert nick in KICK message */
2592     {
2593       struct Client *acptr;
2594       if ((acptr = findNUser(parv[2])) != NULL) /* attempt to convert nick */
2595         sprintf_irc(sendbuf, /* XXX send_hack_notice only called from old m_mode */
2596             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s %s :%s",
2597             me.name, sptr->name, parv[1], acptr->name, parv[3]);
2598       else                      /* if conversion fails, send it 'as is' in <>'s */
2599         sprintf_irc(sendbuf, /* XXX send_hack_notice only called from old m_mode */
2600             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s <%s> :%s",
2601             me.name, sptr->name, parv[1], parv[2], parv[3]);
2602       sendbufto_op_mask(SNO_HACK4); /* XXX DYING */ /* XXX send_hack_notice only called from old m_mode */
2603       break;
2604     }
2605   }
2606 }
2607
2608 /*
2609  * This helper function builds an argument string in strptr, consisting
2610  * of the original string, a space, and str1 and str2 concatenated (if,
2611  * of course, str2 is not NULL)
2612  */
2613 static void
2614 build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
2615 {
2616   if (c)
2617     strptr[(*strptr_i)++] = c;
2618
2619   while (*str1)
2620     strptr[(*strptr_i)++] = *(str1++);
2621
2622   if (str2)
2623     while (*str2)
2624       strptr[(*strptr_i)++] = *(str2++);
2625
2626   strptr[(*strptr_i)] = '\0';
2627 }
2628
2629 /*
2630  * This is the workhorse of our ModeBuf suite; this actually generates the
2631  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
2632  */
2633 static int
2634 modebuf_flush_int(struct ModeBuf *mbuf, int all)
2635 {
2636   /* we only need the flags that don't take args right now */
2637   static int flags[] = {
2638 /*  MODE_CHANOP,        'o', */
2639 /*  MODE_VOICE,         'v', */
2640     MODE_PRIVATE,       'p',
2641     MODE_SECRET,        's',
2642     MODE_MODERATED,     'm',
2643     MODE_TOPICLIMIT,    't',
2644     MODE_INVITEONLY,    'i',
2645     MODE_NOPRIVMSGS,    'n',
2646 /*  MODE_KEY,           'k', */
2647 /*  MODE_BAN,           'b', */
2648 /*  MODE_LIMIT,         'l', */
2649     0x0, 0x0
2650   };
2651   int i;
2652   int *flag_p;
2653
2654   struct Client *app_source; /* where the MODE appears to come from */
2655
2656   char addbuf[20]; /* accumulates +psmtin, etc. */
2657   int addbuf_i = 0;
2658   char rembuf[20]; /* accumulates -psmtin, etc. */
2659   int rembuf_i = 0;
2660   char *bufptr; /* we make use of indirection to simplify the code */
2661   int *bufptr_i;
2662
2663   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
2664   int addstr_i;
2665   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
2666   int remstr_i;
2667   char *strptr; /* more indirection to simplify the code */
2668   int *strptr_i;
2669
2670   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
2671   int tmp;
2672
2673   char limitbuf[20]; /* convert limits to strings */
2674
2675   unsigned int limitdel = MODE_LIMIT;
2676
2677   assert(0 != mbuf);
2678
2679   /* If the ModeBuf is empty, we have nothing to do */
2680   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
2681     return 0;
2682
2683   /* Ok, if we were given the OPMODE flag, hide the source if its a user */
2684   if (mbuf->mb_dest & MODEBUF_DEST_OPMODE && !IsServer(mbuf->mb_source))
2685     app_source = mbuf->mb_source->user->server;
2686   else
2687     app_source = mbuf->mb_source;
2688
2689   /*
2690    * Account for user we're bouncing; we have to get it in on the first
2691    * bounced MODE, or we could have problems
2692    */
2693   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
2694     totalbuflen -= 6; /* numeric nick == 5, plus one space */
2695
2696   /* Calculate the simple flags */
2697   for (flag_p = flags; flag_p[0]; flag_p += 2) {
2698     if (*flag_p & mbuf->mb_add)
2699       addbuf[addbuf_i++] = flag_p[1];
2700     else if (*flag_p & mbuf->mb_rem)
2701       rembuf[rembuf_i++] = flag_p[1];
2702   }
2703
2704   /* Now go through the modes with arguments... */
2705   for (i = 0; i < mbuf->mb_count; i++) {
2706     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2707       bufptr = addbuf;
2708       bufptr_i = &addbuf_i;
2709     } else {
2710       bufptr = rembuf;
2711       bufptr_i = &rembuf_i;
2712     }
2713
2714     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
2715       tmp = strlen(MB_CLIENT(mbuf, i)->name);
2716
2717       if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
2718         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2719       else {
2720         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
2721         totalbuflen -= IRCD_MAX(5, tmp) + 1;
2722       }
2723     } else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN)) {
2724       tmp = strlen(MB_STRING(mbuf, i));
2725
2726       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
2727         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2728       else {
2729         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_KEY ? 'k' : 'b';
2730         totalbuflen -= tmp + 1;
2731       }
2732     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
2733       /* if it's a limit, we also format the number */
2734       sprintf_irc(limitbuf, "%d", MB_UINT(mbuf, i));
2735
2736       tmp = strlen(limitbuf);
2737
2738       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
2739         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2740       else {
2741         bufptr[(*bufptr_i)++] = 'l';
2742         totalbuflen -= tmp + 1;
2743       }
2744     }
2745   }
2746
2747   /* terminate the mode strings */
2748   addbuf[addbuf_i] = '\0';
2749   rembuf[rembuf_i] = '\0';
2750
2751   /* If we're building a user visible MODE or HACK... */
2752   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
2753                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
2754                        MODEBUF_DEST_LOG)) {
2755     /* Set up the parameter strings */
2756     addstr[0] = '\0';
2757     addstr_i = 0;
2758     remstr[0] = '\0';
2759     remstr_i = 0;
2760
2761     for (i = 0; i < mbuf->mb_count; i++) {
2762       if (MB_TYPE(mbuf, i) & MODE_SAVE)
2763         continue;
2764
2765       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2766         strptr = addstr;
2767         strptr_i = &addstr_i;
2768       } else {
2769         strptr = remstr;
2770         strptr_i = &remstr_i;
2771       }
2772
2773       /* deal with clients... */
2774       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
2775         build_string(strptr, strptr_i, MB_CLIENT(mbuf, i)->name, 0, ' ');
2776
2777       /* deal with strings... */
2778       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
2779         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
2780
2781       /*
2782        * deal with limit; note we cannot include the limit parameter if we're
2783        * removing it
2784        */
2785       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
2786                (MODE_ADD | MODE_LIMIT))
2787         build_string(strptr, strptr_i, limitbuf, 0, ' ');
2788     }
2789
2790     /* send the messages off to their destination */
2791     if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
2792       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
2793                            "[%Tu]", app_source->name, mbuf->mb_channel->chname,
2794                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2795                            addbuf, remstr, addstr,
2796                            mbuf->mb_channel->creationtime);
2797       sendcmdto_serv_butone(&me, CMD_DESYNCH, mbuf->mb_connect,
2798                             ":HACK: %s MODE %s %s%s%s%s%s%s [%Tu]",
2799                             app_source->name, mbuf->mb_channel->chname,
2800                             rembuf_i ? "-" : "", rembuf,
2801                             addbuf_i ? "+" : "", addbuf, remstr, addstr,
2802                             mbuf->mb_channel->creationtime);
2803     }
2804
2805     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
2806       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
2807                            "%s%s%s%s%s%s [%Tu]", app_source->name,
2808                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
2809                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
2810                            mbuf->mb_channel->creationtime);
2811
2812     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
2813       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
2814                            "[%Tu]", app_source->name, mbuf->mb_channel->chname,
2815                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2816                            addbuf, remstr, addstr,
2817                            mbuf->mb_channel->creationtime);
2818
2819 #ifdef OPATH
2820     if (mbuf->mb_dest & MODEBUF_DEST_LOG) {
2821       write_log(OPATH, "%Tu %#C OPMODE %H %s%s%s%s%s%s\n", TStime(),
2822                 mbuf->mb_source, mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
2823                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
2824     }
2825 #endif
2826
2827     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
2828       sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
2829                                 "%H %s%s%s%s%s%s", mbuf->mb_channel,
2830                                 rembuf_i ? "-" : "", rembuf,
2831                                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
2832   }
2833
2834   /* Now are we supposed to propagate to other servers? */
2835   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
2836     /* set up parameter string */
2837     addstr[0] = '\0';
2838     addstr_i = 0;
2839     remstr[0] = '\0';
2840     remstr_i = 0;
2841
2842     /*
2843      * limit is supressed if we're removing it; we have to figure out which
2844      * direction is the direction for it to be removed, though...
2845      */
2846     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
2847
2848     for (i = 0; i < mbuf->mb_count; i++) {
2849       if (MB_TYPE(mbuf, i) & MODE_SAVE)
2850         continue;
2851
2852       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2853         strptr = addstr;
2854         strptr_i = &addstr_i;
2855       } else {
2856         strptr = remstr;
2857         strptr_i = &remstr_i;
2858       }
2859
2860       /* deal with modes that take clients */
2861       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
2862         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
2863
2864       /* deal with modes that take strings */
2865       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
2866         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
2867
2868       /*
2869        * deal with the limit.  Logic here is complicated; if HACK2 is set,
2870        * we're bouncing the mode, so sense is reversed, and we have to
2871        * include the original limit if it looks like it's being removed
2872        */
2873       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
2874         build_string(strptr, strptr_i, limitbuf, 0, ' ');
2875     }
2876
2877     /* we were told to deop the source */
2878     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
2879       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
2880       addbuf[addbuf_i] = '\0'; /* terminate the string... */
2881       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
2882
2883       /* mark that we've done this, so we don't do it again */
2884       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
2885     }
2886
2887     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
2888       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
2889       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
2890                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
2891                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2892                             addbuf, remstr, addstr);
2893     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
2894       /*
2895        * If HACK2 was set, we're bouncing; we send the MODE back to the
2896        * connection we got it from with the senses reversed and a TS of 0;
2897        * origin is us
2898        */
2899       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
2900                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
2901                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
2902                     mbuf->mb_channel->creationtime);
2903     } else {
2904       /*
2905        * We're propagating a normal MODE command to the rest of the network;
2906        * we send the actual channel TS unless this is a HACK3 or a HACK4
2907        */
2908       if (IsServer(mbuf->mb_source))
2909         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
2910                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
2911                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2912                               addbuf, remstr, addstr,
2913                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
2914                               mbuf->mb_channel->creationtime);
2915       else
2916         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
2917                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
2918                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2919                               addbuf, remstr, addstr);
2920     }
2921   }
2922
2923   /* We've drained the ModeBuf... */
2924   mbuf->mb_add = 0;
2925   mbuf->mb_rem = 0;
2926   mbuf->mb_count = 0;
2927
2928   /* reinitialize the mode-with-arg slots */
2929   for (i = 0; i < MAXMODEPARAMS; i++) {
2930     /* If we saved any, pack them down */
2931     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
2932       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
2933       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
2934
2935       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
2936         continue;
2937     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
2938       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
2939
2940     MB_TYPE(mbuf, i) = 0;
2941     MB_UINT(mbuf, i) = 0;
2942   }
2943
2944   /* If we're supposed to flush it all, do so--all hail tail recursion */
2945   if (all && mbuf->mb_count)
2946     return modebuf_flush_int(mbuf, 1);
2947
2948   return 0;
2949 }
2950
2951 /*
2952  * This routine just initializes a ModeBuf structure with the information
2953  * needed and the options given.
2954  */
2955 void
2956 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
2957              struct Client *connect, struct Channel *chan, unsigned int dest)
2958 {
2959   int i;
2960
2961   assert(0 != mbuf);
2962   assert(0 != source);
2963   assert(0 != chan);
2964   assert(0 != dest);
2965
2966   mbuf->mb_add = 0;
2967   mbuf->mb_rem = 0;
2968   mbuf->mb_source = source;
2969   mbuf->mb_connect = connect;
2970   mbuf->mb_channel = chan;
2971   mbuf->mb_dest = dest;
2972   mbuf->mb_count = 0;
2973
2974   /* clear each mode-with-parameter slot */
2975   for (i = 0; i < MAXMODEPARAMS; i++) {
2976     MB_TYPE(mbuf, i) = 0;
2977     MB_UINT(mbuf, i) = 0;
2978   }
2979 }
2980
2981 /*
2982  * This routine simply adds modes to be added or deleted; do a binary OR
2983  * with either MODE_ADD or MODE_DEL
2984  */
2985 void
2986 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
2987 {
2988   assert(0 != mbuf);
2989   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
2990
2991   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
2992            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
2993
2994   if (mode & MODE_ADD) {
2995     mbuf->mb_rem &= ~mode;
2996     mbuf->mb_add |= mode;
2997   } else {
2998     mbuf->mb_add &= ~mode;
2999     mbuf->mb_rem |= mode;
3000   }
3001 }
3002
3003 /*
3004  * This routine adds a mode to be added or deleted that takes a unsigned
3005  * int parameter; mode may *only* be the relevant mode flag ORed with one
3006  * of MODE_ADD or MODE_DEL
3007  */
3008 void
3009 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
3010 {
3011   assert(0 != mbuf);
3012   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3013
3014   MB_TYPE(mbuf, mbuf->mb_count) = mode;
3015   MB_UINT(mbuf, mbuf->mb_count) = uint;
3016
3017   /* when we've reached the maximal count, flush the buffer */
3018   if (++mbuf->mb_count >=
3019       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3020     modebuf_flush_int(mbuf, 0);
3021 }
3022
3023 /*
3024  * This routine adds a mode to be added or deleted that takes a string
3025  * parameter; mode may *only* be the relevant mode flag ORed with one of
3026  * MODE_ADD or MODE_DEL
3027  */
3028 void
3029 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
3030                     int free)
3031 {
3032   assert(0 != mbuf);
3033   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3034
3035   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
3036   MB_STRING(mbuf, mbuf->mb_count) = string;
3037
3038   /* when we've reached the maximal count, flush the buffer */
3039   if (++mbuf->mb_count >=
3040       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3041     modebuf_flush_int(mbuf, 0);
3042 }
3043
3044 /*
3045  * This routine adds a mode to be added or deleted that takes a client
3046  * parameter; mode may *only* be the relevant mode flag ORed with one of
3047  * MODE_ADD or MODE_DEL
3048  */
3049 void
3050 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
3051                     struct Client *client)
3052 {
3053   assert(0 != mbuf);
3054   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3055
3056   MB_TYPE(mbuf, mbuf->mb_count) = mode;
3057   MB_CLIENT(mbuf, mbuf->mb_count) = client;
3058
3059   /* when we've reached the maximal count, flush the buffer */
3060   if (++mbuf->mb_count >=
3061       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3062     modebuf_flush_int(mbuf, 0);
3063 }
3064
3065 /*
3066  * This is the exported binding for modebuf_flush()
3067  */
3068 int
3069 modebuf_flush(struct ModeBuf *mbuf)
3070 {
3071   return modebuf_flush_int(mbuf, 1);
3072 }
3073
3074 /*
3075  * This extracts the simple modes contained in mbuf
3076  */
3077 void
3078 modebuf_extract(struct ModeBuf *mbuf, char *buf)
3079 {
3080   static int flags[] = {
3081 /*  MODE_CHANOP,        'o', */
3082 /*  MODE_VOICE,         'v', */
3083     MODE_PRIVATE,       'p',
3084     MODE_SECRET,        's',
3085     MODE_MODERATED,     'm',
3086     MODE_TOPICLIMIT,    't',
3087     MODE_INVITEONLY,    'i',
3088     MODE_NOPRIVMSGS,    'n',
3089     MODE_KEY,           'k',
3090 /*  MODE_BAN,           'b', */
3091     MODE_LIMIT,         'l',
3092     0x0, 0x0
3093   };
3094   unsigned int add;
3095   int i, bufpos = 0, len;
3096   int *flag_p;
3097   char *key = 0, limitbuf[20];
3098
3099   assert(0 != mbuf);
3100   assert(0 != buf);
3101
3102   buf[0] = '\0';
3103
3104   add = mbuf->mb_add;
3105
3106   for (i = 0; i < mbuf->mb_count; i++) { /* find keys and limits */
3107     if (MB_TYPE(mbuf, i) & MODE_ADD) {
3108       add |= MB_TYPE(mbuf, i) & (MODE_KEY | MODE_LIMIT);
3109
3110       if (MB_TYPE(mbuf, i) & MODE_KEY) /* keep strings */
3111         key = MB_STRING(mbuf, i);
3112       else if (MB_TYPE(mbuf, i) & MODE_LIMIT)
3113         ircd_snprintf(0, limitbuf, sizeof(limitbuf), "%d", MB_UINT(mbuf, i));
3114     }
3115   }
3116
3117   if (!add)
3118     return;
3119
3120   buf[bufpos++] = '+'; /* start building buffer */
3121
3122   for (flag_p = flags; flag_p[0]; flag_p += 2)
3123     if (*flag_p & add)
3124       buf[bufpos++] = flag_p[1];
3125
3126   for (i = 0, len = bufpos; i < len; i++) {
3127     if (buf[i] == 'k')
3128       build_string(buf, &bufpos, key, 0, ' ');
3129     else if (buf[i] == 'l')
3130       build_string(buf, &bufpos, limitbuf, 0, ' ');
3131   }
3132
3133   buf[bufpos] = '\0';
3134
3135   return;
3136 }
3137
3138 /*
3139  * Simple function to invalidate bans
3140  */
3141 void
3142 mode_ban_invalidate(struct Channel *chan)
3143 {
3144   struct Membership *member;
3145
3146   for (member = chan->members; member; member = member->next_member)
3147     ClearBanValid(member);
3148 }
3149
3150 /*
3151  * Simple function to drop invite structures
3152  */
3153 void
3154 mode_invite_clear(struct Channel *chan)
3155 {
3156   while (chan->invites)
3157     del_invite(chan->invites->value.cptr, chan);
3158 }
3159
3160 /* What we've done for mode_parse so far... */
3161 #define DONE_LIMIT      0x01    /* We've set the limit */
3162 #define DONE_KEY        0x02    /* We've set the key */
3163 #define DONE_BANLIST    0x04    /* We've sent the ban list */
3164 #define DONE_NOTOPER    0x08    /* We've sent a "Not oper" error */
3165 #define DONE_BANCLEAN   0x10    /* We've cleaned bans... */
3166
3167 struct ParseState {
3168   struct ModeBuf *mbuf;
3169   struct Client *cptr;
3170   struct Client *sptr;
3171   struct Channel *chptr;
3172   int parc;
3173   char **parv;
3174   unsigned int flags;
3175   unsigned int dir;
3176   unsigned int done;
3177   int args_used;
3178   int max_args;
3179   int numbans;
3180   struct SLink banlist[MAXPARA];
3181   struct {
3182     unsigned int flag;
3183     struct Client *client;
3184   } cli_change[MAXPARA];
3185 };
3186
3187 /*
3188  * Here's a helper function to deal with sending along "Not oper" or
3189  * "Not member" messages
3190  */
3191 static void
3192 send_notoper(struct ParseState *state)
3193 {
3194   if (state->done & DONE_NOTOPER)
3195     return;
3196
3197   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
3198              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
3199
3200   state->done |= DONE_NOTOPER;
3201 }
3202
3203 /*
3204  * Helper function to convert limits
3205  */
3206 static void
3207 mode_parse_limit(struct ParseState *state, int *flag_p)
3208 {
3209   unsigned int t_limit;
3210
3211   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
3212     if (MyUser(state->sptr) && state->max_args <= 0) /* too many args? */
3213       return;
3214
3215     if (state->parc <= 0) { /* warn if not enough args */
3216       if (MyUser(state->sptr))
3217         need_more_params(state->sptr, "MODE +l");
3218       return;
3219     }
3220
3221     t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
3222     state->parc--;
3223     state->max_args--;
3224
3225     if (!(state->flags & MODE_PARSE_WIPEOUT) &&
3226         (!t_limit || t_limit == state->chptr->mode.limit))
3227       return;
3228   } else
3229     t_limit = state->chptr->mode.limit;
3230
3231   /* If they're not an oper, they can't change modes */
3232   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3233     send_notoper(state);
3234     return;
3235   }
3236
3237   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
3238     return;
3239   state->done |= DONE_LIMIT;
3240
3241   if (!state->mbuf)
3242     return;
3243
3244   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
3245
3246   if (state->flags & MODE_PARSE_SET) { /* set the limit */
3247     if (state->dir & MODE_ADD) {
3248       state->chptr->mode.mode |= flag_p[0];
3249       state->chptr->mode.limit = t_limit;
3250     } else {
3251       state->chptr->mode.mode &= flag_p[0];
3252       state->chptr->mode.limit = 0;
3253     }
3254   }
3255 }
3256
3257 /*
3258  * Helper function to convert keys
3259  */
3260 static void
3261 mode_parse_key(struct ParseState *state, int *flag_p)
3262 {
3263   char *t_str, *s;
3264   int t_len;
3265
3266   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3267     return;
3268
3269   if (state->parc <= 0) { /* warn if not enough args */
3270     if (MyUser(state->sptr))
3271       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
3272                        "MODE -k");
3273     return;
3274   }
3275
3276   t_str = state->parv[state->args_used++]; /* grab arg */
3277   state->parc--;
3278   state->max_args--;
3279
3280   /* If they're not an oper, they can't change modes */
3281   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3282     send_notoper(state);
3283     return;
3284   }
3285
3286   if (state->done & DONE_KEY) /* allow key to be set only once */
3287     return;
3288   state->done |= DONE_KEY;
3289
3290   t_len = KEYLEN + 1;
3291
3292   /* clean up the key string */
3293   s = t_str;
3294   while (*++s > ' ' && *s != ':' && --t_len)
3295     ;
3296   *s = '\0';
3297
3298   if (!*t_str) { /* warn if empty */
3299     if (MyUser(state->sptr))
3300       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
3301                        "MODE -k");
3302     return;
3303   }
3304
3305   if (!state->mbuf)
3306     return;
3307
3308   /* can't add a key if one is set, nor can one remove the wrong key */
3309   if (!(state->flags & MODE_PARSE_FORCE))
3310     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
3311         (state->dir == MODE_DEL &&
3312          ircd_strcmp(state->chptr->mode.key, t_str))) {
3313       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
3314       return;
3315     }
3316
3317   if (!(state->flags & MODE_PARSE_WIPEOUT) && state->dir == MODE_ADD &&
3318       !ircd_strcmp(state->chptr->mode.key, t_str))
3319     return; /* no key change */
3320
3321   if (state->flags & MODE_PARSE_BOUNCE) {
3322     if (*state->chptr->mode.key) /* reset old key */
3323       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
3324                           state->chptr->mode.key, 0);
3325     else /* remove new bogus key */
3326       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
3327   } else /* send new key */
3328     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
3329
3330   if (state->flags & MODE_PARSE_SET) {
3331     if (state->dir == MODE_ADD) /* set the new key */
3332       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
3333     else /* remove the old key */
3334       *state->chptr->mode.key = '\0';
3335   }
3336 }
3337
3338 /*
3339  * Helper function to convert bans
3340  */
3341 static void
3342 mode_parse_ban(struct ParseState *state, int *flag_p)
3343 {
3344   char *t_str, *s;
3345   struct SLink *ban, *newban = 0;
3346
3347   if (state->parc <= 0) { /* Not enough args, send ban list */
3348     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
3349       send_ban_list(state->sptr, state->chptr);
3350       state->done |= DONE_BANLIST;
3351     }
3352
3353     return;
3354   }
3355
3356   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3357     return;
3358
3359   t_str = state->parv[state->args_used++]; /* grab arg */
3360   state->parc--;
3361   state->max_args--;
3362
3363   /* If they're not an oper, they can't change modes */
3364   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3365     send_notoper(state);
3366     return;
3367   }
3368
3369   if ((s = strchr(t_str, ' ')))
3370     *s = '\0';
3371
3372   if (!*t_str || *t_str == ':') { /* warn if empty */
3373     if (MyUser(state->sptr))
3374       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
3375                        "MODE -b");
3376     return;
3377   }
3378
3379   t_str = collapse(pretty_mask(t_str));
3380
3381   /* remember the ban for the moment... */
3382   if (state->dir == MODE_ADD) {
3383     newban = state->banlist + (state->numbans++);
3384     newban->next = 0;
3385
3386     DupString(newban->value.ban.banstr, t_str);
3387     newban->value.ban.who = state->sptr->name;
3388     newban->value.ban.when = TStime();
3389
3390     newban->flags = CHFL_BAN | MODE_ADD;
3391
3392     if ((s = strrchr(t_str, '@')) && check_if_ipmask(s + 1))
3393       newban->flags |= CHFL_BAN_IPMASK;
3394   }
3395
3396   if (!state->chptr->banlist) {
3397     state->chptr->banlist = newban; /* add our ban with its flags */
3398     state->done |= DONE_BANCLEAN;
3399     return;
3400   }
3401
3402   /* Go through all bans */
3403   for (ban = state->chptr->banlist; ban; ban = ban->next) {
3404     /* first, clean the ban flags up a bit */
3405     if (!(state->done & DONE_BANCLEAN))
3406       /* Note: We're overloading *lots* of bits here; be careful! */
3407       ban->flags &= ~(MODE_ADD | MODE_DEL | CHFL_BAN_OVERLAPPED);
3408
3409     /* Bit meanings:
3410      *
3411      * MODE_ADD            - Ban was added; if we're bouncing modes,
3412      *                       then we'll remove it below; otherwise,
3413      *                       we'll have to allocate a real ban
3414      *
3415      * MODE_DEL            - Ban was marked for deletion; if we're
3416      *                       bouncing modes, we'll have to re-add it,
3417      *                       otherwise, we'll have to remove it
3418      *
3419      * CHFL_BAN_OVERLAPPED - The ban we added turns out to overlap
3420      *                       with a ban already set; if we're
3421      *                       bouncing modes, we'll have to bounce
3422      *                       this one; otherwise, we'll just ignore
3423      *                       it when we process added bans
3424      */
3425
3426     if (state->dir == MODE_DEL && !ircd_strcmp(ban->value.ban.banstr, t_str)) {
3427       ban->flags |= MODE_DEL; /* delete one ban */
3428
3429       if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
3430         break;
3431     } else if (state->dir == MODE_ADD) {
3432       /* if the ban already exists, don't worry about it */
3433       if (!ircd_strcmp(ban->value.ban.banstr, t_str)) {
3434         if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
3435           break;
3436         continue;
3437       } else if (!mmatch(ban->value.ban.banstr, t_str)) {
3438         if (!(ban->flags & MODE_DEL))
3439           newban->flags |= CHFL_BAN_OVERLAPPED; /* our ban overlaps */
3440       } else if (!mmatch(t_str, ban->value.ban.banstr))
3441         ban->flags |= MODE_DEL; /* mark ban for deletion: overlapping */
3442
3443       if (!ban->next) {
3444         ban->next = newban; /* add our ban with its flags */
3445         break; /* get out of loop */
3446       }
3447     }
3448   }
3449   state->done |= DONE_BANCLEAN;
3450 }
3451
3452 /*
3453  * This is the bottom half of the ban processor
3454  */
3455 static void
3456 mode_process_bans(struct ParseState *state)
3457 {
3458   struct SLink *ban, *newban, *prevban, *nextban;
3459   int count = 0;
3460   int len = 0;
3461   int banlen;
3462   int changed = 0;
3463
3464   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
3465     count++;
3466     banlen = strlen(ban->value.ban.banstr);
3467     len += banlen;
3468     nextban = ban->next;
3469
3470     if ((ban->flags & (MODE_DEL | MODE_ADD)) == (MODE_DEL | MODE_ADD)) {
3471       if (prevban)
3472         prevban->next = 0; /* Break the list; ban isn't a real ban */
3473       else
3474         state->chptr->banlist = 0;
3475
3476       count--;
3477       len -= banlen;
3478
3479       MyFree(ban->value.ban.banstr);
3480
3481       continue;
3482     } else if (ban->flags & MODE_DEL) { /* Deleted a ban? */
3483       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
3484                           ban->value.ban.banstr,
3485                           state->flags & MODE_PARSE_SET);
3486
3487       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
3488         if (prevban) /* clip it out of the list... */
3489           prevban->next = ban->next;
3490         else
3491           state->chptr->banlist = ban->next;
3492
3493         count--;
3494         len -= banlen;
3495
3496         MyFree(ban->value.ban.who);
3497         free_link(ban);
3498
3499         changed++;
3500         continue; /* next ban; keep prevban like it is */
3501       } else
3502         ban->flags &= (CHFL_BAN | CHFL_BAN_IPMASK); /* unset other flags */
3503     } else if (ban->flags & MODE_ADD) { /* adding a ban? */
3504       if (prevban)
3505         prevban->next = 0; /* Break the list; ban isn't a real ban */
3506       else
3507         state->chptr->banlist = 0;
3508
3509       /* If we're supposed to ignore it, do so. */
3510       if (ban->flags & CHFL_BAN_OVERLAPPED &&
3511           !(state->flags & MODE_PARSE_BOUNCE)) {
3512         count--;
3513         len -= banlen;
3514
3515         MyFree(ban->value.ban.banstr);
3516       } else {
3517         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
3518             (len > MAXBANLENGTH || count >= MAXBANS)) {
3519           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
3520                      ban->value.ban.banstr);
3521           count--;
3522           len -= banlen;
3523
3524           MyFree(ban->value.ban.banstr);
3525         } else {
3526           /* add the ban to the buffer */
3527           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
3528                               ban->value.ban.banstr,
3529                               !(state->flags & MODE_PARSE_SET));
3530
3531           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
3532             newban = make_link();
3533             newban->value.ban.banstr = ban->value.ban.banstr;
3534             DupString(newban->value.ban.who, ban->value.ban.who);
3535             newban->value.ban.when = ban->value.ban.when;
3536             newban->flags = ban->flags & (CHFL_BAN | CHFL_BAN_IPMASK);
3537
3538             newban->next = state->chptr->banlist; /* and link it in */
3539             state->chptr->banlist = newban;
3540
3541             changed++;
3542           }
3543         }
3544       }
3545     }
3546
3547     prevban = ban;
3548   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
3549
3550   if (changed) /* if we changed the ban list, we must invalidate the bans */
3551     mode_ban_invalidate(state->chptr);
3552 }
3553
3554 /*
3555  * Helper function to process client changes
3556  */
3557 static void
3558 mode_parse_client(struct ParseState *state, int *flag_p)
3559 {
3560   char *t_str;
3561   struct Client *acptr;
3562   int i;
3563
3564   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3565     return;
3566
3567   if (state->parc <= 0) /* return if not enough args */
3568     return;
3569
3570   t_str = state->parv[state->args_used++]; /* grab arg */
3571   state->parc--;
3572   state->max_args--;
3573
3574   /* If they're not an oper, they can't change modes */
3575   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3576     send_notoper(state);
3577     return;
3578   }
3579
3580   if (MyUser(state->sptr)) /* find client we're manipulating */
3581     acptr = find_chasing(state->sptr, t_str, NULL);
3582   else
3583     acptr = findNUser(t_str);
3584
3585   if (!acptr)
3586     return; /* find_chasing() already reported an error to the user */
3587
3588   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
3589     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
3590                                        state->cli_change[i].flag & flag_p[0]))
3591       break; /* found a slot */
3592
3593   /* Store what we're doing to them */
3594   state->cli_change[i].flag = state->dir | flag_p[0];
3595   state->cli_change[i].client = acptr;
3596 }
3597
3598 /*
3599  * Helper function to process the changed client list
3600  */
3601 static void
3602 mode_process_clients(struct ParseState *state)
3603 {
3604   int i;
3605   struct Membership *member;
3606
3607   for (i = 0; state->cli_change[i].flag; i++) {
3608     assert(0 != state->cli_change[i].client);
3609
3610     /* look up member link */
3611     if (!(member = find_member_link(state->chptr,
3612                                     state->cli_change[i].client)) ||
3613         (MyUser(state->sptr) && IsZombie(member))) {
3614       if (MyUser(state->sptr))
3615         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
3616                    state->cli_change[i].client->name, state->chptr->chname);
3617       continue;
3618     }
3619
3620     if ((state->cli_change[i].flag & MODE_ADD &&
3621          (state->cli_change[i].flag & member->status)) ||
3622         (state->cli_change[i].flag & MODE_DEL &&
3623          !(state->cli_change[i].flag & member->status)))
3624       continue; /* no change made, don't do anything */
3625
3626     /* see if the deop is allowed */
3627     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
3628         (MODE_DEL | MODE_CHANOP)) {
3629       /* prevent +k users from being deopped */
3630       if (IsChannelService(state->cli_change[i].client)) {
3631         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
3632           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
3633                                state->chptr,
3634                                (IsServer(state->sptr) ? state->sptr->name :
3635                                 state->sptr->user->server->name));
3636
3637         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
3638           send_reply(state->sptr, ERR_ISCHANSERVICE,
3639                      state->cli_change[i].client->name, state->chptr->chname);
3640           continue;
3641         }
3642       }
3643
3644 #ifdef NO_OPER_DEOP_LCHAN
3645       /* don't allow local opers to be deopped on local channels */
3646       if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
3647           IsOperOnLocalChannel(state->cli_change[i].client,
3648                                state->chptr->chname)) {
3649         send_reply(state->sptr, ERR_ISOPERLCHAN,
3650                    state->cli_change[i].client->name, state->chptr->chname);
3651         continue;
3652       }
3653 #endif
3654     }
3655
3656     /* accumulate the change */
3657     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
3658                         state->cli_change[i].client);
3659
3660     /* actually effect the change */
3661     if (state->flags & MODE_PARSE_SET) {
3662       if (state->cli_change[i].flag & MODE_ADD) {
3663         member->status |= (state->cli_change[i].flag &
3664                            (MODE_CHANOP | MODE_VOICE));
3665         if (state->cli_change[i].flag & MODE_CHANOP)
3666           ClearDeopped(member);
3667       } else
3668         member->status &= ~(state->cli_change[i].flag &
3669                             (MODE_CHANOP | MODE_VOICE));
3670     }
3671   } /* for (i = 0; state->cli_change[i].flags; i++) { */
3672 }
3673
3674 /*
3675  * Helper function to process the simple modes
3676  */
3677 static void
3678 mode_parse_mode(struct ParseState *state, int *flag_p)
3679 {
3680   if ((state->dir == MODE_ADD &&  (flag_p[0] & state->chptr->mode.mode)) ||
3681       (state->dir == MODE_DEL && !(flag_p[0] & state->chptr->mode.mode)))
3682     return; /* no change */
3683
3684   /* If they're not an oper, they can't change modes */
3685   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3686     send_notoper(state);
3687     return;
3688   }
3689
3690   if (!state->mbuf)
3691     return;
3692
3693   modebuf_mode(state->mbuf, state->dir | flag_p[0]);
3694
3695   /* make +p and +s mutually exclusive */
3696   if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
3697     if (flag_p[0] == MODE_SECRET && (state->chptr->mode.mode & MODE_PRIVATE))
3698       modebuf_mode(state->mbuf, MODE_DEL | MODE_PRIVATE);
3699     else if (flag_p[0] == MODE_PRIVATE &&
3700              (state->chptr->mode.mode & MODE_SECRET))
3701       modebuf_mode(state->mbuf, MODE_DEL | MODE_SECRET);
3702   }
3703
3704   if (state->flags & MODE_PARSE_SET) { /* set the flags */
3705     if (state->dir == MODE_ADD) { /* add the mode to the channel */
3706       state->chptr->mode.mode |= flag_p[0];
3707
3708       /* make +p and +s mutually exclusive */
3709       if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
3710         if (flag_p[0] == MODE_PRIVATE)
3711           state->chptr->mode.mode &= ~MODE_SECRET;
3712         else
3713           state->chptr->mode.mode &= ~MODE_PRIVATE;
3714       }
3715     } else /* remove the mode from the channel */
3716       state->chptr->mode.mode &= ~flag_p[0];
3717   }
3718
3719   /* Clear out invite structures if we're removing invites */
3720   if (state->flags & MODE_PARSE_SET && state->dir == MODE_DEL &&
3721       flag_p[0] == MODE_INVITEONLY)
3722     mode_invite_clear(state->chptr);
3723 }
3724
3725 /*
3726  * This routine is intended to parse MODE or OPMODE commands and effect the
3727  * changes (or just build the bounce buffer).  We pass the starting offset
3728  * as a 
3729  */
3730 int
3731 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
3732            struct Channel *chptr, int parc, char *parv[], unsigned int flags)
3733 {
3734   static int chan_flags[] = {
3735     MODE_CHANOP,        'o',
3736     MODE_VOICE,         'v',
3737     MODE_PRIVATE,       'p',
3738     MODE_SECRET,        's',
3739     MODE_MODERATED,     'm',
3740     MODE_TOPICLIMIT,    't',
3741     MODE_INVITEONLY,    'i',
3742     MODE_NOPRIVMSGS,    'n',
3743     MODE_KEY,           'k',
3744     MODE_BAN,           'b',
3745     MODE_LIMIT,         'l',
3746     MODE_ADD,           '+',
3747     MODE_DEL,           '-',
3748     0x0, 0x0
3749   };
3750   int i;
3751   int *flag_p;
3752   char *modestr;
3753   struct ParseState state;
3754
3755   assert(0 != cptr);
3756   assert(0 != sptr);
3757   assert(0 != chptr);
3758   assert(0 != parc);
3759   assert(0 != parv);
3760
3761   state.mbuf = mbuf;
3762   state.cptr = cptr;
3763   state.sptr = sptr;
3764   state.chptr = chptr;
3765   state.parc = parc;
3766   state.parv = parv;
3767   state.flags = flags;
3768   state.dir = MODE_ADD;
3769   state.done = 0;
3770   state.args_used = 0;
3771   state.max_args = MAXMODEPARAMS;
3772   state.numbans = 0;
3773
3774   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
3775     state.banlist[i].next = 0;
3776     state.banlist[i].value.ban.banstr = 0;
3777     state.banlist[i].value.ban.who = 0;
3778     state.banlist[i].value.ban.when = 0;
3779     state.banlist[i].flags = 0;
3780     state.cli_change[i].flag = 0;
3781     state.cli_change[i].client = 0;
3782   }
3783
3784   modestr = state.parv[state.args_used++];
3785   state.parc--;
3786
3787   while (*modestr) {
3788     for (; *modestr; modestr++) {
3789       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
3790         if (flag_p[1] == *modestr)
3791           break;
3792
3793       if (!flag_p[0]) { /* didn't find it?  complain and continue */
3794         if (MyUser(state.sptr))
3795           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
3796         continue;
3797       }
3798
3799       switch (*modestr) {
3800       case '+': /* switch direction to MODE_ADD */
3801       case '-': /* switch direction to MODE_DEL */
3802         state.dir = flag_p[0];
3803         break;
3804
3805       case 'l': /* deal with limits */
3806         mode_parse_limit(&state, flag_p);
3807         break;
3808
3809       case 'k': /* deal with keys */
3810         mode_parse_key(&state, flag_p);
3811         break;
3812
3813       case 'b': /* deal with bans */
3814         mode_parse_ban(&state, flag_p);
3815         break;
3816
3817       case 'o': /* deal with ops/voice */
3818       case 'v':
3819         mode_parse_client(&state, flag_p);
3820         break;
3821
3822       default: /* deal with other modes */
3823         mode_parse_mode(&state, flag_p);
3824         break;
3825       } /* switch (*modestr) { */
3826     } /* for (; *modestr; modestr++) { */
3827
3828     if (state.flags & MODE_PARSE_BURST)
3829       break; /* don't interpret any more arguments */
3830
3831     if (state.parc > 0) { /* process next argument in string */
3832       modestr = state.parv[state.args_used++];
3833       state.parc--;
3834
3835       /* is it a TS? */
3836       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
3837         time_t recv_ts;
3838
3839         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
3840           break;                     /* we're then going to bounce the mode! */
3841
3842         recv_ts = atoi(modestr);
3843
3844         if (recv_ts && recv_ts < state.chptr->creationtime)
3845           state.chptr->creationtime = recv_ts; /* respect earlier TS */
3846
3847         break; /* break out of while loop */
3848       } else if (state.flags & MODE_PARSE_STRICT ||
3849                  (MyUser(state.sptr) && state.max_args <= 0)) {
3850         state.parc++; /* we didn't actually gobble the argument */
3851         state.args_used--;
3852         break; /* break out of while loop */
3853       }
3854     }
3855   } /* while (*modestr) { */
3856
3857   /*
3858    * the rest of the function finishes building resultant MODEs; if the
3859    * origin isn't a member or an oper, skip it.
3860    */
3861   if (!state.mbuf || state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
3862     return state.args_used; /* tell our parent how many args we gobbled */
3863
3864   if (state.flags & MODE_PARSE_WIPEOUT) {
3865     if (state.chptr->mode.limit && !(state.done & DONE_LIMIT))
3866       modebuf_mode_uint(state.mbuf, MODE_DEL | MODE_LIMIT,
3867                         state.chptr->mode.limit);
3868     if (*state.chptr->mode.key && !(state.done & DONE_KEY))
3869       modebuf_mode_string(state.mbuf, MODE_DEL | MODE_KEY,
3870                           state.chptr->mode.key, 0);
3871   }
3872
3873   if (state.done & DONE_BANCLEAN) /* process bans */
3874     mode_process_bans(&state);
3875
3876   /* process client changes */
3877   if (state.cli_change[0].flag)
3878     mode_process_clients(&state);
3879
3880   return state.args_used; /* tell our parent how many args we gobbled */
3881 }
3882
3883 /*
3884  * Initialize a join buffer
3885  */
3886 void
3887 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
3888              struct Client *connect, unsigned int type, char *comment,
3889              time_t create)
3890 {
3891   int i;
3892
3893   assert(0 != jbuf);
3894   assert(0 != source);
3895   assert(0 != connect);
3896
3897   jbuf->jb_source = source; /* just initialize struct JoinBuf */
3898   jbuf->jb_connect = connect;
3899   jbuf->jb_type = type;
3900   jbuf->jb_comment = comment;
3901   jbuf->jb_create = create;
3902   jbuf->jb_count = 0;
3903   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
3904                        type == JOINBUF_TYPE_PART ||
3905                        type == JOINBUF_TYPE_PARTALL) ?
3906                       STARTJOINLEN : STARTCREATELEN) +
3907                      (comment ? strlen(comment) + 2 : 0));
3908
3909   for (i = 0; i < MAXJOINARGS; i++)
3910     jbuf->jb_channels[i] = 0;
3911 }
3912
3913 /*
3914  * Add a channel to the join buffer
3915  */
3916 void
3917 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
3918 {
3919   unsigned int len;
3920
3921   assert(0 != jbuf);
3922
3923   if (chan) {
3924     if (jbuf->jb_type == JOINBUF_TYPE_PART ||
3925         jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
3926       /* Send notification to channel */
3927       if (!(flags & CHFL_ZOMBIE))
3928         sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
3929                                   (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3930                                   ":%H" : "%H :%s", chan, jbuf->jb_comment);
3931       else if (MyUser(jbuf->jb_source))
3932         sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
3933                       (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3934                       ":%H" : "%H :%s", chan, jbuf->jb_comment);
3935       /* XXX: Shouldn't we send a PART here anyway? */
3936       /* to users on the channel?  Why?  From their POV, the user isn't on
3937        * the channel anymore anyway.  We don't send to servers until below,
3938        * when we gang all the channel parts together.  Note that this is
3939        * exactly the same logic, albeit somewhat more concise, as was in
3940        * the original m_part.c */
3941
3942       if (jbuf->jb_type == JOINBUF_TYPE_PARTALL ||
3943           IsLocalChannel(chan->chname)) /* got to remove user here */
3944         remove_user_from_channel(jbuf->jb_source, chan);
3945     } else {
3946       /* Add user to channel */
3947       add_user_to_channel(chan, jbuf->jb_source, flags);
3948
3949       /* Send the notification to the channel */
3950       sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
3951
3952       /* send an op, too, if needed */
3953       if (!MyUser(jbuf->jb_source) && jbuf->jb_type == JOINBUF_TYPE_CREATE &&
3954           !IsModelessChannel(chan->chname))
3955         sendcmdto_channel_butserv(jbuf->jb_source, CMD_MODE, chan, "%H +o %C",
3956                                   chan, jbuf->jb_source);
3957     }
3958
3959     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
3960       return; /* don't send to remote */
3961   }
3962
3963   /* figure out if channel name will cause buffer to be overflowed */
3964   len = chan ? strlen(chan->chname) + 1 : 2;
3965   if (jbuf->jb_strlen + len > IRC_BUFSIZE)
3966     joinbuf_flush(jbuf);
3967
3968   /* add channel to list of channels to send and update counts */
3969   jbuf->jb_channels[jbuf->jb_count++] = chan;
3970   jbuf->jb_strlen += len;
3971
3972   /* if we've used up all slots, flush */
3973   if (jbuf->jb_count >= MAXJOINARGS)
3974     joinbuf_flush(jbuf);
3975 }
3976
3977 /*
3978  * Flush the channel list to remote servers
3979  */
3980 int
3981 joinbuf_flush(struct JoinBuf *jbuf)
3982 {
3983   char chanlist[IRC_BUFSIZE];
3984   int chanlist_i = 0;
3985   int i;
3986
3987   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL)
3988     return 0; /* no joins to process */
3989
3990   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
3991     build_string(chanlist, &chanlist_i,
3992                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
3993                  i == 0 ? '\0' : ',');
3994     if (JOINBUF_TYPE_PART == jbuf->jb_type)
3995       /* Remove user from channel */
3996       remove_user_from_channel(jbuf->jb_source, jbuf->jb_channels[i]);
3997
3998     jbuf->jb_channels[i] = 0; /* mark slot empty */
3999   }
4000
4001   jbuf->jb_count = 0; /* reset base counters */
4002   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_JOIN ||
4003                       jbuf->jb_type == JOINBUF_TYPE_PART ?
4004                       STARTJOINLEN : STARTCREATELEN) +
4005                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
4006
4007   /* and send the appropriate command */
4008   switch (jbuf->jb_type) {
4009   case JOINBUF_TYPE_JOIN:
4010     sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
4011                           "%s", chanlist);
4012     break;
4013
4014   case JOINBUF_TYPE_CREATE:
4015     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
4016                           "%s %Tu", chanlist, jbuf->jb_create);
4017     break;
4018
4019   case JOINBUF_TYPE_PART:
4020     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
4021                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
4022                           jbuf->jb_comment);
4023     break;
4024   }
4025
4026   return 0;
4027 }