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());
82 ServerInstance->Users->uline_count++;
84 // Do not insert FakeUsers into the uuidlist so FindUUID() won't return them which is the desired behavior
85 if (type != USERTYPE_SERVER)
87 if (!ServerInstance->Users.uuidlist.insert(std::make_pair(uuid, this)).second)
88 throw CoreException("Duplicate UUID in User constructor: " + uuid);
92 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
93 : User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL)
100 , quitting_sendq(false)
105 , CommandFloodPenalty(0)
108 signon = ServerInstance->Time();
109 // The user's default nick is their UUID
113 memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
114 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
115 ChangeRealHost(GetIPString(), true);
118 LocalUser::LocalUser(int myfd, const std::string& uid, Serializable::Data& data)
119 : User(uid, ServerInstance->FakeClient->server, USERTYPE_LOCAL)
131 const std::string& User::MakeHost()
133 if (!this->cached_makehost.empty())
134 return this->cached_makehost;
136 this->cached_makehost = ident + "@" + GetRealHost();
137 return this->cached_makehost;
140 const std::string& User::MakeHostIP()
142 if (!this->cached_hostip.empty())
143 return this->cached_hostip;
145 this->cached_hostip = ident + "@" + this->GetIPString();
146 return this->cached_hostip;
149 const std::string& User::GetFullHost()
151 if (!this->cached_fullhost.empty())
152 return this->cached_fullhost;
154 this->cached_fullhost = nick + "!" + ident + "@" + GetDisplayedHost();
155 return this->cached_fullhost;
158 const std::string& User::GetFullRealHost()
160 if (!this->cached_fullrealhost.empty())
161 return this->cached_fullrealhost;
163 this->cached_fullrealhost = nick + "!" + ident + "@" + GetRealHost();
164 return this->cached_fullrealhost;
167 bool User::HasModePermission(const ModeHandler* mh) const
172 bool LocalUser::HasModePermission(const ModeHandler* mh) const
177 const unsigned char mode = mh->GetModeChar();
178 if (!ModeParser::IsModeChar(mode))
181 return ((mh->GetModeType() == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
185 * users on remote servers can completely bypass all permissions based checks.
186 * This prevents desyncs when one server has different type/class tags to another.
187 * That having been said, this does open things up to the possibility of source changes
188 * allowing remote kills, etc - but if they have access to the src, they most likely have
189 * access to the conf - so it's an end to a means either way.
191 bool User::HasCommandPermission(const std::string&)
196 bool LocalUser::HasCommandPermission(const std::string& command)
198 // are they even an oper at all?
204 return oper->AllowedOperCommands.Contains(command);
207 bool User::HasPrivPermission(const std::string& privstr)
212 bool LocalUser::HasPrivPermission(const std::string& privstr)
217 return oper->AllowedPrivs.Contains(privstr);
220 void UserIOHandler::OnDataReady()
225 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
227 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
228 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
229 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
233 unsigned long sendqmax = ULONG_MAX;
234 if (!user->HasPrivPermission("users/flood/increased-buffers"))
235 sendqmax = user->MyClass->GetSendqSoftMax();
237 unsigned long penaltymax = ULONG_MAX;
238 if (!user->HasPrivPermission("users/flood/no-fakelag"))
239 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
241 // The cleaned message sent by the user or empty if not found yet.
244 // The position of the most \n character or npos if not found yet.
245 std::string::size_type eolpos;
247 // The position within the recvq of the current character.
248 std::string::size_type qpos;
250 while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
252 // Check the newly received data for an EOL.
253 eolpos = recvq.find('\n', checked_until);
254 if (eolpos == std::string::npos)
256 checked_until = recvq.length();
260 // We've found a line! Clean it up and move it to the line buffer.
261 line.reserve(eolpos);
262 for (qpos = 0; qpos < eolpos; ++qpos)
264 char c = recvq[qpos];
277 // just found a newline. Terminate the string, and pull it out of recvq
278 recvq.erase(0, eolpos + 1);
281 // TODO should this be moved to when it was inserted in recvq?
282 ServerInstance->stats.Recv += qpos;
283 user->bytes_in += qpos;
286 ServerInstance->Parser.ProcessBuffer(user, line);
290 // clear() does not reclaim memory associated with the string, so our .reserve() call is safe
294 if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
295 ServerInstance->Users->QuitUser(user, "Excess Flood");
298 void UserIOHandler::AddWriteBuf(const std::string &data)
300 if (user->quitting_sendq)
302 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
303 !user->HasPrivPermission("users/flood/increased-buffers"))
305 user->quitting_sendq = true;
306 ServerInstance->GlobalCulls.AddSQItem(user);
310 // We still want to append data to the sendq of a quitting user,
311 // e.g. their ERROR message that says 'closing link'
316 void UserIOHandler::SwapInternals(UserIOHandler& other)
318 StreamSocket::SwapInternals(other);
319 std::swap(checked_until, other.checked_until);
322 bool UserIOHandler::OnSetEndPoint(const irc::sockets::sockaddrs& server, const irc::sockets::sockaddrs& client)
324 memcpy(&user->server_sa, &server, sizeof(irc::sockets::sockaddrs));
325 user->SetClientIP(client);
326 return !user->quitting;
329 void UserIOHandler::OnError(BufferedSocketError sockerr)
332 FIRST_MOD_RESULT(OnConnectionFail, res, (user, sockerr));
333 if (res != MOD_RES_ALLOW)
334 ServerInstance->Users->QuitUser(user, getError());
337 CullResult User::cull()
340 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
342 if (client_sa.family() != AF_UNSPEC)
343 ServerInstance->Users->RemoveCloneCounts(this);
345 if (server->IsULine() && ServerInstance->Users->uline_count)
346 ServerInstance->Users->uline_count--;
348 return Extensible::cull();
351 CullResult LocalUser::cull()
357 CullResult FakeUser::cull()
359 // Fake users don't quit, they just get culled.
361 // Fake users are not inserted into UserManager::clientlist or uuidlist, so we don't need to modify those here
365 void User::Oper(OperInfo* info)
367 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
370 if (this->IsModeSet(opermh))
372 this->SetMode(opermh, true);
376 LocalUser* localuser = IS_LOCAL(this);
379 Modes::ChangeList changelist;
380 changelist.push_add(opermh);
381 ClientProtocol::Events::Mode modemsg(ServerInstance->FakeClient, NULL, localuser, changelist);
382 localuser->Send(modemsg);
385 FOREACH_MOD(OnOper, (this, info->name));
387 std::string opername;
388 if (info->oper_block)
389 opername = info->oper_block->getString("name");
391 ServerInstance->SNO->WriteToSnoMask('o', "%s (%s@%s) is now a server operator of type %s (using oper '%s')",
392 nick.c_str(), ident.c_str(), GetRealHost().c_str(), oper->name.c_str(), opername.c_str());
393 this->WriteNumeric(RPL_YOUAREOPER, InspIRCd::Format("You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str()));
395 ServerInstance->Users->all_opers.push_back(this);
397 // Expand permissions from config for faster lookup
401 FOREACH_MOD(OnPostOper, (this, oper->name, opername));
404 void OperInfo::init()
406 AllowedOperCommands.Clear();
407 AllowedPrivs.Clear();
408 AllowedUserModes.reset();
409 AllowedChanModes.reset();
410 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
412 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
414 ConfigTag* tag = *iter;
416 AllowedOperCommands.AddList(tag->getString("commands"));
417 AllowedPrivs.AddList(tag->getString("privs"));
419 std::string modes = tag->getString("usermodes");
420 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
424 this->AllowedUserModes.set();
426 else if (*c >= 'A' && *c <= 'z')
428 this->AllowedUserModes[*c - 'A'] = true;
432 modes = tag->getString("chanmodes");
433 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
437 this->AllowedChanModes.set();
439 else if (*c >= 'A' && *c <= 'z')
441 this->AllowedChanModes[*c - 'A'] = true;
453 * unset their oper type (what IS_OPER checks).
454 * note, order is important - this must come before modes as -o attempts
455 * to call UnOper. -- w00t
459 // Remove the user from the oper list
460 stdalgo::vector::swaperase(ServerInstance->Users->all_opers, this);
462 // If the user is quitting we shouldn't remove any modes as it results in
463 // mode messages being broadcast across the network.
467 /* Remove all oper only modes from the user when the deoper - Bug #466*/
468 Modes::ChangeList changelist;
469 const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
470 for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); ++i)
472 ModeHandler* mh = i->second;
474 changelist.push_remove(mh);
477 ServerInstance->Modes->Process(this, NULL, this, changelist);
479 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
481 this->SetMode(opermh, false);
482 FOREACH_MOD(OnPostDeoper, (this));
486 * Check class restrictions
488 void LocalUser::CheckClass(bool clone_count)
490 ConnectClass* a = this->MyClass;
494 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
497 else if (a->type == CC_DENY)
499 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection"));
502 else if (clone_count)
504 const UserManager::CloneCounts& clonecounts = ServerInstance->Users->GetCloneCounts(this);
505 if ((a->GetMaxLocal()) && (clonecounts.local > a->GetMaxLocal()))
507 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
510 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum local connections for the %s class (%ld) exceeded by %s",
511 a->name.c_str(), a->GetMaxLocal(), this->GetIPString().c_str());
515 else if ((a->GetMaxGlobal()) && (clonecounts.global > a->GetMaxGlobal()))
517 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
520 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum global connections for the %s class (%ld) exceeded by %s",
521 a->name.c_str(), a->GetMaxGlobal(), this->GetIPString().c_str());
527 this->nextping = ServerInstance->Time() + a->GetPingTime();
530 bool LocalUser::CheckLines(bool doZline)
532 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
536 for (int n = 0; check[n]; ++n)
538 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
551 void LocalUser::FullConnect()
553 ServerInstance->stats.Connects++;
554 this->idle_lastmsg = ServerInstance->Time();
557 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
558 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
559 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
560 * Don't remove this! -- w00t
571 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
572 * for a user that doesn't exist yet.
574 FOREACH_MOD(OnUserConnect, (this));
577 if (ServerInstance->Users->unregistered_count)
578 ServerInstance->Users->unregistered_count--;
579 this->registered = REG_ALL;
581 FOREACH_MOD(OnPostConnect, (this));
583 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
584 this->server_sa.port(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->GetRealName().c_str());
585 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
586 ServerInstance->BanCache.AddHit(this->GetIPString(), "", "");
587 // reset the flood penalty (which could have been raised due to things like auto +x)
588 CommandFloodPenalty = 0;
591 void User::InvalidateCache()
593 /* Invalidate cache */
595 cached_fullhost.clear();
596 cached_hostip.clear();
597 cached_makehost.clear();
598 cached_fullrealhost.clear();
601 bool User::ChangeNick(const std::string& newnick, time_t newts)
605 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
609 User* const InUse = ServerInstance->FindNickOnly(newnick);
612 // case change, don't need to check campers
613 // and, if it's identical including case, we can leave right now
614 // We also don't update the nick TS if it's a case change, either
621 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
622 * then we have a potential collide. Check whether someone else is camping on the nick
623 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
624 * camper to their UID, and allow the incoming nick change.
626 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
627 * because the nick is already (rightfully) in use. -- w00t
631 if (InUse->registered != REG_ALL)
633 /* force the camper to their UUID, and ask them to re-send a NICK. */
634 LocalUser* const localuser = static_cast<LocalUser*>(InUse);
635 localuser->OverruleNick();
639 /* No camping, tell the incoming user to stop trying to change nick ;p */
640 this->WriteNumeric(ERR_NICKNAMEINUSE, newnick, "Nickname is already in use.");
645 age = newts ? newts : ServerInstance->Time();
648 if (this->registered == REG_ALL)
650 ClientProtocol::Messages::Nick nickmsg(this, newnick);
651 ClientProtocol::Event nickevent(ServerInstance->GetRFCEvents().nick, nickmsg);
652 this->WriteCommonRaw(nickevent, true);
654 const std::string oldnick = nick;
658 ServerInstance->Users->clientlist.erase(oldnick);
659 ServerInstance->Users->clientlist[newnick] = this;
661 if (registered == REG_ALL)
662 FOREACH_MOD(OnUserPostNick, (this,oldnick));
667 void LocalUser::OverruleNick()
670 ClientProtocol::Messages::Nick nickmsg(this, this->uuid);
671 this->Send(ServerInstance->GetRFCEvents().nick, nickmsg);
673 this->WriteNumeric(ERR_NICKNAMEINUSE, this->nick, "Nickname overruled.");
675 // Clear the bit before calling ChangeNick() to make it NOT run the OnUserPostNick() hook
676 this->registered &= ~REG_NICK;
677 this->ChangeNick(this->uuid);
680 const std::string& User::GetIPString()
682 if (cachedip.empty())
684 cachedip = client_sa.addr();
685 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
686 if (cachedip[0] == ':')
687 cachedip.insert(cachedip.begin(),1,'0');
693 const std::string& User::GetHost(bool uncloak) const
695 return uncloak ? GetRealHost() : GetDisplayedHost();
698 const std::string& User::GetDisplayedHost() const
700 return displayhost.empty() ? realhost : displayhost;
703 const std::string& User::GetRealHost() const
708 const std::string& User::GetRealName() const
713 irc::sockets::cidr_mask User::GetCIDRMask()
715 unsigned char range = 0;
716 switch (client_sa.family())
719 range = ServerInstance->Config->c_ipv6_range;
722 range = ServerInstance->Config->c_ipv4_range;
725 return irc::sockets::cidr_mask(client_sa, range);
728 bool User::SetClientIP(const std::string& address)
730 irc::sockets::sockaddrs sa;
731 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
734 User::SetClientIP(sa);
738 void User::SetClientIP(const irc::sockets::sockaddrs& sa)
740 const std::string oldip(GetIPString());
741 memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
742 this->InvalidateCache();
744 // If the users hostname was their IP then update it.
745 if (GetRealHost() == oldip)
746 ChangeRealHost(GetIPString(), false);
747 if (GetDisplayedHost() == oldip)
748 ChangeDisplayedHost(GetIPString());
751 bool LocalUser::SetClientIP(const std::string& address)
753 irc::sockets::sockaddrs sa;
754 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
757 LocalUser::SetClientIP(sa);
761 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa)
766 ServerInstance->Users->RemoveCloneCounts(this);
767 User::SetClientIP(sa);
768 ServerInstance->Users->AddClone(this);
770 // Recheck the connect class.
771 this->MyClass = NULL;
776 FOREACH_MOD(OnSetUserIP, (this));
779 void LocalUser::Write(const ClientProtocol::SerializedMessage& text)
781 if (!SocketEngine::BoundsCheckFd(&eh))
784 if (ServerInstance->Config->RawLog)
789 std::string::size_type nlpos = text.find_first_of("\r\n", 0, 2);
790 if (nlpos == std::string::npos)
791 nlpos = text.length(); // TODO is this ok, test it
793 ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %.*s", uuid.c_str(), (int) nlpos, text.c_str());
796 eh.AddWriteBuf(text);
798 const size_t bytessent = text.length() + 2;
799 ServerInstance->stats.Sent += bytessent;
800 this->bytes_out += bytessent;
804 void LocalUser::Send(ClientProtocol::Event& protoev)
808 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "BUG: LocalUser::Send() called on %s who does not have a serializer!",
809 GetFullRealHost().c_str());
813 // In the most common case a static LocalUser field, sendmsglist, is passed to the event to be
814 // populated. The list is cleared before returning.
815 // To handle re-enters, if sendmsglist is non-empty upon entering the method then a temporary
816 // list is used instead of the static one.
817 if (sendmsglist.empty())
819 Send(protoev, sendmsglist);
824 ClientProtocol::MessageList msglist;
825 Send(protoev, msglist);
829 void LocalUser::Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist)
831 // Modules can personalize the messages sent per user for the event
832 protoev.GetMessagesForUser(this, msglist);
833 for (ClientProtocol::MessageList::const_iterator i = msglist.begin(); i != msglist.end(); ++i)
835 ClientProtocol::Message& curr = **i;
837 FIRST_MOD_RESULT(OnUserWrite, res, (this, curr));
838 if (res != MOD_RES_DENY)
839 Write(serializer->SerializeForUser(this, curr));
843 void User::WriteNumeric(const Numeric::Numeric& numeric)
845 LocalUser* const localuser = IS_LOCAL(this);
849 ModResult MOD_RESULT;
851 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric));
853 if (MOD_RESULT == MOD_RES_DENY)
856 ClientProtocol::Messages::Numeric numericmsg(numeric, localuser);
857 localuser->Send(ServerInstance->GetRFCEvents().numeric, numericmsg);
860 void User::WriteRemoteNotice(const std::string& text)
862 ServerInstance->PI->SendMessage(this, text, MSG_NOTICE);
865 void LocalUser::WriteRemoteNotice(const std::string& text)
872 class WriteCommonRawHandler : public User::ForEachNeighborHandler
874 ClientProtocol::Event& ev;
876 void Execute(LocalUser* user) CXX11_OVERRIDE
882 WriteCommonRawHandler(ClientProtocol::Event& protoev)
889 void User::WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self)
891 WriteCommonRawHandler handler(protoev);
892 ForEachNeighbor(handler, include_self);
895 void User::ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self)
897 // The basic logic for visiting the neighbors of a user is to iterate the channel list of the user
898 // and visit all users on those channels. Because two users may share more than one common channel,
899 // we must skip users that we have already visited.
900 // To do this, we make use of a global counter and an integral 'already_sent' field in LocalUser.
901 // The global counter is incremented every time we do something for each neighbor of a user. Then,
902 // before visiting a member we examine user->already_sent. If it's equal to the current counter, we
903 // skip the member. Otherwise, we set it to the current counter and visit the member.
905 // Ask modules to build a list of exceptions.
906 // Mods may also exclude entire channels by erasing them from include_chans.
907 IncludeChanList include_chans(chans.begin(), chans.end());
908 std::map<User*, bool> exceptions;
909 exceptions[this] = include_self;
910 FOREACH_MOD(OnBuildNeighborList, (this, include_chans, exceptions));
912 // Get next id, guaranteed to differ from the already_sent field of all users
913 const already_sent_t newid = ServerInstance->Users.NextAlreadySentId();
915 // Handle exceptions first
916 for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i)
918 LocalUser* curr = IS_LOCAL(i->first);
921 // Mark as visited to ensure we won't visit again if there is a common channel
922 curr->already_sent = newid;
923 // Always treat quitting users as excluded
924 if ((i->second) && (!curr->quitting))
925 handler.Execute(curr);
929 // Now consider the real neighbors
930 for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i)
932 Channel* chan = (*i)->chan;
933 const Channel::MemberMap& userlist = chan->GetUsers();
934 for (Channel::MemberMap::const_iterator j = userlist.begin(); j != userlist.end(); ++j)
936 LocalUser* curr = IS_LOCAL(j->first);
937 // User not yet visited?
938 if ((curr) && (curr->already_sent != newid))
940 // Mark as visited and execute function
941 curr->already_sent = newid;
942 handler.Execute(curr);
948 void User::WriteRemoteNumeric(const Numeric::Numeric& numeric)
950 WriteNumeric(numeric);
953 /* return 0 or 1 depending if users u and u2 share one or more common channels
954 * (used by QUIT, NICK etc which arent channel specific notices)
956 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
957 * the first users channels then the second users channels within the outer loop,
958 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
959 * all possible iterations). However this new function instead checks against the
960 * channel's userlist in the inner loop which is a std::map<User*,User*>
961 * and saves us time as we already know what pointer value we are after.
962 * Don't quote me on the maths as i am not a mathematician or computer scientist,
963 * but i believe this algorithm is now x+(log y) maximum iterations instead.
965 bool User::SharesChannelWith(User *other)
968 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); ++i)
970 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
971 * by replacing it with a map::find which *should* be more efficient
973 if ((*i)->chan->HasUser(other))
979 bool User::ChangeRealName(const std::string& real)
981 if (!this->realname.compare(real))
986 ModResult MOD_RESULT;
987 FIRST_MOD_RESULT(OnPreChangeRealName, MOD_RESULT, (IS_LOCAL(this), real));
988 if (MOD_RESULT == MOD_RES_DENY)
990 FOREACH_MOD(OnChangeRealName, (this, real));
992 this->realname.assign(real, 0, ServerInstance->Config->Limits.MaxReal);
997 bool User::ChangeDisplayedHost(const std::string& shost)
999 if (GetDisplayedHost() == shost)
1002 LocalUser* luser = IS_LOCAL(this);
1005 ModResult MOD_RESULT;
1006 FIRST_MOD_RESULT(OnPreChangeHost, MOD_RESULT, (luser, shost));
1007 if (MOD_RESULT == MOD_RES_DENY)
1011 FOREACH_MOD(OnChangeHost, (this,shost));
1013 if (realhost == shost)
1014 this->displayhost.clear();
1016 this->displayhost.assign(shost, 0, ServerInstance->Config->Limits.MaxHost);
1018 this->InvalidateCache();
1020 if (IS_LOCAL(this) && this->registered != REG_NONE)
1021 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, this->GetDisplayedHost(), "is now your displayed host");
1026 void User::ChangeRealHost(const std::string& host, bool resetdisplay)
1028 // If the real host is the new host and we are not resetting the
1029 // display host then we have nothing to do.
1030 const bool changehost = (realhost != host);
1031 if (!changehost && !resetdisplay)
1034 // If the displayhost is not set and we are not resetting it then
1035 // we need to copy it to the displayhost field.
1036 if (displayhost.empty() && !resetdisplay)
1037 displayhost = realhost;
1039 // If the displayhost is the new host or we are resetting it then
1040 // we clear its contents to save memory.
1041 else if (displayhost == host || resetdisplay)
1042 displayhost.clear();
1044 // If we are just resetting the display host then we don't need to
1045 // do anything else.
1050 this->InvalidateCache();
1053 bool User::ChangeIdent(const std::string& newident)
1055 if (this->ident == newident)
1058 FOREACH_MOD(OnChangeIdent, (this,newident));
1060 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1061 this->InvalidateCache();
1067 * Sets a user's connection class.
1068 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1069 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1070 * then their ip will be taken as 'priority' anyway, so for example,
1071 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1073 void LocalUser::SetClass(const std::string &explicit_name)
1075 ConnectClass *found = NULL;
1077 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1079 if (!explicit_name.empty())
1081 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1083 ConnectClass* c = *i;
1085 if (explicit_name == c->name)
1087 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Explicitly set to %s", explicit_name.c_str());
1094 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1096 ConnectClass* c = *i;
1097 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking %s", c->GetName().c_str());
1099 ModResult MOD_RESULT;
1100 FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1101 if (MOD_RESULT == MOD_RES_DENY)
1103 if (MOD_RESULT == MOD_RES_ALLOW)
1105 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class forced by module to %s", c->GetName().c_str());
1110 if (c->type == CC_NAMED)
1113 bool regdone = (registered != REG_NONE);
1114 if (c->config->getBool("registered", regdone) != regdone)
1117 /* check if host matches.. */
1118 if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1119 !InspIRCd::MatchCIDR(this->GetRealHost(), c->GetHost(), NULL))
1121 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "No host match (for %s)", c->GetHost().c_str());
1126 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1127 * because we should attempt to find another class if this one doesn't match us. -- w00t
1129 if (c->limit && (c->GetReferenceCount() >= c->limit))
1131 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1135 /* if it requires a port ... */
1136 if (!c->ports.empty())
1138 /* and our port doesn't match, fail. */
1139 if (!c->ports.count(this->server_sa.port()))
1141 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Requires a different port, skipping");
1146 if (regdone && !c->config->getString("password").empty())
1148 if (!ServerInstance->PassCompare(this, c->config->getString("password"), password, c->config->getString("hash")))
1150 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Bad password, skipping");
1155 /* we stop at the first class that meets ALL critera. */
1162 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1170 void User::PurgeEmptyChannels()
1172 // firstly decrement the count on each channel
1173 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); )
1175 Channel* c = (*i)->chan;
1181 void User::WriteNotice(const std::string& text)
1183 LocalUser* const localuser = IS_LOCAL(this);
1187 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, localuser, text, MSG_NOTICE);
1188 localuser->Send(ServerInstance->GetRFCEvents().privmsg, msg);
1191 const std::string& FakeUser::GetFullHost()
1193 if (!ServerInstance->Config->HideServer.empty())
1194 return ServerInstance->Config->HideServer;
1195 return server->GetName();
1198 const std::string& FakeUser::GetFullRealHost()
1200 if (!ServerInstance->Config->HideServer.empty())
1201 return ServerInstance->Config->HideServer;
1202 return server->GetName();
1205 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1210 , registration_timeout(0)
1216 , penaltythreshold(0)
1223 , resolvehostnames(true)
1227 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1234 // Connect classes can inherit from each other but this is problematic for modules which can't use
1235 // ConnectClass::Update so we build a hybrid tag containing all of the values set on this class as
1236 // well as the parent class.
1237 ConfigItems* items = NULL;
1238 config = ConfigTag::create(tag->tag, tag->src_name, tag->src_line, items);
1240 const ConfigItems& parentkeys = parent.config->getItems();
1241 for (ConfigItems::const_iterator piter = parentkeys.begin(); piter != parentkeys.end(); ++piter)
1243 // The class name and parent name are not inherited
1244 if (stdalgo::string::equalsci(piter->first, "name") || stdalgo::string::equalsci(piter->first, "parent"))
1247 // Store the item in the config tag. If this item also
1248 // exists in the child it will be overwritten.
1249 (*items)[piter->first] = piter->second;
1252 const ConfigItems& childkeys = tag->getItems();
1253 for (ConfigItems::const_iterator citer = childkeys.begin(); citer != childkeys.end(); ++citer)
1255 // This will overwrite the parent value if present.
1256 (*items)[citer->first] = citer->second;
1260 void ConnectClass::Update(const ConnectClass* src)
1262 config = src->config;
1264 fakelag = src->fakelag;
1266 registration_timeout = src->registration_timeout;
1268 pingtime = src->pingtime;
1269 softsendqmax = src->softsendqmax;
1270 hardsendqmax = src->hardsendqmax;
1271 recvqmax = src->recvqmax;
1272 penaltythreshold = src->penaltythreshold;
1273 commandrate = src->commandrate;
1274 maxlocal = src->maxlocal;
1275 maxglobal = src->maxglobal;
1276 maxconnwarn = src->maxconnwarn;
1277 maxchans = src->maxchans;
1279 resolvehostnames = src->resolvehostnames;