4927d078b0ed926dd5fcab1cb57e8a419ad724d5
[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   Debug((DEBUG_INFO, "%s is now a zombie on %s", who->name, chptr->chname));
2494 }
2495
2496 int number_of_zombies(struct Channel *chptr)
2497 {
2498   struct Membership* member;
2499   int                count = 0;
2500
2501   assert(0 != chptr);
2502   for (member = chptr->members; member; member = member->next_member) {
2503     if (IsZombie(member))
2504       ++count;
2505   }
2506   return count;
2507 }
2508
2509 /* XXX we can probably get rid of send_user_joins */
2510 void send_user_joins(struct Client *cptr, struct Client *user)
2511 {
2512   struct Membership* chan;
2513   struct Channel*    chptr;
2514   int   cnt = 0;
2515   int   len = 0;
2516   int   clen;
2517   char* mask;
2518   char  buf[BUFSIZE];
2519
2520   *buf = ':';
2521   strcpy(buf + 1, user->name);
2522   strcat(buf, " JOIN ");
2523   len = strlen(user->name) + 7;
2524
2525   for (chan = user->user->channel; chan; chan = chan->next_channel)
2526   {
2527     chptr = chan->channel;
2528     assert(0 != chptr);
2529
2530     if ((mask = strchr(chptr->chname, ':')))
2531       if (match(++mask, cptr->name))
2532         continue;
2533     if (*chptr->chname == '&')
2534       continue;
2535     if (IsZombie(chan))
2536       continue;
2537     clen = strlen(chptr->chname);
2538     if (clen + 1 + len > BUFSIZE - 3)
2539     {
2540       if (cnt)
2541       {
2542         buf[len - 1] = '\0';
2543         sendto_one(cptr, "%s", buf); /* XXX Possibly DEAD */
2544       }
2545       *buf = ':';
2546       strcpy(buf + 1, user->name);
2547       strcat(buf, " JOIN ");
2548       len = strlen(user->name) + 7;
2549       cnt = 0;
2550     }
2551     strcpy(buf + len, chptr->chname);
2552     cnt++;
2553     len += clen;
2554     if (chan->next_channel)
2555     {
2556       len++;
2557       strcat(buf, ",");
2558     }
2559   }
2560   if (*buf && cnt)
2561     sendto_one(cptr, "%s", buf); /* XXX Possibly DEAD */
2562 }
2563
2564 /*
2565  * send_hack_notice()
2566  *
2567  * parc & parv[] are the same as that of the calling function:
2568  *   mtype == 1 is from m_mode, 2 is from m_create, 3 is from m_kick.
2569  *
2570  * This function prepares sendbuf with the server notices and wallops
2571  *   to be sent for all hacks.  -Ghostwolf 18-May-97
2572  */
2573 /* XXX let's get rid of this if we can */
2574 void send_hack_notice(struct Client *cptr, struct Client *sptr, int parc,
2575                       char *parv[], int badop, int mtype)
2576 {
2577   struct Channel *chptr;
2578   static char params[MODEBUFLEN];
2579   int i = 3;
2580   chptr = FindChannel(parv[1]);
2581   *params = '\0';
2582
2583   /* P10 servers require numeric nick conversion before sending. */
2584   switch (mtype)
2585   {
2586     case 1:                     /* Convert nicks for MODE HACKs here  */
2587     {
2588       char *mode = parv[2];
2589       while (i < parc)
2590       {
2591         while (*mode && *mode != 'o' && *mode != 'v')
2592           ++mode;
2593         strcat(params, " ");
2594         if (*mode == 'o' || *mode == 'v')
2595         {
2596           /*
2597            * blindly stumble through parameter list hoping one of them
2598            * might turn out to be a numeric nick
2599            * NOTE: this should not cause a problem but _may_ end up finding
2600            * something we aren't looking for. findNUser should be able to
2601            * handle any garbage that is thrown at it, but may return a client
2602            * if we happen to get lucky with a mode string or a timestamp
2603            */
2604           struct Client *acptr;
2605           if ((acptr = findNUser(parv[i])) != NULL)     /* Convert nicks here */
2606             strcat(params, acptr->name);
2607           else
2608           {
2609             strcat(params, "<");
2610             strcat(params, parv[i]);
2611             strcat(params, ">");
2612           }
2613         }
2614         else                    /* If it isn't a numnick, send it 'as is' */
2615           strcat(params, parv[i]);
2616         i++;
2617       }
2618       sprintf_irc(sendbuf,
2619           ":%s NOTICE * :*** Notice -- %sHACK(%d): %s MODE %s %s%s ["
2620           TIME_T_FMT "]", me.name, (badop == 3) ? "BOUNCE or " : "", badop,
2621           parv[0], parv[1], parv[2], params, chptr->creationtime);
2622       sendbufto_op_mask((badop == 3) ? SNO_HACK3 : (badop == /* XXX DYING */
2623           4) ? SNO_HACK4 : SNO_HACK2);
2624
2625       if ((IsServer(sptr)) && (badop == 2))
2626       {
2627         sprintf_irc(sendbuf, ":%s DESYNCH :HACK: %s MODE %s %s%s",
2628             me.name, parv[0], parv[1], parv[2], params);
2629         sendbufto_serv_butone(cptr); /* XXX DYING */
2630       }
2631       break;
2632     }
2633     case 2:                     /* No conversion is needed for CREATE; the only numnick is sptr */
2634     {
2635       sendto_serv_butone(cptr, ":%s DESYNCH :HACK: %s CREATE %s %s", /* XXX DYING */
2636           me.name, sptr->name, chptr->chname, parv[2]);
2637       sendto_op_mask(SNO_HACK2, "HACK(2): %s CREATE %s %s", /* XXX DYING */
2638           sptr->name, chptr->chname, parv[2]);
2639       break;
2640     }
2641     case 3:                     /* Convert nick in KICK message */
2642     {
2643       struct Client *acptr;
2644       if ((acptr = findNUser(parv[2])) != NULL) /* attempt to convert nick */
2645         sprintf_irc(sendbuf,
2646             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s %s :%s",
2647             me.name, sptr->name, parv[1], acptr->name, parv[3]);
2648       else                      /* if conversion fails, send it 'as is' in <>'s */
2649         sprintf_irc(sendbuf,
2650             ":%s NOTICE * :*** Notice -- HACK: %s KICK %s <%s> :%s",
2651             me.name, sptr->name, parv[1], parv[2], parv[3]);
2652       sendbufto_op_mask(SNO_HACK4); /* XXX DYING */
2653       break;
2654     }
2655   }
2656 }
2657
2658 /*
2659  * This helper function builds an argument string in strptr, consisting
2660  * of the original string, a space, and str1 and str2 concatenated (if,
2661  * of course, str2 is not NULL)
2662  */
2663 static void
2664 build_string(char *strptr, int *strptr_i, char *str1, char *str2, char c)
2665 {
2666   if (c)
2667     strptr[(*strptr_i)++] = c;
2668
2669   while (*str1)
2670     strptr[(*strptr_i)++] = *(str1++);
2671
2672   if (str2)
2673     while (*str2)
2674       strptr[(*strptr_i)++] = *(str2++);
2675
2676   strptr[(*strptr_i)] = '\0';
2677 }
2678
2679 /*
2680  * This is the workhorse of our ModeBuf suite; this actually generates the
2681  * output MODE commands, HACK notices, or whatever.  It's pretty complicated.
2682  */
2683 static int
2684 modebuf_flush_int(struct ModeBuf *mbuf, int all)
2685 {
2686   /* we only need the flags that don't take args right now */
2687   static int flags[] = {
2688 /*  MODE_CHANOP,        'o', */
2689 /*  MODE_VOICE,         'v', */
2690     MODE_PRIVATE,       'p',
2691     MODE_SECRET,        's',
2692     MODE_MODERATED,     'm',
2693     MODE_TOPICLIMIT,    't',
2694     MODE_INVITEONLY,    'i',
2695     MODE_NOPRIVMSGS,    'n',
2696 /*  MODE_KEY,           'k', */
2697 /*  MODE_BAN,           'b', */
2698 /*  MODE_LIMIT,         'l', */
2699     0x0, 0x0
2700   };
2701   int i;
2702   int *flag_p;
2703
2704   struct Client *app_source; /* where the MODE appears to come from */
2705
2706   char addbuf[20]; /* accumulates +psmtin, etc. */
2707   int addbuf_i = 0;
2708   char rembuf[20]; /* accumulates -psmtin, etc. */
2709   int rembuf_i = 0;
2710   char *bufptr; /* we make use of indirection to simplify the code */
2711   int *bufptr_i;
2712
2713   char addstr[BUFSIZE]; /* accumulates MODE parameters to add */
2714   int addstr_i;
2715   char remstr[BUFSIZE]; /* accumulates MODE parameters to remove */
2716   int remstr_i;
2717   char *strptr; /* more indirection to simplify the code */
2718   int *strptr_i;
2719
2720   int totalbuflen = BUFSIZE - 200; /* fuzz factor -- don't overrun buffer! */
2721   int tmp;
2722
2723   char limitbuf[20]; /* convert limits to strings */
2724
2725   unsigned int limitdel = MODE_LIMIT;
2726
2727   assert(0 != mbuf);
2728
2729   /* If the ModeBuf is empty, we have nothing to do */
2730   if (mbuf->mb_add == 0 && mbuf->mb_rem == 0 && mbuf->mb_count == 0)
2731     return 0;
2732
2733   /* Ok, if we were given the OPMODE flag, hide the source if its a user */
2734   if (mbuf->mb_dest & MODEBUF_DEST_OPMODE && !IsServer(mbuf->mb_source))
2735     app_source = mbuf->mb_source->user->server;
2736   else
2737     app_source = mbuf->mb_source;
2738
2739   /*
2740    * Account for user we're bouncing; we have to get it in on the first
2741    * bounced MODE, or we could have problems
2742    */
2743   if (mbuf->mb_dest & MODEBUF_DEST_DEOP)
2744     totalbuflen -= 6; /* numeric nick == 5, plus one space */
2745
2746   /* Calculate the simple flags */
2747   for (flag_p = flags; flag_p[0]; flag_p += 2) {
2748     if (*flag_p & mbuf->mb_add)
2749       addbuf[addbuf_i++] = flag_p[1];
2750     else if (*flag_p & mbuf->mb_rem)
2751       rembuf[rembuf_i++] = flag_p[1];
2752   }
2753
2754   /* Now go through the modes with arguments... */
2755   for (i = 0; i < mbuf->mb_count; i++) {
2756     if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2757       bufptr = addbuf;
2758       bufptr_i = &addbuf_i;
2759     } else {
2760       bufptr = rembuf;
2761       bufptr_i = &rembuf_i;
2762     }
2763
2764     if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE)) {
2765       tmp = strlen(MB_CLIENT(mbuf, i)->name);
2766
2767       if ((totalbuflen - IRCD_MAX(5, tmp)) <= 0) /* don't overflow buffer */
2768         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2769       else {
2770         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_CHANOP ? 'o' : 'v';
2771         totalbuflen -= IRCD_MAX(5, tmp) + 1;
2772       }
2773     } else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN)) {
2774       tmp = strlen(MB_STRING(mbuf, i));
2775
2776       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
2777         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2778       else {
2779         bufptr[(*bufptr_i)++] = MB_TYPE(mbuf, i) & MODE_KEY ? 'k' : 'b';
2780         totalbuflen -= tmp + 1;
2781       }
2782     } else if (MB_TYPE(mbuf, i) & MODE_LIMIT) {
2783       /* if it's a limit, we also format the number */
2784       sprintf_irc(limitbuf, "%d", MB_UINT(mbuf, i));
2785
2786       tmp = strlen(limitbuf);
2787
2788       if ((totalbuflen - tmp) <= 0) /* don't overflow buffer */
2789         MB_TYPE(mbuf, i) |= MODE_SAVE; /* save for later */
2790       else {
2791         bufptr[(*bufptr_i)++] = 'l';
2792         totalbuflen -= tmp + 1;
2793       }
2794     }
2795   }
2796
2797   /* terminate the mode strings */
2798   addbuf[addbuf_i] = '\0';
2799   rembuf[rembuf_i] = '\0';
2800
2801   /* If we're building a user visible MODE or HACK... */
2802   if (mbuf->mb_dest & (MODEBUF_DEST_CHANNEL | MODEBUF_DEST_HACK2 |
2803                        MODEBUF_DEST_HACK3   | MODEBUF_DEST_HACK4 |
2804                        MODEBUF_DEST_LOG)) {
2805     /* Set up the parameter strings */
2806     addstr[0] = '\0';
2807     addstr_i = 0;
2808     remstr[0] = '\0';
2809     remstr_i = 0;
2810
2811     for (i = 0; i < mbuf->mb_count; i++) {
2812       if (MB_TYPE(mbuf, i) & MODE_SAVE)
2813         continue;
2814
2815       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2816         strptr = addstr;
2817         strptr_i = &addstr_i;
2818       } else {
2819         strptr = remstr;
2820         strptr_i = &remstr_i;
2821       }
2822
2823       /* deal with clients... */
2824       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
2825         build_string(strptr, strptr_i, MB_CLIENT(mbuf, i)->name, 0, ' ');
2826
2827       /* deal with strings... */
2828       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
2829         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
2830
2831       /*
2832        * deal with limit; note we cannot include the limit parameter if we're
2833        * removing it
2834        */
2835       else if ((MB_TYPE(mbuf, i) & (MODE_ADD | MODE_LIMIT)) ==
2836                (MODE_ADD | MODE_LIMIT))
2837         build_string(strptr, strptr_i, limitbuf, 0, ' ');
2838     }
2839
2840     /* send the messages off to their destination */
2841     if (mbuf->mb_dest & MODEBUF_DEST_HACK2) {
2842       sendto_opmask_butone(0, SNO_HACK2, "HACK(2): %s MODE %s %s%s%s%s%s%s "
2843                            "[%Tu]", app_source->name, mbuf->mb_channel->chname,
2844                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2845                            addbuf, remstr, addstr,
2846                            mbuf->mb_channel->creationtime);
2847       sendcmdto_serv_butone(&me, CMD_DESYNCH, mbuf->mb_connect,
2848                             ":HACK: %s MODE %s %s%s%s%s%s%s [%Tu]",
2849                             app_source->name, mbuf->mb_channel->chname,
2850                             rembuf_i ? "-" : "", rembuf,
2851                             addbuf_i ? "+" : "", addbuf, remstr, addstr,
2852                             mbuf->mb_channel->creationtime);
2853     }
2854
2855     if (mbuf->mb_dest & MODEBUF_DEST_HACK3)
2856       sendto_opmask_butone(0, SNO_HACK3, "BOUNCE or HACK(3): %s MODE %s "
2857                            "%s%s%s%s%s%s [%Tu]", app_source->name,
2858                            mbuf->mb_channel->chname, rembuf_i ? "-" : "",
2859                            rembuf, addbuf_i ? "+" : "", addbuf, remstr, addstr,
2860                            mbuf->mb_channel->creationtime);
2861
2862     if (mbuf->mb_dest & MODEBUF_DEST_HACK4)
2863       sendto_opmask_butone(0, SNO_HACK4, "HACK(4): %s MODE %s %s%s%s%s%s%s "
2864                            "[%Tu]", app_source->name, mbuf->mb_channel->chname,
2865                            rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2866                            addbuf, remstr, addstr,
2867                            mbuf->mb_channel->creationtime);
2868
2869 #ifdef OPATH
2870     if (mbuf->mb_dest & MODEBUF_DEST_LOG) {
2871       write_log(OPATH, "%Tu %#C OPMODE %H %s%s%s%s%s%s\n", TStime(),
2872                 mbuf->mb_source, mbuf->mb_channel, rembuf_i ? "-" : "", rembuf,
2873                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
2874     }
2875 #endif
2876
2877     if (mbuf->mb_dest & MODEBUF_DEST_CHANNEL)
2878       sendcmdto_channel_butserv(app_source, CMD_MODE, mbuf->mb_channel,
2879                                 "%H %s%s%s%s%s%s", mbuf->mb_channel,
2880                                 rembuf_i ? "-" : "", rembuf,
2881                                 addbuf_i ? "+" : "", addbuf, remstr, addstr);
2882   }
2883
2884   /* Now are we supposed to propagate to other servers? */
2885   if (mbuf->mb_dest & MODEBUF_DEST_SERVER) {
2886     /* set up parameter string */
2887     addstr[0] = '\0';
2888     addstr_i = 0;
2889     remstr[0] = '\0';
2890     remstr_i = 0;
2891
2892     /*
2893      * limit is supressed if we're removing it; we have to figure out which
2894      * direction is the direction for it to be removed, though...
2895      */
2896     limitdel |= (mbuf->mb_dest & MODEBUF_DEST_HACK2) ? MODE_DEL : MODE_ADD;
2897
2898     for (i = 0; i < mbuf->mb_count; i++) {
2899       if (MB_TYPE(mbuf, i) & MODE_SAVE)
2900         continue;
2901
2902       if (MB_TYPE(mbuf, i) & MODE_ADD) { /* adding or removing? */
2903         strptr = addstr;
2904         strptr_i = &addstr_i;
2905       } else {
2906         strptr = remstr;
2907         strptr_i = &remstr_i;
2908       }
2909
2910       /* deal with modes that take clients */
2911       if (MB_TYPE(mbuf, i) & (MODE_CHANOP | MODE_VOICE))
2912         build_string(strptr, strptr_i, NumNick(MB_CLIENT(mbuf, i)), ' ');
2913
2914       /* deal with modes that take strings */
2915       else if (MB_TYPE(mbuf, i) & (MODE_KEY | MODE_BAN))
2916         build_string(strptr, strptr_i, MB_STRING(mbuf, i), 0, ' ');
2917
2918       /*
2919        * deal with the limit.  Logic here is complicated; if HACK2 is set,
2920        * we're bouncing the mode, so sense is reversed, and we have to
2921        * include the original limit if it looks like it's being removed
2922        */
2923       else if ((MB_TYPE(mbuf, i) & limitdel) == limitdel)
2924         build_string(strptr, strptr_i, limitbuf, 0, ' ');
2925     }
2926
2927     /* we were told to deop the source */
2928     if (mbuf->mb_dest & MODEBUF_DEST_DEOP) {
2929       addbuf[addbuf_i++] = 'o'; /* remember, sense is reversed */
2930       addbuf[addbuf_i] = '\0'; /* terminate the string... */
2931       build_string(addstr, &addstr_i, NumNick(mbuf->mb_source), ' ');
2932
2933       /* mark that we've done this, so we don't do it again */
2934       mbuf->mb_dest &= ~MODEBUF_DEST_DEOP;
2935     }
2936
2937     if (mbuf->mb_dest & MODEBUF_DEST_OPMODE) {
2938       /* If OPMODE was set, we're propagating the mode as an OPMODE message */
2939       sendcmdto_serv_butone(mbuf->mb_source, CMD_OPMODE, mbuf->mb_connect,
2940                             "%H %s%s%s%s%s%s", mbuf->mb_channel,
2941                             rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2942                             addbuf, remstr, addstr);
2943     } else if (mbuf->mb_dest & MODEBUF_DEST_BOUNCE) {
2944       /*
2945        * If HACK2 was set, we're bouncing; we send the MODE back to the
2946        * connection we got it from with the senses reversed and a TS of 0;
2947        * origin is us
2948        */
2949       sendcmdto_one(&me, CMD_MODE, mbuf->mb_connect, "%H %s%s%s%s%s%s %Tu",
2950                     mbuf->mb_channel, addbuf_i ? "-" : "", addbuf,
2951                     rembuf_i ? "+" : "", rembuf, addstr, remstr,
2952                     mbuf->mb_channel->creationtime);
2953     } else {
2954       /*
2955        * We're propagating a normal MODE command to the rest of the network;
2956        * we send the actual channel TS unless this is a HACK3 or a HACK4
2957        */
2958       if (IsServer(mbuf->mb_source))
2959         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
2960                               "%H %s%s%s%s%s%s %Tu", mbuf->mb_channel,
2961                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2962                               addbuf, remstr, addstr,
2963                               (mbuf->mb_dest & MODEBUF_DEST_HACK4) ? 0 :
2964                               mbuf->mb_channel->creationtime);
2965       else
2966         sendcmdto_serv_butone(mbuf->mb_source, CMD_MODE, mbuf->mb_connect,
2967                               "%H %s%s%s%s%s%s", mbuf->mb_channel,
2968                               rembuf_i ? "-" : "", rembuf, addbuf_i ? "+" : "",
2969                               addbuf, remstr, addstr);
2970     }
2971   }
2972
2973   /* We've drained the ModeBuf... */
2974   mbuf->mb_add = 0;
2975   mbuf->mb_rem = 0;
2976   mbuf->mb_count = 0;
2977
2978   /* reinitialize the mode-with-arg slots */
2979   for (i = 0; i < MAXMODEPARAMS; i++) {
2980     /* If we saved any, pack them down */
2981     if (MB_TYPE(mbuf, i) & MODE_SAVE) {
2982       mbuf->mb_modeargs[mbuf->mb_count] = mbuf->mb_modeargs[i];
2983       MB_TYPE(mbuf, mbuf->mb_count) &= ~MODE_SAVE; /* don't save anymore */
2984
2985       if (mbuf->mb_count++ == i) /* don't overwrite our hard work */
2986         continue;
2987     } else if (MB_TYPE(mbuf, i) & MODE_FREE)
2988       MyFree(MB_STRING(mbuf, i)); /* free string if needed */
2989
2990     MB_TYPE(mbuf, i) = 0;
2991     MB_UINT(mbuf, i) = 0;
2992   }
2993
2994   /* If we're supposed to flush it all, do so--all hail tail recursion */
2995   if (all && mbuf->mb_count)
2996     return modebuf_flush_int(mbuf, 1);
2997
2998   return 0;
2999 }
3000
3001 /*
3002  * This routine just initializes a ModeBuf structure with the information
3003  * needed and the options given.
3004  */
3005 void
3006 modebuf_init(struct ModeBuf *mbuf, struct Client *source,
3007              struct Client *connect, struct Channel *chan, unsigned int dest)
3008 {
3009   int i;
3010
3011   assert(0 != mbuf);
3012   assert(0 != source);
3013   assert(0 != chan);
3014   assert(0 != dest);
3015
3016   mbuf->mb_add = 0;
3017   mbuf->mb_rem = 0;
3018   mbuf->mb_source = source;
3019   mbuf->mb_connect = connect;
3020   mbuf->mb_channel = chan;
3021   mbuf->mb_dest = dest;
3022   mbuf->mb_count = 0;
3023
3024   /* clear each mode-with-parameter slot */
3025   for (i = 0; i < MAXMODEPARAMS; i++) {
3026     MB_TYPE(mbuf, i) = 0;
3027     MB_UINT(mbuf, i) = 0;
3028   }
3029 }
3030
3031 /*
3032  * This routine simply adds modes to be added or deleted; do a binary OR
3033  * with either MODE_ADD or MODE_DEL
3034  */
3035 void
3036 modebuf_mode(struct ModeBuf *mbuf, unsigned int mode)
3037 {
3038   assert(0 != mbuf);
3039   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3040
3041   mode &= (MODE_ADD | MODE_DEL | MODE_PRIVATE | MODE_SECRET | MODE_MODERATED |
3042            MODE_TOPICLIMIT | MODE_INVITEONLY | MODE_NOPRIVMSGS);
3043
3044   if (mode & MODE_ADD) {
3045     mbuf->mb_rem &= ~mode;
3046     mbuf->mb_add |= mode;
3047   } else {
3048     mbuf->mb_add &= ~mode;
3049     mbuf->mb_rem |= mode;
3050   }
3051 }
3052
3053 /*
3054  * This routine adds a mode to be added or deleted that takes a unsigned
3055  * int parameter; mode may *only* be the relevant mode flag ORed with one
3056  * of MODE_ADD or MODE_DEL
3057  */
3058 void
3059 modebuf_mode_uint(struct ModeBuf *mbuf, unsigned int mode, unsigned int uint)
3060 {
3061   assert(0 != mbuf);
3062   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3063
3064   MB_TYPE(mbuf, mbuf->mb_count) = mode;
3065   MB_UINT(mbuf, mbuf->mb_count) = uint;
3066
3067   /* when we've reached the maximal count, flush the buffer */
3068   if (++mbuf->mb_count >=
3069       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3070     modebuf_flush_int(mbuf, 0);
3071 }
3072
3073 /*
3074  * This routine adds a mode to be added or deleted that takes a string
3075  * parameter; mode may *only* be the relevant mode flag ORed with one of
3076  * MODE_ADD or MODE_DEL
3077  */
3078 void
3079 modebuf_mode_string(struct ModeBuf *mbuf, unsigned int mode, char *string,
3080                     int free)
3081 {
3082   assert(0 != mbuf);
3083   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3084
3085   MB_TYPE(mbuf, mbuf->mb_count) = mode | (free ? MODE_FREE : 0);
3086   MB_STRING(mbuf, mbuf->mb_count) = string;
3087
3088   /* when we've reached the maximal count, flush the buffer */
3089   if (++mbuf->mb_count >=
3090       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3091     modebuf_flush_int(mbuf, 0);
3092 }
3093
3094 /*
3095  * This routine adds a mode to be added or deleted that takes a client
3096  * parameter; mode may *only* be the relevant mode flag ORed with one of
3097  * MODE_ADD or MODE_DEL
3098  */
3099 void
3100 modebuf_mode_client(struct ModeBuf *mbuf, unsigned int mode,
3101                     struct Client *client)
3102 {
3103   assert(0 != mbuf);
3104   assert(0 != (mode & (MODE_ADD | MODE_DEL)));
3105
3106   MB_TYPE(mbuf, mbuf->mb_count) = mode;
3107   MB_CLIENT(mbuf, mbuf->mb_count) = client;
3108
3109   /* when we've reached the maximal count, flush the buffer */
3110   if (++mbuf->mb_count >=
3111       (MAXMODEPARAMS - (mbuf->mb_dest & MODEBUF_DEST_DEOP ? 1 : 0)))
3112     modebuf_flush_int(mbuf, 0);
3113 }
3114
3115 /*
3116  * This is the exported binding for modebuf_flush()
3117  */
3118 int
3119 modebuf_flush(struct ModeBuf *mbuf)
3120 {
3121   return modebuf_flush_int(mbuf, 1);
3122 }
3123
3124 /*
3125  * Simple function to invalidate bans
3126  */
3127 void
3128 mode_ban_invalidate(struct Channel *chan)
3129 {
3130   struct Membership *member;
3131
3132   for (member = chan->members; member; member = member->next_member)
3133     ClearBanValid(member);
3134 }
3135
3136 /*
3137  * Simple function to drop invite structures
3138  */
3139 void
3140 mode_invite_clear(struct Channel *chan)
3141 {
3142   while (chan->invites)
3143     del_invite(chan->invites->value.cptr, chan);
3144 }
3145
3146 /* What we've done for mode_parse so far... */
3147 #define DONE_LIMIT      0x01    /* We've set the limit */
3148 #define DONE_KEY        0x02    /* We've set the key */
3149 #define DONE_BANLIST    0x04    /* We've sent the ban list */
3150 #define DONE_NOTOPER    0x08    /* We've sent a "Not oper" error */
3151 #define DONE_BANCLEAN   0x10    /* We've cleaned bans... */
3152
3153 struct ParseState {
3154   struct ModeBuf *mbuf;
3155   struct Client *cptr;
3156   struct Client *sptr;
3157   struct Channel *chptr;
3158   int parc;
3159   char **parv;
3160   unsigned int flags;
3161   unsigned int dir;
3162   unsigned int done;
3163   int args_used;
3164   int max_args;
3165   int numbans;
3166   struct SLink banlist[MAXPARA];
3167   struct {
3168     unsigned int flag;
3169     struct Client *client;
3170   } cli_change[MAXPARA];
3171 };
3172
3173 /*
3174  * Here's a helper function to deal with sending along "Not oper" or
3175  * "Not member" messages
3176  */
3177 static void
3178 send_notoper(struct ParseState *state)
3179 {
3180   if (state->done & DONE_NOTOPER)
3181     return;
3182
3183   send_reply(state->sptr, (state->flags & MODE_PARSE_NOTOPER) ?
3184              ERR_CHANOPRIVSNEEDED : ERR_NOTONCHANNEL, state->chptr->chname);
3185
3186   state->done |= DONE_NOTOPER;
3187 }
3188
3189 /*
3190  * Helper function to convert limits
3191  */
3192 static void
3193 mode_parse_limit(struct ParseState *state, int *flag_p)
3194 {
3195   unsigned int t_limit;
3196
3197   if (state->dir == MODE_ADD) { /* convert arg only if adding limit */
3198     if (MyUser(state->sptr) && state->max_args <= 0) /* 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, "MODE +l");
3204       return;
3205     }
3206
3207     t_limit = atoi(state->parv[state->args_used++]); /* grab arg */
3208     state->parc--;
3209     state->max_args--;
3210
3211     if (!t_limit) /* if it was zero, ignore it */
3212       return;
3213   } else
3214     t_limit = state->chptr->mode.limit;
3215
3216   /* If they're not an oper, they can't change modes */
3217   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3218     send_notoper(state);
3219     return;
3220   }
3221
3222   if (state->done & DONE_LIMIT) /* allow limit to be set only once */
3223     return;
3224   state->done |= DONE_LIMIT;
3225
3226   assert(0 != state->mbuf);
3227
3228   modebuf_mode_uint(state->mbuf, state->dir | flag_p[0], t_limit);
3229
3230   if (state->flags & MODE_PARSE_SET) { /* set the limit */
3231     if (state->dir & MODE_ADD) {
3232       state->chptr->mode.mode |= flag_p[0];
3233       state->chptr->mode.limit = t_limit;
3234     } else {
3235       state->chptr->mode.mode &= flag_p[0];
3236       state->chptr->mode.limit = 0;
3237     }
3238   }
3239 }
3240
3241 /*
3242  * Helper function to convert keys
3243  */
3244 static void
3245 mode_parse_key(struct ParseState *state, int *flag_p)
3246 {
3247   char *t_str, *s;
3248   int t_len;
3249
3250   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3251     return;
3252
3253   if (state->parc <= 0) { /* warn if not enough args */
3254     if (MyUser(state->sptr))
3255       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
3256                        "MODE -k");
3257     return;
3258   }
3259
3260   t_str = state->parv[state->args_used++]; /* grab arg */
3261   state->parc--;
3262   state->max_args--;
3263
3264   /* If they're not an oper, they can't change modes */
3265   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3266     send_notoper(state);
3267     return;
3268   }
3269
3270   if (state->done & DONE_KEY) /* allow key to be set only once */
3271     return;
3272   state->done |= DONE_KEY;
3273
3274   t_len = KEYLEN + 1;
3275
3276   /* clean up the key string */
3277   s = t_str;
3278   while (*++s > ' ' && *s != ':' && --t_len)
3279     ;
3280   *s = '\0';
3281
3282   if (!*t_str) { /* warn if empty */
3283     if (MyUser(state->sptr))
3284       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +k" :
3285                        "MODE -k");
3286     return;
3287   }
3288
3289   /* can't add a key if one is set, nor can one remove the wrong key */
3290   if (!(state->flags & MODE_PARSE_FORCE))
3291     if ((state->dir == MODE_ADD && *state->chptr->mode.key) ||
3292         (state->dir == MODE_DEL &&
3293          ircd_strcmp(state->chptr->mode.key, t_str))) {
3294       send_reply(state->sptr, ERR_KEYSET, state->chptr->chname);
3295       return;
3296     }
3297
3298   assert(0 != state->mbuf);
3299
3300   if (state->flags & MODE_PARSE_BOUNCE) {
3301     if (*state->chptr->mode.key) /* reset old key */
3302       modebuf_mode_string(state->mbuf, MODE_DEL | flag_p[0],
3303                           state->chptr->mode.key, 0);
3304     else /* remove new bogus key */
3305       modebuf_mode_string(state->mbuf, MODE_ADD | flag_p[0], t_str, 0);
3306   } else /* send new key */
3307     modebuf_mode_string(state->mbuf, state->dir | flag_p[0], t_str, 0);
3308
3309   if (state->flags & MODE_PARSE_SET) {
3310     if (state->dir == MODE_ADD) /* set the new key */
3311       ircd_strncpy(state->chptr->mode.key, t_str, KEYLEN);
3312     else /* remove the old key */
3313       *state->chptr->mode.key = '\0';
3314   }
3315 }
3316
3317 /*
3318  * Helper function to convert bans
3319  */
3320 static void
3321 mode_parse_ban(struct ParseState *state, int *flag_p)
3322 {
3323   char *t_str, *s;
3324   struct SLink *ban, *newban = 0;
3325
3326   if (state->parc <= 0) { /* Not enough args, send ban list */
3327     if (MyUser(state->sptr) && !(state->done & DONE_BANLIST)) {
3328       send_ban_list(state->sptr, state->chptr);
3329       state->done |= DONE_BANLIST;
3330     }
3331
3332     return;
3333   }
3334
3335   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3336     return;
3337
3338   t_str = state->parv[state->args_used++]; /* grab arg */
3339   state->parc--;
3340   state->max_args--;
3341
3342   /* If they're not an oper, they can't change modes */
3343   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3344     send_notoper(state);
3345     return;
3346   }
3347
3348   if ((s = strchr(t_str, ' ')))
3349     *s = '\0';
3350
3351   if (!*t_str || *t_str == ':') { /* warn if empty */
3352     if (MyUser(state->sptr))
3353       need_more_params(state->sptr, state->dir == MODE_ADD ? "MODE +b" :
3354                        "MODE -b");
3355     return;
3356   }
3357
3358   t_str = collapse(pretty_mask(t_str));
3359
3360   /* remember the ban for the moment... */
3361   if (state->dir == MODE_ADD) {
3362     newban = state->banlist + (state->numbans++);
3363     newban->next = 0;
3364
3365     DupString(newban->value.ban.banstr, t_str);
3366     newban->value.ban.who = state->sptr->name;
3367     newban->value.ban.when = TStime();
3368
3369     newban->flags = CHFL_BAN | MODE_ADD;
3370
3371     if ((s = strrchr(t_str, '@')) && check_if_ipmask(s + 1))
3372       newban->flags |= CHFL_BAN_IPMASK;
3373   }
3374
3375   if (!state->chptr->banlist) {
3376     state->chptr->banlist = newban; /* add our ban with its flags */
3377     state->done |= DONE_BANCLEAN;
3378     return;
3379   }
3380
3381   /* Go through all bans */
3382   for (ban = state->chptr->banlist; ban; ban = ban->next) {
3383     /* first, clean the ban flags up a bit */
3384     if (!(state->done & DONE_BANCLEAN))
3385       /* Note: We're overloading *lots* of bits here; be careful! */
3386       ban->flags &= ~(MODE_ADD | MODE_DEL | CHFL_BAN_OVERLAPPED);
3387
3388     /* Bit meanings:
3389      *
3390      * MODE_ADD            - Ban was added; if we're bouncing modes,
3391      *                       then we'll remove it below; otherwise,
3392      *                       we'll have to allocate a real ban
3393      *
3394      * MODE_DEL            - Ban was marked for deletion; if we're
3395      *                       bouncing modes, we'll have to re-add it,
3396      *                       otherwise, we'll have to remove it
3397      *
3398      * CHFL_BAN_OVERLAPPED - The ban we added turns out to overlap
3399      *                       with a ban already set; if we're
3400      *                       bouncing modes, we'll have to bounce
3401      *                       this one; otherwise, we'll just ignore
3402      *                       it when we process added bans
3403      */
3404
3405     if (state->dir == MODE_DEL && !ircd_strcmp(ban->value.ban.banstr, t_str)) {
3406       ban->flags |= MODE_DEL; /* delete one ban */
3407
3408       if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
3409         break;
3410     } else if (state->dir == MODE_ADD) {
3411       /* if the ban already exists, don't worry about it */
3412       if (!ircd_strcmp(ban->value.ban.banstr, t_str)) {
3413         if (state->done & DONE_BANCLEAN) /* If we're cleaning, finish */
3414           break;
3415         continue;
3416       } else if (!mmatch(ban->value.ban.banstr, t_str)) {
3417         if (!(ban->flags & MODE_DEL))
3418           newban->flags |= CHFL_BAN_OVERLAPPED; /* our ban overlaps */
3419       } else if (!mmatch(t_str, ban->value.ban.banstr))
3420         ban->flags |= MODE_DEL; /* mark ban for deletion: overlapping */
3421
3422       if (!ban->next) {
3423         ban->next = newban; /* add our ban with its flags */
3424         break; /* get out of loop */
3425       }
3426     }
3427   }
3428   state->done |= DONE_BANCLEAN;
3429 }
3430
3431 /*
3432  * This is the bottom half of the ban processor
3433  */
3434 static void
3435 mode_process_bans(struct ParseState *state)
3436 {
3437   struct SLink *ban, *newban, *prevban, *nextban;
3438   int count = 0;
3439   int len = 0;
3440   int banlen;
3441   int changed = 0;
3442
3443   for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) {
3444     count++;
3445     banlen = strlen(ban->value.ban.banstr);
3446     len += banlen;
3447     nextban = ban->next;
3448
3449     if ((ban->flags & (MODE_DEL | MODE_ADD)) == (MODE_DEL | MODE_ADD)) {
3450       if (prevban)
3451         prevban->next = 0; /* Break the list; ban isn't a real ban */
3452       else
3453         state->chptr->banlist = 0;
3454
3455       count--;
3456       len -= banlen;
3457
3458       MyFree(ban->value.ban.banstr);
3459
3460       continue;
3461     } else if (ban->flags & MODE_DEL) { /* Deleted a ban? */
3462       modebuf_mode_string(state->mbuf, MODE_DEL | MODE_BAN,
3463                           ban->value.ban.banstr,
3464                           state->flags & MODE_PARSE_SET);
3465
3466       if (state->flags & MODE_PARSE_SET) { /* Ok, make it take effect */
3467         if (prevban) /* clip it out of the list... */
3468           prevban->next = ban->next;
3469         else
3470           state->chptr->banlist = ban->next;
3471
3472         count--;
3473         len -= banlen;
3474
3475         MyFree(ban->value.ban.who);
3476         free_link(ban);
3477
3478         changed++;
3479         continue; /* next ban; keep prevban like it is */
3480       } else
3481         ban->flags &= (CHFL_BAN | CHFL_BAN_IPMASK); /* unset other flags */
3482     } else if (ban->flags & MODE_ADD) { /* adding a ban? */
3483       if (prevban)
3484         prevban->next = 0; /* Break the list; ban isn't a real ban */
3485       else
3486         state->chptr->banlist = 0;
3487
3488       /* If we're supposed to ignore it, do so. */
3489       if (ban->flags & CHFL_BAN_OVERLAPPED &&
3490           !(state->flags & MODE_PARSE_BOUNCE)) {
3491         count--;
3492         len -= banlen;
3493
3494         MyFree(ban->value.ban.banstr);
3495       } else {
3496         if (state->flags & MODE_PARSE_SET && MyUser(state->sptr) &&
3497             (len > MAXBANLENGTH || count >= MAXBANS)) {
3498           send_reply(state->sptr, ERR_BANLISTFULL, state->chptr->chname,
3499                      ban->value.ban.banstr);
3500           count--;
3501           len -= banlen;
3502
3503           MyFree(ban->value.ban.banstr);
3504         } else {
3505           /* add the ban to the buffer */
3506           modebuf_mode_string(state->mbuf, MODE_ADD | MODE_BAN,
3507                               ban->value.ban.banstr,
3508                               !(state->flags & MODE_PARSE_SET));
3509
3510           if (state->flags & MODE_PARSE_SET) { /* create a new ban */
3511             newban = make_link();
3512             newban->value.ban.banstr = ban->value.ban.banstr;
3513             DupString(newban->value.ban.who, ban->value.ban.who);
3514             newban->value.ban.when = ban->value.ban.when;
3515             newban->flags = ban->flags & (CHFL_BAN | CHFL_BAN_IPMASK);
3516
3517             newban->next = state->chptr->banlist; /* and link it in */
3518             state->chptr->banlist = newban;
3519
3520             changed++;
3521           }
3522         }
3523       }
3524     }
3525
3526     prevban = ban;
3527   } /* for (prevban = 0, ban = state->chptr->banlist; ban; ban = nextban) { */
3528
3529   if (changed) /* if we changed the ban list, we must invalidate the bans */
3530     mode_ban_invalidate(state->chptr);
3531 }
3532
3533 /*
3534  * Helper function to process client changes
3535  */
3536 static void
3537 mode_parse_client(struct ParseState *state, int *flag_p)
3538 {
3539   char *t_str;
3540   struct Client *acptr;
3541   int i;
3542
3543   if (MyUser(state->sptr) && state->max_args <= 0) /* drop if too many args */
3544     return;
3545
3546   if (state->parc <= 0) { /* warn if not enough args */
3547     if (MyUser(state->sptr))
3548       need_more_params(state->sptr, state->dir == MODE_ADD ?
3549                        (flag_p[0] == MODE_CHANOP ? "MODE +o" : "MODE +v") :
3550                        (flag_p[0] == MODE_CHANOP ? "MODE -o" : "MODE -v"));
3551     return;
3552   }
3553
3554   t_str = state->parv[state->args_used++]; /* grab arg */
3555   state->parc--;
3556   state->max_args--;
3557
3558   /* If they're not an oper, they can't change modes */
3559   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3560     send_notoper(state);
3561     return;
3562   }
3563
3564   if (MyUser(state->sptr)) /* find client we're manipulating */
3565     acptr = find_chasing(state->sptr, t_str, NULL);
3566   else
3567     acptr = findNUser(t_str);
3568
3569   if (!acptr)
3570     return; /* find_chasing() already reported an error to the user */
3571
3572   for (i = 0; i < MAXPARA; i++) /* find an element to stick them in */
3573     if (!state->cli_change[i].flag || (state->cli_change[i].client == acptr &&
3574                                        state->cli_change[i].flag & flag_p[0]))
3575       break; /* found a slot */
3576
3577   /* Store what we're doing to them */
3578   state->cli_change[i].flag = state->dir | flag_p[0];
3579   state->cli_change[i].client = acptr;
3580 }
3581
3582 /*
3583  * Helper function to process the changed client list
3584  */
3585 static void
3586 mode_process_clients(struct ParseState *state)
3587 {
3588   int i;
3589   struct Membership *member;
3590
3591   for (i = 0; state->cli_change[i].flag; i++) {
3592     assert(0 != state->cli_change[i].client);
3593
3594     /* look up member link */
3595     if (!(member = find_member_link(state->chptr,
3596                                     state->cli_change[i].client)) ||
3597         (MyUser(state->sptr) && IsZombie(member))) {
3598       if (MyUser(state->sptr))
3599         send_reply(state->sptr, ERR_USERNOTINCHANNEL,
3600                    state->cli_change[i].client->name, state->chptr->chname);
3601       continue;
3602     }
3603
3604     if ((state->cli_change[i].flag & MODE_ADD &&
3605          (state->cli_change[i].flag & member->status)) ||
3606         (state->cli_change[i].flag & MODE_DEL &&
3607          !(state->cli_change[i].flag & member->status)))
3608       continue; /* no change made, don't do anything */
3609
3610     /* see if the deop is allowed */
3611     if ((state->cli_change[i].flag & (MODE_DEL | MODE_CHANOP)) ==
3612         (MODE_DEL | MODE_CHANOP)) {
3613       /* prevent +k users from being deopped */
3614       if (IsChannelService(state->cli_change[i].client)) {
3615         if (state->flags & MODE_PARSE_FORCE) /* it was forced */
3616           sendto_opmask_butone(0, SNO_HACK4, "Deop of +k user on %H by %s",
3617                                state->chptr,
3618                                (IsServer(state->sptr) ? state->sptr->name :
3619                                 state->sptr->user->server->name));
3620
3621         else if (MyUser(state->sptr) && state->flags & MODE_PARSE_SET) {
3622           send_reply(state->sptr, ERR_ISCHANSERVICE,
3623                      state->cli_change[i].client->name, state->chptr->chname);
3624           continue;
3625         }
3626       }
3627
3628 #ifdef NO_OPER_DEOP_LCHAN
3629       /* don't allow local opers to be deopped on local channels */
3630       if (MyUser(state->sptr) && state->cli_change[i].client != state->sptr &&
3631           IsOperOnLocalChannel(state->cli_change[i].client,
3632                                state->chptr->chname)) {
3633         send_reply(state->sptr, ERR_ISOPERLCHAN,
3634                    state->cli_change[i].client->name, state->chptr->chname);
3635         continue;
3636       }
3637 #endif
3638     }
3639
3640     /* accumulate the change */
3641     modebuf_mode_client(state->mbuf, state->cli_change[i].flag,
3642                         state->cli_change[i].client);
3643
3644     /* actually effect the change */
3645     if (state->flags & MODE_PARSE_SET) {
3646       if (state->cli_change[i].flag & MODE_ADD) {
3647         member->status |= (state->cli_change[i].flag &
3648                            (MODE_CHANOP | MODE_VOICE));
3649         if (state->cli_change[i].flag & MODE_CHANOP)
3650           ClearDeopped(member);
3651       } else
3652         member->status &= ~(state->cli_change[i].flag &
3653                             (MODE_CHANOP | MODE_VOICE));
3654     }
3655   } /* for (i = 0; state->cli_change[i].flags; i++) { */
3656 }
3657
3658 /*
3659  * Helper function to process the simple modes
3660  */
3661 static void
3662 mode_parse_mode(struct ParseState *state, int *flag_p)
3663 {
3664   if ((state->dir == MODE_ADD &&  (flag_p[0] & state->chptr->mode.mode)) ||
3665       (state->dir == MODE_DEL && !(flag_p[0] & state->chptr->mode.mode)))
3666     return; /* no change */
3667
3668   /* If they're not an oper, they can't change modes */
3669   if (state->flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER)) {
3670     send_notoper(state);
3671     return;
3672   }
3673
3674   assert(0 != state->mbuf);
3675
3676   modebuf_mode(state->mbuf, state->dir | flag_p[0]);
3677
3678   /* make +p and +s mutually exclusive */
3679   if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
3680     if (flag_p[0] == MODE_SECRET && (state->chptr->mode.mode & MODE_PRIVATE))
3681       modebuf_mode(state->mbuf, MODE_DEL | MODE_PRIVATE);
3682     else if (flag_p[0] == MODE_PRIVATE &&
3683              (state->chptr->mode.mode & MODE_SECRET))
3684       modebuf_mode(state->mbuf, MODE_DEL | MODE_SECRET);
3685   }
3686
3687   if (state->flags & MODE_PARSE_SET) { /* set the flags */
3688     if (state->dir == MODE_ADD) { /* add the mode to the channel */
3689       state->chptr->mode.mode |= flag_p[0];
3690
3691       /* make +p and +s mutually exclusive */
3692       if (state->dir == MODE_ADD && flag_p[0] & (MODE_SECRET | MODE_PRIVATE)) {
3693         if (flag_p[0] == MODE_PRIVATE)
3694           state->chptr->mode.mode &= ~MODE_SECRET;
3695         else
3696           state->chptr->mode.mode &= ~MODE_PRIVATE;
3697       }
3698     } else /* remove the mode from the channel */
3699       state->chptr->mode.mode &= ~flag_p[0];
3700   }
3701
3702   /* Clear out invite structures if we're removing invites */
3703   if (state->flags & MODE_PARSE_SET && state->dir == MODE_DEL &&
3704       flag_p[0] == MODE_INVITEONLY)
3705     mode_invite_clear(state->chptr);
3706 }
3707
3708 /*
3709  * This routine is intended to parse MODE or OPMODE commands and effect the
3710  * changes (or just build the bounce buffer).  We pass the starting offset
3711  * as a 
3712  */
3713 int
3714 mode_parse(struct ModeBuf *mbuf, struct Client *cptr, struct Client *sptr,
3715            struct Channel *chptr, int parc, char *parv[], unsigned int flags)
3716 {
3717   static int chan_flags[] = {
3718     MODE_CHANOP,        'o',
3719     MODE_VOICE,         'v',
3720     MODE_PRIVATE,       'p',
3721     MODE_SECRET,        's',
3722     MODE_MODERATED,     'm',
3723     MODE_TOPICLIMIT,    't',
3724     MODE_INVITEONLY,    'i',
3725     MODE_NOPRIVMSGS,    'n',
3726     MODE_KEY,           'k',
3727     MODE_BAN,           'b',
3728     MODE_LIMIT,         'l',
3729     MODE_ADD,           '+',
3730     MODE_DEL,           '-',
3731     0x0, 0x0
3732   };
3733   int i;
3734   int *flag_p;
3735   char *modestr;
3736   struct ParseState state;
3737
3738   assert(0 != cptr);
3739   assert(0 != sptr);
3740   assert(0 != chptr);
3741   assert(0 != parc);
3742   assert(0 != parv);
3743
3744   state.mbuf = mbuf;
3745   state.cptr = cptr;
3746   state.sptr = sptr;
3747   state.chptr = chptr;
3748   state.parc = parc;
3749   state.parv = parv;
3750   state.flags = flags;
3751   state.dir = MODE_ADD;
3752   state.done = 0;
3753   state.args_used = 0;
3754   state.max_args = MAXMODEPARAMS;
3755   state.numbans = 0;
3756
3757   for (i = 0; i < MAXPARA; i++) { /* initialize ops/voices arrays */
3758     state.banlist[i].next = 0;
3759     state.banlist[i].value.ban.banstr = 0;
3760     state.banlist[i].value.ban.who = 0;
3761     state.banlist[i].value.ban.when = 0;
3762     state.banlist[i].flags = 0;
3763     state.cli_change[i].flag = 0;
3764     state.cli_change[i].client = 0;
3765   }
3766
3767   modestr = state.parv[state.args_used++];
3768   state.parc--;
3769
3770   while (*modestr) {
3771     for (; *modestr; modestr++) {
3772       for (flag_p = chan_flags; flag_p[0]; flag_p += 2) /* look up flag */
3773         if (flag_p[1] == *modestr)
3774           break;
3775
3776       if (!flag_p[0]) { /* didn't find it?  complain and continue */
3777         if (MyUser(state.sptr))
3778           send_reply(state.sptr, ERR_UNKNOWNMODE, *modestr);
3779         continue;
3780       }
3781
3782       switch (*modestr) {
3783       case '+': /* switch direction to MODE_ADD */
3784       case '-': /* switch direction to MODE_DEL */
3785         state.dir = flag_p[0];
3786         break;
3787
3788       case 'l': /* deal with limits */
3789         mode_parse_limit(&state, flag_p);
3790         break;
3791
3792       case 'k': /* deal with keys */
3793         mode_parse_key(&state, flag_p);
3794         break;
3795
3796       case 'b': /* deal with bans */
3797         mode_parse_ban(&state, flag_p);
3798         break;
3799
3800       case 'o': /* deal with ops/voice */
3801       case 'v':
3802         mode_parse_client(&state, flag_p);
3803         break;
3804
3805       default: /* deal with other modes */
3806         mode_parse_mode(&state, flag_p);
3807         break;
3808       } /* switch (*modestr) { */
3809     } /* for (; *modestr; modestr++) { */
3810
3811     if (state.parc > 0) { /* process next argument in string */
3812       modestr = state.parv[state.args_used++];
3813       state.parc--;
3814
3815       /* is it a TS? */
3816       if (IsServer(state.sptr) && !state.parc && IsDigit(*modestr)) {
3817         time_t recv_ts;
3818
3819         if (!(state.flags & MODE_PARSE_SET))      /* don't set earlier TS if */
3820           break;                     /* we're then going to bounce the mode! */
3821
3822         recv_ts = atoi(modestr);
3823
3824         if (recv_ts && recv_ts < state.chptr->creationtime)
3825           state.chptr->creationtime = recv_ts; /* respect earlier TS */
3826
3827         break; /* break out of while loop */
3828       } else if (state.flags & MODE_PARSE_STRICT ||
3829                  (MyUser(state.sptr) && state.max_args <= 0)) {
3830         state.parc++; /* we didn't actually gobble the argument */
3831         state.args_used--;
3832         break; /* break out of while loop */
3833       }
3834     }
3835   } /* while (*modestr) { */
3836
3837   /*
3838    * the rest of the function finishes building resultant MODEs; if the
3839    * origin isn't a member or an oper, skip it.
3840    */
3841   if (state.flags & (MODE_PARSE_NOTOPER | MODE_PARSE_NOTMEMBER))
3842     return state.args_used; /* tell our parent how many args we gobbled */
3843
3844   assert(0 != state.mbuf);
3845
3846   if (state.done & DONE_BANCLEAN) /* process bans */
3847     mode_process_bans(&state);
3848
3849   /* process client changes */
3850   if (state.cli_change[0].flag)
3851     mode_process_clients(&state);
3852
3853   return state.args_used; /* tell our parent how many args we gobbled */
3854 }
3855
3856 /*
3857  * Initialize a join buffer
3858  */
3859 void
3860 joinbuf_init(struct JoinBuf *jbuf, struct Client *source,
3861              struct Client *connect, unsigned int type, char *comment,
3862              time_t create)
3863 {
3864   int i;
3865
3866   assert(0 != jbuf);
3867   assert(0 != source);
3868   assert(0 != connect);
3869
3870   jbuf->jb_source = source; /* just initialize struct JoinBuf */
3871   jbuf->jb_connect = connect;
3872   jbuf->jb_type = type;
3873   jbuf->jb_comment = comment;
3874   jbuf->jb_create = create;
3875   jbuf->jb_count = 0;
3876   jbuf->jb_strlen = (((type == JOINBUF_TYPE_JOIN ||
3877                        type == JOINBUF_TYPE_PART ||
3878                        type == JOINBUF_TYPE_PARTALL) ?
3879                       STARTJOINLEN : STARTCREATELEN) +
3880                      (comment ? strlen(comment) + 2 : 0));
3881
3882   for (i = 0; i < MAXJOINARGS; i++)
3883     jbuf->jb_channels[i] = 0;
3884 }
3885
3886 /*
3887  * Add a channel to the join buffer
3888  */
3889 void
3890 joinbuf_join(struct JoinBuf *jbuf, struct Channel *chan, unsigned int flags)
3891 {
3892   unsigned int len;
3893
3894   assert(0 != jbuf);
3895
3896   if (chan) {
3897     if (jbuf->jb_type == JOINBUF_TYPE_PART ||
3898         jbuf->jb_type == JOINBUF_TYPE_PARTALL) {
3899       /* Send notification to channel */
3900       if (!(flags & CHFL_ZOMBIE))
3901         sendcmdto_channel_butserv(jbuf->jb_source, CMD_PART, chan,
3902                                   (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3903                                   ":%H" : "%H :%s", chan, jbuf->jb_comment);
3904       else if (MyUser(jbuf->jb_source))
3905         sendcmdto_one(jbuf->jb_source, CMD_PART, jbuf->jb_source,
3906                       (flags & CHFL_BANNED || !jbuf->jb_comment) ?
3907                       ":%H" : "%H :%s", chan, jbuf->jb_comment);
3908
3909       /* Remove user from channel */
3910       remove_user_from_channel(jbuf->jb_source, chan);
3911     } else {
3912       /* Add user to channel */
3913       add_user_to_channel(chan, jbuf->jb_source, flags);
3914
3915       /* Send the notification to the channel */
3916       sendcmdto_channel_butserv(jbuf->jb_source, CMD_JOIN, chan, ":%H", chan);
3917
3918       /* send an op, too, if needed */
3919       if (jbuf->jb_type == JOINBUF_TYPE_CREATE &&
3920           !IsModelessChannel(chan->chname))
3921         sendcmdto_channel_butserv(jbuf->jb_source, CMD_MODE, chan, "%H +o %C",
3922                                   chan, jbuf->jb_source);
3923     }
3924
3925     if (jbuf->jb_type == JOINBUF_TYPE_PARTALL || IsLocalChannel(chan->chname))
3926       return; /* don't send to remote */
3927   }
3928
3929   /* figure out if channel name will cause buffer to be overflowed */
3930   len = chan ? strlen(chan->chname) + 1 : 2;
3931   if (jbuf->jb_strlen + len > IRC_BUFSIZE)
3932     joinbuf_flush(jbuf);
3933
3934   /* add channel to list of channels to send and update counts */
3935   jbuf->jb_channels[jbuf->jb_count++] = chan;
3936   jbuf->jb_strlen += len;
3937
3938   /* if we've used up all slots, flush */
3939   if (jbuf->jb_count >= MAXJOINARGS)
3940     joinbuf_flush(jbuf);
3941 }
3942
3943 /*
3944  * Flush the channel list to remote servers
3945  */
3946 int
3947 joinbuf_flush(struct JoinBuf *jbuf)
3948 {
3949   char chanlist[IRC_BUFSIZE];
3950   int chanlist_i = 0;
3951   int i;
3952
3953   if (!jbuf->jb_count || jbuf->jb_type == JOINBUF_TYPE_PARTALL)
3954     return 0; /* no joins to process */
3955
3956   for (i = 0; i < jbuf->jb_count; i++) { /* build channel list */
3957     build_string(chanlist, &chanlist_i,
3958                  jbuf->jb_channels[i] ? jbuf->jb_channels[i]->chname : "0", 0,
3959                  i == 0 ? '\0' : ',');
3960
3961     jbuf->jb_channels[i] = 0; /* mark slot empty */
3962   }
3963
3964   jbuf->jb_count = 0; /* reset base counters */
3965   jbuf->jb_strlen = ((jbuf->jb_type == JOINBUF_TYPE_JOIN ||
3966                       jbuf->jb_type == JOINBUF_TYPE_PART ?
3967                       STARTJOINLEN : STARTCREATELEN) +
3968                      (jbuf->jb_comment ? strlen(jbuf->jb_comment) + 2 : 0));
3969
3970   /* and send the appropriate command */
3971   switch (jbuf->jb_type) {
3972   case JOINBUF_TYPE_JOIN:
3973     sendcmdto_serv_butone(jbuf->jb_source, CMD_JOIN, jbuf->jb_connect,
3974                           "%s", chanlist);
3975     break;
3976
3977   case JOINBUF_TYPE_CREATE:
3978     sendcmdto_serv_butone(jbuf->jb_source, CMD_CREATE, jbuf->jb_connect,
3979                           "%s %Tu", chanlist, jbuf->jb_create);
3980     break;
3981
3982   case JOINBUF_TYPE_PART:
3983     sendcmdto_serv_butone(jbuf->jb_source, CMD_PART, jbuf->jb_connect,
3984                           jbuf->jb_comment ? "%s :%s" : "%s", chanlist,
3985                           jbuf->jb_comment);
3986     break;
3987   }
3988
3989   return 0;
3990 }