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