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