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);
94 ServerInstance->GlobalCulls.AddItem(this);
97 void Channel::DelUser(const MemberMap::iterator& membiter)
99 Membership* memb = membiter->second;
102 userlist.erase(membiter);
104 // If this channel became empty then it should be removed
108 Membership* Channel::GetUser(User* user)
110 MemberMap::iterator i = userlist.find(user);
111 if (i == userlist.end())
116 void Channel::SetDefaultModes()
118 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
119 ServerInstance->Config->DefaultModes.c_str());
120 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
122 std::string parameter;
124 list.GetToken(modeseq);
126 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
128 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
131 if (mode->IsPrefixMode())
134 if (mode->GetNumParams(true))
136 list.GetToken(parameter);
137 // If the parameter begins with a ':' then it's invalid
138 if (parameter.c_str()[0] == ':')
144 if ((mode->GetNumParams(true)) && (parameter.empty()))
147 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
153 * add a channel to a user, creating the record for it if needed and linking
154 * it to the user record
156 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
158 if (user->registered != REG_ALL)
160 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
165 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
166 * We restrict local users to <connect:maxchans> channels.
167 * We restrict local operators to <oper:maxchans> channels.
168 * This is a lot more logical than how it was formerly. -- w00t
172 unsigned int maxchans = user->GetClass()->maxchans;
175 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
176 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
178 opermaxchans = ServerInstance->Config->OperMaxChans;
180 maxchans = opermaxchans;
182 if (user->chans.size() >= maxchans)
184 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
189 // Crop channel name if it's too long
190 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
191 cname.resize(ServerInstance->Config->Limits.ChanMax);
193 Channel* chan = ServerInstance->FindChan(cname);
194 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
195 std::string privs; // Prefix mode(letter)s to give to the joining user
199 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
201 if (override == false)
203 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
204 ModResult MOD_RESULT;
205 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
206 if (MOD_RESULT == MOD_RES_DENY)
207 return NULL; // A module wasn't happy with the join, abort
210 chan = new Channel(cname, ServerInstance->Time());
211 // Set the default modes on the channel (<options:defaultmodes>)
212 chan->SetDefaultModes();
216 /* Already on the channel */
217 if (chan->HasUser(user))
220 if (override == false)
222 ModResult MOD_RESULT;
223 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
225 // A module explicitly denied the join and (hopefully) generated a message
226 // describing the situation, so we may stop here without sending anything
227 if (MOD_RESULT == MOD_RES_DENY)
230 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
231 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
233 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
234 // then this entire section is skipped
235 if (MOD_RESULT == MOD_RES_PASSTHRU)
237 std::string ckey = chan->GetModeParameter(keymode);
240 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
241 if (!MOD_RESULT.check(InspIRCd::TimingSafeCompare(ckey, key)))
243 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
244 user->WriteNumeric(ERR_BADCHANNELKEY, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
249 if (chan->IsModeSet(inviteonlymode))
251 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
252 if (MOD_RESULT != MOD_RES_ALLOW)
254 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
259 std::string limit = chan->GetModeParameter(limitmode);
262 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
263 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()))))
265 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
270 if (chan->IsBanned(user))
272 user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
279 // We figured that this join is allowed and also created the
280 // channel if it didn't exist before, now do the actual join
281 chan->ForceJoin(user, &privs, false, created_by_local);
285 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
289 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
293 Membership* memb = this->AddUser(user);
295 return NULL; // Already on the channel
297 user->chans.push_front(memb);
301 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
302 // remote user and his own server set the modes), then set them internally now
303 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
305 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
308 std::string nick = user->nick;
309 // Set the mode on the user
310 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
315 // 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
317 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
319 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
321 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
322 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
324 std::string ms = memb->modes;
325 for(unsigned int i=0; i < memb->modes.length(); i++)
326 ms.append(" ").append(user->nick);
328 except_list.insert(user);
329 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
332 FOREACH_MOD(OnPostJoin, (memb));
336 bool Channel::IsBanned(User* user)
339 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
341 if (result != MOD_RES_PASSTHRU)
342 return (result == MOD_RES_DENY);
344 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
345 const ListModeBase::ModeList* bans = banlm->GetList(this);
348 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
350 if (CheckBan(user, it->mask))
357 bool Channel::CheckBan(User* user, const std::string& mask)
360 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
361 if (result != MOD_RES_PASSTHRU)
362 return (result == MOD_RES_DENY);
364 // extbans were handled above, if this is one it obviously didn't match
365 if ((mask.length() <= 2) || (mask[1] == ':'))
368 std::string::size_type at = mask.find('@');
369 if (at == std::string::npos)
372 const std::string nickIdent = user->nick + "!" + user->ident;
373 std::string prefix(mask, 0, at);
374 if (InspIRCd::Match(nickIdent, prefix, NULL))
376 std::string suffix(mask, at + 1);
377 if (InspIRCd::Match(user->host, suffix, NULL) ||
378 InspIRCd::Match(user->dhost, suffix, NULL) ||
379 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
385 ModResult Channel::GetExtBanStatus(User *user, char type)
388 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
389 if (rv != MOD_RES_PASSTHRU)
392 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
393 const ListModeBase::ModeList* bans = banlm->GetList(this);
396 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
398 if (CheckBan(user, it->mask))
402 return MOD_RES_PASSTHRU;
406 * Remove a channel from a users record, remove the reference to the Membership object
407 * from the channel and destroy it.
409 void Channel::PartUser(User *user, std::string &reason)
411 MemberMap::iterator membiter = userlist.find(user);
413 if (membiter != userlist.end())
415 Membership* memb = membiter->second;
417 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
419 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
421 // Remove this channel from the user's chanlist
422 user->chans.erase(memb);
423 // Remove the Membership from this channel's userlist and destroy it
424 this->DelUser(membiter);
428 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
430 Membership* memb = victimiter->second;
432 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
434 User* victim = memb->user;
435 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
437 victim->chans.erase(memb);
438 this->DelUser(victimiter);
441 void Channel::WriteChannel(User* user, const char* text, ...)
443 std::string textbuffer;
444 VAFORMAT(textbuffer, text, text);
445 this->WriteChannel(user, textbuffer);
448 void Channel::WriteChannel(User* user, const std::string &text)
450 const std::string message = ":" + user->GetFullHost() + " " + text;
452 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
454 if (IS_LOCAL(i->first))
455 i->first->Write(message);
459 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
461 std::string textbuffer;
462 VAFORMAT(textbuffer, text, text);
463 this->WriteChannelWithServ(ServName, textbuffer);
466 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
468 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
470 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
472 if (IS_LOCAL(i->first))
473 i->first->Write(message);
477 /* write formatted text from a source user to all users on a channel except
478 * for the sender (for privmsg etc) */
479 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
481 std::string textbuffer;
482 VAFORMAT(textbuffer, text, text);
483 this->WriteAllExceptSender(user, serversource, status, textbuffer);
486 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
488 std::string textbuffer;
489 VAFORMAT(textbuffer, text, text);
490 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
491 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
494 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
496 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
497 this->RawWriteAllExcept(user, serversource, status, except_list, message);
500 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
502 unsigned int minrank = 0;
505 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
507 minrank = mh->GetPrefixRank();
509 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
511 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
513 /* User doesn't have the status we're after */
514 if (minrank && i->second->getRank() < minrank)
517 i->first->Write(out);
522 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
525 except_list.insert(user);
526 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
529 const char* Channel::ChanModes(bool showkey)
531 static std::string scratch;
536 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
537 for(int n = 0; n < 64; n++)
539 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
540 if (mh && IsModeSet(mh))
542 scratch.push_back(n + 65);
544 ParamModeBase* pm = mh->IsParameterMode();
548 if (n == 'k' - 65 && !showkey)
555 pm->GetParameter(this, sparam);
561 return scratch.c_str();
564 /* returns the status character for a given user on a channel, e.g. @ for op,
565 * % for halfop etc. If the user has several modes set, the highest mode
566 * the user has must be returned.
568 char Membership::GetPrefixChar() const
571 unsigned int bestrank = 0;
573 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
575 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
576 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
578 bestrank = mh->GetPrefixRank();
579 pf = mh->GetPrefix();
585 unsigned int Membership::getRank()
587 char mchar = modes.c_str()[0];
591 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
593 rv = mh->GetPrefixRank();
598 const char* Membership::GetAllPrefixChars() const
600 static char prefix[64];
603 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
605 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
606 if (mh && mh->GetPrefix())
607 prefix[ctr++] = mh->GetPrefix();
614 unsigned int Channel::GetPrefixValue(User* user)
616 MemberMap::iterator m = userlist.find(user);
617 if (m == userlist.end())
619 return m->second->getRank();
622 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
624 char prefix = delta_mh->GetModeChar();
625 for (unsigned int i = 0; i < modes.length(); i++)
627 char mchar = modes[i];
628 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
629 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
631 modes = modes.substr(0,i) +
632 (adding ? std::string(1, prefix) : "") +
633 modes.substr(mchar == prefix ? i+1 : i);
634 return adding != (mchar == prefix);
638 modes.push_back(prefix);
642 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
644 if ((timeout != 0) && (ServerInstance->Time() >= timeout))
645 // Expired, don't bother
648 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
650 Invitation* inv = Invitation::Find(c, u, false);
653 if ((inv->expiry == 0) || (inv->expiry > timeout))
655 inv->expiry = timeout;
656 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
660 inv = new Invitation(c, u, timeout);
661 c->invites.push_front(inv);
662 u->invites.push_front(inv);
663 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
667 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
669 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find chan=%s user=%s check_expired=%d", c ? c->name.c_str() : "NULL", u ? u->uuid.c_str() : "NULL", check_expired);
671 Invitation* result = NULL;
672 for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
674 Invitation* inv = *i;
677 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
679 /* Expired invite, remove it. */
680 std::string expiration = InspIRCd::TimeString(inv->expiry);
681 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
686 /* Is it what we're searching for? */
695 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
699 Invitation::~Invitation()
701 // Remove this entry from both lists
702 chan->invites.erase(this);
703 user->invites.erase(this);
704 ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);