2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2018 systocrat <systocrat@outlook.com>
6 * Copyright (C) 2018 Dylan Frank <b00mx0r@aureus.pw>
7 * Copyright (C) 2014 satmd <satmd@lain.at>
8 * Copyright (C) 2013-2014, 2016-2019 Sadie Powell <sadie@witchery.services>
9 * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
10 * Copyright (C) 2013 ChrisTX <xpipe@hotmail.de>
11 * Copyright (C) 2013 Adam <Adam@anope.org>
12 * Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
13 * Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
14 * Copyright (C) 2012 DjSlash <djslash@djslash.org>
15 * Copyright (C) 2011 jackmcbarn <jackmcbarn@inspircd.org>
16 * Copyright (C) 2009-2011 Daniel De Graaf <danieldg@inspircd.org>
17 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
18 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
19 * Copyright (C) 2008 John Brooks <special@inspircd.org>
20 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
21 * Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
22 * Copyright (C) 2006-2009 Craig Edwards <brain@inspircd.org>
24 * This file is part of InspIRCd. InspIRCd is free software: you can
25 * redistribute it and/or modify it under the terms of the GNU General Public
26 * License as published by the Free Software Foundation, version 2.
28 * This program is distributed in the hope that it will be useful, but WITHOUT
29 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
30 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
33 * You should have received a copy of the GNU General Public License
34 * along with this program. If not, see <http://www.gnu.org/licenses/>.
41 ClientProtocol::MessageList LocalUser::sendmsglist;
43 bool User::IsNoticeMaskSet(unsigned char sm)
47 return (snomasks[sm-65]);
50 bool User::IsModeSet(unsigned char m) const
52 ModeHandler* mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
53 return (mh && modes[mh->GetId()]);
56 std::string User::GetModeLetters(bool includeparams) const
58 std::string ret(1, '+');
61 for (unsigned char i = 'A'; i <= 'z'; i++)
63 const ModeHandler* const mh = ServerInstance->Modes.FindMode(i, MODETYPE_USER);
64 if ((!mh) || (!IsModeSet(mh)))
67 ret.push_back(mh->GetModeChar());
68 if ((includeparams) && (mh->NeedsParam(true)))
70 const std::string val = mh->GetUserParameter(this);
72 params.append(1, ' ').append(val);
80 User::User(const std::string& uid, Server* srv, UserType type)
81 : age(ServerInstance->Time())
85 , registered(REG_NONE)
89 client_sa.sa.sa_family = AF_UNSPEC;
91 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New UUID for user: %s", uuid.c_str());
94 ServerInstance->Users.all_ulines.push_back(this);
96 // Do not insert FakeUsers into the uuidlist so FindUUID() won't return them which is the desired behavior
97 if (type != USERTYPE_SERVER)
99 if (!ServerInstance->Users.uuidlist.insert(std::make_pair(uuid, this)).second)
100 throw CoreException("Duplicate UUID in User constructor: " + uuid);
104 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
105 : User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL)
112 , quitting_sendq(false)
117 , CommandFloodPenalty(0)
120 signon = ServerInstance->Time();
121 // The user's default nick is their UUID
125 memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
126 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
127 ChangeRealHost(GetIPString(), true);
130 LocalUser::LocalUser(int myfd, const std::string& uid, Serializable::Data& data)
131 : User(uid, ServerInstance->FakeClient->server, USERTYPE_LOCAL)
143 const std::string& User::MakeHost()
145 if (!this->cached_makehost.empty())
146 return this->cached_makehost;
148 this->cached_makehost = ident + "@" + GetRealHost();
149 return this->cached_makehost;
152 const std::string& User::MakeHostIP()
154 if (!this->cached_hostip.empty())
155 return this->cached_hostip;
157 this->cached_hostip = ident + "@" + this->GetIPString();
158 return this->cached_hostip;
161 const std::string& User::GetFullHost()
163 if (!this->cached_fullhost.empty())
164 return this->cached_fullhost;
166 this->cached_fullhost = nick + "!" + ident + "@" + GetDisplayedHost();
167 return this->cached_fullhost;
170 const std::string& User::GetFullRealHost()
172 if (!this->cached_fullrealhost.empty())
173 return this->cached_fullrealhost;
175 this->cached_fullrealhost = nick + "!" + ident + "@" + GetRealHost();
176 return this->cached_fullrealhost;
179 bool User::HasModePermission(const ModeHandler* mh) const
184 bool LocalUser::HasModePermission(const ModeHandler* mh) const
189 const unsigned char mode = mh->GetModeChar();
190 if (!ModeParser::IsModeChar(mode))
193 return ((mh->GetModeType() == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
197 * users on remote servers can completely bypass all permissions based checks.
198 * This prevents desyncs when one server has different type/class tags to another.
199 * That having been said, this does open things up to the possibility of source changes
200 * allowing remote kills, etc - but if they have access to the src, they most likely have
201 * access to the conf - so it's an end to a means either way.
203 bool User::HasCommandPermission(const std::string&)
208 bool LocalUser::HasCommandPermission(const std::string& command)
210 // are they even an oper at all?
216 return oper->AllowedOperCommands.Contains(command);
219 bool User::HasPrivPermission(const std::string& privstr)
224 bool LocalUser::HasPrivPermission(const std::string& privstr)
229 return oper->AllowedPrivs.Contains(privstr);
232 void UserIOHandler::OnDataReady()
237 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
239 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
240 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
241 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
245 unsigned long sendqmax = ULONG_MAX;
246 if (!user->HasPrivPermission("users/flood/increased-buffers"))
247 sendqmax = user->MyClass->GetSendqSoftMax();
249 unsigned long penaltymax = ULONG_MAX;
250 if (!user->HasPrivPermission("users/flood/no-fakelag"))
251 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
253 // The cleaned message sent by the user or empty if not found yet.
256 // The position of the most \n character or npos if not found yet.
257 std::string::size_type eolpos;
259 // The position within the recvq of the current character.
260 std::string::size_type qpos;
262 while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
264 // Check the newly received data for an EOL.
265 eolpos = recvq.find('\n', checked_until);
266 if (eolpos == std::string::npos)
268 checked_until = recvq.length();
272 // We've found a line! Clean it up and move it to the line buffer.
273 line.reserve(eolpos);
274 for (qpos = 0; qpos < eolpos; ++qpos)
276 char c = recvq[qpos];
289 // just found a newline. Terminate the string, and pull it out of recvq
290 recvq.erase(0, eolpos + 1);
293 // TODO should this be moved to when it was inserted in recvq?
294 ServerInstance->stats.Recv += qpos;
295 user->bytes_in += qpos;
298 ServerInstance->Parser.ProcessBuffer(user, line);
302 // clear() does not reclaim memory associated with the string, so our .reserve() call is safe
306 if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
307 ServerInstance->Users->QuitUser(user, "Excess Flood");
310 void UserIOHandler::AddWriteBuf(const std::string &data)
312 if (user->quitting_sendq)
314 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
315 !user->HasPrivPermission("users/flood/increased-buffers"))
317 user->quitting_sendq = true;
318 ServerInstance->GlobalCulls.AddSQItem(user);
322 // We still want to append data to the sendq of a quitting user,
323 // e.g. their ERROR message that says 'closing link'
328 void UserIOHandler::SwapInternals(UserIOHandler& other)
330 StreamSocket::SwapInternals(other);
331 std::swap(checked_until, other.checked_until);
334 bool UserIOHandler::OnSetEndPoint(const irc::sockets::sockaddrs& server, const irc::sockets::sockaddrs& client)
336 memcpy(&user->server_sa, &server, sizeof(irc::sockets::sockaddrs));
337 user->SetClientIP(client);
338 return !user->quitting;
341 void UserIOHandler::OnError(BufferedSocketError sockerr)
344 FIRST_MOD_RESULT(OnConnectionFail, res, (user, sockerr));
345 if (res != MOD_RES_ALLOW)
346 ServerInstance->Users->QuitUser(user, getError());
349 CullResult User::cull()
352 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
354 if (client_sa.family() != AF_UNSPEC)
355 ServerInstance->Users->RemoveCloneCounts(this);
357 if (server->IsULine())
358 stdalgo::erase(ServerInstance->Users->all_ulines, this);
360 return Extensible::cull();
363 CullResult LocalUser::cull()
369 CullResult FakeUser::cull()
371 // Fake users don't quit, they just get culled.
373 // Fake users are not inserted into UserManager::clientlist or uuidlist, so we don't need to modify those here
377 void User::Oper(OperInfo* info)
379 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
382 if (this->IsModeSet(opermh))
384 this->SetMode(opermh, true);
388 LocalUser* localuser = IS_LOCAL(this);
391 Modes::ChangeList changelist;
392 changelist.push_add(opermh);
393 ClientProtocol::Events::Mode modemsg(ServerInstance->FakeClient, NULL, localuser, changelist);
394 localuser->Send(modemsg);
397 FOREACH_MOD(OnOper, (this, info->name));
399 std::string opername;
400 if (info->oper_block)
401 opername = info->oper_block->getString("name");
403 ServerInstance->SNO->WriteToSnoMask('o', "%s (%s@%s) is now a server operator of type %s (using oper '%s')",
404 nick.c_str(), ident.c_str(), GetRealHost().c_str(), oper->name.c_str(), opername.c_str());
405 this->WriteNumeric(RPL_YOUAREOPER, InspIRCd::Format("You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str()));
407 ServerInstance->Users->all_opers.push_back(this);
409 // Expand permissions from config for faster lookup
413 FOREACH_MOD(OnPostOper, (this, oper->name, opername));
416 void OperInfo::init()
418 AllowedOperCommands.Clear();
419 AllowedPrivs.Clear();
420 AllowedUserModes.reset();
421 AllowedChanModes.reset();
422 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
424 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
426 ConfigTag* tag = *iter;
428 AllowedOperCommands.AddList(tag->getString("commands"));
429 AllowedPrivs.AddList(tag->getString("privs"));
431 std::string modes = tag->getString("usermodes");
432 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
436 this->AllowedUserModes.set();
438 else if (*c >= 'A' && *c <= 'z')
440 this->AllowedUserModes[*c - 'A'] = true;
444 modes = tag->getString("chanmodes");
445 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
449 this->AllowedChanModes.set();
451 else if (*c >= 'A' && *c <= 'z')
453 this->AllowedChanModes[*c - 'A'] = true;
465 * unset their oper type (what IS_OPER checks).
466 * note, order is important - this must come before modes as -o attempts
467 * to call UnOper. -- w00t
471 // Remove the user from the oper list
472 stdalgo::vector::swaperase(ServerInstance->Users->all_opers, this);
474 // If the user is quitting we shouldn't remove any modes as it results in
475 // mode messages being broadcast across the network.
479 /* Remove all oper only modes from the user when the deoper - Bug #466*/
480 Modes::ChangeList changelist;
481 const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
482 for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); ++i)
484 ModeHandler* mh = i->second;
486 changelist.push_remove(mh);
489 ServerInstance->Modes->Process(this, NULL, this, changelist);
491 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
493 this->SetMode(opermh, false);
494 FOREACH_MOD(OnPostDeoper, (this));
498 * Check class restrictions
500 void LocalUser::CheckClass(bool clone_count)
502 ConnectClass* a = this->MyClass;
506 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
509 else if (a->type == CC_DENY)
511 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection", 1));
514 else if (clone_count)
516 const UserManager::CloneCounts& clonecounts = ServerInstance->Users->GetCloneCounts(this);
517 if ((a->GetMaxLocal()) && (clonecounts.local > a->GetMaxLocal()))
519 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
522 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum local connections for the %s class (%ld) exceeded by %s",
523 a->name.c_str(), a->GetMaxLocal(), this->GetIPString().c_str());
527 else if ((a->GetMaxGlobal()) && (clonecounts.global > a->GetMaxGlobal()))
529 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
532 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum global connections for the %s class (%ld) exceeded by %s",
533 a->name.c_str(), a->GetMaxGlobal(), this->GetIPString().c_str());
539 this->nextping = ServerInstance->Time() + a->GetPingTime();
542 bool LocalUser::CheckLines(bool doZline)
544 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
548 for (int n = 0; check[n]; ++n)
550 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
563 void LocalUser::FullConnect()
565 ServerInstance->stats.Connects++;
566 this->idle_lastmsg = ServerInstance->Time();
569 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
570 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
571 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
572 * Don't remove this! -- w00t
583 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
584 * for a user that doesn't exist yet.
586 FOREACH_MOD(OnUserConnect, (this));
589 if (ServerInstance->Users->unregistered_count)
590 ServerInstance->Users->unregistered_count--;
591 this->registered = REG_ALL;
593 FOREACH_MOD(OnPostConnect, (this));
595 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
596 this->server_sa.port(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->GetRealName().c_str());
597 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
598 ServerInstance->BanCache.AddHit(this->GetIPString(), "", "");
599 // reset the flood penalty (which could have been raised due to things like auto +x)
600 CommandFloodPenalty = 0;
603 void User::InvalidateCache()
605 /* Invalidate cache */
607 cached_fullhost.clear();
608 cached_hostip.clear();
609 cached_makehost.clear();
610 cached_fullrealhost.clear();
613 bool User::ChangeNick(const std::string& newnick, time_t newts)
617 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
621 User* const InUse = ServerInstance->FindNickOnly(newnick);
624 // case change, don't need to check campers
625 // and, if it's identical including case, we can leave right now
626 // We also don't update the nick TS if it's a case change, either
633 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
634 * then we have a potential collide. Check whether someone else is camping on the nick
635 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
636 * camper to their UID, and allow the incoming nick change.
638 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
639 * because the nick is already (rightfully) in use. -- w00t
643 if (InUse->registered != REG_ALL)
645 /* force the camper to their UUID, and ask them to re-send a NICK. */
646 LocalUser* const localuser = static_cast<LocalUser*>(InUse);
647 localuser->OverruleNick();
651 /* No camping, tell the incoming user to stop trying to change nick ;p */
652 this->WriteNumeric(ERR_NICKNAMEINUSE, newnick, "Nickname is already in use.");
657 age = newts ? newts : ServerInstance->Time();
660 if (this->registered == REG_ALL)
662 ClientProtocol::Messages::Nick nickmsg(this, newnick);
663 ClientProtocol::Event nickevent(ServerInstance->GetRFCEvents().nick, nickmsg);
664 this->WriteCommonRaw(nickevent, true);
666 const std::string oldnick = nick;
670 ServerInstance->Users->clientlist.erase(oldnick);
671 ServerInstance->Users->clientlist[newnick] = this;
673 if (registered == REG_ALL)
674 FOREACH_MOD(OnUserPostNick, (this,oldnick));
679 void LocalUser::OverruleNick()
682 ClientProtocol::Messages::Nick nickmsg(this, this->uuid);
683 this->Send(ServerInstance->GetRFCEvents().nick, nickmsg);
685 this->WriteNumeric(ERR_NICKNAMEINUSE, this->nick, "Nickname overruled.");
687 // Clear the bit before calling ChangeNick() to make it NOT run the OnUserPostNick() hook
688 this->registered &= ~REG_NICK;
689 this->ChangeNick(this->uuid);
692 const std::string& User::GetIPString()
694 if (cachedip.empty())
696 cachedip = client_sa.addr();
697 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
698 if (cachedip[0] == ':')
699 cachedip.insert(cachedip.begin(),1,'0');
705 const std::string& User::GetHost(bool uncloak) const
707 return uncloak ? GetRealHost() : GetDisplayedHost();
710 const std::string& User::GetDisplayedHost() const
712 return displayhost.empty() ? realhost : displayhost;
715 const std::string& User::GetRealHost() const
720 const std::string& User::GetRealName() const
725 irc::sockets::cidr_mask User::GetCIDRMask()
727 unsigned char range = 0;
728 switch (client_sa.family())
731 range = ServerInstance->Config->c_ipv6_range;
734 range = ServerInstance->Config->c_ipv4_range;
737 return irc::sockets::cidr_mask(client_sa, range);
740 bool User::SetClientIP(const std::string& address)
742 irc::sockets::sockaddrs sa;
743 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
746 User::SetClientIP(sa);
750 void User::SetClientIP(const irc::sockets::sockaddrs& sa)
752 const std::string oldip(GetIPString());
753 memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
754 this->InvalidateCache();
756 // If the users hostname was their IP then update it.
757 if (GetRealHost() == oldip)
758 ChangeRealHost(GetIPString(), false);
759 if (GetDisplayedHost() == oldip)
760 ChangeDisplayedHost(GetIPString());
763 bool LocalUser::SetClientIP(const std::string& address)
765 irc::sockets::sockaddrs sa;
766 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
769 LocalUser::SetClientIP(sa);
773 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa)
778 ServerInstance->Users->RemoveCloneCounts(this);
779 User::SetClientIP(sa);
780 ServerInstance->Users->AddClone(this);
782 // Recheck the connect class.
783 this->MyClass = NULL;
788 FOREACH_MOD(OnSetUserIP, (this));
791 void LocalUser::Write(const ClientProtocol::SerializedMessage& text)
793 if (!SocketEngine::BoundsCheckFd(&eh))
796 if (ServerInstance->Config->RawLog)
801 std::string::size_type nlpos = text.find_first_of("\r\n", 0, 2);
802 if (nlpos == std::string::npos)
803 nlpos = text.length(); // TODO is this ok, test it
805 ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %.*s", uuid.c_str(), (int) nlpos, text.c_str());
808 eh.AddWriteBuf(text);
810 const size_t bytessent = text.length() + 2;
811 ServerInstance->stats.Sent += bytessent;
812 this->bytes_out += bytessent;
816 void LocalUser::Send(ClientProtocol::Event& protoev)
820 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "BUG: LocalUser::Send() called on %s who does not have a serializer!",
821 GetFullRealHost().c_str());
825 // In the most common case a static LocalUser field, sendmsglist, is passed to the event to be
826 // populated. The list is cleared before returning.
827 // To handle re-enters, if sendmsglist is non-empty upon entering the method then a temporary
828 // list is used instead of the static one.
829 if (sendmsglist.empty())
831 Send(protoev, sendmsglist);
836 ClientProtocol::MessageList msglist;
837 Send(protoev, msglist);
841 void LocalUser::Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist)
843 // Modules can personalize the messages sent per user for the event
844 protoev.GetMessagesForUser(this, msglist);
845 for (ClientProtocol::MessageList::const_iterator i = msglist.begin(); i != msglist.end(); ++i)
847 ClientProtocol::Message& curr = **i;
849 FIRST_MOD_RESULT(OnUserWrite, res, (this, curr));
850 if (res != MOD_RES_DENY)
851 Write(serializer->SerializeForUser(this, curr));
855 void User::WriteNumeric(const Numeric::Numeric& numeric)
857 LocalUser* const localuser = IS_LOCAL(this);
861 ModResult MOD_RESULT;
863 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric));
865 if (MOD_RESULT == MOD_RES_DENY)
868 ClientProtocol::Messages::Numeric numericmsg(numeric, localuser);
869 localuser->Send(ServerInstance->GetRFCEvents().numeric, numericmsg);
872 void User::WriteRemoteNotice(const std::string& text)
874 ServerInstance->PI->SendMessage(this, text, MSG_NOTICE);
877 void LocalUser::WriteRemoteNotice(const std::string& text)
884 class WriteCommonRawHandler : public User::ForEachNeighborHandler
886 ClientProtocol::Event& ev;
888 void Execute(LocalUser* user) CXX11_OVERRIDE
894 WriteCommonRawHandler(ClientProtocol::Event& protoev)
901 void User::WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self)
903 WriteCommonRawHandler handler(protoev);
904 ForEachNeighbor(handler, include_self);
907 void User::ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self)
909 // The basic logic for visiting the neighbors of a user is to iterate the channel list of the user
910 // and visit all users on those channels. Because two users may share more than one common channel,
911 // we must skip users that we have already visited.
912 // To do this, we make use of a global counter and an integral 'already_sent' field in LocalUser.
913 // The global counter is incremented every time we do something for each neighbor of a user. Then,
914 // before visiting a member we examine user->already_sent. If it's equal to the current counter, we
915 // skip the member. Otherwise, we set it to the current counter and visit the member.
917 // Ask modules to build a list of exceptions.
918 // Mods may also exclude entire channels by erasing them from include_chans.
919 IncludeChanList include_chans(chans.begin(), chans.end());
920 std::map<User*, bool> exceptions;
921 exceptions[this] = include_self;
922 FOREACH_MOD(OnBuildNeighborList, (this, include_chans, exceptions));
924 // Get next id, guaranteed to differ from the already_sent field of all users
925 const already_sent_t newid = ServerInstance->Users.NextAlreadySentId();
927 // Handle exceptions first
928 for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i)
930 LocalUser* curr = IS_LOCAL(i->first);
933 // Mark as visited to ensure we won't visit again if there is a common channel
934 curr->already_sent = newid;
935 // Always treat quitting users as excluded
936 if ((i->second) && (!curr->quitting))
937 handler.Execute(curr);
941 // Now consider the real neighbors
942 for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i)
944 Channel* chan = (*i)->chan;
945 const Channel::MemberMap& userlist = chan->GetUsers();
946 for (Channel::MemberMap::const_iterator j = userlist.begin(); j != userlist.end(); ++j)
948 LocalUser* curr = IS_LOCAL(j->first);
949 // User not yet visited?
950 if ((curr) && (curr->already_sent != newid))
952 // Mark as visited and execute function
953 curr->already_sent = newid;
954 handler.Execute(curr);
960 void User::WriteRemoteNumeric(const Numeric::Numeric& numeric)
962 WriteNumeric(numeric);
965 /* return 0 or 1 depending if users u and u2 share one or more common channels
966 * (used by QUIT, NICK etc which arent channel specific notices)
968 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
969 * the first users channels then the second users channels within the outer loop,
970 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
971 * all possible iterations). However this new function instead checks against the
972 * channel's userlist in the inner loop which is a std::map<User*,User*>
973 * and saves us time as we already know what pointer value we are after.
974 * Don't quote me on the maths as i am not a mathematician or computer scientist,
975 * but i believe this algorithm is now x+(log y) maximum iterations instead.
977 bool User::SharesChannelWith(User *other)
980 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); ++i)
982 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
983 * by replacing it with a map::find which *should* be more efficient
985 if ((*i)->chan->HasUser(other))
991 bool User::ChangeRealName(const std::string& real)
993 if (!this->realname.compare(real))
998 ModResult MOD_RESULT;
999 FIRST_MOD_RESULT(OnPreChangeRealName, MOD_RESULT, (IS_LOCAL(this), real));
1000 if (MOD_RESULT == MOD_RES_DENY)
1002 FOREACH_MOD(OnChangeRealName, (this, real));
1004 this->realname.assign(real, 0, ServerInstance->Config->Limits.MaxReal);
1009 bool User::ChangeDisplayedHost(const std::string& shost)
1011 if (GetDisplayedHost() == shost)
1014 LocalUser* luser = IS_LOCAL(this);
1017 ModResult MOD_RESULT;
1018 FIRST_MOD_RESULT(OnPreChangeHost, MOD_RESULT, (luser, shost));
1019 if (MOD_RESULT == MOD_RES_DENY)
1023 FOREACH_MOD(OnChangeHost, (this,shost));
1025 if (realhost == shost)
1026 this->displayhost.clear();
1028 this->displayhost.assign(shost, 0, ServerInstance->Config->Limits.MaxHost);
1030 this->InvalidateCache();
1032 if (IS_LOCAL(this) && this->registered != REG_NONE)
1033 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, this->GetDisplayedHost(), "is now your displayed host");
1038 void User::ChangeRealHost(const std::string& host, bool resetdisplay)
1040 // If the real host is the new host and we are not resetting the
1041 // display host then we have nothing to do.
1042 const bool changehost = (realhost != host);
1043 if (!changehost && !resetdisplay)
1046 // If the displayhost is not set and we are not resetting it then
1047 // we need to copy it to the displayhost field.
1048 if (displayhost.empty() && !resetdisplay)
1049 displayhost = realhost;
1051 // If the displayhost is the new host or we are resetting it then
1052 // we clear its contents to save memory.
1053 else if (displayhost == host || resetdisplay)
1054 displayhost.clear();
1056 // If we are just resetting the display host then we don't need to
1057 // do anything else.
1062 this->InvalidateCache();
1065 bool User::ChangeIdent(const std::string& newident)
1067 if (this->ident == newident)
1070 FOREACH_MOD(OnChangeIdent, (this,newident));
1072 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1073 this->InvalidateCache();
1079 * Sets a user's connection class.
1080 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1081 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1082 * then their ip will be taken as 'priority' anyway, so for example,
1083 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1085 void LocalUser::SetClass(const std::string &explicit_name)
1087 ConnectClass *found = NULL;
1089 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1091 if (!explicit_name.empty())
1093 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1095 ConnectClass* c = *i;
1097 if (explicit_name == c->name)
1099 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Explicitly set to %s", explicit_name.c_str());
1106 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1108 ConnectClass* c = *i;
1109 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking %s", c->GetName().c_str());
1111 ModResult MOD_RESULT;
1112 FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1113 if (MOD_RESULT == MOD_RES_DENY)
1115 if (MOD_RESULT == MOD_RES_ALLOW)
1117 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class forced by module to %s", c->GetName().c_str());
1122 if (c->type == CC_NAMED)
1125 bool regdone = (registered != REG_NONE);
1126 if (c->config->getBool("registered", regdone) != regdone)
1129 /* check if host matches.. */
1130 if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1131 !InspIRCd::MatchCIDR(this->GetRealHost(), c->GetHost(), NULL))
1133 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "No host match (for %s)", c->GetHost().c_str());
1138 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1139 * because we should attempt to find another class if this one doesn't match us. -- w00t
1141 if (c->limit && (c->GetReferenceCount() >= c->limit))
1143 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1147 /* if it requires a port ... */
1148 if (!c->ports.empty())
1150 /* and our port doesn't match, fail. */
1151 if (!c->ports.count(this->server_sa.port()))
1153 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Requires a different port, skipping");
1158 if (regdone && !c->password.empty())
1160 if (!ServerInstance->PassCompare(this, c->password, password, c->passwordhash))
1162 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Bad password, skipping");
1167 /* we stop at the first class that meets ALL critera. */
1174 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1182 void User::PurgeEmptyChannels()
1184 // firstly decrement the count on each channel
1185 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); )
1187 Channel* c = (*i)->chan;
1193 void User::WriteNotice(const std::string& text)
1195 LocalUser* const localuser = IS_LOCAL(this);
1199 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, localuser, text, MSG_NOTICE);
1200 localuser->Send(ServerInstance->GetRFCEvents().privmsg, msg);
1203 const std::string& FakeUser::GetFullHost()
1205 if (!ServerInstance->Config->HideServer.empty())
1206 return ServerInstance->Config->HideServer;
1207 return server->GetName();
1210 const std::string& FakeUser::GetFullRealHost()
1212 if (!ServerInstance->Config->HideServer.empty())
1213 return ServerInstance->Config->HideServer;
1214 return server->GetName();
1217 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1222 , registration_timeout(0)
1228 , penaltythreshold(0)
1235 , resolvehostnames(true)
1239 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1246 // Connect classes can inherit from each other but this is problematic for modules which can't use
1247 // ConnectClass::Update so we build a hybrid tag containing all of the values set on this class as
1248 // well as the parent class.
1249 ConfigItems* items = NULL;
1250 config = ConfigTag::create(tag->tag, tag->src_name, tag->src_line, items);
1252 const ConfigItems& parentkeys = parent.config->getItems();
1253 for (ConfigItems::const_iterator piter = parentkeys.begin(); piter != parentkeys.end(); ++piter)
1255 // The class name and parent name are not inherited
1256 if (stdalgo::string::equalsci(piter->first, "name") || stdalgo::string::equalsci(piter->first, "parent"))
1259 // Store the item in the config tag. If this item also
1260 // exists in the child it will be overwritten.
1261 (*items)[piter->first] = piter->second;
1264 const ConfigItems& childkeys = tag->getItems();
1265 for (ConfigItems::const_iterator citer = childkeys.begin(); citer != childkeys.end(); ++citer)
1267 // This will overwrite the parent value if present.
1268 (*items)[citer->first] = citer->second;
1272 void ConnectClass::Update(const ConnectClass* src)
1274 config = src->config;
1276 fakelag = src->fakelag;
1278 registration_timeout = src->registration_timeout;
1280 pingtime = src->pingtime;
1281 softsendqmax = src->softsendqmax;
1282 hardsendqmax = src->hardsendqmax;
1283 recvqmax = src->recvqmax;
1284 penaltythreshold = src->penaltythreshold;
1285 commandrate = src->commandrate;
1286 maxlocal = src->maxlocal;
1287 maxglobal = src->maxglobal;
1288 maxconnwarn = src->maxconnwarn;
1289 maxchans = src->maxchans;
1291 resolvehostnames = src->resolvehostnames;
1293 password = src->password;
1294 passwordhash = src->passwordhash;