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