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);
238 bool invited = user->IsInvited(chan);
239 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
243 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
244 if (!MOD_RESULT.check((ckey == key) || can_bypass))
246 // If no key provided, or key is not the right one, and can't bypass +k (not invited or option not enabled)
247 user->WriteNumeric(ERR_BADCHANNELKEY, "%s :Cannot join channel (Incorrect channel key)", chan->name.c_str());
252 if (chan->IsModeSet(inviteonlymode))
254 FIRST_MOD_RESULT(OnCheckInvite, MOD_RESULT, (user, chan));
255 if (!MOD_RESULT.check(invited))
257 user->WriteNumeric(ERR_INVITEONLYCHAN, "%s :Cannot join channel (Invite only)", chan->name.c_str());
262 std::string limit = chan->GetModeParameter(limitmode);
265 FIRST_MOD_RESULT(OnCheckLimit, MOD_RESULT, (user, chan));
266 if (!MOD_RESULT.check((chan->GetUserCounter() < atol(limit.c_str()) || can_bypass)))
268 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
273 if (chan->IsBanned(user) && !can_bypass)
275 user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
280 * If the user has invites for this channel, remove them now
281 * after a successful join so they don't build up.
285 user->RemoveInvite(chan);
291 // We figured that this join is allowed and also created the
292 // channel if it didn't exist before, now do the actual join
293 chan->ForceJoin(user, &privs, false, created_by_local);
297 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
301 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
305 Membership* memb = this->AddUser(user);
307 return NULL; // Already on the channel
309 user->chans.push_front(memb);
313 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
314 // remote user and his own server set the modes), then set them internally now
315 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
317 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
320 std::string nick = user->nick;
321 // Set the mode on the user
322 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
327 // 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
329 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
331 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
333 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
334 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
336 std::string ms = memb->modes;
337 for(unsigned int i=0; i < memb->modes.length(); i++)
338 ms.append(" ").append(user->nick);
340 except_list.insert(user);
341 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
344 FOREACH_MOD(OnPostJoin, (memb));
348 bool Channel::IsBanned(User* user)
351 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
353 if (result != MOD_RES_PASSTHRU)
354 return (result == MOD_RES_DENY);
356 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
357 const ListModeBase::ModeList* bans = banlm->GetList(this);
360 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
362 if (CheckBan(user, it->mask))
369 bool Channel::CheckBan(User* user, const std::string& mask)
372 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
373 if (result != MOD_RES_PASSTHRU)
374 return (result == MOD_RES_DENY);
376 // extbans were handled above, if this is one it obviously didn't match
377 if ((mask.length() <= 2) || (mask[1] == ':'))
380 std::string::size_type at = mask.find('@');
381 if (at == std::string::npos)
384 const std::string nickIdent = user->nick + "!" + user->ident;
385 std::string prefix(mask, 0, at);
386 if (InspIRCd::Match(nickIdent, prefix, NULL))
388 std::string suffix(mask, at + 1);
389 if (InspIRCd::Match(user->host, suffix, NULL) ||
390 InspIRCd::Match(user->dhost, suffix, NULL) ||
391 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
397 ModResult Channel::GetExtBanStatus(User *user, char type)
400 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
401 if (rv != MOD_RES_PASSTHRU)
404 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
405 const ListModeBase::ModeList* bans = banlm->GetList(this);
408 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
410 if (CheckBan(user, it->mask))
414 return MOD_RES_PASSTHRU;
418 * Remove a channel from a users record, remove the reference to the Membership object
419 * from the channel and destroy it.
421 void Channel::PartUser(User *user, std::string &reason)
423 MemberMap::iterator membiter = userlist.find(user);
425 if (membiter != userlist.end())
427 Membership* memb = membiter->second;
429 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
431 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
433 // Remove this channel from the user's chanlist
434 user->chans.erase(memb);
435 // Remove the Membership from this channel's userlist and destroy it
436 this->DelUser(membiter);
440 void Channel::KickUser(User* src, const MemberMap::iterator& victimiter, const std::string& reason)
442 Membership* memb = victimiter->second;
444 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
446 User* victim = memb->user;
447 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
449 victim->chans.erase(memb);
450 this->DelUser(victimiter);
453 void Channel::WriteChannel(User* user, const char* text, ...)
455 std::string textbuffer;
456 VAFORMAT(textbuffer, text, text);
457 this->WriteChannel(user, textbuffer);
460 void Channel::WriteChannel(User* user, const std::string &text)
462 const std::string message = ":" + user->GetFullHost() + " " + text;
464 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
466 if (IS_LOCAL(i->first))
467 i->first->Write(message);
471 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
473 std::string textbuffer;
474 VAFORMAT(textbuffer, text, text);
475 this->WriteChannelWithServ(ServName, textbuffer);
478 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
480 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
482 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
484 if (IS_LOCAL(i->first))
485 i->first->Write(message);
489 /* write formatted text from a source user to all users on a channel except
490 * for the sender (for privmsg etc) */
491 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
493 std::string textbuffer;
494 VAFORMAT(textbuffer, text, text);
495 this->WriteAllExceptSender(user, serversource, status, textbuffer);
498 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
500 std::string textbuffer;
501 VAFORMAT(textbuffer, text, text);
502 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
503 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
506 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
508 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
509 this->RawWriteAllExcept(user, serversource, status, except_list, message);
512 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
514 unsigned int minrank = 0;
517 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
519 minrank = mh->GetPrefixRank();
521 for (MemberMap::iterator i = userlist.begin(); i != userlist.end(); i++)
523 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
525 /* User doesn't have the status we're after */
526 if (minrank && i->second->getRank() < minrank)
529 i->first->Write(out);
534 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
537 except_list.insert(user);
538 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
541 const char* Channel::ChanModes(bool showkey)
543 static std::string scratch;
548 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
549 for(int n = 0; n < 64; n++)
551 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
552 if (mh && IsModeSet(mh))
554 scratch.push_back(n + 65);
556 ParamModeBase* pm = mh->IsParameterMode();
560 if (n == 'k' - 65 && !showkey)
567 pm->GetParameter(this, sparam);
573 return scratch.c_str();
576 /* returns the status character for a given user on a channel, e.g. @ for op,
577 * % for halfop etc. If the user has several modes set, the highest mode
578 * the user has must be returned.
580 char Membership::GetPrefixChar() const
583 unsigned int bestrank = 0;
585 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
587 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
588 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
590 bestrank = mh->GetPrefixRank();
591 pf = mh->GetPrefix();
597 unsigned int Membership::getRank()
599 char mchar = modes.c_str()[0];
603 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
605 rv = mh->GetPrefixRank();
610 const char* Membership::GetAllPrefixChars() const
612 static char prefix[64];
615 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
617 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
618 if (mh && mh->GetPrefix())
619 prefix[ctr++] = mh->GetPrefix();
626 unsigned int Channel::GetPrefixValue(User* user)
628 MemberMap::iterator m = userlist.find(user);
629 if (m == userlist.end())
631 return m->second->getRank();
634 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
636 char prefix = delta_mh->GetModeChar();
637 for (unsigned int i = 0; i < modes.length(); i++)
639 char mchar = modes[i];
640 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
641 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
643 modes = modes.substr(0,i) +
644 (adding ? std::string(1, prefix) : "") +
645 modes.substr(mchar == prefix ? i+1 : i);
646 return adding != (mchar == prefix);
650 modes.push_back(prefix);
654 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
656 if ((timeout != 0) && (ServerInstance->Time() >= timeout))
657 // Expired, don't bother
660 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
662 Invitation* inv = Invitation::Find(c, u, false);
665 if ((inv->expiry == 0) || (inv->expiry > timeout))
667 inv->expiry = timeout;
668 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
672 inv = new Invitation(c, u, timeout);
673 c->invites.push_front(inv);
674 u->invites.push_front(inv);
675 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
679 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
681 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);
683 Invitation* result = NULL;
684 for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
686 Invitation* inv = *i;
689 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
691 /* Expired invite, remove it. */
692 std::string expiration = InspIRCd::TimeString(inv->expiry);
693 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
698 /* Is it what we're searching for? */
707 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
711 Invitation::~Invitation()
713 // Remove this entry from both lists
714 chan->invites.erase(this);
715 user->invites.erase(this);
716 ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);