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