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) 2013, 2016-2020 Sadie Powell <sadie@witchery.services>
8 * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
9 * Copyright (C) 2013 ChrisTX <xpipe@hotmail.de>
10 * Copyright (C) 2013 Adam <Adam@anope.org>
11 * Copyright (C) 2012-2016, 2018 Attila Molnar <attilamolnar@hush.com>
12 * Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
13 * Copyright (C) 2012 DjSlash <djslash@djslash.org>
14 * Copyright (C) 2011 jackmcbarn <jackmcbarn@inspircd.org>
15 * Copyright (C) 2009-2011 Daniel De Graaf <danieldg@inspircd.org>
16 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
17 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
18 * Copyright (C) 2008 John Brooks <special@inspircd.org>
19 * Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
20 * Copyright (C) 2007, 2009 Dennis Friis <peavey@inspircd.org>
21 * Copyright (C) 2006-2009 Craig Edwards <brain@inspircd.org>
23 * This file is part of InspIRCd. InspIRCd is free software: you can
24 * redistribute it and/or modify it under the terms of the GNU General Public
25 * License as published by the Free Software Foundation, version 2.
27 * This program is distributed in the hope that it will be useful, but WITHOUT
28 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
29 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
32 * You should have received a copy of the GNU General Public License
33 * along with this program. If not, see <http://www.gnu.org/licenses/>.
40 ClientProtocol::MessageList LocalUser::sendmsglist;
42 bool User::IsNoticeMaskSet(unsigned char sm)
46 return (snomasks[sm-65]);
49 bool User::IsModeSet(unsigned char m) const
51 ModeHandler* mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
52 return (mh && modes[mh->GetId()]);
55 std::string User::GetModeLetters(bool includeparams) const
57 std::string ret(1, '+');
60 for (unsigned char i = 'A'; i <= 'z'; i++)
62 const ModeHandler* const mh = ServerInstance->Modes.FindMode(i, MODETYPE_USER);
63 if ((!mh) || (!IsModeSet(mh)))
66 ret.push_back(mh->GetModeChar());
67 if ((includeparams) && (mh->NeedsParam(true)))
69 const std::string val = mh->GetUserParameter(this);
71 params.append(1, ' ').append(val);
79 User::User(const std::string& uid, Server* srv, UserType type)
80 : age(ServerInstance->Time())
84 , registered(REG_NONE)
88 client_sa.sa.sa_family = AF_UNSPEC;
90 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New UUID for user: %s", uuid.c_str());
93 ServerInstance->Users.all_ulines.push_back(this);
95 // Do not insert FakeUsers into the uuidlist so FindUUID() won't return them which is the desired behavior
96 if (type != USERTYPE_SERVER)
98 if (!ServerInstance->Users.uuidlist.insert(std::make_pair(uuid, this)).second)
99 throw CoreException("Duplicate UUID in User constructor: " + uuid);
103 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
104 : User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL)
111 , quitting_sendq(false)
116 , CommandFloodPenalty(0)
119 signon = ServerInstance->Time();
120 // The user's default nick is their UUID
124 memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
125 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
126 ChangeRealHost(GetIPString(), true);
129 LocalUser::LocalUser(int myfd, const std::string& uid, Serializable::Data& data)
130 : User(uid, ServerInstance->FakeClient->server, USERTYPE_LOCAL)
142 const std::string& User::MakeHost()
144 if (!this->cached_makehost.empty())
145 return this->cached_makehost;
147 this->cached_makehost = ident + "@" + GetRealHost();
148 return this->cached_makehost;
151 const std::string& User::MakeHostIP()
153 if (!this->cached_hostip.empty())
154 return this->cached_hostip;
156 this->cached_hostip = ident + "@" + this->GetIPString();
157 return this->cached_hostip;
160 const std::string& User::GetFullHost()
162 if (!this->cached_fullhost.empty())
163 return this->cached_fullhost;
165 this->cached_fullhost = nick + "!" + ident + "@" + GetDisplayedHost();
166 return this->cached_fullhost;
169 const std::string& User::GetFullRealHost()
171 if (!this->cached_fullrealhost.empty())
172 return this->cached_fullrealhost;
174 this->cached_fullrealhost = nick + "!" + ident + "@" + GetRealHost();
175 return this->cached_fullrealhost;
178 bool User::HasModePermission(const ModeHandler* mh) const
183 bool LocalUser::HasModePermission(const ModeHandler* mh) const
188 const unsigned char mode = mh->GetModeChar();
189 if (!ModeParser::IsModeChar(mode))
192 return ((mh->GetModeType() == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
196 * users on remote servers can completely bypass all permissions based checks.
197 * This prevents desyncs when one server has different type/class tags to another.
198 * That having been said, this does open things up to the possibility of source changes
199 * allowing remote kills, etc - but if they have access to the src, they most likely have
200 * access to the conf - so it's an end to a means either way.
202 bool User::HasCommandPermission(const std::string&)
207 bool LocalUser::HasCommandPermission(const std::string& command)
209 // are they even an oper at all?
215 return oper->AllowedOperCommands.Contains(command);
218 bool User::HasPrivPermission(const std::string& privstr)
223 bool LocalUser::HasPrivPermission(const std::string& privstr)
228 return oper->AllowedPrivs.Contains(privstr);
231 bool User::HasSnomaskPermission(char chr) const
236 bool LocalUser::HasSnomaskPermission(char chr) const
238 if (!this->IsOper() || !ModeParser::IsModeChar(chr))
241 return this->oper->AllowedSnomasks[chr - 'A'];
244 void UserIOHandler::OnDataReady()
249 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
251 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
252 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
253 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
257 unsigned long sendqmax = ULONG_MAX;
258 if (!user->HasPrivPermission("users/flood/increased-buffers"))
259 sendqmax = user->MyClass->GetSendqSoftMax();
261 unsigned long penaltymax = ULONG_MAX;
262 if (!user->HasPrivPermission("users/flood/no-fakelag"))
263 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
265 // The cleaned message sent by the user or empty if not found yet.
268 // The position of the most \n character or npos if not found yet.
269 std::string::size_type eolpos;
271 // The position within the recvq of the current character.
272 std::string::size_type qpos;
274 while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
276 // Check the newly received data for an EOL.
277 eolpos = recvq.find('\n', checked_until);
278 if (eolpos == std::string::npos)
280 checked_until = recvq.length();
284 // We've found a line! Clean it up and move it to the line buffer.
285 line.reserve(eolpos);
286 for (qpos = 0; qpos < eolpos; ++qpos)
288 char c = recvq[qpos];
301 // just found a newline. Terminate the string, and pull it out of recvq
302 recvq.erase(0, eolpos + 1);
305 // TODO should this be moved to when it was inserted in recvq?
306 ServerInstance->stats.Recv += qpos;
307 user->bytes_in += qpos;
310 ServerInstance->Parser.ProcessBuffer(user, line);
314 // clear() does not reclaim memory associated with the string, so our .reserve() call is safe
318 if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
319 ServerInstance->Users->QuitUser(user, "Excess Flood");
322 void UserIOHandler::AddWriteBuf(const std::string &data)
324 if (user->quitting_sendq)
326 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
327 !user->HasPrivPermission("users/flood/increased-buffers"))
329 user->quitting_sendq = true;
330 ServerInstance->GlobalCulls.AddSQItem(user);
334 // We still want to append data to the sendq of a quitting user,
335 // e.g. their ERROR message that says 'closing link'
340 void UserIOHandler::SwapInternals(UserIOHandler& other)
342 StreamSocket::SwapInternals(other);
343 std::swap(checked_until, other.checked_until);
346 bool UserIOHandler::OnSetEndPoint(const irc::sockets::sockaddrs& server, const irc::sockets::sockaddrs& client)
348 memcpy(&user->server_sa, &server, sizeof(irc::sockets::sockaddrs));
349 user->SetClientIP(client);
350 return !user->quitting;
353 void UserIOHandler::OnError(BufferedSocketError sockerr)
356 FIRST_MOD_RESULT(OnConnectionFail, res, (user, sockerr));
357 if (res != MOD_RES_ALLOW)
358 ServerInstance->Users->QuitUser(user, getError());
361 CullResult User::cull()
364 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
366 if (client_sa.family() != AF_UNSPEC)
367 ServerInstance->Users->RemoveCloneCounts(this);
369 if (server->IsULine())
370 stdalgo::erase(ServerInstance->Users->all_ulines, this);
372 return Extensible::cull();
375 CullResult LocalUser::cull()
381 CullResult FakeUser::cull()
383 // Fake users don't quit, they just get culled.
385 // Fake users are not inserted into UserManager::clientlist or uuidlist, so we don't need to modify those here
389 void User::Oper(OperInfo* info)
391 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
394 if (this->IsModeSet(opermh))
396 this->SetMode(opermh, true);
400 LocalUser* localuser = IS_LOCAL(this);
403 Modes::ChangeList changelist;
404 changelist.push_add(opermh);
405 ClientProtocol::Events::Mode modemsg(ServerInstance->FakeClient, NULL, localuser, changelist);
406 localuser->Send(modemsg);
409 FOREACH_MOD(OnOper, (this, info->name));
411 std::string opername;
412 if (info->oper_block)
413 opername = info->oper_block->getString("name");
415 ServerInstance->SNO->WriteToSnoMask('o', "%s (%s@%s) is now a server operator of type %s (using oper '%s')",
416 nick.c_str(), ident.c_str(), GetRealHost().c_str(), oper->name.c_str(), opername.c_str());
417 this->WriteNumeric(RPL_YOUAREOPER, InspIRCd::Format("You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str()));
419 ServerInstance->Users->all_opers.push_back(this);
421 // Expand permissions from config for faster lookup
425 FOREACH_MOD(OnPostOper, (this, oper->name, opername));
430 bool ParseModeList(std::bitset<64>& modeset, ConfigTag* tag, const std::string& field)
433 bool hasmodes = tag->readString(field, modes);
434 for (std::string::const_iterator iter = modes.begin(); iter != modes.end(); ++iter)
436 const char& chr = *iter;
439 else if (ModeParser::IsModeChar(chr))
440 modeset.set(chr - 'A');
442 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "'%c' is not a valid value for <class:%s>, ignoring...", chr, field.c_str());
448 void OperInfo::init()
450 AllowedOperCommands.Clear();
451 AllowedPrivs.Clear();
452 AllowedUserModes.reset();
453 AllowedChanModes.reset();
454 AllowedSnomasks.reset();
455 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
457 bool defaultsnomasks = true;
458 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
460 ConfigTag* tag = *iter;
462 AllowedOperCommands.AddList(tag->getString("commands"));
463 AllowedPrivs.AddList(tag->getString("privs"));
465 ParseModeList(AllowedChanModes, tag, "chanmodes");
466 ParseModeList(AllowedUserModes, tag, "usermodes");
467 if (ParseModeList(AllowedSnomasks, tag, "snomasks"))
468 defaultsnomasks = false;
471 // Compatibility for older configs that don't have the snomasks field.
472 // TODO: remove this before v4 is released.
474 AllowedSnomasks.set();
483 * unset their oper type (what IS_OPER checks).
484 * note, order is important - this must come before modes as -o attempts
485 * to call UnOper. -- w00t
489 // Remove the user from the oper list
490 stdalgo::vector::swaperase(ServerInstance->Users->all_opers, this);
492 // If the user is quitting we shouldn't remove any modes as it results in
493 // mode messages being broadcast across the network.
497 /* Remove all oper only modes from the user when the deoper - Bug #466*/
498 Modes::ChangeList changelist;
499 const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
500 for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); ++i)
502 ModeHandler* mh = i->second;
504 changelist.push_remove(mh);
507 ServerInstance->Modes->Process(this, NULL, this, changelist);
509 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
511 this->SetMode(opermh, false);
512 FOREACH_MOD(OnPostDeoper, (this));
516 * Check class restrictions
518 void LocalUser::CheckClass(bool clone_count)
520 ConnectClass* a = this->MyClass;
524 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
527 else if (a->type == CC_DENY)
529 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection", 1));
532 else if (clone_count)
534 const UserManager::CloneCounts& clonecounts = ServerInstance->Users->GetCloneCounts(this);
535 if ((a->GetMaxLocal()) && (clonecounts.local > a->GetMaxLocal()))
537 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
540 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum local connections for the %s class (%ld) exceeded by %s",
541 a->name.c_str(), a->GetMaxLocal(), this->GetIPString().c_str());
545 else if ((a->GetMaxGlobal()) && (clonecounts.global > a->GetMaxGlobal()))
547 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
550 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum global connections for the %s class (%ld) exceeded by %s",
551 a->name.c_str(), a->GetMaxGlobal(), this->GetIPString().c_str());
557 this->nextping = ServerInstance->Time() + a->GetPingTime();
560 bool LocalUser::CheckLines(bool doZline)
562 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
566 for (int n = 0; check[n]; ++n)
568 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
581 void LocalUser::FullConnect()
583 ServerInstance->stats.Connects++;
584 this->idle_lastmsg = ServerInstance->Time();
587 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
588 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
589 * may put the user into a totally separate class with different restrictions! so we *must* check again.
590 * Don't remove this! -- w00t
601 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
602 * for a user that doesn't exist yet.
604 FOREACH_MOD(OnUserConnect, (this));
607 if (ServerInstance->Users->unregistered_count)
608 ServerInstance->Users->unregistered_count--;
609 this->registered = REG_ALL;
611 FOREACH_MOD(OnPostConnect, (this));
613 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
614 this->server_sa.port(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->GetRealName().c_str());
615 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
616 ServerInstance->BanCache.AddHit(this->GetIPString(), "", "");
617 // reset the flood penalty (which could have been raised due to things like auto +x)
618 CommandFloodPenalty = 0;
621 void User::InvalidateCache()
623 /* Invalidate cache */
625 cached_fullhost.clear();
626 cached_hostip.clear();
627 cached_makehost.clear();
628 cached_fullrealhost.clear();
631 bool User::ChangeNick(const std::string& newnick, time_t newts)
635 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
639 User* const InUse = ServerInstance->FindNickOnly(newnick);
642 // case change, don't need to check campers
643 // and, if it's identical including case, we can leave right now
644 // We also don't update the nick TS if it's a case change, either
651 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
652 * then we have a potential collide. Check whether someone else is camping on the nick
653 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
654 * camper to their UID, and allow the incoming nick change.
656 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
657 * because the nick is already (rightfully) in use. -- w00t
661 if (InUse->registered != REG_ALL)
663 /* force the camper to their UUID, and ask them to re-send a NICK. */
664 LocalUser* const localuser = static_cast<LocalUser*>(InUse);
665 localuser->OverruleNick();
669 /* No camping, tell the incoming user to stop trying to change nick ;p */
670 this->WriteNumeric(ERR_NICKNAMEINUSE, newnick, "Nickname is already in use.");
675 age = newts ? newts : ServerInstance->Time();
678 if (this->registered == REG_ALL)
680 ClientProtocol::Messages::Nick nickmsg(this, newnick);
681 ClientProtocol::Event nickevent(ServerInstance->GetRFCEvents().nick, nickmsg);
682 this->WriteCommonRaw(nickevent, true);
684 const std::string oldnick = nick;
688 ServerInstance->Users->clientlist.erase(oldnick);
689 ServerInstance->Users->clientlist[newnick] = this;
691 if (registered == REG_ALL)
692 FOREACH_MOD(OnUserPostNick, (this,oldnick));
697 void LocalUser::OverruleNick()
700 ClientProtocol::Messages::Nick nickmsg(this, this->uuid);
701 this->Send(ServerInstance->GetRFCEvents().nick, nickmsg);
703 this->WriteNumeric(ERR_NICKNAMEINUSE, this->nick, "Nickname overruled.");
705 // Clear the bit before calling ChangeNick() to make it NOT run the OnUserPostNick() hook
706 this->registered &= ~REG_NICK;
707 this->ChangeNick(this->uuid);
710 const std::string& User::GetIPString()
712 if (cachedip.empty())
714 cachedip = client_sa.addr();
715 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
716 if (cachedip[0] == ':')
717 cachedip.insert(cachedip.begin(),1,'0');
723 const std::string& User::GetHost(bool uncloak) const
725 return uncloak ? GetRealHost() : GetDisplayedHost();
728 const std::string& User::GetDisplayedHost() const
730 return displayhost.empty() ? realhost : displayhost;
733 const std::string& User::GetRealHost() const
738 const std::string& User::GetRealName() const
743 irc::sockets::cidr_mask User::GetCIDRMask()
745 unsigned char range = 0;
746 switch (client_sa.family())
749 range = ServerInstance->Config->c_ipv6_range;
752 range = ServerInstance->Config->c_ipv4_range;
755 return irc::sockets::cidr_mask(client_sa, range);
758 bool User::SetClientIP(const std::string& address)
760 irc::sockets::sockaddrs sa;
761 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
764 User::SetClientIP(sa);
768 void User::SetClientIP(const irc::sockets::sockaddrs& sa)
770 const std::string oldip(GetIPString());
771 memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
772 this->InvalidateCache();
774 // If the users hostname was their IP then update it.
775 if (GetRealHost() == oldip)
776 ChangeRealHost(GetIPString(), false);
777 if (GetDisplayedHost() == oldip)
778 ChangeDisplayedHost(GetIPString());
781 bool LocalUser::SetClientIP(const std::string& address)
783 irc::sockets::sockaddrs sa;
784 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
787 LocalUser::SetClientIP(sa);
791 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa)
796 ServerInstance->Users->RemoveCloneCounts(this);
797 User::SetClientIP(sa);
798 ServerInstance->Users->AddClone(this);
800 // Recheck the connect class.
801 this->MyClass = NULL;
806 FOREACH_MOD(OnSetUserIP, (this));
809 void LocalUser::Write(const ClientProtocol::SerializedMessage& text)
811 if (!SocketEngine::BoundsCheckFd(&eh))
814 if (ServerInstance->Config->RawLog)
819 std::string::size_type nlpos = text.find_first_of("\r\n", 0, 2);
820 if (nlpos == std::string::npos)
821 nlpos = text.length(); // TODO is this ok, test it
823 ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %.*s", uuid.c_str(), (int) nlpos, text.c_str());
826 eh.AddWriteBuf(text);
828 const size_t bytessent = text.length() + 2;
829 ServerInstance->stats.Sent += bytessent;
830 this->bytes_out += bytessent;
834 void LocalUser::Send(ClientProtocol::Event& protoev)
838 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "BUG: LocalUser::Send() called on %s who does not have a serializer!",
839 GetFullRealHost().c_str());
843 // In the most common case a static LocalUser field, sendmsglist, is passed to the event to be
844 // populated. The list is cleared before returning.
845 // To handle re-enters, if sendmsglist is non-empty upon entering the method then a temporary
846 // list is used instead of the static one.
847 if (sendmsglist.empty())
849 Send(protoev, sendmsglist);
854 ClientProtocol::MessageList msglist;
855 Send(protoev, msglist);
859 void LocalUser::Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist)
861 // Modules can personalize the messages sent per user for the event
862 protoev.GetMessagesForUser(this, msglist);
863 for (ClientProtocol::MessageList::const_iterator i = msglist.begin(); i != msglist.end(); ++i)
865 ClientProtocol::Message& curr = **i;
867 FIRST_MOD_RESULT(OnUserWrite, res, (this, curr));
868 if (res != MOD_RES_DENY)
869 Write(serializer->SerializeForUser(this, curr));
873 void User::WriteNumeric(const Numeric::Numeric& numeric)
875 LocalUser* const localuser = IS_LOCAL(this);
879 ModResult MOD_RESULT;
881 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric));
883 if (MOD_RESULT == MOD_RES_DENY)
886 ClientProtocol::Messages::Numeric numericmsg(numeric, localuser);
887 localuser->Send(ServerInstance->GetRFCEvents().numeric, numericmsg);
890 void User::WriteRemoteNotice(const std::string& text)
892 ServerInstance->PI->SendMessage(this, text, MSG_NOTICE);
895 void LocalUser::WriteRemoteNotice(const std::string& text)
902 class WriteCommonRawHandler : public User::ForEachNeighborHandler
904 ClientProtocol::Event& ev;
906 void Execute(LocalUser* user) CXX11_OVERRIDE
912 WriteCommonRawHandler(ClientProtocol::Event& protoev)
919 void User::WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self)
921 WriteCommonRawHandler handler(protoev);
922 ForEachNeighbor(handler, include_self);
925 void User::ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self)
927 // The basic logic for visiting the neighbors of a user is to iterate the channel list of the user
928 // and visit all users on those channels. Because two users may share more than one common channel,
929 // we must skip users that we have already visited.
930 // To do this, we make use of a global counter and an integral 'already_sent' field in LocalUser.
931 // The global counter is incremented every time we do something for each neighbor of a user. Then,
932 // before visiting a member we examine user->already_sent. If it's equal to the current counter, we
933 // skip the member. Otherwise, we set it to the current counter and visit the member.
935 // Ask modules to build a list of exceptions.
936 // Mods may also exclude entire channels by erasing them from include_chans.
937 IncludeChanList include_chans(chans.begin(), chans.end());
938 std::map<User*, bool> exceptions;
939 exceptions[this] = include_self;
940 FOREACH_MOD(OnBuildNeighborList, (this, include_chans, exceptions));
942 // Get next id, guaranteed to differ from the already_sent field of all users
943 const already_sent_t newid = ServerInstance->Users.NextAlreadySentId();
945 // Handle exceptions first
946 for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i)
948 LocalUser* curr = IS_LOCAL(i->first);
951 // Mark as visited to ensure we won't visit again if there is a common channel
952 curr->already_sent = newid;
953 // Always treat quitting users as excluded
954 if ((i->second) && (!curr->quitting))
955 handler.Execute(curr);
959 // Now consider the real neighbors
960 for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i)
962 Channel* chan = (*i)->chan;
963 const Channel::MemberMap& userlist = chan->GetUsers();
964 for (Channel::MemberMap::const_iterator j = userlist.begin(); j != userlist.end(); ++j)
966 LocalUser* curr = IS_LOCAL(j->first);
967 // User not yet visited?
968 if ((curr) && (curr->already_sent != newid))
970 // Mark as visited and execute function
971 curr->already_sent = newid;
972 handler.Execute(curr);
978 void User::WriteRemoteNumeric(const Numeric::Numeric& numeric)
980 WriteNumeric(numeric);
983 /* return 0 or 1 depending if users u and u2 share one or more common channels
984 * (used by QUIT, NICK etc which arent channel specific notices)
986 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
987 * the first users channels then the second users channels within the outer loop,
988 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
989 * all possible iterations). However this new function instead checks against the
990 * channel's userlist in the inner loop which is a std::map<User*,User*>
991 * and saves us time as we already know what pointer value we are after.
992 * Don't quote me on the maths as i am not a mathematician or computer scientist,
993 * but i believe this algorithm is now x+(log y) maximum iterations instead.
995 bool User::SharesChannelWith(User *other)
998 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); ++i)
1000 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
1001 * by replacing it with a map::find which *should* be more efficient
1003 if ((*i)->chan->HasUser(other))
1009 bool User::ChangeRealName(const std::string& real)
1011 if (!this->realname.compare(real))
1016 ModResult MOD_RESULT;
1017 FIRST_MOD_RESULT(OnPreChangeRealName, MOD_RESULT, (IS_LOCAL(this), real));
1018 if (MOD_RESULT == MOD_RES_DENY)
1021 FOREACH_MOD(OnChangeRealName, (this, real));
1022 this->realname.assign(real, 0, ServerInstance->Config->Limits.MaxReal);
1027 bool User::ChangeDisplayedHost(const std::string& shost)
1029 if (GetDisplayedHost() == shost)
1032 LocalUser* luser = IS_LOCAL(this);
1035 ModResult MOD_RESULT;
1036 FIRST_MOD_RESULT(OnPreChangeHost, MOD_RESULT, (luser, shost));
1037 if (MOD_RESULT == MOD_RES_DENY)
1041 FOREACH_MOD(OnChangeHost, (this,shost));
1043 if (realhost == shost)
1044 this->displayhost.clear();
1046 this->displayhost.assign(shost, 0, ServerInstance->Config->Limits.MaxHost);
1048 this->InvalidateCache();
1050 if (IS_LOCAL(this) && this->registered != REG_NONE)
1051 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, this->GetDisplayedHost(), "is now your displayed host");
1056 void User::ChangeRealHost(const std::string& host, bool resetdisplay)
1058 // If the real host is the new host and we are not resetting the
1059 // display host then we have nothing to do.
1060 const bool changehost = (realhost != host);
1061 if (!changehost && !resetdisplay)
1064 // If the displayhost is not set and we are not resetting it then
1065 // we need to copy it to the displayhost field.
1066 if (displayhost.empty() && !resetdisplay)
1067 displayhost = realhost;
1069 // If the displayhost is the new host or we are resetting it then
1070 // we clear its contents to save memory.
1071 else if (displayhost == host || resetdisplay)
1072 displayhost.clear();
1074 // If we are just resetting the display host then we don't need to
1075 // do anything else.
1079 // Don't call the OnChangeRealHost event when initialising a user.
1080 if (!realhost.empty())
1081 FOREACH_MOD(OnChangeRealHost, (this, host));
1084 this->InvalidateCache();
1087 bool User::ChangeIdent(const std::string& newident)
1089 if (this->ident == newident)
1092 FOREACH_MOD(OnChangeIdent, (this,newident));
1094 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1095 this->InvalidateCache();
1101 * Sets a user's connection class.
1102 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1103 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1104 * then their ip will be taken as 'priority' anyway, so for example,
1105 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1107 void LocalUser::SetClass(const std::string &explicit_name)
1109 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for %s (%s) ...",
1110 this->uuid.c_str(), this->GetFullRealHost().c_str());
1112 ConnectClass *found = NULL;
1113 if (!explicit_name.empty())
1115 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1117 ConnectClass* c = *i;
1119 if (explicit_name == c->name)
1121 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Connect class explicitly set to %s",
1122 explicit_name.c_str());
1129 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1131 ConnectClass* c = *i;
1132 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking the %s connect class ...",
1133 c->GetName().c_str());
1135 ModResult MOD_RESULT;
1136 FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1137 if (MOD_RESULT == MOD_RES_DENY)
1140 if (MOD_RESULT == MOD_RES_ALLOW)
1142 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class was explicitly chosen by a module",
1143 c->GetName().c_str());
1148 if (c->type == CC_NAMED)
1150 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as neither <connect:allow> nor <connect:deny> are set",
1151 c->GetName().c_str());
1155 bool regdone = (registered != REG_NONE);
1156 if (c->config->getBool("registered", regdone) != regdone)
1158 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it requires that the user is %s",
1159 c->GetName().c_str(), regdone ? "not fully connected" : "fully connected");
1163 /* check if host matches.. */
1164 if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1165 !InspIRCd::MatchCIDR(this->GetRealHost(), c->GetHost(), NULL))
1167 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as neither the host (%s) nor the IP (%s) matches %s",
1168 c->GetName().c_str(), this->GetRealHost().c_str(), this->GetIPString().c_str(), c->GetHost().c_str());
1173 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1174 * because we should attempt to find another class if this one doesn't match us. -- w00t
1176 if (c->limit && (c->GetReferenceCount() >= c->limit))
1178 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as it has reached its user limit (%lu)",
1179 c->GetName().c_str(), c->limit);
1183 /* if it requires a port and our port doesn't match, fail */
1184 if (!c->ports.empty() && !c->ports.count(this->server_sa.port()))
1186 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as the connection port (%d) is not any of %s",
1187 c->GetName().c_str(), this->server_sa.port(), stdalgo::string::join(c->ports).c_str());
1191 if (regdone && !c->password.empty() && !ServerInstance->PassCompare(this, c->password, password, c->passwordhash))
1193 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is not suitable as requires a password and %s",
1194 c->GetName().c_str(), password.empty() ? "one was not provided" : "the provided password was incorrect");
1198 /* we stop at the first class that meets ALL critera. */
1199 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "The %s connect class is suitable for %s (%s)",
1200 c->GetName().c_str(), this->uuid.c_str(), this->GetFullRealHost().c_str());
1207 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1215 void User::PurgeEmptyChannels()
1217 // firstly decrement the count on each channel
1218 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); )
1220 Channel* c = (*i)->chan;
1226 void User::WriteNotice(const std::string& text)
1228 LocalUser* const localuser = IS_LOCAL(this);
1232 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, localuser, text, MSG_NOTICE);
1233 localuser->Send(ServerInstance->GetRFCEvents().privmsg, msg);
1236 const std::string& FakeUser::GetFullHost()
1238 if (!ServerInstance->Config->HideServer.empty())
1239 return ServerInstance->Config->HideServer;
1240 return server->GetName();
1243 const std::string& FakeUser::GetFullRealHost()
1245 if (!ServerInstance->Config->HideServer.empty())
1246 return ServerInstance->Config->HideServer;
1247 return server->GetName();
1250 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1255 , registration_timeout(0)
1261 , penaltythreshold(0)
1268 , resolvehostnames(true)
1272 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1279 // Connect classes can inherit from each other but this is problematic for modules which can't use
1280 // ConnectClass::Update so we build a hybrid tag containing all of the values set on this class as
1281 // well as the parent class.
1282 ConfigItems* items = NULL;
1283 config = ConfigTag::create(tag->tag, tag->src_name, tag->src_line, items);
1285 const ConfigItems& parentkeys = parent.config->getItems();
1286 for (ConfigItems::const_iterator piter = parentkeys.begin(); piter != parentkeys.end(); ++piter)
1288 // The class name and parent name are not inherited
1289 if (stdalgo::string::equalsci(piter->first, "name") || stdalgo::string::equalsci(piter->first, "parent"))
1292 // Store the item in the config tag. If this item also
1293 // exists in the child it will be overwritten.
1294 (*items)[piter->first] = piter->second;
1297 const ConfigItems& childkeys = tag->getItems();
1298 for (ConfigItems::const_iterator citer = childkeys.begin(); citer != childkeys.end(); ++citer)
1300 // This will overwrite the parent value if present.
1301 (*items)[citer->first] = citer->second;
1305 void ConnectClass::Update(const ConnectClass* src)
1307 config = src->config;
1309 fakelag = src->fakelag;
1311 registration_timeout = src->registration_timeout;
1313 pingtime = src->pingtime;
1314 softsendqmax = src->softsendqmax;
1315 hardsendqmax = src->hardsendqmax;
1316 recvqmax = src->recvqmax;
1317 penaltythreshold = src->penaltythreshold;
1318 commandrate = src->commandrate;
1319 maxlocal = src->maxlocal;
1320 maxglobal = src->maxglobal;
1321 maxconnwarn = src->maxconnwarn;
1322 maxchans = src->maxchans;
1324 resolvehostnames = src->resolvehostnames;
1326 password = src->password;
1327 passwordhash = src->passwordhash;