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");
35 ChanModeReference secretmode(NULL, "secret");
36 ChanModeReference privatemode(NULL, "private");
37 UserModeReference invisiblemode(NULL, "invisible");
40 Channel::Channel(const std::string &cname, time_t ts)
41 : name(cname), age(ts), topicset(0)
43 if (!ServerInstance->chanlist.insert(std::make_pair(cname, this)).second)
44 throw CoreException("Cannot create duplicate channel " + cname);
47 void Channel::SetMode(ModeHandler* mh, bool on)
49 modes[mh->GetId()] = on;
52 void Channel::SetTopic(User* u, const std::string& ntopic)
54 this->topic.assign(ntopic, 0, ServerInstance->Config->Limits.MaxTopic);
55 this->setby.assign(ServerInstance->Config->FullHostInTopic ? u->GetFullHost() : u->nick, 0, 128);
56 this->WriteChannel(u, "TOPIC %s :%s", this->name.c_str(), this->topic.c_str());
57 this->topicset = ServerInstance->Time();
59 FOREACH_MOD(OnPostTopicChange, (u, this, this->topic));
62 Membership* Channel::AddUser(User* user)
64 Membership*& memb = userlist[user];
68 memb = new Membership(user, this);
72 void Channel::DelUser(User* user)
74 UserMembIter it = userlist.find(user);
75 if (it != userlist.end())
79 void Channel::CheckDestroy()
81 if (!userlist.empty())
85 FIRST_MOD_RESULT(OnChannelPreDelete, res, (this));
86 if (res == MOD_RES_DENY)
89 chan_hash::iterator iter = ServerInstance->chanlist.find(this->name);
91 if (iter != ServerInstance->chanlist.end())
93 FOREACH_MOD(OnChannelDelete, (this));
94 ServerInstance->chanlist.erase(iter);
98 ServerInstance->GlobalCulls.AddItem(this);
101 void Channel::DelUser(const UserMembIter& membiter)
103 Membership* memb = membiter->second;
106 userlist.erase(membiter);
108 // If this channel became empty then it should be removed
112 Membership* Channel::GetUser(User* user)
114 UserMembIter i = userlist.find(user);
115 if (i == userlist.end())
120 void Channel::SetDefaultModes()
122 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "SetDefaultModes %s",
123 ServerInstance->Config->DefaultModes.c_str());
124 irc::spacesepstream list(ServerInstance->Config->DefaultModes);
126 std::string parameter;
128 list.GetToken(modeseq);
130 for (std::string::iterator n = modeseq.begin(); n != modeseq.end(); ++n)
132 ModeHandler* mode = ServerInstance->Modes->FindMode(*n, MODETYPE_CHANNEL);
135 if (mode->IsPrefixMode())
138 if (mode->GetNumParams(true))
139 list.GetToken(parameter);
143 mode->OnModeChange(ServerInstance->FakeClient, ServerInstance->FakeClient, this, parameter, true);
149 * add a channel to a user, creating the record for it if needed and linking
150 * it to the user record
152 Channel* Channel::JoinUser(LocalUser* user, std::string cname, bool override, const std::string& key)
154 if (user->registered != REG_ALL)
156 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join unregistered user " + user->uuid + " to channel " + cname);
161 * We don't restrict the number of channels that remote users or users that are override-joining may be in.
162 * We restrict local users to <connect:maxchans> channels.
163 * We restrict local operators to <oper:maxchans> channels.
164 * This is a lot more logical than how it was formerly. -- w00t
168 unsigned int maxchans = user->GetClass()->maxchans;
171 unsigned int opermaxchans = ConvToInt(user->oper->getConfig("maxchans"));
172 // If not set, use 2.0's <channels:opers>, if that's not set either, use limit from CC
174 opermaxchans = ServerInstance->Config->OperMaxChans;
176 maxchans = opermaxchans;
178 if (user->chans.size() >= maxchans)
180 user->WriteNumeric(ERR_TOOMANYCHANNELS, "%s :You are on too many channels", cname.c_str());
185 // Crop channel name if it's too long
186 if (cname.length() > ServerInstance->Config->Limits.ChanMax)
187 cname.resize(ServerInstance->Config->Limits.ChanMax);
189 Channel* chan = ServerInstance->FindChan(cname);
190 bool created_by_local = (chan == NULL); // Flag that will be passed to modules in the OnUserJoin() hook later
191 std::string privs; // Prefix mode(letter)s to give to the joining user
195 privs = ServerInstance->Config->DefaultModes.substr(0, ServerInstance->Config->DefaultModes.find(' '));
197 if (override == false)
199 // Ask the modules whether they're ok with the join, pass NULL as Channel* as the channel is yet to be created
200 ModResult MOD_RESULT;
201 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, NULL, cname, privs, key));
202 if (MOD_RESULT == MOD_RES_DENY)
203 return NULL; // A module wasn't happy with the join, abort
206 chan = new Channel(cname, ServerInstance->Time());
207 // Set the default modes on the channel (<options:defaultmodes>)
208 chan->SetDefaultModes();
212 /* Already on the channel */
213 if (chan->HasUser(user))
216 if (override == false)
218 ModResult MOD_RESULT;
219 FIRST_MOD_RESULT(OnUserPreJoin, MOD_RESULT, (user, chan, cname, privs, key));
221 // A module explicitly denied the join and (hopefully) generated a message
222 // describing the situation, so we may stop here without sending anything
223 if (MOD_RESULT == MOD_RES_DENY)
226 // If no module returned MOD_RES_DENY or MOD_RES_ALLOW (which is the case
227 // most of the time) then proceed to check channel modes +k, +i, +l and bans,
229 // If a module explicitly allowed the join (by returning MOD_RES_ALLOW),
230 // then this entire section is skipped
231 if (MOD_RESULT == MOD_RES_PASSTHRU)
233 std::string ckey = chan->GetModeParameter(keymode);
234 bool invited = user->IsInvited(chan);
235 bool can_bypass = ServerInstance->Config->InvBypassModes && invited;
239 FIRST_MOD_RESULT(OnCheckKey, MOD_RESULT, (user, chan, key));
240 if (!MOD_RESULT.check((ckey == key) || can_bypass))
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.check(invited))
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()) || can_bypass)))
264 user->WriteNumeric(ERR_CHANNELISFULL, "%s :Cannot join channel (Channel is full)", chan->name.c_str());
269 if (chan->IsBanned(user) && !can_bypass)
271 user->WriteNumeric(ERR_BANNEDFROMCHAN, "%s :Cannot join channel (You're banned)", chan->name.c_str());
276 * If the user has invites for this channel, remove them now
277 * after a successful join so they don't build up.
281 user->RemoveInvite(chan);
287 // We figured that this join is allowed and also created the
288 // channel if it didn't exist before, now do the actual join
289 chan->ForceJoin(user, &privs, false, created_by_local);
293 Membership* Channel::ForceJoin(User* user, const std::string* privs, bool bursting, bool created_by_local)
297 ServerInstance->Logs->Log("CHANNELS", LOG_DEBUG, "Attempted to join server user " + user->uuid + " to channel " + this->name);
301 Membership* memb = this->AddUser(user);
303 return NULL; // Already on the channel
305 user->chans.push_front(memb);
309 // If the user was granted prefix modes (in the OnUserPreJoin hook, or he's a
310 // remote user and his own server set the modes), then set them internally now
311 for (std::string::const_iterator i = privs->begin(); i != privs->end(); ++i)
313 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
316 std::string nick = user->nick;
317 // Set the mode on the user
318 mh->OnModeChange(ServerInstance->FakeClient, NULL, this, nick, true);
323 // 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
325 FOREACH_MOD(OnUserJoin, (memb, bursting, created_by_local, except_list));
327 this->WriteAllExcept(user, false, 0, except_list, "JOIN :%s", this->name.c_str());
329 /* Theyre not the first ones in here, make sure everyone else sees the modes we gave the user */
330 if ((GetUserCounter() > 1) && (!memb->modes.empty()))
332 std::string ms = memb->modes;
333 for(unsigned int i=0; i < memb->modes.length(); i++)
334 ms.append(" ").append(user->nick);
336 except_list.insert(user);
337 this->WriteAllExcept(user, !ServerInstance->Config->CycleHostsFromUser, 0, except_list, "MODE %s +%s", this->name.c_str(), ms.c_str());
344 user->WriteNumeric(RPL_TOPIC, "%s :%s", this->name.c_str(), this->topic.c_str());
345 user->WriteNumeric(RPL_TOPICTIME, "%s %s %lu", this->name.c_str(), this->setby.c_str(), (unsigned long)this->topicset);
347 this->UserList(user);
350 FOREACH_MOD(OnPostJoin, (memb));
354 bool Channel::IsBanned(User* user)
357 FIRST_MOD_RESULT(OnCheckChannelBan, result, (user, this));
359 if (result != MOD_RES_PASSTHRU)
360 return (result == MOD_RES_DENY);
362 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
363 const ListModeBase::ModeList* bans = banlm->GetList(this);
366 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); it++)
368 if (CheckBan(user, it->mask))
375 bool Channel::CheckBan(User* user, const std::string& mask)
378 FIRST_MOD_RESULT(OnCheckBan, result, (user, this, mask));
379 if (result != MOD_RES_PASSTHRU)
380 return (result == MOD_RES_DENY);
382 // extbans were handled above, if this is one it obviously didn't match
383 if ((mask.length() <= 2) || (mask[1] == ':'))
386 std::string::size_type at = mask.find('@');
387 if (at == std::string::npos)
390 const std::string nickIdent = user->nick + "!" + user->ident;
391 std::string prefix = mask.substr(0, at);
392 if (InspIRCd::Match(nickIdent, prefix, NULL))
394 std::string suffix = mask.substr(at + 1);
395 if (InspIRCd::Match(user->host, suffix, NULL) ||
396 InspIRCd::Match(user->dhost, suffix, NULL) ||
397 InspIRCd::MatchCIDR(user->GetIPString(), suffix, NULL))
403 ModResult Channel::GetExtBanStatus(User *user, char type)
406 FIRST_MOD_RESULT(OnExtBanCheck, rv, (user, this, type));
407 if (rv != MOD_RES_PASSTHRU)
410 ListModeBase* banlm = static_cast<ListModeBase*>(*ban);
411 const ListModeBase::ModeList* bans = banlm->GetList(this);
414 for (ListModeBase::ModeList::const_iterator it = bans->begin(); it != bans->end(); ++it)
416 if (CheckBan(user, it->mask))
420 return MOD_RES_PASSTHRU;
424 * Remove a channel from a users record, remove the reference to the Membership object
425 * from the channel and destroy it.
427 void Channel::PartUser(User *user, std::string &reason)
429 UserMembIter membiter = userlist.find(user);
431 if (membiter != userlist.end())
433 Membership* memb = membiter->second;
435 FOREACH_MOD(OnUserPart, (memb, reason, except_list));
437 WriteAllExcept(user, false, 0, except_list, "PART %s%s%s", this->name.c_str(), reason.empty() ? "" : " :", reason.c_str());
439 // Remove this channel from the user's chanlist
440 user->chans.erase(memb);
441 // Remove the Membership from this channel's userlist and destroy it
442 this->DelUser(membiter);
446 void Channel::KickUser(User* src, const UserMembIter& victimiter, const std::string& reason)
448 Membership* memb = victimiter->second;
450 FOREACH_MOD(OnUserKick, (src, memb, reason, except_list));
452 User* victim = memb->user;
453 WriteAllExcept(src, false, 0, except_list, "KICK %s %s :%s", name.c_str(), victim->nick.c_str(), reason.c_str());
455 victim->chans.erase(memb);
456 this->DelUser(victimiter);
459 void Channel::WriteChannel(User* user, const char* text, ...)
461 std::string textbuffer;
462 VAFORMAT(textbuffer, text, text);
463 this->WriteChannel(user, textbuffer);
466 void Channel::WriteChannel(User* user, const std::string &text)
468 const std::string message = ":" + user->GetFullHost() + " " + text;
470 for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
472 if (IS_LOCAL(i->first))
473 i->first->Write(message);
477 void Channel::WriteChannelWithServ(const std::string& ServName, const char* text, ...)
479 std::string textbuffer;
480 VAFORMAT(textbuffer, text, text);
481 this->WriteChannelWithServ(ServName, textbuffer);
484 void Channel::WriteChannelWithServ(const std::string& ServName, const std::string &text)
486 const std::string message = ":" + (ServName.empty() ? ServerInstance->Config->ServerName : ServName) + " " + text;
488 for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
490 if (IS_LOCAL(i->first))
491 i->first->Write(message);
495 /* write formatted text from a source user to all users on a channel except
496 * for the sender (for privmsg etc) */
497 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const char* text, ...)
499 std::string textbuffer;
500 VAFORMAT(textbuffer, text, text);
501 this->WriteAllExceptSender(user, serversource, status, textbuffer);
504 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const char* text, ...)
506 std::string textbuffer;
507 VAFORMAT(textbuffer, text, text);
508 textbuffer = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + textbuffer;
509 this->RawWriteAllExcept(user, serversource, status, except_list, textbuffer);
512 void Channel::WriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &text)
514 const std::string message = ":" + (serversource ? ServerInstance->Config->ServerName : user->GetFullHost()) + " " + text;
515 this->RawWriteAllExcept(user, serversource, status, except_list, message);
518 void Channel::RawWriteAllExcept(User* user, bool serversource, char status, CUList &except_list, const std::string &out)
520 unsigned int minrank = 0;
523 PrefixMode* mh = ServerInstance->Modes->FindPrefix(status);
525 minrank = mh->GetPrefixRank();
527 for (UserMembIter i = userlist.begin(); i != userlist.end(); i++)
529 if (IS_LOCAL(i->first) && (except_list.find(i->first) == except_list.end()))
531 /* User doesn't have the status we're after */
532 if (minrank && i->second->getRank() < minrank)
535 i->first->Write(out);
540 void Channel::WriteAllExceptSender(User* user, bool serversource, char status, const std::string& text)
543 except_list.insert(user);
544 this->WriteAllExcept(user, serversource, status, except_list, std::string(text));
547 const char* Channel::ChanModes(bool showkey)
549 static std::string scratch;
554 /* This was still iterating up to 190, Channel::modes is only 64 elements -- Om */
555 for(int n = 0; n < 64; n++)
557 ModeHandler* mh = ServerInstance->Modes->FindMode(n + 65, MODETYPE_CHANNEL);
558 if (mh && IsModeSet(mh))
560 scratch.push_back(n + 65);
562 ParamModeBase* pm = mh->IsParameterMode();
566 if (n == 'k' - 65 && !showkey)
573 pm->GetParameter(this, sparam);
579 return scratch.c_str();
582 /* compile a userlist of a channel into a string, each nick seperated by
583 * spaces and op, voice etc status shown as @ and +, and send it to 'user'
585 void Channel::UserList(User* user, bool has_user)
587 bool has_privs = user->HasPrivPermission("channels/auspex");
589 list.push_back(this->IsModeSet(secretmode) ? '@' : this->IsModeSet(privatemode) ? '*' : '=');
591 list.append(this->name).append(" :");
592 std::string::size_type pos = list.size();
594 const size_t maxlen = ServerInstance->Config->Limits.MaxLine - 10 - ServerInstance->Config->ServerName.size();
595 std::string prefixlist;
597 for (UserMembIter i = userlist.begin(); i != userlist.end(); ++i)
599 if ((!has_user) && (i->first->IsModeSet(invisiblemode)) && (!has_privs))
602 * user is +i, and source not on the channel, does not show
608 Membership* memb = i->second;
611 char prefix = memb->GetPrefixChar();
613 prefixlist.push_back(prefix);
614 nick = i->first->nick;
617 FIRST_MOD_RESULT(OnNamesListItem, res, (user, memb, prefixlist, nick));
619 // See if a module wants us to exclude this user from NAMES
620 if (res == MOD_RES_DENY)
623 if (list.size() + prefixlist.length() + nick.length() + 1 > maxlen)
625 /* list overflowed into multiple numerics */
626 user->WriteNumeric(RPL_NAMREPLY, list);
628 // Erase all nicks, keep the constant part
632 list.append(prefixlist).append(nick).push_back(' ');
635 // Only send the user list numeric if there is at least one user in it
636 if (list.size() != pos)
637 user->WriteNumeric(RPL_NAMREPLY, list);
639 user->WriteNumeric(RPL_ENDOFNAMES, "%s :End of /NAMES list.", this->name.c_str());
642 /* returns the status character for a given user on a channel, e.g. @ for op,
643 * % for halfop etc. If the user has several modes set, the highest mode
644 * the user has must be returned.
646 char Membership::GetPrefixChar() const
649 unsigned int bestrank = 0;
651 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
653 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
654 if (mh && mh->GetPrefixRank() > bestrank && mh->GetPrefix())
656 bestrank = mh->GetPrefixRank();
657 pf = mh->GetPrefix();
663 unsigned int Membership::getRank()
665 char mchar = modes.c_str()[0];
669 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
671 rv = mh->GetPrefixRank();
676 const char* Membership::GetAllPrefixChars() const
678 static char prefix[64];
681 for (std::string::const_iterator i = modes.begin(); i != modes.end(); ++i)
683 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(*i);
684 if (mh && mh->GetPrefix())
685 prefix[ctr++] = mh->GetPrefix();
692 unsigned int Channel::GetPrefixValue(User* user)
694 UserMembIter m = userlist.find(user);
695 if (m == userlist.end())
697 return m->second->getRank();
700 bool Membership::SetPrefix(PrefixMode* delta_mh, bool adding)
702 char prefix = delta_mh->GetModeChar();
703 for (unsigned int i = 0; i < modes.length(); i++)
705 char mchar = modes[i];
706 PrefixMode* mh = ServerInstance->Modes->FindPrefixMode(mchar);
707 if (mh && mh->GetPrefixRank() <= delta_mh->GetPrefixRank())
709 modes = modes.substr(0,i) +
710 (adding ? std::string(1, prefix) : "") +
711 modes.substr(mchar == prefix ? i+1 : i);
712 return adding != (mchar == prefix);
716 modes.push_back(prefix);
720 void Invitation::Create(Channel* c, LocalUser* u, time_t timeout)
722 if ((timeout != 0) && (ServerInstance->Time() >= timeout))
723 // Expired, don't bother
726 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create chan=%s user=%s", c->name.c_str(), u->uuid.c_str());
728 Invitation* inv = Invitation::Find(c, u, false);
731 if ((inv->expiry == 0) || (inv->expiry > timeout))
733 inv->expiry = timeout;
734 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create changed expiry in existing invitation %p", (void*) inv);
738 inv = new Invitation(c, u, timeout);
739 c->invites.push_front(inv);
740 u->invites.push_front(inv);
741 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Create created new invitation %p", (void*) inv);
745 Invitation* Invitation::Find(Channel* c, LocalUser* u, bool check_expired)
747 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);
749 Invitation* result = NULL;
750 for (InviteList::iterator i = u->invites.begin(); i != u->invites.end(); )
752 Invitation* inv = *i;
755 if ((check_expired) && (inv->expiry != 0) && (inv->expiry <= ServerInstance->Time()))
757 /* Expired invite, remove it. */
758 std::string expiration = InspIRCd::TimeString(inv->expiry);
759 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find ecountered expired entry: %p expired %s", (void*) inv, expiration.c_str());
764 /* Is it what we're searching for? */
773 ServerInstance->Logs->Log("INVITATION", LOG_DEBUG, "Invitation::Find result=%p", (void*) result);
777 Invitation::~Invitation()
779 // Remove this entry from both lists
780 chan->invites.erase(this);
781 user->invites.erase(this);
782 ServerInstance->Logs->Log("INVITEBASE", LOG_DEBUG, "Invitation::~ %p", (void*) this);