]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/channels.cpp
Fix for bug #510
[user/henk/code/inspircd.git] / src / channels.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core: libIRCDchannels */
15
16 #include "inspircd.h"
17 #include <stdarg.h>
18 #include "wildcard.h"
19 #include "mode.h"
20
21 Channel::Channel(InspIRCd* Instance, const std::string &cname, time_t ts) : ServerInstance(Instance)
22 {
23         chan_hash::iterator findchan = ServerInstance->chanlist->find(cname);
24         if (findchan != Instance->chanlist->end())
25                 throw CoreException("Cannot create duplicate channel " + cname);
26
27         (*(ServerInstance->chanlist))[cname.c_str()] = this;
28         strlcpy(this->name, cname.c_str(), CHANMAX);
29         this->created = ts ? ts : ServerInstance->Time();
30         this->age = this->created;
31
32
33
34
35         *topic = *setby = *key = 0;
36         maxbans = topicset = limit = 0;
37         memset(&modes,0,64);
38 }
39
40 void Channel::SetMode(char mode,bool mode_on)
41 {
42         modes[mode-65] = mode_on;
43         if (!mode_on)
44                 this->SetModeParam(mode,"",false);
45 }
46
47
48 void Channel::SetModeParam(char mode,const char* parameter,bool mode_on)
49 {
50         CustomModeList::iterator n = custom_mode_params.find(mode);     
51
52         if (mode_on)
53         {
54                 if (n == custom_mode_params.end())
55                         custom_mode_params[mode] = strdup(parameter);
56         }
57         else
58         {
59                 if (n != custom_mode_params.end())
60                 {
61                         free(n->second);
62                         custom_mode_params.erase(n);
63                 }
64         }
65 }
66
67 bool Channel::IsModeSet(char mode)
68 {
69         return modes[mode-65];
70 }
71
72 std::string Channel::GetModeParameter(char mode)
73 {
74         switch (mode)
75         {
76                 case 'k':
77                         return this->key;
78                 case 'l':
79                         return ConvToStr(this->limit);
80                 default:
81                         CustomModeList::iterator n = custom_mode_params.find(mode);
82                         if (n != custom_mode_params.end())
83                                 return n->second;
84                         return "";
85                 break;
86         }
87 }
88
89 long Channel::GetUserCounter()
90 {
91         return (this->internal_userlist.size());
92 }
93
94 void Channel::AddUser(User* user)
95 {
96         internal_userlist[user] = user->nick;
97 }
98
99 unsigned long Channel::DelUser(User* user)
100 {
101         CUListIter a = internal_userlist.find(user);
102         
103         if (a != internal_userlist.end())
104         {
105                 internal_userlist.erase(a);
106                 /* And tidy any others... */
107                 DelOppedUser(user);
108                 DelHalfoppedUser(user);
109                 DelVoicedUser(user);
110         }
111         
112         return internal_userlist.size();
113 }
114
115 bool Channel::HasUser(User* user)
116 {
117         return (internal_userlist.find(user) != internal_userlist.end());
118 }
119
120 void Channel::AddOppedUser(User* user)
121 {
122         internal_op_userlist[user] = user->nick;
123 }
124
125 void Channel::DelOppedUser(User* user)
126 {
127         CUListIter a = internal_op_userlist.find(user);
128         if (a != internal_op_userlist.end())
129         {
130                 internal_op_userlist.erase(a);
131                 return;
132         }
133 }
134
135 void Channel::AddHalfoppedUser(User* user)
136 {
137         internal_halfop_userlist[user] = user->nick;
138 }
139
140 void Channel::DelHalfoppedUser(User* user)
141 {
142         CUListIter a = internal_halfop_userlist.find(user);
143
144         if (a != internal_halfop_userlist.end())
145         {   
146                 internal_halfop_userlist.erase(a);
147         }
148 }
149
150 void Channel::AddVoicedUser(User* user)
151 {
152         internal_voice_userlist[user] = user->nick;
153 }
154
155 void Channel::DelVoicedUser(User* user)
156 {
157         CUListIter a = internal_voice_userlist.find(user);
158         
159         if (a != internal_voice_userlist.end())
160         {
161                 internal_voice_userlist.erase(a);
162         }
163 }
164
165 CUList* Channel::GetUsers()
166 {
167         return &internal_userlist;
168 }
169
170 CUList* Channel::GetOppedUsers()
171 {
172         return &internal_op_userlist;
173 }
174
175 CUList* Channel::GetHalfoppedUsers()
176 {
177         return &internal_halfop_userlist;
178 }
179
180 CUList* Channel::GetVoicedUsers()
181 {
182         return &internal_voice_userlist;
183 }
184
185 void Channel::SetDefaultModes()
186 {
187         ServerInstance->Logs->Log("CHANNELS", DEBUG, "SetDefaultModes %s", ServerInstance->Config->DefaultModes);
188         irc::spacesepstream list(ServerInstance->Config->DefaultModes);
189         std::string modeseq;
190         std::string parameter;
191
192         list.GetToken(modeseq);
193
194         for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
195         {
196                 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
197                 if (mode)
198                 {
199                         if (mode->GetNumParams(true))
200                                 list.GetToken(parameter);
201                         else
202                                 parameter.clear();
203
204                         mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
205                 }
206         }
207 }
208
209 /* 
210  * add a channel to a user, creating the record for it if needed and linking
211  * it to the user record 
212  */
213 Channel* Channel::JoinUser(InspIRCd* Instance, User *user, const char* cn, bool override, const char* key, bool bursting, time_t TS)
214 {
215         if (!user || !cn)
216                 return NULL;
217
218         char cname[MAXBUF];
219         int MOD_RESULT = 0;
220         std::string privs;
221         Channel *Ptr;
222
223         /*
224          * We don't restrict the number of channels that remote users or users that are override-joining may be in.
225          * We restrict local users to MaxChans channels.
226          * We restrict local operators to OperMaxChans channels.
227          * This is a lot more logical than how it was formerly. -- w00t
228          */
229         if (IS_LOCAL(user) && !override)
230         {
231                 if (user->GetMaxChans())
232                 {
233                         if (user->chans.size() >= user->GetMaxChans())
234                         {
235                                 user->WriteNumeric(405, "%s %s :You are on too many channels",user->nick, cn);
236                                 return NULL;
237                         }
238                 }
239                 else
240                 {
241                         if (IS_OPER(user))
242                         {
243                                 if (user->chans.size() >= Instance->Config->OperMaxChans)
244                                 {
245                                         user->WriteNumeric(405, "%s %s :You are on too many channels",user->nick, cn);
246                                         return NULL;
247                                 }
248                         }
249                         else
250                         {
251                                 if (user->chans.size() >= Instance->Config->MaxChans)
252                                 {
253                                         user->WriteNumeric(405, "%s %s :You are on too many channels",user->nick, cn);
254                                         return NULL;
255                                 }
256                         }
257                 }
258         }
259
260         strlcpy(cname, cn, CHANMAX);
261         Ptr = Instance->FindChan(cname);
262
263         if (!Ptr)
264         {
265                 /*
266                  * Fix: desync bug was here, don't set @ on remote users - spanningtree handles their permissions. bug #358. -- w00t
267                  */
268                 if (!IS_LOCAL(user))
269                 {
270                         if (!TS)
271                                 Instance->Logs->Log("CHANNEL",DEBUG,"*** BUG *** Channel::JoinUser called for REMOTE user '%s' on channel '%s' but no TS given!", user->nick, cn);
272                 }
273                 else
274                 {
275                         privs = "@";
276                 }
277
278                 if (IS_LOCAL(user) && override == false)
279                 {
280                         MOD_RESULT = 0;
281                         FOREACH_RESULT_I(Instance,I_OnUserPreJoin,OnUserPreJoin(user,NULL,cname,privs));
282                         if (MOD_RESULT == 1)
283                                 return NULL;
284                 }
285
286                 Ptr = new Channel(Instance, cname, TS);
287         }
288         else
289         {
290                 /* Already on the channel */
291                 if (Ptr->HasUser(user))
292                         return NULL;
293
294                 /*
295                  * remote users are allowed us to bypass channel modes
296                  * and bans (used by servers)
297                  */
298                 if (IS_LOCAL(user) && override == false)
299                 {
300                         MOD_RESULT = 0;
301                         FOREACH_RESULT_I(Instance,I_OnUserPreJoin,OnUserPreJoin(user,Ptr,cname,privs));
302                         if (MOD_RESULT == 1)
303                         {
304                                 return NULL;
305                         }
306                         else if (MOD_RESULT == 0)
307                         {
308                                 if (*Ptr->key)
309                                 {
310                                         MOD_RESULT = 0;
311                                         FOREACH_RESULT_I(Instance,I_OnCheckKey,OnCheckKey(user, Ptr, key ? key : ""));
312                                         if (!MOD_RESULT)
313                                         {
314                                                 if ((!key) || strcmp(key,Ptr->key))
315                                                 {
316                                                         user->WriteNumeric(475, "%s %s :Cannot join channel (Incorrect channel key)",user->nick, Ptr->name);
317                                                         return NULL;
318                                                 }
319                                         }
320                                 }
321                                 if (Ptr->IsModeSet('i'))
322                                 {
323                                         MOD_RESULT = 0;
324                                         FOREACH_RESULT_I(Instance,I_OnCheckInvite,OnCheckInvite(user, Ptr));
325                                         if (!MOD_RESULT)
326                                         {
327                                                 if (!user->IsInvited(Ptr->name))
328                                                 {
329                                                         user->WriteNumeric(473, "%s %s :Cannot join channel (Invite only)",user->nick, Ptr->name);
330                                                         return NULL;
331                                                 }
332                                         }
333                                         user->RemoveInvite(Ptr->name);
334                                 }
335                                 if (Ptr->limit)
336                                 {
337                                         MOD_RESULT = 0;
338                                         FOREACH_RESULT_I(Instance,I_OnCheckLimit,OnCheckLimit(user, Ptr));
339                                         if (!MOD_RESULT)
340                                         {
341                                                 if (Ptr->GetUserCounter() >= Ptr->limit)
342                                                 {
343                                                         user->WriteNumeric(471, "%s %s :Cannot join channel (Channel is full)",user->nick, Ptr->name);
344                                                         return NULL;
345                                                 }
346                                         }
347                                 }
348                                 if (Ptr->bans.size())
349                                 {
350                                         if (Ptr->IsBanned(user))
351                                         {
352                                                 user->WriteNumeric(474, "%s %s :Cannot join channel (You're banned)",user->nick, Ptr->name);
353                                                 return NULL;
354                                         }
355                                 }
356                         }
357                 }
358         }
359
360         /* As spotted by jilles, dont bother to set this on remote users */
361         if (IS_LOCAL(user) && Ptr->GetUserCounter() == 0)
362                 Ptr->SetDefaultModes();
363
364         return Channel::ForceChan(Instance, Ptr, user, privs, bursting);
365 }
366
367 Channel* Channel::ForceChan(InspIRCd* Instance, Channel* Ptr, User* user, const std::string &privs, bool bursting)
368 {
369         std::string nick = user->nick;
370         bool silent = false;
371
372         Ptr->AddUser(user);
373
374         /* Just in case they have no permissions */
375         user->chans[Ptr] = 0;
376
377         for (std::string::const_iterator x = privs.begin(); x != privs.end(); x++)
378         {
379                 const char status = *x;
380                 ModeHandler* mh = Instance->Modes->FindPrefix(status);
381                 if (mh)
382                 {
383                         /* Set, and make sure that the mode handler knows this mode was now set */
384                         Ptr->SetPrefix(user, status, mh->GetPrefixRank(), true);
385                         mh->OnModeChange(Instance->FakeClient, Instance->FakeClient, Ptr, nick, true);
386
387                         switch (mh->GetPrefix())
388                         {
389                                 /* These logic ops are SAFE IN THIS CASE because if the entry doesnt exist,
390                                  * addressing operator[] creates it. If they do exist, it points to it.
391                                  * At all other times where we dont want to create an item if it doesnt exist, we
392                                  * must stick to ::find().
393                                  */
394                                 case '@':
395                                         user->chans[Ptr] |= UCMODE_OP;
396                                 break;
397                                 case '%':
398                                         user->chans[Ptr] |= UCMODE_HOP;
399                                 break;
400                                 case '+':
401                                         user->chans[Ptr] |= UCMODE_VOICE;
402                                 break;
403                         }
404                 }
405         }
406
407         FOREACH_MOD_I(Instance,I_OnUserJoin,OnUserJoin(user, Ptr, bursting, silent));
408
409         if (!silent)
410                 Ptr->WriteChannel(user,"JOIN :%s",Ptr->name);
411
412         /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
413         std::string ms = Instance->Modes->ModeString(user, Ptr);
414         if ((Ptr->GetUserCounter() > 1) && (ms.length()))
415                 Ptr->WriteAllExceptSender(user, true, 0, "MODE %s +%s", Ptr->name, ms.c_str());
416
417         /* Major improvement by Brain - we dont need to be calculating all this pointlessly for remote users */
418         if (IS_LOCAL(user))
419         {
420                 if (Ptr->topicset)
421                 {
422                         user->WriteNumeric(332, "%s %s :%s", user->nick, Ptr->name, Ptr->topic);
423                         user->WriteNumeric(333, "%s %s %s %lu", user->nick, Ptr->name, Ptr->setby, (unsigned long)Ptr->topicset);
424                 }
425                 Ptr->UserList(user);
426         }
427         FOREACH_MOD_I(Instance,I_OnPostJoin,OnPostJoin(user, Ptr));
428         return Ptr;
429 }
430
431 bool Channel::IsBanned(User* user)
432 {
433         char mask[MAXBUF];
434         int MOD_RESULT = 0;
435         FOREACH_RESULT(I_OnCheckBan,OnCheckBan(user, this));
436         if (!MOD_RESULT)
437         {
438                 snprintf(mask, MAXBUF, "%s!%s@%s", user->nick, user->ident, user->GetIPString());
439                 for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
440                 {
441                         /* This allows CIDR ban matching
442                          * 
443                          *        Full masked host                      Full unmasked host                   IP with/without CIDR
444                          */
445                         if ((match(user->GetFullHost(),i->data)) || (match(user->GetFullRealHost(),i->data)) || (match(mask, i->data, true)))
446                         {
447                                 return true;
448                         }
449                 }
450         }
451         return false;
452 }
453
454 bool Channel::IsExtBanned(User *user, char type)
455 {
456         // XXX. do we need events?
457         char mask[MAXBUF];
458         char *maskptr;
459
460         snprintf(mask, MAXBUF, "%s!%s@%s", user->nick, user->ident, user->GetIPString());
461
462         for (BanList::iterator i = this->bans.begin(); i != this->bans.end(); i++)
463         {
464                 if (i->data[0] != type || i->data[1] != ':')
465                         continue;
466
467                 // Iterate past char and : to get to the mask without doing a data copy(!)
468                 maskptr = i->data;
469                 maskptr++; // past the char
470                 maskptr++; // past the :
471
472                 /* This allows CIDR ban matching
473                  * 
474                  *        Full masked host                             Full unmasked host                     IP with/without CIDR
475                  */
476                 if ((match(user->GetFullHost(), maskptr)) || (match(user->GetFullRealHost(), maskptr)) || (match(mask, maskptr, true)))
477                 {
478                         return true;
479                 }
480         }
481
482         return false;
483 }
484
485 /* Channel::PartUser
486  * remove a channel from a users record, and return the number of users left.
487  * Therefore, if this function returns 0 the caller should delete the Channel.
488  */
489 long Channel::PartUser(User *user, const char* reason)
490 {
491         bool silent = false;
492
493         if (!user)
494                 return this->GetUserCounter();
495
496         UCListIter i = user->chans.find(this);
497         if (i != user->chans.end())
498         {
499                 FOREACH_MOD(I_OnUserPart,OnUserPart(user, this, reason ? reason : "", silent));
500
501                 if (!silent)
502                         this->WriteChannel(user, "PART %s%s%s", this->name, reason ? " :" : "", reason ? reason : "");
503
504                 user->chans.erase(i);
505                 this->RemoveAllPrefixes(user);
506         }
507
508         if (!this->DelUser(user)) /* if there are no users left on the channel... */
509         {
510                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
511                 /* kill the record */
512                 if (iter != ServerInstance->chanlist->end())
513                 {
514                         int MOD_RESULT = 0;
515                         FOREACH_RESULT_I(ServerInstance,I_OnChannelPreDelete, OnChannelPreDelete(this));
516                         if (MOD_RESULT == 1)
517                                 return 1; // delete halted by module
518                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
519                         ServerInstance->chanlist->erase(iter);
520                 }
521                 return 0;
522         }
523
524         return this->GetUserCounter();
525 }
526
527 long Channel::ServerKickUser(User* user, const char* reason, bool triggerevents, const char* servername)
528 {
529         bool silent = false;
530
531         if (!user || !reason)
532                 return this->GetUserCounter();
533
534         if (IS_LOCAL(user))
535         {
536                 if (!this->HasUser(user))
537                 {
538                         /* Not on channel */
539                         return this->GetUserCounter();
540                 }
541         }
542
543         if (servername == NULL || *ServerInstance->Config->HideWhoisServer)
544                 servername = ServerInstance->Config->ServerName;
545
546         if (triggerevents)
547         {
548                 FOREACH_MOD(I_OnUserKick,OnUserKick(NULL, user, this, reason, silent));
549         }
550
551         UCListIter i = user->chans.find(this);
552         if (i != user->chans.end())
553         {
554                 if (!silent)
555                         this->WriteChannelWithServ(servername, "KICK %s %s :%s", this->name, user->nick, reason);
556
557                 user->chans.erase(i);
558                 this->RemoveAllPrefixes(user);
559         }
560
561         if (!this->DelUser(user))
562         {
563                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
564                 /* kill the record */
565                 if (iter != ServerInstance->chanlist->end())
566                 {
567                         int MOD_RESULT = 0;
568                         FOREACH_RESULT_I(ServerInstance,I_OnChannelPreDelete, OnChannelPreDelete(this));
569                         if (MOD_RESULT == 1)
570                                 return 1; // delete halted by module
571                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
572                         ServerInstance->chanlist->erase(iter);
573                 }
574                 return 0;
575         }
576
577         return this->GetUserCounter();
578 }
579
580 long Channel::KickUser(User *src, User *user, const char* reason)
581 {
582         bool silent = false;
583
584         if (!src || !user || !reason)
585                 return this->GetUserCounter();
586
587         if (IS_LOCAL(src))
588         {
589                 if (!this->HasUser(user))
590                 {
591                         src->WriteNumeric(441, "%s %s %s :They are not on that channel",src->nick, user->nick, this->name);
592                         return this->GetUserCounter();
593                 }
594                 if ((ServerInstance->ULine(user->server)) && (!ServerInstance->ULine(src->server)))
595                 {
596                         src->WriteNumeric(482, "%s %s :Only a u-line may kick a u-line from a channel.",src->nick, this->name);
597                         return this->GetUserCounter();
598                 }
599                 int MOD_RESULT = 0;
600
601                 if (!ServerInstance->ULine(src->server))
602                 {
603                         MOD_RESULT = 0;
604                         FOREACH_RESULT(I_OnUserPreKick,OnUserPreKick(src,user,this,reason));
605                         if (MOD_RESULT == 1)
606                                 return this->GetUserCounter();
607                 }
608                 /* Set to -1 by OnUserPreKick if explicit allow was set */
609                 if (MOD_RESULT != -1)
610                 {
611                         FOREACH_RESULT(I_OnAccessCheck,OnAccessCheck(src,user,this,AC_KICK));
612                         if ((MOD_RESULT == ACR_DENY) && (!ServerInstance->ULine(src->server)))
613                                 return this->GetUserCounter();
614         
615                         if ((MOD_RESULT == ACR_DEFAULT) || (!ServerInstance->ULine(src->server)))
616                         {
617                                 int them = this->GetStatus(src);
618                                 int us = this->GetStatus(user);
619                                 if ((them < STATUS_HOP) || (them < us))
620                                 {
621                                         src->WriteNumeric(482, "%s %s :You must be a channel %soperator",src->nick, this->name, them == STATUS_HOP ? "" : "half-");
622                                         return this->GetUserCounter();
623                                 }
624                         }
625                 }
626         }
627
628         FOREACH_MOD(I_OnUserKick,OnUserKick(src, user, this, reason, silent));
629
630         UCListIter i = user->chans.find(this);
631         if (i != user->chans.end())
632         {
633                 /* zap it from the channel list of the user */
634                 if (!silent)
635                         this->WriteChannel(src, "KICK %s %s :%s", this->name, user->nick, reason);
636
637                 user->chans.erase(i);
638                 this->RemoveAllPrefixes(user);
639         }
640
641         if (!this->DelUser(user))
642         /* if there are no users left on the channel */
643         {
644                 chan_hash::iterator iter = ServerInstance->chanlist->find(this->name);
645
646                 /* kill the record */
647                 if (iter != ServerInstance->chanlist->end())
648                 {
649                         int MOD_RESULT = 0;
650                         FOREACH_RESULT_I(ServerInstance,I_OnChannelPreDelete, OnChannelPreDelete(this));
651                         if (MOD_RESULT == 1)
652                                 return 1; // delete halted by module
653                         FOREACH_MOD(I_OnChannelDelete, OnChannelDelete(this));
654                         ServerInstance->chanlist->erase(iter);
655                 }
656                 return 0;
657         }
658
659         return this->GetUserCounter();
660 }
661
662 void Channel::WriteChannel(User* user, const char* text, ...)
663 {
664         char textbuffer[MAXBUF];
665         va_list argsPtr;
666
667         if (!user || !text)
668                 return;
669
670         va_start(argsPtr, text);
671         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
672         va_end(argsPtr);
673
674         this->WriteChannel(user, std::string(textbuffer));
675 }
676
677 void Channel::WriteChannel(User* user, const std::string &text)
678 {
679         CUList *ulist = this->GetUsers();
680         char tb[MAXBUF];
681
682         if (!user)
683                 return;
684
685         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
686         std::string out = tb;
687
688         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
689         {
690                 if (IS_LOCAL(i->first))
691                         i->first->Write(out);
692         }
693 }
694
695 void Channel::WriteChannelWithServ(const char* ServName, const char* text, ...)
696 {
697         char textbuffer[MAXBUF];
698         va_list argsPtr;
699
700         if (!text)
701                 return;
702
703         va_start(argsPtr, text);
704         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
705         va_end(argsPtr);
706
707         this->WriteChannelWithServ(ServName, std::string(textbuffer));
708 }
709
710 void Channel::WriteChannelWithServ(const char* ServName, const std::string &text)
711 {
712         CUList *ulist = this->GetUsers();
713         char tb[MAXBUF];
714
715         snprintf(tb,MAXBUF,":%s %s",ServName ? ServName : ServerInstance->Config->ServerName, text.c_str());
716         std::string out = tb;
717
718         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
719         {
720                 if (IS_LOCAL(i->first))
721                         i->first->Write(out);
722         }
723 }
724
725 /* write formatted text from a source user to all users on a channel except
726  * for the sender (for privmsg etc) */
727 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
728 {
729         char textbuffer[MAXBUF];
730         va_list argsPtr;
731
732         if (!text)
733                 return;
734
735         va_start(argsPtr, text);
736         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
737         va_end(argsPtr);
738
739         this->WriteAllExceptSender(user, serversource, status, std::string(textbuffer));
740 }
741
742 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
743 {
744         char textbuffer[MAXBUF];
745         va_list argsPtr;
746
747         if (!text)
748                 return;
749
750         va_start(argsPtr, text);
751         vsnprintf(textbuffer, MAXBUF, text, argsPtr);
752         va_end(argsPtr);
753
754         this->WriteAllExcept(user, serversource, status, except_list, std::string(textbuffer));
755 }
756
757 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
758 {
759         CUList *ulist = this->GetUsers();
760         char tb[MAXBUF];
761
762         snprintf(tb,MAXBUF,":%s %s",user->GetFullHost(),text.c_str());
763         std::string out = tb;
764
765         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
766         {
767                 if ((IS_LOCAL(i->first)) && (except_list.find(i->first) == except_list.end()))
768                 {
769                         /* User doesnt have the status we're after */
770                         if (status && !strchr(this->GetAllPrefixChars(i->first), status))
771                                 continue;
772
773                         if (serversource)
774                                 i->first->WriteServ(text);
775                         else
776                                 i->first->Write(out);
777                 }
778         }
779 }
780
781 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
782 {
783         CUList except_list;
784         except_list[user] = user->nick;
785         this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
786 }
787
788 /*
789  * return a count of the users on a specific channel accounting for
790  * invisible users who won't increase the count. e.g. for /LIST
791  */
792 int Channel::CountInvisible()
793 {
794         int count = 0;
795         CUList *ulist= this->GetUsers();
796         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
797         {
798                 if (!(i->first->IsModeSet('i')))
799                         count++;
800         }
801
802         return count;
803 }
804
805 char* Channel::ChanModes(bool showkey)
806 {
807         static char scratch[MAXBUF];
808         static char sparam[MAXBUF];
809         char* offset = scratch;
810         std::string extparam;
811
812         *scratch = '\0';
813         *sparam = '\0';
814
815         /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
816         for(int n = 0; n < 64; n++)
817         {
818                 if(this->modes[n])
819                 {
820                         *offset++ = n + 65;
821                         extparam.clear();
822                         switch (n)
823                         {
824                                 case CM_KEY:
825                                         extparam = (showkey ? this->key : "<key>");
826                                 break;
827                                 case CM_LIMIT:
828                                         extparam = ConvToStr(this->limit);
829                                 break;
830                                 case CM_NOEXTERNAL:
831                                 case CM_TOPICLOCK:
832                                 case CM_INVITEONLY:
833                                 case CM_MODERATED:
834                                 case CM_SECRET:
835                                 case CM_PRIVATE:
836                                         /* We know these have no parameters */
837                                 break;
838                                 default:
839                                         extparam = this->GetModeParameter(n + 65);
840                                 break;
841                         }
842                         if (!extparam.empty())
843                         {
844                                 charlcat(sparam,' ',MAXBUF);
845                                 strlcat(sparam,extparam.c_str(),MAXBUF);
846                         }
847                 }
848         }
849
850         /* Null terminate scratch */
851         *offset = '\0';
852         strlcat(scratch,sparam,MAXBUF);
853         return scratch;
854 }
855
856 /* compile a userlist of a channel into a string, each nick seperated by
857  * spaces and op, voice etc status shown as @ and +, and send it to 'user'
858  */
859 void Channel::UserList(User *user, CUList *ulist)
860 {
861         char list[MAXBUF];
862         size_t dlen, curlen;
863         int MOD_RESULT = 0;
864         bool call_modules = true;
865
866         if (!IS_LOCAL(user))
867                 return;
868
869         FOREACH_RESULT(I_OnUserList,OnUserList(user, this, ulist));
870         if (MOD_RESULT == 1)
871                 call_modules = false;
872
873         if (MOD_RESULT != -1)
874         {
875                 if ((this->IsModeSet('s')) && (!this->HasUser(user)))
876                 {
877                         user->WriteNumeric(401, "%s %s :No such nick/channel",user->nick, this->name);
878                         return;
879                 }
880         }
881
882         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick, this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=',  this->name);
883
884         int numusers = 0;
885         char* ptr = list + dlen;
886
887         if (!ulist)
888                 ulist = this->GetUsers();
889
890         /* Improvement by Brain - this doesnt change in value, so why was it inside
891          * the loop?
892          */
893         bool has_user = this->HasUser(user);
894
895         for (CUList::iterator i = ulist->begin(); i != ulist->end(); i++)
896         {
897                 if ((!has_user) && (i->first->IsModeSet('i')))
898                 {
899                         /*
900                          * user is +i, and source not on the channel, does not show
901                          * nick in NAMES list
902                          */
903                         continue;
904                 }
905
906                 if (i->first->Visibility && !i->first->Visibility->VisibleTo(user))
907                         continue;
908
909                 std::string prefixlist = this->GetPrefixChar(i->first);
910                 std::string nick = i->first->nick;
911
912                 if (call_modules)
913                 {
914                         FOREACH_MOD(I_OnNamesListItem, OnNamesListItem(user, i->first, this, prefixlist, nick));
915         
916                         /* Nick was nuked, a module wants us to skip it */
917                         if (nick.empty())
918                                 continue;
919                 }
920                 
921                 size_t ptrlen = 0;
922
923                 if (curlen > (480-NICKMAX))
924                 {
925                         /* list overflowed into multiple numerics */
926                         user->WriteServ(std::string(list));
927
928                         /* reset our lengths */
929                         dlen = curlen = snprintf(list,MAXBUF,"%s %c %s :", user->nick, this->IsModeSet('s') ? '@' : this->IsModeSet('p') ? '*' : '=', this->name);
930                         ptr = list + dlen;
931
932                         ptrlen = 0;
933                         numusers = 0;
934                 }
935
936                 ptrlen = snprintf(ptr, MAXBUF, "%s%s ", prefixlist.c_str(), nick.c_str());
937
938                 curlen += ptrlen;
939                 ptr += ptrlen;
940
941                 numusers++;
942         }
943
944         /* if whats left in the list isnt empty, send it */
945         if (numusers)
946         {
947                 user->WriteNumeric(353,std::string(list));
948         }
949
950         user->WriteNumeric(366, "%s %s :End of /NAMES list.", user->nick, this->name);
951 }
952
953 long Channel::GetMaxBans()
954 {
955         /* Return the cached value if there is one */
956         if (this->maxbans)
957                 return this->maxbans;
958
959         /* If there isnt one, we have to do some O(n) hax to find it the first time. (ick) */
960         for (std::map<std::string,int>::iterator n = ServerInstance->Config->maxbans.begin(); n != ServerInstance->Config->maxbans.end(); n++)
961         {
962                 if (match(this->name,n->first.c_str()))
963                 {
964                         this->maxbans = n->second;
965                         return n->second;
966                 }
967         }
968
969         /* Screw it, just return the default of 64 */
970         this->maxbans = 64;
971         return this->maxbans;
972 }
973
974 void Channel::ResetMaxBans()
975 {
976         this->maxbans = 0;
977 }
978
979 /* returns the status character for a given user on a channel, e.g. @ for op,
980  * % for halfop etc. If the user has several modes set, the highest mode
981  * the user has must be returned.
982  */
983 const char* Channel::GetPrefixChar(User *user)
984 {
985         static char pf[2] = {0, 0};
986         
987         prefixlist::iterator n = prefixes.find(user);
988         if (n != prefixes.end())
989         {
990                 if (n->second.size())
991                 {
992                         /* If the user has any prefixes, their highest prefix
993                          * will always be at the head of the list, as the list is
994                          * sorted in rank order highest first (see SetPrefix()
995                          * for reasons why)
996                          */
997                         *pf = n->second.begin()->first;
998                         return pf;
999                 }
1000         }
1001
1002         *pf = 0;
1003         return pf;
1004 }
1005
1006
1007 const char* Channel::GetAllPrefixChars(User* user)
1008 {
1009         static char prefix[MAXBUF];
1010         int ctr = 0;
1011         *prefix = 0;
1012
1013         prefixlist::iterator n = prefixes.find(user);
1014         if (n != prefixes.end())
1015         {
1016                 for (std::vector<prefixtype>::iterator x = n->second.begin(); x != n->second.end(); x++)
1017                 {
1018                         prefix[ctr++] = x->first;
1019                 }
1020         }
1021
1022         prefix[ctr] = 0;
1023
1024         return prefix;
1025 }
1026
1027 unsigned int Channel::GetPrefixValue(User* user)
1028 {
1029         prefixlist::iterator n = prefixes.find(user);
1030         if (n != prefixes.end())
1031         {
1032                 if (n->second.size())
1033                         return n->second.begin()->second;
1034         }
1035         return 0;
1036 }
1037
1038 int Channel::GetStatusFlags(User *user)
1039 {
1040         UCListIter i = user->chans.find(this);
1041         if (i != user->chans.end())
1042         {
1043                 return i->second;
1044         }
1045         return 0;
1046 }
1047
1048 int Channel::GetStatus(User *user)
1049 {
1050         if (ServerInstance->ULine(user->server))
1051                 return STATUS_OP;
1052
1053         UCListIter i = user->chans.find(this);
1054         if (i != user->chans.end())
1055         {
1056                 if ((i->second & UCMODE_OP) > 0)
1057                 {
1058                         return STATUS_OP;
1059                 }
1060                 if ((i->second & UCMODE_HOP) > 0)
1061                 {
1062                         return STATUS_HOP;
1063                 }
1064                 if ((i->second & UCMODE_VOICE) > 0)
1065                 {
1066                         return STATUS_VOICE;
1067                 }
1068                 return STATUS_NORMAL;
1069         }
1070         return STATUS_NORMAL;
1071 }
1072
1073 void Channel::SetPrefix(User* user, char prefix, unsigned int prefix_value, bool adding)
1074 {
1075         prefixlist::iterator n = prefixes.find(user);
1076         prefixtype pfx = std::make_pair(prefix,prefix_value);
1077         if (adding)
1078         {
1079                 if (n != prefixes.end())
1080                 {
1081                         if (std::find(n->second.begin(), n->second.end(), pfx) == n->second.end())
1082                         {
1083                                 n->second.push_back(pfx);
1084                                 /* We must keep prefixes in rank order, largest first.
1085                                  * This is for two reasons, firstly because x-chat *ass-u-me's* this
1086                                  * state, and secondly it turns out to be a benefit to us later.
1087                                  * See above in GetPrefix().
1088                                  */
1089                                 std::sort(n->second.begin(), n->second.end(), ModeParser::PrefixComparison);
1090                         }
1091                 }
1092                 else
1093                 {
1094                         pfxcontainer one;
1095                         one.push_back(pfx);
1096                         prefixes.insert(std::make_pair<User*,pfxcontainer>(user, one));
1097                 }
1098         }
1099         else
1100         {
1101                 if (n != prefixes.end())
1102                 {
1103                         pfxcontainer::iterator x = std::find(n->second.begin(), n->second.end(), pfx);
1104                         if (x != n->second.end())
1105                                 n->second.erase(x);
1106                 }
1107         }
1108 }
1109
1110 void Channel::RemoveAllPrefixes(User* user)
1111 {
1112         prefixlist::iterator n = prefixes.find(user);
1113         if (n != prefixes.end())
1114         {
1115                 prefixes.erase(n);
1116         }
1117 }
1118