2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2006, 2008 Oliver Lupton <oliverlupton@gmail.com>
7 * Copyright (C) 2008 Pippijn van Steenhoven <pip88nl@gmail.com>
8 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
9 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
10 * Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31 ChanModeReference ban(NULL, "ban");
32 ChanModeReference inviteonlymode(NULL, "inviteonly");
33 ChanModeReference keymode(NULL, "key");
34 ChanModeReference limitmode(NULL, "limit");
37 Channel::Channel(const std::string &cname, time_t ts)
38 : name(cname), age(ts), topicset(0)
40 if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
41 throw CoreException("Cannot create duplicate channel " + cname);
44 void Channel::SetMode(ModeHandler* mh, bool on)
46 modes[mh->GetId()] = on;
49 void Channel::SetTopic(User* u, const std::string& ntopic)
51 this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
52 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
53 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
54 this->topicset = ServerInstance->Time();
56 FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
59 Membership* Channel::AddUser(User* user)
61 std::pair<MemberMap::iterator, bool> ret = userlist.insert(std::make_pair(user, insp::aligned_storage<Membership>()));
65 Membership* memb = new(ret.first->second) Membership(user, this);
69 void Channel::DelUser(User* user)
71 MemberMap::iterator it = userlist.find(user);
72 if (it != userlist.end())
76 void Channel::CheckDestroy()
78 if (!userlist.empty())
82 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
83 if (res == MOD_RES_DENY)
86 // If the channel isn't in chanlist then it is already in the cull list, don't add it again
87 chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
88 if ((iter == ServerInstance->chanlist.end()) || (iter->second != this))
91 FOREACH_MOD(OnChannelDelete, (this));
92 ServerInstance->chanlist.erase(iter);
93 ServerInstance->GlobalCulls.AddItem(this);
96 void Channel::DelUser(const MemberMap::iterator& membiter)
98 Membership* memb = membiter->second;
101 userlist.erase(membiter);
103 // If this channel became empty then it should be removed
107 Membership* Channel::GetUser(User* user)
109 MemberMap::iterator i = userlist.find(user);
110 if (i == userlist.end())
115 void Channel::SetDefaultModes()
117 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
118 ServerInstance->Config->DefaultModes.c_str());
119 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
121 std::string parameter;
123 list.GetToken(modeseq);
125 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
127 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
130 if (mode->IsPrefixMode())
133 if (mode->GetNumParams(true))
135 list.GetToken(parameter);
136 // If the parameter begins with a ':' then it's invalid
137 if (parameter.c_str()[0] == ':')
143 if ((mode->GetNumParams(true)) && (parameter.empty()))
146 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
152 * add a channel to a user, creating the record for it if needed and linking
153 * it to the user record
155 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
157 if (user->registered != REG_ALL)
159 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
164 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
165 * We restrict local users to <connect:maxchans> channels.
166 * We restrict local operators to <oper:maxchans> channels.
167 * This is a lot more logical than how it was formerly. -- w00t
171 unsigned int maxchans = user->GetClass()->maxchans;
174 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
175 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
177 opermaxchans = ServerInstance->Config->OperMaxChans;
179 maxchans = opermaxchans;
181 if (user->chans.size() >= maxchans)
183 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
188 // Crop channel name if it's too long
189 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
190 cname.resize(ServerInstance->Config->Limits.ChanMax);
192 Channel* chan = ServerInstance->FindChan(cname);
193 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
194 std::string privs; // Prefix mode(letter)s to give to the joining user
198 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
200 if (override == false)
202 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
203 ModResult MOD_RESULT;
204 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
205 if (MOD_RESULT == MOD_RES_DENY)
206 return NULL; // A module wasn't happy with the join, abort
209 chan = new Channel(cname, ServerInstance->Time());
210 // Set the default modes on the channel (<options:defaultmodes>)
211 chan->SetDefaultModes();
215 /* Already on the channel */
216 if (chan->HasUser(user))
219 if (override == false)
221 ModResult MOD_RESULT;
222 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
224 // A module explicitly denied the join and (hopefully) generated a message
225 // describing the situation, so we may stop here without sending anything
226 if (MOD_RESULT == MOD_RES_DENY)
229 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
230 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
232 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
233 // then this entire section is skipped
234 if (MOD_RESULT == MOD_RES_PASSTHRU)
236 std::string ckey = chan->GetModeParameter(keymode);
239 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
240 if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, key)))
242 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
243 user->WriteNumeric(ERR_BADCHANNELKEY, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
248 if (chan->IsModeSet(inviteonlymode))
250 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
251 if (MOD_RESULT != MOD_RES_ALLOW)
253 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
258 std::string limit = chan->GetModeParameter(limitmode);
261 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
262 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()))))
264 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
269 if (chan->IsBanned(user))
271 user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
278 // We figured that this join is allowed and also created the
279 // channel if it didn't exist before, now do the actual join
280 chan->ForceJoin(user, &privs, false, created_by_local);
284 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
288 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
292 Membership* memb = this->AddUser(user);
294 return NULL; // Already on the channel
296 user->chans.push_front(memb);
300 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
301 // remote user and his own server set the modes), then set them internally now
302 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
304 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
307 std::string nick = user->nick;
308 // Set the mode on the user
309 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
314 // Tell modules about this join, they have the chance now to populate except_list with users we won't send the JOIN (and possibly MODE) to
316 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
318 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
320 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
321 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
323 std::string ms = memb->modes;
324 for(unsigned int i=0; i < memb->modes.length(); i++)
325 ms.append(" ").append(user->nick);
327 except_list.insert(user);
328 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
331 FOREACH_MOD(OnPostJoin, (memb));
335 bool Channel::IsBanned(User* user)
338 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
340 if (result != MOD_RES_PASSTHRU)
341 return (result == MOD_RES_DENY);
343 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
344 const ListModeBase::ModeList* bans = banlm->GetList(this);
347 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
349 if (CheckBan(user, it->mask))
356 bool Channel::CheckBan(User* user, const std::string& mask)
359 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
360 if (result != MOD_RES_PASSTHRU)
361 return (result == MOD_RES_DENY);
363 // extbans were handled above, if this is one it obviously didn't match
364 if ((mask.length() <= 2) || (mask[1] == ':'))
367 std::string::size_type at = mask.find('@');
368 if (at == std::string::npos)
371 const std::string nickIdent = user->nick + "!" + user->ident;
372 std::string prefix(mask, 0, at);
373 if (InspIRCd::Match(nickIdent, prefix, NULL))
375 std::string suffix(mask, at + 1);
376 if (InspIRCd::Match(user->host, suffix, NULL) ||
377 InspIRCd::Match(user->dhost, suffix, NULL) ||
378 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
384 ModResult Channel::GetExtBanStatus(User *user, char type)
387 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
388 if (rv != MOD_RES_PASSTHRU)
391 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
392 const ListModeBase::ModeList* bans = banlm->GetList(this);
395 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
397 if (CheckBan(user, it->mask))
401 return MOD_RES_PASSTHRU;
405 * Remove a channel from a users record, remove the reference to the Membership object
406 * from the channel and destroy it.
408 void Channel::PartUser(User *user, std::string &reason)
410 MemberMap::iterator membiter = userlist.find(user);
412 if (membiter != userlist.end())
414 Membership* memb = membiter->second;
416 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
418 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
420 // Remove this channel from the user's chanlist
421 user->chans.erase(memb);
422 // Remove the Membership from this channel's userlist and destroy it
423 this->DelUser(membiter);
427 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
429 Membership* memb = victimiter->second;
431 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
433 User* victim = memb->user;
434 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
436 victim->chans.erase(memb);
437 this->DelUser(victimiter);
440 void Channel::WriteChannel(User* user, const char* text, ...)
442 std::string textbuffer;
443 VAFORMAT(textbuffer, text, text);
444 this->WriteChannel(user, textbuffer);
447 void Channel::WriteChannel(User* user, const std::string &text)
449 const std::string message = ":" + user->GetFullHost() + " " + text;
451 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
453 if (IS_LOCAL(i->first))
454 i->first->Write(message);
458 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
460 std::string textbuffer;
461 VAFORMAT(textbuffer, text, text);
462 this->WriteChannelWithServ(ServName, textbuffer);
465 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
467 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
469 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
471 if (IS_LOCAL(i->first))
472 i->first->Write(message);
476 /* write formatted text from a source user to all users on a channel except
477 * for the sender (for privmsg etc) */
478 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
480 std::string textbuffer;
481 VAFORMAT(textbuffer, text, text);
482 this->WriteAllExceptSender(user, serversource, status, textbuffer);
485 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
487 std::string textbuffer;
488 VAFORMAT(textbuffer, text, text);
489 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
490 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
493 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
495 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
496 this->RawWriteAllExcept(user, serversource, status, except_list, message);
499 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
501 unsigned int minrank = 0;
504 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
506 minrank = mh->GetPrefixRank();
508 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
510 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
512 /* User doesn't have the status we're after */
513 if (minrank && i->second->getRank() < minrank)
516 i->first->Write(out);
521 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
524 except_list.insert(user);
525 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
528 const char* Channel::ChanModes(bool showkey)
530 static std::string scratch;
535 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
536 for(int n = 0; n < 64; n++)
538 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
539 if (mh && IsModeSet(mh))
541 scratch.push_back(n + 65);
543 ParamModeBase* pm = mh->IsParameterMode();
547 if (n == 'k' - 65 && !showkey)
554 pm->GetParameter(this, sparam);
560 return scratch.c_str();
563 /* returns the status character for a given user on a channel, e.g. @ for op,
564 * % for halfop etc. If the user has several modes set, the highest mode
565 * the user has must be returned.
567 char Membership::GetPrefixChar() const
570 unsigned int bestrank = 0;
572 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
574 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
575 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
577 bestrank = mh->GetPrefixRank();
578 pf = mh->GetPrefix();
584 unsigned int Membership::getRank()
586 char mchar = modes.c_str()[0];
590 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
592 rv = mh->GetPrefixRank();
597 const char* Membership::GetAllPrefixChars() const
599 static char prefix[64];
602 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
604 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
605 if (mh && mh->GetPrefix())
606 prefix[ctr++] = mh->GetPrefix();
613 unsigned int Channel::GetPrefixValue(User* user)
615 MemberMap::iterator m = userlist.find(user);
616 if (m == userlist.end())
618 return m->second->getRank();
621 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
623 char prefix = delta_mh->GetModeChar();
624 for (unsigned int i = 0; i < modes.length(); i++)
626 char mchar = modes[i];
627 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
628 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
630 modes = modes.substr(0,i) +
631 (adding ? std::string(1, prefix) : "") +
632 modes.substr(mchar == prefix ? i+1 : i);
633 return adding != (mchar == prefix);
637 modes.push_back(prefix);