2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2009 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2006-2007, 2009 Dennis Friis <peavey@inspircd.org>
7 * Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
8 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9 * Copyright (C) 2008 Oliver Lupton <oliverlupton@gmail.com>
10 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
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/>.
29 ClientProtocol::MessageList LocalUser::sendmsglist;
31 bool User::IsNoticeMaskSet(unsigned char sm)
35 return (snomasks[sm-65]);
38 bool User::IsModeSet(unsigned char m) const
40 ModeHandler* mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
41 return (mh && modes[mh->GetId()]);
44 std::string User::GetModeLetters(bool includeparams) const
46 std::string ret(1, '+');
49 for (unsigned char i = 'A'; i < 'z'; i++)
51 const ModeHandler* const mh = ServerInstance->Modes.FindMode(i, MODETYPE_USER);
52 if ((!mh) || (!IsModeSet(mh)))
55 ret.push_back(mh->GetModeChar());
56 if ((includeparams) && (mh->NeedsParam(true)))
58 const std::string val = mh->GetUserParameter(this);
60 params.append(1, ' ').append(val);
68 User::User(const std::string& uid, Server* srv, UserType type)
69 : age(ServerInstance->Time())
73 , registered(REG_NONE)
77 client_sa.sa.sa_family = AF_UNSPEC;
79 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New UUID for user: %s", uuid.c_str());
81 // Do not insert FakeUsers into the uuidlist so FindUUID() won't return them which is the desired behavior
82 if (type != USERTYPE_SERVER)
84 if (!ServerInstance->Users.uuidlist.insert(std::make_pair(uuid, this)).second)
85 throw CoreException("Duplicate UUID in User constructor: " + uuid);
89 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
90 : User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL)
97 , quitting_sendq(false)
102 , CommandFloodPenalty(0)
105 signon = ServerInstance->Time();
106 // The user's default nick is their UUID
110 memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
111 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
112 ChangeRealHost(GetIPString(), true);
119 const std::string& User::MakeHost()
121 if (!this->cached_makehost.empty())
122 return this->cached_makehost;
124 // XXX: Is there really a need to cache this?
125 this->cached_makehost = ident + "@" + GetRealHost();
126 return this->cached_makehost;
129 const std::string& User::MakeHostIP()
131 if (!this->cached_hostip.empty())
132 return this->cached_hostip;
134 // XXX: Is there really a need to cache this?
135 this->cached_hostip = ident + "@" + this->GetIPString();
136 return this->cached_hostip;
139 const std::string& User::GetFullHost()
141 if (!this->cached_fullhost.empty())
142 return this->cached_fullhost;
144 // XXX: Is there really a need to cache this?
145 this->cached_fullhost = nick + "!" + ident + "@" + GetDisplayedHost();
146 return this->cached_fullhost;
149 const std::string& User::GetFullRealHost()
151 if (!this->cached_fullrealhost.empty())
152 return this->cached_fullrealhost;
154 // XXX: Is there really a need to cache this?
155 this->cached_fullrealhost = nick + "!" + ident + "@" + GetRealHost();
156 return this->cached_fullrealhost;
159 bool User::HasModePermission(const ModeHandler* mh) const
164 bool LocalUser::HasModePermission(const ModeHandler* mh) const
169 const unsigned char mode = mh->GetModeChar();
170 if (mode < 'A' || mode > ('A' + 64)) return false;
172 return ((mh->GetModeType() == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
176 * users on remote servers can completely bypass all permissions based checks.
177 * This prevents desyncs when one server has different type/class tags to another.
178 * That having been said, this does open things up to the possibility of source changes
179 * allowing remote kills, etc - but if they have access to the src, they most likely have
180 * access to the conf - so it's an end to a means either way.
182 bool User::HasPermission(const std::string&)
187 bool LocalUser::HasPermission(const std::string &command)
189 // are they even an oper at all?
195 return oper->AllowedOperCommands.Contains(command);
198 bool User::HasPrivPermission(const std::string &privstr, bool noisy)
203 bool LocalUser::HasPrivPermission(const std::string &privstr, bool noisy)
208 this->WriteNotice("You are not an oper");
212 if (oper->AllowedPrivs.Contains(privstr))
216 this->WriteNotice("Oper type " + oper->name + " does not have access to priv " + privstr);
221 void UserIOHandler::OnDataReady()
226 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
228 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
229 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
230 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
234 unsigned long sendqmax = ULONG_MAX;
235 if (!user->HasPrivPermission("users/flood/increased-buffers"))
236 sendqmax = user->MyClass->GetSendqSoftMax();
238 unsigned long penaltymax = ULONG_MAX;
239 if (!user->HasPrivPermission("users/flood/no-fakelag"))
240 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
242 // The maximum size of an IRC message minus the terminating CR+LF.
243 const size_t maxmessage = ServerInstance->Config->Limits.MaxLine - 2;
245 line.reserve(maxmessage);
248 std::string::size_type qpos;
250 while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
255 const size_t qlen = recvq.length();
258 char c = recvq[qpos++];
274 if (line.length() < maxmessage)
278 // if we return here, we haven't found a newline and make no modifications to recvq
279 // so we can wait for more data
283 // just found a newline. Terminate the string, and pull it out of recvq
284 recvq.erase(0, qpos);
286 // TODO should this be moved to when it was inserted in recvq?
287 ServerInstance->stats.Recv += qpos;
288 user->bytes_in += qpos;
291 ServerInstance->Parser.ProcessBuffer(user, line);
295 // clear() does not reclaim memory associated with the string, so our .reserve() call is safe
299 if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
300 ServerInstance->Users->QuitUser(user, "Excess Flood");
303 void UserIOHandler::AddWriteBuf(const std::string &data)
305 if (user->quitting_sendq)
307 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
308 !user->HasPrivPermission("users/flood/increased-buffers"))
310 user->quitting_sendq = true;
311 ServerInstance->GlobalCulls.AddSQItem(user);
315 // We still want to append data to the sendq of a quitting user,
316 // e.g. their ERROR message that says 'closing link'
321 void UserIOHandler::OnSetEndPoint(const irc::sockets::sockaddrs& server, const irc::sockets::sockaddrs& client)
323 memcpy(&user->server_sa, &server, sizeof(irc::sockets::sockaddrs));
324 user->SetClientIP(client);
327 void UserIOHandler::OnError(BufferedSocketError)
329 ServerInstance->Users->QuitUser(user, getError());
332 CullResult User::cull()
335 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
337 if (client_sa.family() != AF_UNSPEC)
338 ServerInstance->Users->RemoveCloneCounts(this);
340 return Extensible::cull();
343 CullResult LocalUser::cull()
349 CullResult FakeUser::cull()
351 // Fake users don't quit, they just get culled.
353 // Fake users are not inserted into UserManager::clientlist or uuidlist, so we don't need to modify those here
357 void User::Oper(OperInfo* info)
359 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
360 if (this->IsModeSet(opermh))
363 this->SetMode(opermh, true);
366 LocalUser* localuser = IS_LOCAL(this);
369 Modes::ChangeList changelist;
370 changelist.push_add(opermh);
371 ClientProtocol::Events::Mode modemsg(ServerInstance->FakeClient, NULL, localuser, changelist);
372 localuser->Send(modemsg);
375 FOREACH_MOD(OnOper, (this, info->name));
377 std::string opername;
378 if (info->oper_block)
379 opername = info->oper_block->getString("name");
383 LocalUser* l = IS_LOCAL(this);
384 std::string vhost = oper->getConfig("vhost");
386 l->ChangeDisplayedHost(vhost);
387 std::string opClass = oper->getConfig("class");
388 if (!opClass.empty())
389 l->SetClass(opClass);
392 ServerInstance->SNO->WriteToSnoMask('o',"%s (%s@%s) is now an IRC operator of type %s (using oper '%s')",
393 nick.c_str(), ident.c_str(), GetRealHost().c_str(), oper->name.c_str(), opername.c_str());
394 this->WriteNumeric(RPL_YOUAREOPER, InspIRCd::Format("You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str()));
396 ServerInstance->Users->all_opers.push_back(this);
398 // Expand permissions from config for faster lookup
402 FOREACH_MOD(OnPostOper, (this, oper->name, opername));
405 void OperInfo::init()
407 AllowedOperCommands.Clear();
408 AllowedPrivs.Clear();
409 AllowedUserModes.reset();
410 AllowedChanModes.reset();
411 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
413 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
415 ConfigTag* tag = *iter;
417 AllowedOperCommands.AddList(tag->getString("commands"));
418 AllowedPrivs.AddList(tag->getString("privs"));
420 std::string modes = tag->getString("usermodes");
421 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
425 this->AllowedUserModes.set();
427 else if (*c >= 'A' && *c <= 'z')
429 this->AllowedUserModes[*c - 'A'] = true;
433 modes = tag->getString("chanmodes");
434 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
438 this->AllowedChanModes.set();
440 else if (*c >= 'A' && *c <= 'z')
442 this->AllowedChanModes[*c - 'A'] = true;
454 * unset their oper type (what IS_OPER checks).
455 * note, order is important - this must come before modes as -o attempts
456 * to call UnOper. -- w00t
461 /* Remove all oper only modes from the user when the deoper - Bug #466*/
462 Modes::ChangeList changelist;
463 const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
464 for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); ++i)
466 ModeHandler* mh = i->second;
468 changelist.push_remove(mh);
471 ServerInstance->Modes->Process(this, NULL, this, changelist);
473 // Remove the user from the oper list
474 stdalgo::vector::swaperase(ServerInstance->Users->all_opers, this);
476 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
477 this->SetMode(opermh, false);
478 FOREACH_MOD(OnPostDeoper, (this));
482 * Check class restrictions
484 void LocalUser::CheckClass(bool clone_count)
486 ConnectClass* a = this->MyClass;
490 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
493 else if (a->type == CC_DENY)
495 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection"));
498 else if (clone_count)
500 const UserManager::CloneCounts& clonecounts = ServerInstance->Users->GetCloneCounts(this);
501 if ((a->GetMaxLocal()) && (clonecounts.local > a->GetMaxLocal()))
503 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
505 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum LOCAL connections (%ld) exceeded for IP %s", a->GetMaxLocal(), this->GetIPString().c_str());
508 else if ((a->GetMaxGlobal()) && (clonecounts.global > a->GetMaxGlobal()))
510 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
512 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum GLOBAL connections (%ld) exceeded for IP %s", a->GetMaxGlobal(), this->GetIPString().c_str());
517 this->nping = ServerInstance->Time() + a->GetPingTime();
520 bool LocalUser::CheckLines(bool doZline)
522 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
526 for (int n = 0; check[n]; ++n)
528 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
541 void LocalUser::FullConnect()
543 ServerInstance->stats.Connects++;
544 this->idle_lastmsg = ServerInstance->Time();
547 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
548 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
549 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
550 * Don't remove this! -- w00t
561 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
562 * for a user that doesn't exist yet.
564 FOREACH_MOD(OnUserConnect, (this));
567 if (ServerInstance->Users->unregistered_count)
568 ServerInstance->Users->unregistered_count--;
569 this->registered = REG_ALL;
571 FOREACH_MOD(OnPostConnect, (this));
573 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
574 this->GetServerPort(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->GetRealName().c_str());
575 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
576 ServerInstance->BanCache.AddHit(this->GetIPString(), "", "");
577 // reset the flood penalty (which could have been raised due to things like auto +x)
578 CommandFloodPenalty = 0;
581 void User::InvalidateCache()
583 /* Invalidate cache */
585 cached_fullhost.clear();
586 cached_hostip.clear();
587 cached_makehost.clear();
588 cached_fullrealhost.clear();
591 bool User::ChangeNick(const std::string& newnick, time_t newts)
595 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
599 User* const InUse = ServerInstance->FindNickOnly(newnick);
602 // case change, don't need to check campers
603 // and, if it's identical including case, we can leave right now
604 // We also don't update the nick TS if it's a case change, either
611 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
612 * then we have a potential collide. Check whether someone else is camping on the nick
613 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
614 * camper to their UID, and allow the incoming nick change.
616 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
617 * because the nick is already (rightfully) in use. -- w00t
621 if (InUse->registered != REG_ALL)
623 /* force the camper to their UUID, and ask them to re-send a NICK. */
624 LocalUser* const localuser = static_cast<LocalUser*>(InUse);
625 localuser->OverruleNick();
629 /* No camping, tell the incoming user to stop trying to change nick ;p */
630 this->WriteNumeric(ERR_NICKNAMEINUSE, newnick, "Nickname is already in use.");
635 age = newts ? newts : ServerInstance->Time();
638 if (this->registered == REG_ALL)
640 ClientProtocol::Messages::Nick nickmsg(this, newnick);
641 ClientProtocol::Event nickevent(ServerInstance->GetRFCEvents().nick, nickmsg);
642 this->WriteCommonRaw(nickevent, true);
644 const std::string oldnick = nick;
648 ServerInstance->Users->clientlist.erase(oldnick);
649 ServerInstance->Users->clientlist[newnick] = this;
651 if (registered == REG_ALL)
652 FOREACH_MOD(OnUserPostNick, (this,oldnick));
657 void LocalUser::OverruleNick()
660 ClientProtocol::Messages::Nick nickmsg(this, this->uuid);
661 this->Send(ServerInstance->GetRFCEvents().nick, nickmsg);
663 this->WriteNumeric(ERR_NICKNAMEINUSE, this->nick, "Nickname overruled.");
665 // Clear the bit before calling ChangeNick() to make it NOT run the OnUserPostNick() hook
666 this->registered &= ~REG_NICK;
667 this->ChangeNick(this->uuid);
670 int LocalUser::GetServerPort()
672 return this->server_sa.port();
675 const std::string& User::GetIPString()
677 if (cachedip.empty())
679 cachedip = client_sa.addr();
680 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
681 if (cachedip[0] == ':')
682 cachedip.insert(cachedip.begin(),1,'0');
688 const std::string& User::GetHost(bool uncloak) const
690 return uncloak ? GetRealHost() : GetDisplayedHost();
693 const std::string& User::GetDisplayedHost() const
695 return displayhost.empty() ? realhost : displayhost;
698 const std::string& User::GetRealHost() const
703 const std::string& User::GetRealName() const
708 irc::sockets::cidr_mask User::GetCIDRMask()
710 unsigned char range = 0;
711 switch (client_sa.family())
714 range = ServerInstance->Config->c_ipv6_range;
717 range = ServerInstance->Config->c_ipv4_range;
720 return irc::sockets::cidr_mask(client_sa, range);
723 bool User::SetClientIP(const std::string& address, bool recheck_eline)
725 this->InvalidateCache();
726 return irc::sockets::aptosa(address, 0, client_sa);
729 void User::SetClientIP(const irc::sockets::sockaddrs& sa, bool recheck_eline)
731 this->InvalidateCache();
732 memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
735 bool LocalUser::SetClientIP(const std::string& address, bool recheck_eline)
737 irc::sockets::sockaddrs sa;
738 if (!irc::sockets::aptosa(address, 0, sa))
742 LocalUser::SetClientIP(sa, recheck_eline);
746 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa, bool recheck_eline)
750 User::SetClientIP(sa);
752 this->exempt = (ServerInstance->XLines->MatchesLine("E", this) != NULL);
754 FOREACH_MOD(OnSetUserIP, (this));
758 void LocalUser::Write(const ClientProtocol::SerializedMessage& text)
760 if (!SocketEngine::BoundsCheckFd(&eh))
763 if (ServerInstance->Config->RawLog)
768 std::string::size_type nlpos = text.find_first_of("\r\n", 0, 2);
769 if (nlpos == std::string::npos)
770 nlpos = text.length(); // TODO is this ok, test it
772 ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %.*s", uuid.c_str(), (int) nlpos, text.c_str());
775 eh.AddWriteBuf(text);
777 const size_t bytessent = text.length() + 2;
778 ServerInstance->stats.Sent += bytessent;
779 this->bytes_out += bytessent;
783 void LocalUser::Send(ClientProtocol::Event& protoev)
788 // In the most common case a static LocalUser field, sendmsglist, is passed to the event to be
789 // populated. The list is cleared before returning.
790 // To handle re-enters, if sendmsglist is non-empty upon entering the method then a temporary
791 // list is used instead of the static one.
792 if (sendmsglist.empty())
794 Send(protoev, sendmsglist);
799 ClientProtocol::MessageList msglist;
800 Send(protoev, msglist);
804 void LocalUser::Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist)
806 // Modules can personalize the messages sent per user for the event
807 protoev.GetMessagesForUser(this, msglist);
808 for (ClientProtocol::MessageList::const_iterator i = msglist.begin(); i != msglist.end(); ++i)
810 ClientProtocol::Message& curr = **i;
812 FIRST_MOD_RESULT(OnUserWrite, res, (this, curr));
813 if (res != MOD_RES_DENY)
814 Write(serializer->SerializeForUser(this, curr));
818 void User::WriteNumeric(const Numeric::Numeric& numeric)
820 LocalUser* const localuser = IS_LOCAL(this);
824 ModResult MOD_RESULT;
826 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric));
828 if (MOD_RESULT == MOD_RES_DENY)
831 ClientProtocol::Messages::Numeric numericmsg(numeric, localuser);
832 localuser->Send(ServerInstance->GetRFCEvents().numeric, numericmsg);
835 void User::WriteRemoteNotice(const std::string& text)
837 ServerInstance->PI->SendUserNotice(this, text);
840 void LocalUser::WriteRemoteNotice(const std::string& text)
847 class WriteCommonRawHandler : public User::ForEachNeighborHandler
849 ClientProtocol::Event& ev;
851 void Execute(LocalUser* user) CXX11_OVERRIDE
857 WriteCommonRawHandler(ClientProtocol::Event& protoev)
864 void User::WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self)
866 WriteCommonRawHandler handler(protoev);
867 ForEachNeighbor(handler, include_self);
870 void User::ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self)
872 // The basic logic for visiting the neighbors of a user is to iterate the channel list of the user
873 // and visit all users on those channels. Because two users may share more than one common channel,
874 // we must skip users that we have already visited.
875 // To do this, we make use of a global counter and an integral 'already_sent' field in LocalUser.
876 // The global counter is incremented every time we do something for each neighbor of a user. Then,
877 // before visiting a member we examine user->already_sent. If it's equal to the current counter, we
878 // skip the member. Otherwise, we set it to the current counter and visit the member.
880 // Ask modules to build a list of exceptions.
881 // Mods may also exclude entire channels by erasing them from include_chans.
882 IncludeChanList include_chans(chans.begin(), chans.end());
883 std::map<User*, bool> exceptions;
884 exceptions[this] = include_self;
885 FOREACH_MOD(OnBuildNeighborList, (this, include_chans, exceptions));
887 // Get next id, guaranteed to differ from the already_sent field of all users
888 const already_sent_t newid = ServerInstance->Users.NextAlreadySentId();
890 // Handle exceptions first
891 for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i)
893 LocalUser* curr = IS_LOCAL(i->first);
896 // Mark as visited to ensure we won't visit again if there is a common channel
897 curr->already_sent = newid;
898 // Always treat quitting users as excluded
899 if ((i->second) && (!curr->quitting))
900 handler.Execute(curr);
904 // Now consider the real neighbors
905 for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i)
907 Channel* chan = (*i)->chan;
908 const Channel::MemberMap& userlist = chan->GetUsers();
909 for (Channel::MemberMap::const_iterator j = userlist.begin(); j != userlist.end(); ++j)
911 LocalUser* curr = IS_LOCAL(j->first);
912 // User not yet visited?
913 if ((curr) && (curr->already_sent != newid))
915 // Mark as visited and execute function
916 curr->already_sent = newid;
917 handler.Execute(curr);
923 void User::WriteRemoteNumeric(const Numeric::Numeric& numeric)
925 WriteNumeric(numeric);
928 /* return 0 or 1 depending if users u and u2 share one or more common channels
929 * (used by QUIT, NICK etc which arent channel specific notices)
931 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
932 * the first users channels then the second users channels within the outer loop,
933 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
934 * all possible iterations). However this new function instead checks against the
935 * channel's userlist in the inner loop which is a std::map<User*,User*>
936 * and saves us time as we already know what pointer value we are after.
937 * Don't quote me on the maths as i am not a mathematician or computer scientist,
938 * but i believe this algorithm is now x+(log y) maximum iterations instead.
940 bool User::SharesChannelWith(User *other)
943 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); ++i)
945 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
946 * by replacing it with a map::find which *should* be more efficient
948 if ((*i)->chan->HasUser(other))
954 bool User::ChangeRealName(const std::string& real)
956 if (!this->realname.compare(real))
961 ModResult MOD_RESULT;
962 FIRST_MOD_RESULT(OnPreChangeRealName, MOD_RESULT, (IS_LOCAL(this), real));
963 if (MOD_RESULT == MOD_RES_DENY)
965 FOREACH_MOD(OnChangeRealName, (this, real));
967 this->realname.assign(real, 0, ServerInstance->Config->Limits.MaxReal);
972 bool User::ChangeDisplayedHost(const std::string& shost)
974 if (GetDisplayedHost() == shost)
977 LocalUser* luser = IS_LOCAL(this);
980 ModResult MOD_RESULT;
981 FIRST_MOD_RESULT(OnPreChangeHost, MOD_RESULT, (luser, shost));
982 if (MOD_RESULT == MOD_RES_DENY)
986 FOREACH_MOD(OnChangeHost, (this,shost));
988 if (realhost == shost)
989 this->displayhost.clear();
991 this->displayhost.assign(shost, 0, ServerInstance->Config->Limits.MaxHost);
993 this->InvalidateCache();
996 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, this->GetDisplayedHost(), "is now your displayed host");
1001 void User::ChangeRealHost(const std::string& host, bool resetdisplay)
1003 // If the real host is the new host and we are not resetting the
1004 // display host then we have nothing to do.
1005 const bool changehost = (realhost != host);
1006 if (!changehost && !resetdisplay)
1009 // If the displayhost is not set and we are not resetting it then
1010 // we need to copy it to the displayhost field.
1011 if (displayhost.empty() && !resetdisplay)
1012 displayhost = realhost;
1014 // If the displayhost is the new host or we are resetting it then
1015 // we clear its contents to save memory.
1016 else if (displayhost == host || resetdisplay)
1017 displayhost.clear();
1019 // If we are just resetting the display host then we don't need to
1020 // do anything else.
1025 this->InvalidateCache();
1028 bool User::ChangeIdent(const std::string& newident)
1030 if (this->ident == newident)
1033 FOREACH_MOD(OnChangeIdent, (this,newident));
1035 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1036 this->InvalidateCache();
1042 * Sets a user's connection class.
1043 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1044 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1045 * then their ip will be taken as 'priority' anyway, so for example,
1046 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1048 void LocalUser::SetClass(const std::string &explicit_name)
1050 ConnectClass *found = NULL;
1052 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1054 if (!explicit_name.empty())
1056 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1058 ConnectClass* c = *i;
1060 if (explicit_name == c->name)
1062 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Explicitly set to %s", explicit_name.c_str());
1069 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1071 ConnectClass* c = *i;
1072 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking %s", c->GetName().c_str());
1074 ModResult MOD_RESULT;
1075 FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1076 if (MOD_RESULT == MOD_RES_DENY)
1078 if (MOD_RESULT == MOD_RES_ALLOW)
1080 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class forced by module to %s", c->GetName().c_str());
1085 if (c->type == CC_NAMED)
1088 bool regdone = (registered != REG_NONE);
1089 if (c->config->getBool("registered", regdone) != regdone)
1092 /* check if host matches.. */
1093 if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1094 !InspIRCd::MatchCIDR(this->GetRealHost(), c->GetHost(), NULL))
1096 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "No host match (for %s)", c->GetHost().c_str());
1101 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1102 * because we should attempt to find another class if this one doesn't match us. -- w00t
1104 if (c->limit && (c->GetReferenceCount() >= c->limit))
1106 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1110 /* if it requires a port ... */
1111 if (!c->ports.empty())
1113 /* and our port doesn't match, fail. */
1114 if (!c->ports.count(this->GetServerPort()))
1116 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Requires a different port, skipping");
1121 if (regdone && !c->config->getString("password").empty())
1123 if (!ServerInstance->PassCompare(this, c->config->getString("password"), password, c->config->getString("hash")))
1125 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Bad password, skipping");
1130 /* we stop at the first class that meets ALL critera. */
1137 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1145 void User::PurgeEmptyChannels()
1147 // firstly decrement the count on each channel
1148 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); )
1150 Channel* c = (*i)->chan;
1158 void User::WriteNotice(const std::string& text)
1160 LocalUser* const localuser = IS_LOCAL(this);
1164 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, localuser, text, MSG_NOTICE);
1165 localuser->Send(ServerInstance->GetRFCEvents().privmsg, msg);
1168 const std::string& FakeUser::GetFullHost()
1170 if (!ServerInstance->Config->HideServer.empty())
1171 return ServerInstance->Config->HideServer;
1172 return server->GetName();
1175 const std::string& FakeUser::GetFullRealHost()
1177 if (!ServerInstance->Config->HideServer.empty())
1178 return ServerInstance->Config->HideServer;
1179 return server->GetName();
1182 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1183 : config(tag), type(t), fakelag(true), name("unnamed"), registration_timeout(0), host(mask),
1184 pingtime(0), softsendqmax(0), hardsendqmax(0), recvqmax(0),
1185 penaltythreshold(0), commandrate(0), maxlocal(0), maxglobal(0), maxconnwarn(true), maxchans(ServerInstance->Config->MaxChans),
1186 limit(0), resolvehostnames(true)
1190 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1197 // Connect classes can inherit from each other but this is problematic for modules which can't use
1198 // ConnectClass::Update so we build a hybrid tag containing all of the values set on this class as
1199 // well as the parent class.
1200 ConfigItems* items = NULL;
1201 config = ConfigTag::create(tag->tag, tag->src_name, tag->src_line, items);
1203 const ConfigItems& parentkeys = parent.config->getItems();
1204 for (ConfigItems::const_iterator piter = parentkeys.begin(); piter != parentkeys.end(); ++piter)
1206 // The class name and parent name are not inherited
1207 if (stdalgo::string::equalsci(piter->first, "name") || stdalgo::string::equalsci(piter->first, "parent"))
1210 // Store the item in the config tag. If this item also
1211 // exists in the child it will be overwritten.
1212 (*items)[piter->first] = piter->second;
1215 const ConfigItems& childkeys = tag->getItems();
1216 for (ConfigItems::const_iterator citer = childkeys.begin(); citer != childkeys.end(); ++citer)
1218 // This will overwrite the parent value if present.
1219 (*items)[citer->first] = citer->second;
1223 void ConnectClass::Update(const ConnectClass* src)
1225 config = src->config;
1227 fakelag = src->fakelag;
1229 registration_timeout = src->registration_timeout;
1231 pingtime = src->pingtime;
1232 softsendqmax = src->softsendqmax;
1233 hardsendqmax = src->hardsendqmax;
1234 recvqmax = src->recvqmax;
1235 penaltythreshold = src->penaltythreshold;
1236 commandrate = src->commandrate;
1237 maxlocal = src->maxlocal;
1238 maxglobal = src->maxglobal;
1239 maxconnwarn = src->maxconnwarn;
1240 maxchans = src->maxchans;
1242 resolvehostnames = src->resolvehostnames;