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 "gline.h"        /* bad_channel */
25 #include "hash.h"
26 #include "ircd.h"
27 #include "ircd_alloc.h"
28 #include "ircd_chattr.h"
29 #include "ircd_reply.h"
30 #include "ircd_string.h"
31 #include "list.h"
32 #include "match.h"
33 #include "msg.h"
34 #include "numeric.h"
35 #include "numnicks.h"
36 #include "querycmds.h"
37 #include "s_bsd.h"
38 #include "s_conf.h"
39 #include "s_debug.h"
40 #include "s_misc.h"
41 #include "s_user.h"
42 #include "send.h"
43 #include "sprintf_irc.h"
44 #include "struct.h"
45 #include "support.h"
46 #include "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 = CurrentTime;
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 #ifdef OPER_WALK_THROUGH_LMODES
2104   /* An oper can force a join on a local channel using "OVERRIDE" as the key. 
2105      a HACK(4) notice will be sent if he would not have been supposed
2106      to join normally. */ 
2107   if (IsOperOnLocalChannel(sptr,chptr->chname) && !BadPtr(key) && compall("OVERRIDE",key) == 0)
2108   {
2109     overrideJoin = MAGIC_OPER_OVERRIDE;
2110   }
2111 #endif
2112   /*
2113    * Now a banned user CAN join if invited -- Nemesi
2114    * Now a user CAN escape channel limit if invited -- bfriendly
2115    */
2116   if ((chptr->mode.mode & MODE_INVITEONLY) || (is_banned(sptr, chptr, NULL)
2117       || (chptr->mode.limit && chptr->users >= chptr->mode.limit)))
2118   {
2119     for (lp = sptr->user->invited; lp; lp = lp->next)
2120       if (lp->value.chptr == chptr)
2121         break;
2122     if (!lp)
2123     {
2124       if (chptr->mode.limit && chptr->users >= chptr->mode.limit)
2125         return (overrideJoin + ERR_CHANNELISFULL);
2126       /*
2127        * This can return an "Invite only" msg instead of the "You are banned"
2128        * if _both_ conditions are true, but who can say what is more
2129        * appropriate ? checking again IsBanned would be _SO_ cpu-xpensive !
2130        */
2131       return overrideJoin + ((chptr->mode.mode & MODE_INVITEONLY) ?
2132           ERR_INVITEONLYCHAN : ERR_BANNEDFROMCHAN);
2133     }
2134   }
2135
2136   /*
2137    * now using compall (above) to test against a whole key ring -Kev
2138    */
2139   if (*chptr->mode.key && (EmptyString(key) || compall(chptr->mode.key, key)))
2140     return overrideJoin + (ERR_BADCHANNELKEY);
2141
2142   return 0;
2143 }
2144
2145 /*
2146  * Remove bells and commas from channel name
2147  */
2148 void clean_channelname(char *cn)
2149 {
2150   for (; *cn; ++cn) {
2151     if (!IsChannelChar(*cn)) {
2152       *cn = '\0';
2153       return;
2154     }
2155     if (IsChannelLower(*cn)) {
2156       *cn = ToLower(*cn);
2157 #ifndef FIXME
2158       /*
2159        * Remove for .08+
2160        * toupper(0xd0)
2161        */
2162       if ((unsigned char)(*cn) == 0xd0)
2163         *cn = (char) 0xf0;
2164 #endif
2165     }
2166   }
2167 }
2168
2169 /*
2170  *  Get Channel block for i (and allocate a new channel
2171  *  block, if it didn't exists before).
2172  */
2173 struct Channel *get_channel(struct Client *cptr, char *chname, ChannelGetType flag)
2174 {
2175   struct Channel *chptr;
2176   int len;
2177
2178   if (EmptyString(chname))
2179     return NULL;
2180
2181   len = strlen(chname);
2182   if (MyUser(cptr) && len > CHANNELLEN)
2183   {
2184     len = CHANNELLEN;
2185     *(chname + CHANNELLEN) = '\0';
2186   }
2187   if ((chptr = FindChannel(chname)))
2188     return (chptr);
2189   if (flag == CGT_CREATE)
2190   {
2191     chptr = (struct Channel*) MyMalloc(sizeof(struct Channel) + len);
2192     assert(0 != chptr);
2193     ++UserStats.channels;
2194     memset(chptr, 0, sizeof(struct Channel));
2195     strcpy(chptr->chname, chname);
2196     if (GlobalChannelList)
2197       GlobalChannelList->prev = chptr;
2198     chptr->prev = NULL;
2199     chptr->next = GlobalChannelList;
2200     chptr->creationtime = MyUser(cptr) ? TStime() : (time_t) 0;
2201     GlobalChannelList = chptr;
2202     hAddChannel(chptr);
2203   }
2204   return chptr;
2205 }
2206
2207 void add_invite(struct Client *cptr, struct Channel *chptr)
2208 {
2209   struct SLink *inv, **tmp;
2210
2211   del_invite(cptr, chptr);
2212   /*
2213    * Delete last link in chain if the list is max length
2214    */
2215   assert(list_length(cptr->user->invited) == cptr->user->invites);
2216   if (cptr->user->invites>=MAXCHANNELSPERUSER)
2217     del_invite(cptr, cptr->user->invited->value.chptr);
2218   /*
2219    * Add client to channel invite list
2220    */
2221   inv = make_link();
2222   inv->value.cptr = cptr;
2223   inv->next = chptr->invites;
2224   chptr->invites = inv;
2225   /*
2226    * Add channel to the end of the client invite list
2227    */
2228   for (tmp = &(cptr->user->invited); *tmp; tmp = &((*tmp)->next));
2229   inv = make_link();
2230   inv->value.chptr = chptr;
2231   inv->next = NULL;
2232   (*tmp) = inv;
2233   cptr->user->invites++;
2234 }
2235
2236 /*
2237  * Delete Invite block from channel invite list and client invite list
2238  */
2239 void del_invite(struct Client *cptr, struct Channel *chptr)
2240 {
2241   struct SLink **inv, *tmp;
2242
2243   for (inv = &(chptr->invites); (tmp = *inv); inv = &tmp->next)
2244     if (tmp->value.cptr == cptr)
2245     {
2246       *inv = tmp->next;
2247       free_link(tmp);
2248       tmp = 0;
2249       cptr->user->invites--;
2250       break;
2251     }
2252
2253   for (inv = &(cptr->user->invited); (tmp = *inv); inv = &tmp->next)
2254     if (tmp->value.chptr == chptr)
2255     {
2256       *inv = tmp->next;
2257       free_link(tmp);
2258       tmp = 0;
2259       break;
2260     }
2261 }
2262
2263 /* List and skip all channels that are listen */
2264 void list_next_channels(struct Client *cptr, int nr)
2265 {
2266   struct ListingArgs *args = cptr->listing;
2267   struct Channel *chptr = args->chptr;
2268   chptr->mode.mode &= ~MODE_LISTED;
2269   while (is_listed(chptr) || --nr >= 0)
2270   {
2271     for (; chptr; chptr = chptr->next)
2272     {
2273       if (!cptr->user || (SecretChannel(chptr) && !find_channel_member(cptr, chptr)))
2274         continue;
2275       if (chptr->users > args->min_users && chptr->users < args->max_users &&
2276           chptr->creationtime > args->min_time &&
2277           chptr->creationtime < args->max_time &&
2278           (!args->topic_limits || (*chptr->topic &&
2279           chptr->topic_time > args->min_topic_time &&
2280           chptr->topic_time < args->max_topic_time)))
2281       {
2282         if (ShowChannel(cptr,chptr))
2283           sendto_one(cptr, rpl_str(RPL_LIST), me.name, cptr->name,
2284             chptr->chname,
2285             chptr->users, chptr->topic);
2286         chptr = chptr->next;
2287         break;
2288       }
2289     }
2290     if (!chptr)
2291     {
2292       MyFree(cptr->listing);
2293       cptr->listing = NULL;
2294       sendto_one(cptr, rpl_str(RPL_LISTEND), me.name, cptr->name);
2295       break;
2296     }
2297   }
2298   if (chptr)
2299   {
2300     cptr->listing->chptr = chptr;
2301     chptr->mode.mode |= MODE_LISTED;
2302   }
2303 }
2304
2305
2306 void add_token_to_sendbuf(char *token, size_t *sblenp, int *firstp,
2307     int *send_itp, char is_a_ban, int mode)
2308 {
2309   int first = *firstp;
2310
2311   /*
2312    * Heh - we do not need to test if it still fits in the buffer, because
2313    * this BURST message is reconstructed from another BURST message, and
2314    * it only can become smaller. --Run
2315    */
2316
2317   if (*firstp)                  /* First token in this parameter ? */
2318   {
2319     *firstp = 0;
2320     if (*send_itp == 0)
2321       *send_itp = 1;            /* Buffer contains data to be sent */
2322     sendbuf[(*sblenp)++] = ' ';
2323     if (is_a_ban)
2324     {
2325       sendbuf[(*sblenp)++] = ':';       /* Bans are always the last "parv" */
2326       sendbuf[(*sblenp)++] = is_a_ban;
2327     }
2328   }
2329   else                          /* Of course, 'send_it' is already set here */
2330     /* Seperate banmasks with a space because
2331        they can contain commas themselfs: */
2332     sendbuf[(*sblenp)++] = is_a_ban ? ' ' : ',';
2333   strcpy(sendbuf + *sblenp, token);
2334   *sblenp += strlen(token);
2335   if (!is_a_ban)                /* nick list ? Need to take care
2336                                    of modes for nicks: */
2337   {
2338     static int last_mode = 0;
2339     mode &= CHFL_CHANOP | CHFL_VOICE;
2340     if (first)
2341       last_mode = 0;
2342     if (last_mode != mode)      /* Append mode like ':ov' if changed */
2343     {
2344       last_mode = mode;
2345       sendbuf[(*sblenp)++] = ':';
2346       if (mode & CHFL_CHANOP)
2347         sendbuf[(*sblenp)++] = 'o';
2348       if (mode & CHFL_VOICE)
2349         sendbuf[(*sblenp)++] = 'v';
2350     }
2351     sendbuf[*sblenp] = '\0';
2352   }
2353 }
2354
2355 void cancel_mode(struct Client *sptr, struct Channel *chptr, char m,
2356                         const char *param, int *count)
2357 {
2358   static char* pb;
2359   static char* sbp;
2360   static char* sbpi;
2361   int          paramdoesntfit = 0;
2362   char parabuf[MODEBUFLEN];
2363
2364   assert(0 != sptr);
2365   assert(0 != chptr);
2366   assert(0 != count);
2367   
2368   if (*count == -1)             /* initialize ? */
2369   {
2370     sbp = sbpi =
2371         sprintf_irc(sendbuf, ":%s MODE %s -", sptr->name, chptr->chname);
2372     pb = parabuf;
2373     *count = 0;
2374   }
2375   /* m == 0 means flush */
2376   if (m)
2377   {
2378     if (param)
2379     {
2380       size_t nplen = strlen(param);
2381       if (pb - parabuf + nplen + 23 > MODEBUFLEN)
2382         paramdoesntfit = 1;
2383       else
2384       {
2385         *sbp++ = m;
2386         *pb++ = ' ';
2387         strcpy(pb, param);
2388         pb += nplen;
2389         ++*count;
2390       }
2391     }
2392     else
2393       *sbp++ = m;
2394   }
2395   else if (*count == 0)
2396     return;
2397   if (*count == 6 || !m || paramdoesntfit)
2398   {
2399     struct Membership* member;
2400     strcpy(sbp, parabuf);
2401     for (member = chptr->members; member; member = member->next_member)
2402       if (MyUser(member->user))
2403         sendbufto_one(member->user);
2404     sbp = sbpi;
2405     pb = parabuf;
2406     *count = 0;
2407   }
2408   if (paramdoesntfit)
2409   {
2410     *sbp++ = m;
2411     *pb++ = ' ';
2412     strcpy(pb, param);
2413     pb += strlen(param);
2414     ++*count;
2415   }
2416 }
2417
2418
2419 /*
2420  * Consider:
2421  *
2422  *                     client
2423  *                       |
2424  *                       c
2425  *                       |
2426  *     X --a--> A --b--> B --d--> D
2427  *                       |
2428  *                      who
2429  *
2430  * Where `who' is being KICK-ed by a "KICK" message received by server 'A'
2431  * via 'a', or on server 'B' via either 'b' or 'c', or on server D via 'd'.
2432  *
2433  * a) On server A : set CHFL_ZOMBIE for `who' (lp) and pass on the KICK.
2434  *    Remove the user immedeately when no users are left on the channel.
2435  * b) On server B : remove the user (who/lp) from the channel, send a
2436  *    PART upstream (to A) and pass on the KICK.
2437  * c) KICKed by `client'; On server B : remove the user (who/lp) from the
2438  *    channel, and pass on the KICK.
2439  * d) On server D : remove the user (who/lp) from the channel, and pass on
2440  *    the KICK.
2441  *
2442  * Note:
2443  * - Setting the ZOMBIE flag never hurts, we either remove the
2444  *   client after that or we don't.
2445  * - The KICK message was already passed on, as should be in all cases.
2446  * - `who' is removed in all cases except case a) when users are left.
2447  * - A PART is only sent upstream in case b).
2448  *
2449  * 2 aug 97:
2450  *
2451  *              6
2452  *              |
2453  *  1 --- 2 --- 3 --- 4 --- 5
2454  *        |           |
2455  *      kicker       who
2456  *
2457  * We also need to turn 'who' into a zombie on servers 1 and 6,
2458  * because a KICK from 'who' (kicking someone else in that direction)
2459  * can arrive there afterwards - which should not be bounced itself.
2460  * Therefore case a) also applies for servers 1 and 6.
2461  *
2462  * --Run
2463  */
2464 void make_zombie(struct Membership* member, struct Client* who, struct Client* cptr,
2465                  struct Client* sptr, struct Channel* chptr)
2466 {
2467   assert(0 != member);
2468   assert(0 != who);
2469   assert(0 != cptr);
2470   assert(0 != chptr);
2471
2472   /* Default for case a): */
2473   SetZombie(member);
2474
2475   /* Case b) or c) ?: */
2476   if (MyUser(who))      /* server 4 */
2477   {
2478     if (IsServer(cptr)) /* Case b) ? */
2479       sendto_one(cptr, PartFmt1, who->name, chptr->chname);
2480     remove_user_from_channel(who, chptr);
2481     return;
2482   }
2483   if (who->from == cptr)        /* True on servers 1, 5 and 6 */
2484   {
2485     struct Client *acptr = IsServer(sptr) ? sptr : sptr->user->server;
2486     for (; acptr != &me; acptr = acptr->serv->up)
2487       if (acptr == who->user->server)   /* Case d) (server 5) */
2488       {
2489         remove_user_from_channel(who, chptr);
2490         return;
2491       }
2492   }
2493
2494   /* Case a) (servers 1, 2, 3 and 6) */
2495   if (channel_all_zombies(chptr))
2496     remove_user_from_channel(who, chptr);
2497
2498   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
2499 }
2500
2501 int number_of_zombies(struct Channel *chptr)
2502 {
2503   struct Membership* member;
2504   int                count = 0;
2505
2506   assert(0 != chptr);
2507   for (member = chptr->members; member; member = member->next_member) {
2508     if (IsZombie(member))
2509       ++count;
2510   }
2511   return count;
2512 }
2513
2514 void send_user_joins(struct Client *cptr, struct Client *user)
2515 {
2516   struct Membership* chan;
2517   struct Channel*    chptr;
2518   int   cnt = 0;
2519   int   len = 0;
2520   int   clen;
2521   char* mask;
2522   char  buf[BUFSIZE];
2523
2524   *buf = ':';
2525   strcpy(buf + 1, user->name);
2526   strcat(buf, " JOIN ");
2527   len = strlen(user->name) + 7;
2528
2529   for (chan = user->user->channel; chan; chan = chan->next_channel)
2530   {
2531     chptr = chan->channel;
2532     assert(0 != chptr);
2533
2534     if ((mask = strchr(chptr->chname, ':')))
2535       if (match(++mask, cptr->name))
2536         continue;
2537     if (*chptr->chname == '&')
2538       continue;
2539     if (IsZombie(chan))
2540       continue;
2541     clen = strlen(chptr->chname);
2542     if (clen + 1 + len > BUFSIZE - 3)
2543     {
2544       if (cnt)
2545       {
2546         buf[len - 1] = '\0';
2547         sendto_one(cptr, "%s", buf);
2548       }
2549       *buf = ':';
2550       strcpy(buf + 1, user->name);
2551       strcat(buf, " JOIN ");
2552       len = strlen(user->name) + 7;
2553       cnt = 0;
2554     }
2555     strcpy(buf + len, chptr->chname);
2556     cnt++;
2557     len += clen;
2558     if (chan->next_channel)
2559     {
2560       len++;
2561       strcat(buf, ",");
2562     }
2563   }
2564   if (*buf && cnt)
2565     sendto_one(cptr, "%s", buf);
2566 }
2567
2568 /*
2569  * send_hack_notice()
2570  *
2571  * parc & parv[] are the same as that of the calling function:
2572  *   mtype == 1 is from m_mode, 2 is from m_create, 3 is from m_kick.
2573  *
2574  * This function prepares sendbuf with the server notices and wallops
2575  *   to be sent for all hacks.  -Ghostwolf 18-May-97
2576  */
2577
2578 void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
2579                       char *parv[], int badop, int mtype)
2580 {
2581   struct Channel *chptr;
2582   static char params[MODEBUFLEN];
2583   int i = 3;
2584   chptr = FindChannel(parv[1]);
2585   *params = '\0';
2586
2587   /* P10 servers require numeric nick conversion before sending. */
2588   switch (mtype)
2589   {
2590     case 1:                     /* Convert nicks for MODE HACKs here  */
2591     {
2592       char *mode = parv[2];
2593       while (i < parc)
2594       {
2595         while (*mode && *mode != 'o' && *mode != 'v')
2596           ++mode;
2597         strcat(params, " ");
2598         if (*mode == 'o' || *mode == 'v')
2599         {
2600           /*
2601            * blindly stumble through parameter list hoping one of them
2602            * might turn out to be a numeric nick
2603            * NOTE: this should not cause a problem but _may_ end up finding
2604            * something we aren't looking for. findNUser should be able to
2605            * handle any garbage that is thrown at it, but may return a client
2606            * if we happen to get lucky with a mode string or a timestamp
2607            */
2608           struct Client *acptr;
2609           if ((acptr = findNUser(parv[i])) != NULL)     /* Convert nicks here */
2610             strcat(params, acptr->name);
2611           else
2612           {
2613             strcat(params, "<");
2614             strcat(params, parv[i]);
2615             strcat(params, ">");
2616           }
2617         }
2618         else                    /* If it isn't a numnick, send it 'as is' */
2619           strcat(params, parv[i]);
2620         i++;
2621       }
2622       sprintf_irc(sendbuf,
2623           ":%s NOTICE * :*** Notice -- %sHACK(%d): %s MODE %s %s%s ["
2624           TIME_T_FMT "]", me.name, (badop == 3) ? "BOUNCE or " : "", badop,
2625           parv[0], parv[1], parv[2], params, chptr->creationtime);
2626       sendbufto_op_mask((badop == 3) ? SNO_HACK3 : (badop ==
2627           4) ? SNO_HACK4 : SNO_HACK2);
2628
2629       if ((IsServer(sptr)) && (badop == 2))
2630       {
2631         sprintf_irc(sendbuf, ":%s DESYNCH :HACK: %s MODE %s %s%s",
2632             me.name, parv[0], parv[1], parv[2], params);
2633         sendbufto_serv_butone(cptr);
2634       }
2635       break;
2636     }
2637     case 2:                     /* No conversion is needed for CREATE; the only numnick is sptr */
2638     {
2639       sendto_serv_butone(cptr, ":%s DESYNCH :HACK: %s CREATE %s %s",
2640           me.name, sptr->name, chptr->chname, parv[2]);
2641       sendto_op_mask(SNO_HACK2, "HACK(2): %s CREATE %s %s",
2642           sptr->name, chptr->chname, parv[2]);
2643       break;
2644     }
2645     case 3:                     /* Convert nick in KICK message */
2646     {
2647       struct Client *acptr;
2648       if ((acptr = findNUser(parv[2])) != NULL) /* attempt to convert nick */
2649         sprintf_irc(sendbuf,
2650             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s %s :%s",
2651             me.name, sptr->name, parv[1], acptr->name, parv[3]);
2652       else                      /* if conversion fails, send it 'as is' in <>'s */
2653         sprintf_irc(sendbuf,
2654             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s <%s> :%s",
2655             me.name, sptr->name, parv[1], parv[2], parv[3]);
2656       sendbufto_op_mask(SNO_HACK4);
2657       break;
2658     }
2659   }
2660 }