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