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