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, time_t topicts, const std::string* setter)
51 // Send a TOPIC message to the channel only if the new topic text differs
52 if (this->topic != ntopic)
55 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
58 // Always update setter and set time
60 setter = ServerInstance->Config->FullHostInTopic ? &u->GetFullHost() : &u->nick;
61 this->setby.assign(*setter, 0, ServerInstance->Config->Limits.GetMaxMask());
62 this->topicset = topicts;
64 FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
67 Membership* Channel::AddUser(User* user)
69 std::pair<MemberMap::iterator, bool> ret = userlist.insert(std::make_pair(user, insp::aligned_storage<Membership>()));
73 Membership* memb = new(ret.first->second) Membership(user, this);
77 void Channel::DelUser(User* user)
79 MemberMap::iterator it = userlist.find(user);
80 if (it != userlist.end())
84 void Channel::CheckDestroy()
86 if (!userlist.empty())
90 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
91 if (res == MOD_RES_DENY)
94 // If the channel isn't in chanlist then it is already in the cull list, don't add it again
95 chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
96 if ((iter == ServerInstance->chanlist.end()) || (iter->second != this))
99 FOREACH_MOD(OnChannelDelete, (this));
100 ServerInstance->chanlist.erase(iter);
101 ServerInstance->GlobalCulls.AddItem(this);
104 void Channel::DelUser(const MemberMap::iterator& membiter)
106 Membership* memb = membiter->second;
109 userlist.erase(membiter);
111 // If this channel became empty then it should be removed
115 Membership* Channel::GetUser(User* user)
117 MemberMap::iterator i = userlist.find(user);
118 if (i == userlist.end())
123 void Channel::SetDefaultModes()
125 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
126 ServerInstance->Config->DefaultModes.c_str());
127 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
129 std::string parameter;
131 list.GetToken(modeseq);
133 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
135 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
138 if (mode->IsPrefixMode())
141 if (mode->NeedsParam(true))
143 list.GetToken(parameter);
144 // If the parameter begins with a ':' then it's invalid
145 if (parameter.c_str()[0] == ':')
151 if ((mode->NeedsParam(true)) && (parameter.empty()))
154 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
160 * add a channel to a user, creating the record for it if needed and linking
161 * it to the user record
163 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
165 if (user->registered != REG_ALL)
167 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
172 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
173 * We restrict local users to <connect:maxchans> channels.
174 * We restrict local operators to <oper:maxchans> channels.
175 * This is a lot more logical than how it was formerly. -- w00t
179 unsigned int maxchans = user->GetClass()->maxchans;
182 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
183 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
184 if (!opermaxchans && user->HasPrivPermission("channels/high-join-limit"))
185 opermaxchans = ServerInstance->Config->OperMaxChans;
187 maxchans = opermaxchans;
189 if (user->chans.size() >= maxchans)
191 user->WriteNumeric(ERR_TOOMANYCHANNELS, cname, "You are on too many channels");
196 // Crop channel name if it's too long
197 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
198 cname.resize(ServerInstance->Config->Limits.ChanMax);
200 Channel* chan = ServerInstance->FindChan(cname);
201 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
202 std::string privs; // Prefix mode(letter)s to give to the joining user
206 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
208 if (override == false)
210 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
211 ModResult MOD_RESULT;
212 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
213 if (MOD_RESULT == MOD_RES_DENY)
214 return NULL; // A module wasn't happy with the join, abort
217 chan = new Channel(cname, ServerInstance->Time());
218 // Set the default modes on the channel (<options:defaultmodes>)
219 chan->SetDefaultModes();
223 /* Already on the channel */
224 if (chan->HasUser(user))
227 if (override == false)
229 ModResult MOD_RESULT;
230 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
232 // A module explicitly denied the join and (hopefully) generated a message
233 // describing the situation, so we may stop here without sending anything
234 if (MOD_RESULT == MOD_RES_DENY)
237 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
238 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
240 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
241 // then this entire section is skipped
242 if (MOD_RESULT == MOD_RES_PASSTHRU)
244 std::string ckey = chan->GetModeParameter(keymode);
247 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
248 if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, key)))
250 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
251 user->WriteNumeric(ERR_BADCHANNELKEY, chan->name, "Cannot join channel (Incorrect channel key)");
256 if (chan->IsModeSet(inviteonlymode))
258 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
259 if (MOD_RESULT != MOD_RES_ALLOW)
261 user->WriteNumeric(ERR_INVITEONLYCHAN, chan->name, "Cannot join channel (Invite only)");
266 std::string limit = chan->GetModeParameter(limitmode);
269 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
270 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()))))
272 user->WriteNumeric(ERR_CHANNELISFULL, chan->name, "Cannot join channel (Channel is full)");
277 if (chan->IsBanned(user))
279 user->WriteNumeric(ERR_BANNEDFROMCHAN, chan->name, "Cannot join channel (You're banned)");
286 // We figured that this join is allowed and also created the
287 // channel if it didn't exist before, now do the actual join
288 chan->ForceJoin(user, &privs, false, created_by_local);
292 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
296 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
300 Membership* memb = this->AddUser(user);
302 return NULL; // Already on the channel
304 user->chans.push_front(memb);
308 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
309 // remote user and his own server set the modes), then set them internally now
310 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
312 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
315 std::string nick = user->nick;
316 // Set the mode on the user
317 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
322 // 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
324 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
326 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
328 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
329 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
331 std::string ms = memb->modes;
332 for(unsigned int i=0; i < memb->modes.length(); i++)
333 ms.append(" ").append(user->nick);
335 except_list.insert(user);
336 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
339 FOREACH_MOD(OnPostJoin, (memb));
343 bool Channel::IsBanned(User* user)
346 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
348 if (result != MOD_RES_PASSTHRU)
349 return (result == MOD_RES_DENY);
351 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
352 const ListModeBase::ModeList* bans = banlm->GetList(this);
355 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
357 if (CheckBan(user, it->mask))
364 bool Channel::CheckBan(User* user, const std::string& mask)
367 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
368 if (result != MOD_RES_PASSTHRU)
369 return (result == MOD_RES_DENY);
371 // extbans were handled above, if this is one it obviously didn't match
372 if ((mask.length() <= 2) || (mask[1] == ':'))
375 std::string::size_type at = mask.find('@');
376 if (at == std::string::npos)
379 const std::string nickIdent = user->nick + "!" + user->ident;
380 std::string prefix(mask, 0, at);
381 if (InspIRCd::Match(nickIdent, prefix, NULL))
383 std::string suffix(mask, at + 1);
384 if (InspIRCd::Match(user->host, suffix, NULL) ||
385 InspIRCd::Match(user->dhost, suffix, NULL) ||
386 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
392 ModResult Channel::GetExtBanStatus(User *user, char type)
395 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
396 if (rv != MOD_RES_PASSTHRU)
399 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
400 const ListModeBase::ModeList* bans = banlm->GetList(this);
403 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
405 if (CheckBan(user, it->mask))
409 return MOD_RES_PASSTHRU;
413 * Remove a channel from a users record, remove the reference to the Membership object
414 * from the channel and destroy it.
416 bool Channel::PartUser(User* user, std::string& reason)
418 MemberMap::iterator membiter = userlist.find(user);
420 if (membiter == userlist.end())
423 Membership* memb = membiter->second;
425 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
427 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
429 // Remove this channel from the user's chanlist
430 user->chans.erase(memb);
431 // Remove the Membership from this channel's userlist and destroy it
432 this->DelUser(membiter);
437 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
439 Membership* memb = victimiter->second;
441 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
443 User* victim = memb->user;
444 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
446 victim->chans.erase(memb);
447 this->DelUser(victimiter);
450 void Channel::WriteChannel(User* user, const char* text, ...)
452 std::string textbuffer;
453 VAFORMAT(textbuffer, text, text);
454 this->WriteChannel(user, textbuffer);
457 void Channel::WriteChannel(User* user, const std::string &text)
459 const std::string message = ":" + user->GetFullHost() + " " + text;
461 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
463 if (IS_LOCAL(i->first))
464 i->first->Write(message);
468 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
470 std::string textbuffer;
471 VAFORMAT(textbuffer, text, text);
472 this->WriteChannelWithServ(ServName, textbuffer);
475 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
477 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
479 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
481 if (IS_LOCAL(i->first))
482 i->first->Write(message);
486 /* write formatted text from a source user to all users on a channel except
487 * for the sender (for privmsg etc) */
488 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
490 std::string textbuffer;
491 VAFORMAT(textbuffer, text, text);
492 this->WriteAllExceptSender(user, serversource, status, textbuffer);
495 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
497 std::string textbuffer;
498 VAFORMAT(textbuffer, text, text);
499 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
500 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
503 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
505 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
506 this->RawWriteAllExcept(user, serversource, status, except_list, message);
509 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
511 unsigned int minrank = 0;
514 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
516 minrank = mh->GetPrefixRank();
518 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
520 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
522 /* User doesn't have the status we're after */
523 if (minrank && i->second->getRank() < minrank)
526 i->first->Write(out);
531 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
534 except_list.insert(user);
535 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
538 const char* Channel::ChanModes(bool showkey)
540 static std::string scratch;
545 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
546 for(int n = 0; n < 64; n++)
548 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
549 if (mh && IsModeSet(mh))
551 scratch.push_back(n + 65);
553 ParamModeBase* pm = mh->IsParameterMode();
557 if (n == 'k' - 65 && !showkey)
564 pm->GetParameter(this, sparam);
570 return scratch.c_str();
573 void Channel::WriteNotice(const std::string& text)
575 std::string rawmsg = "NOTICE ";
576 rawmsg.append(this->name).append(" :").append(text);
577 WriteChannelWithServ(ServerInstance->Config->ServerName, rawmsg);
580 /* returns the status character for a given user on a channel, e.g. @ for op,
581 * % for halfop etc. If the user has several modes set, the highest mode
582 * the user has must be returned.
584 char Membership::GetPrefixChar() const
587 unsigned int bestrank = 0;
589 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
591 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
592 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
594 bestrank = mh->GetPrefixRank();
595 pf = mh->GetPrefix();
601 unsigned int Membership::getRank()
603 char mchar = modes.c_str()[0];
607 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
609 rv = mh->GetPrefixRank();
614 std::string Membership::GetAllPrefixChars() const
617 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
619 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
620 if (mh && mh->GetPrefix())
621 ret.push_back(mh->GetPrefix());
627 unsigned int Channel::GetPrefixValue(User* user)
629 MemberMap::iterator m = userlist.find(user);
630 if (m == userlist.end())
632 return m->second->getRank();
635 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
637 char prefix = delta_mh->GetModeChar();
638 for (unsigned int i = 0; i < modes.length(); i++)
640 char mchar = modes[i];
641 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
642 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
644 modes = modes.substr(0,i) +
645 (adding ? std::string(1, prefix) : "") +
646 modes.substr(mchar == prefix ? i+1 : i);
647 return adding != (mchar == prefix);
651 modes.push_back(prefix);