2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2006-2009 Robin Burchell <robin+git@viroteck.net>
6 * Copyright (C) 2006-2007, 2009 Dennis Friis <peavey@inspircd.org>
7 * Copyright (C) 2008 John Brooks <john.brooks@dereferenced.net>
8 * Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9 * Copyright (C) 2008 Oliver Lupton <oliverlupton@gmail.com>
10 * Copyright (C) 2003-2008 Craig Edwards <craigedwards@brainbox.cc>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 ClientProtocol::MessageList LocalUser::sendmsglist;
31 bool User::IsNoticeMaskSet(unsigned char sm)
35 return (snomasks[sm-65]);
38 bool User::IsModeSet(unsigned char m) const
40 ModeHandler* mh = ServerInstance->Modes->FindMode(m, MODETYPE_USER);
41 return (mh && modes[mh->GetId()]);
44 std::string User::GetModeLetters(bool includeparams) const
46 std::string ret(1, '+');
49 for (unsigned char i = 'A'; i <= 'z'; i++)
51 const ModeHandler* const mh = ServerInstance->Modes.FindMode(i, MODETYPE_USER);
52 if ((!mh) || (!IsModeSet(mh)))
55 ret.push_back(mh->GetModeChar());
56 if ((includeparams) && (mh->NeedsParam(true)))
58 const std::string val = mh->GetUserParameter(this);
60 params.append(1, ' ').append(val);
68 User::User(const std::string& uid, Server* srv, UserType type)
69 : age(ServerInstance->Time())
73 , registered(REG_NONE)
77 client_sa.sa.sa_family = AF_UNSPEC;
79 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New UUID for user: %s", uuid.c_str());
81 // Do not insert FakeUsers into the uuidlist so FindUUID() won't return them which is the desired behavior
82 if (type != USERTYPE_SERVER)
84 if (!ServerInstance->Users.uuidlist.insert(std::make_pair(uuid, this)).second)
85 throw CoreException("Duplicate UUID in User constructor: " + uuid);
89 LocalUser::LocalUser(int myfd, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* servaddr)
90 : User(ServerInstance->UIDGen.GetUID(), ServerInstance->FakeClient->server, USERTYPE_LOCAL)
97 , quitting_sendq(false)
102 , CommandFloodPenalty(0)
105 signon = ServerInstance->Time();
106 // The user's default nick is their UUID
110 memcpy(&client_sa, client, sizeof(irc::sockets::sockaddrs));
111 memcpy(&server_sa, servaddr, sizeof(irc::sockets::sockaddrs));
112 ChangeRealHost(GetIPString(), true);
119 const std::string& User::MakeHost()
121 if (!this->cached_makehost.empty())
122 return this->cached_makehost;
124 this->cached_makehost = ident + "@" + GetRealHost();
125 return this->cached_makehost;
128 const std::string& User::MakeHostIP()
130 if (!this->cached_hostip.empty())
131 return this->cached_hostip;
133 this->cached_hostip = ident + "@" + this->GetIPString();
134 return this->cached_hostip;
137 const std::string& User::GetFullHost()
139 if (!this->cached_fullhost.empty())
140 return this->cached_fullhost;
142 this->cached_fullhost = nick + "!" + ident + "@" + GetDisplayedHost();
143 return this->cached_fullhost;
146 const std::string& User::GetFullRealHost()
148 if (!this->cached_fullrealhost.empty())
149 return this->cached_fullrealhost;
151 this->cached_fullrealhost = nick + "!" + ident + "@" + GetRealHost();
152 return this->cached_fullrealhost;
155 bool User::HasModePermission(const ModeHandler* mh) const
160 bool LocalUser::HasModePermission(const ModeHandler* mh) const
165 const unsigned char mode = mh->GetModeChar();
166 if (!ModeParser::IsModeChar(mode))
169 return ((mh->GetModeType() == MODETYPE_USER ? oper->AllowedUserModes : oper->AllowedChanModes))[(mode - 'A')];
173 * users on remote servers can completely bypass all permissions based checks.
174 * This prevents desyncs when one server has different type/class tags to another.
175 * That having been said, this does open things up to the possibility of source changes
176 * allowing remote kills, etc - but if they have access to the src, they most likely have
177 * access to the conf - so it's an end to a means either way.
179 bool User::HasCommandPermission(const std::string&)
184 bool LocalUser::HasCommandPermission(const std::string& command)
186 // are they even an oper at all?
192 return oper->AllowedOperCommands.Contains(command);
195 bool User::HasPrivPermission(const std::string& privstr)
200 bool LocalUser::HasPrivPermission(const std::string& privstr)
205 return oper->AllowedPrivs.Contains(privstr);
208 void UserIOHandler::OnDataReady()
213 if (recvq.length() > user->MyClass->GetRecvqMax() && !user->HasPrivPermission("users/flood/increased-buffers"))
215 ServerInstance->Users->QuitUser(user, "RecvQ exceeded");
216 ServerInstance->SNO->WriteToSnoMask('a', "User %s RecvQ of %lu exceeds connect class maximum of %lu",
217 user->nick.c_str(), (unsigned long)recvq.length(), user->MyClass->GetRecvqMax());
221 unsigned long sendqmax = ULONG_MAX;
222 if (!user->HasPrivPermission("users/flood/increased-buffers"))
223 sendqmax = user->MyClass->GetSendqSoftMax();
225 unsigned long penaltymax = ULONG_MAX;
226 if (!user->HasPrivPermission("users/flood/no-fakelag"))
227 penaltymax = user->MyClass->GetPenaltyThreshold() * 1000;
229 // The cleaned message sent by the user or empty if not found yet.
232 // The position of the most \n character or npos if not found yet.
233 std::string::size_type eolpos;
235 // The position within the recvq of the current character.
236 std::string::size_type qpos;
238 while (user->CommandFloodPenalty < penaltymax && getSendQSize() < sendqmax)
240 // Check the newly received data for an EOL.
241 eolpos = recvq.find('\n', checked_until);
242 if (eolpos == std::string::npos)
244 checked_until = recvq.length();
248 // We've found a line! Clean it up and move it to the line buffer.
249 line.reserve(eolpos);
250 for (qpos = 0; qpos < eolpos; ++qpos)
252 char c = recvq[qpos];
265 // just found a newline. Terminate the string, and pull it out of recvq
266 recvq.erase(0, eolpos + 1);
269 // TODO should this be moved to when it was inserted in recvq?
270 ServerInstance->stats.Recv += qpos;
271 user->bytes_in += qpos;
274 ServerInstance->Parser.ProcessBuffer(user, line);
278 // clear() does not reclaim memory associated with the string, so our .reserve() call is safe
282 if (user->CommandFloodPenalty >= penaltymax && !user->MyClass->fakelag)
283 ServerInstance->Users->QuitUser(user, "Excess Flood");
286 void UserIOHandler::AddWriteBuf(const std::string &data)
288 if (user->quitting_sendq)
290 if (!user->quitting && getSendQSize() + data.length() > user->MyClass->GetSendqHardMax() &&
291 !user->HasPrivPermission("users/flood/increased-buffers"))
293 user->quitting_sendq = true;
294 ServerInstance->GlobalCulls.AddSQItem(user);
298 // We still want to append data to the sendq of a quitting user,
299 // e.g. their ERROR message that says 'closing link'
304 void UserIOHandler::SwapInternals(UserIOHandler& other)
306 StreamSocket::SwapInternals(other);
307 std::swap(checked_until, other.checked_until);
310 bool UserIOHandler::OnSetEndPoint(const irc::sockets::sockaddrs& server, const irc::sockets::sockaddrs& client)
312 memcpy(&user->server_sa, &server, sizeof(irc::sockets::sockaddrs));
313 user->SetClientIP(client);
314 return !user->quitting;
317 void UserIOHandler::OnError(BufferedSocketError error)
320 FIRST_MOD_RESULT(OnConnectionFail, res, (user, error));
321 if (res != MOD_RES_ALLOW)
322 ServerInstance->Users->QuitUser(user, getError());
325 CullResult User::cull()
328 ServerInstance->Users->QuitUser(this, "Culled without QuitUser");
330 if (client_sa.family() != AF_UNSPEC)
331 ServerInstance->Users->RemoveCloneCounts(this);
333 return Extensible::cull();
336 CullResult LocalUser::cull()
342 CullResult FakeUser::cull()
344 // Fake users don't quit, they just get culled.
346 // Fake users are not inserted into UserManager::clientlist or uuidlist, so we don't need to modify those here
350 void User::Oper(OperInfo* info)
352 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
355 if (this->IsModeSet(opermh))
357 this->SetMode(opermh, true);
361 LocalUser* localuser = IS_LOCAL(this);
364 Modes::ChangeList changelist;
365 changelist.push_add(opermh);
366 ClientProtocol::Events::Mode modemsg(ServerInstance->FakeClient, NULL, localuser, changelist);
367 localuser->Send(modemsg);
370 FOREACH_MOD(OnOper, (this, info->name));
372 std::string opername;
373 if (info->oper_block)
374 opername = info->oper_block->getString("name");
376 ServerInstance->SNO->WriteToSnoMask('o', "%s (%s@%s) is now a server operator of type %s (using oper '%s')",
377 nick.c_str(), ident.c_str(), GetRealHost().c_str(), oper->name.c_str(), opername.c_str());
378 this->WriteNumeric(RPL_YOUAREOPER, InspIRCd::Format("You are now %s %s", strchr("aeiouAEIOU", oper->name[0]) ? "an" : "a", oper->name.c_str()));
380 ServerInstance->Users->all_opers.push_back(this);
382 // Expand permissions from config for faster lookup
386 FOREACH_MOD(OnPostOper, (this, oper->name, opername));
389 void OperInfo::init()
391 AllowedOperCommands.Clear();
392 AllowedPrivs.Clear();
393 AllowedUserModes.reset();
394 AllowedChanModes.reset();
395 AllowedUserModes['o' - 'A'] = true; // Call me paranoid if you want.
397 for(std::vector<reference<ConfigTag> >::iterator iter = class_blocks.begin(); iter != class_blocks.end(); ++iter)
399 ConfigTag* tag = *iter;
401 AllowedOperCommands.AddList(tag->getString("commands"));
402 AllowedPrivs.AddList(tag->getString("privs"));
404 std::string modes = tag->getString("usermodes");
405 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
409 this->AllowedUserModes.set();
411 else if (*c >= 'A' && *c <= 'z')
413 this->AllowedUserModes[*c - 'A'] = true;
417 modes = tag->getString("chanmodes");
418 for (std::string::const_iterator c = modes.begin(); c != modes.end(); ++c)
422 this->AllowedChanModes.set();
424 else if (*c >= 'A' && *c <= 'z')
426 this->AllowedChanModes[*c - 'A'] = true;
438 * unset their oper type (what IS_OPER checks).
439 * note, order is important - this must come before modes as -o attempts
440 * to call UnOper. -- w00t
445 /* Remove all oper only modes from the user when the deoper - Bug #466*/
446 Modes::ChangeList changelist;
447 const ModeParser::ModeHandlerMap& usermodes = ServerInstance->Modes->GetModes(MODETYPE_USER);
448 for (ModeParser::ModeHandlerMap::const_iterator i = usermodes.begin(); i != usermodes.end(); ++i)
450 ModeHandler* mh = i->second;
452 changelist.push_remove(mh);
455 ServerInstance->Modes->Process(this, NULL, this, changelist);
457 // Remove the user from the oper list
458 stdalgo::vector::swaperase(ServerInstance->Users->all_opers, this);
460 ModeHandler* opermh = ServerInstance->Modes->FindMode('o', MODETYPE_USER);
462 this->SetMode(opermh, false);
463 FOREACH_MOD(OnPostDeoper, (this));
467 * Check class restrictions
469 void LocalUser::CheckClass(bool clone_count)
471 ConnectClass* a = this->MyClass;
475 ServerInstance->Users->QuitUser(this, "Access denied by configuration");
478 else if (a->type == CC_DENY)
480 ServerInstance->Users->QuitUser(this, a->config->getString("reason", "Unauthorised connection"));
483 else if (clone_count)
485 const UserManager::CloneCounts& clonecounts = ServerInstance->Users->GetCloneCounts(this);
486 if ((a->GetMaxLocal()) && (clonecounts.local > a->GetMaxLocal()))
488 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (local)");
491 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum local connections for the %s class (%ld) exceeded by %s",
492 a->name.c_str(), a->GetMaxLocal(), this->GetIPString().c_str());
496 else if ((a->GetMaxGlobal()) && (clonecounts.global > a->GetMaxGlobal()))
498 ServerInstance->Users->QuitUser(this, "No more connections allowed from your host via this connect class (global)");
501 ServerInstance->SNO->WriteToSnoMask('a', "WARNING: maximum global connections for the %s class (%ld) exceeded by %s",
502 a->name.c_str(), a->GetMaxGlobal(), this->GetIPString().c_str());
508 this->nextping = ServerInstance->Time() + a->GetPingTime();
511 bool LocalUser::CheckLines(bool doZline)
513 const char* check[] = { "G" , "K", (doZline) ? "Z" : NULL, NULL };
517 for (int n = 0; check[n]; ++n)
519 XLine *r = ServerInstance->XLines->MatchesLine(check[n], this);
532 void LocalUser::FullConnect()
534 ServerInstance->stats.Connects++;
535 this->idle_lastmsg = ServerInstance->Time();
538 * You may be thinking "wtf, we checked this in User::AddClient!" - and yes, we did, BUT.
539 * At the time AddClient is called, we don't have a resolved host, by here we probably do - which
540 * may put the user into a totally seperate class with different restrictions! so we *must* check again.
541 * Don't remove this! -- w00t
552 * We don't set REG_ALL until triggering OnUserConnect, so some module events don't spew out stuff
553 * for a user that doesn't exist yet.
555 FOREACH_MOD(OnUserConnect, (this));
558 if (ServerInstance->Users->unregistered_count)
559 ServerInstance->Users->unregistered_count--;
560 this->registered = REG_ALL;
562 FOREACH_MOD(OnPostConnect, (this));
564 ServerInstance->SNO->WriteToSnoMask('c',"Client connecting on port %d (class %s): %s (%s) [%s]",
565 this->server_sa.port(), this->MyClass->name.c_str(), GetFullRealHost().c_str(), this->GetIPString().c_str(), this->GetRealName().c_str());
566 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Adding NEGATIVE hit for " + this->GetIPString());
567 ServerInstance->BanCache.AddHit(this->GetIPString(), "", "");
568 // reset the flood penalty (which could have been raised due to things like auto +x)
569 CommandFloodPenalty = 0;
572 void User::InvalidateCache()
574 /* Invalidate cache */
576 cached_fullhost.clear();
577 cached_hostip.clear();
578 cached_makehost.clear();
579 cached_fullrealhost.clear();
582 bool User::ChangeNick(const std::string& newnick, time_t newts)
586 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Attempted to change nick of a quitting user: " + this->nick);
590 User* const InUse = ServerInstance->FindNickOnly(newnick);
593 // case change, don't need to check campers
594 // and, if it's identical including case, we can leave right now
595 // We also don't update the nick TS if it's a case change, either
602 * Uh oh.. if the nickname is in use, and it's not in use by the person using it (doh) --
603 * then we have a potential collide. Check whether someone else is camping on the nick
604 * (i.e. connect -> send NICK, don't send USER.) If they are camping, force-change the
605 * camper to their UID, and allow the incoming nick change.
607 * If the guy using the nick is already using it, tell the incoming nick change to gtfo,
608 * because the nick is already (rightfully) in use. -- w00t
612 if (InUse->registered != REG_ALL)
614 /* force the camper to their UUID, and ask them to re-send a NICK. */
615 LocalUser* const localuser = static_cast<LocalUser*>(InUse);
616 localuser->OverruleNick();
620 /* No camping, tell the incoming user to stop trying to change nick ;p */
621 this->WriteNumeric(ERR_NICKNAMEINUSE, newnick, "Nickname is already in use.");
626 age = newts ? newts : ServerInstance->Time();
629 if (this->registered == REG_ALL)
631 ClientProtocol::Messages::Nick nickmsg(this, newnick);
632 ClientProtocol::Event nickevent(ServerInstance->GetRFCEvents().nick, nickmsg);
633 this->WriteCommonRaw(nickevent, true);
635 const std::string oldnick = nick;
639 ServerInstance->Users->clientlist.erase(oldnick);
640 ServerInstance->Users->clientlist[newnick] = this;
642 if (registered == REG_ALL)
643 FOREACH_MOD(OnUserPostNick, (this,oldnick));
648 void LocalUser::OverruleNick()
651 ClientProtocol::Messages::Nick nickmsg(this, this->uuid);
652 this->Send(ServerInstance->GetRFCEvents().nick, nickmsg);
654 this->WriteNumeric(ERR_NICKNAMEINUSE, this->nick, "Nickname overruled.");
656 // Clear the bit before calling ChangeNick() to make it NOT run the OnUserPostNick() hook
657 this->registered &= ~REG_NICK;
658 this->ChangeNick(this->uuid);
661 const std::string& User::GetIPString()
663 if (cachedip.empty())
665 cachedip = client_sa.addr();
666 /* IP addresses starting with a : on irc are a Bad Thing (tm) */
667 if (cachedip[0] == ':')
668 cachedip.insert(cachedip.begin(),1,'0');
674 const std::string& User::GetHost(bool uncloak) const
676 return uncloak ? GetRealHost() : GetDisplayedHost();
679 const std::string& User::GetDisplayedHost() const
681 return displayhost.empty() ? realhost : displayhost;
684 const std::string& User::GetRealHost() const
689 const std::string& User::GetRealName() const
694 irc::sockets::cidr_mask User::GetCIDRMask()
696 unsigned char range = 0;
697 switch (client_sa.family())
700 range = ServerInstance->Config->c_ipv6_range;
703 range = ServerInstance->Config->c_ipv4_range;
706 return irc::sockets::cidr_mask(client_sa, range);
709 bool User::SetClientIP(const std::string& address)
711 irc::sockets::sockaddrs sa;
712 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
715 User::SetClientIP(sa);
719 void User::SetClientIP(const irc::sockets::sockaddrs& sa)
721 const std::string oldip(GetIPString());
722 memcpy(&client_sa, &sa, sizeof(irc::sockets::sockaddrs));
723 this->InvalidateCache();
725 // If the users hostname was their IP then update it.
726 if (GetRealHost() == oldip)
727 ChangeRealHost(GetIPString(), false);
728 if (GetDisplayedHost() == oldip)
729 ChangeDisplayedHost(GetIPString());
732 bool LocalUser::SetClientIP(const std::string& address)
734 irc::sockets::sockaddrs sa;
735 if (!irc::sockets::aptosa(address, client_sa.port(), sa))
738 LocalUser::SetClientIP(sa);
742 void LocalUser::SetClientIP(const irc::sockets::sockaddrs& sa)
747 ServerInstance->Users->RemoveCloneCounts(this);
749 User::SetClientIP(sa);
751 FOREACH_MOD(OnSetUserIP, (this));
753 ServerInstance->Users->AddClone(this);
755 // Recheck the connect class.
756 this->MyClass = NULL;
761 void LocalUser::Write(const ClientProtocol::SerializedMessage& text)
763 if (!SocketEngine::BoundsCheckFd(&eh))
766 if (ServerInstance->Config->RawLog)
771 std::string::size_type nlpos = text.find_first_of("\r\n", 0, 2);
772 if (nlpos == std::string::npos)
773 nlpos = text.length(); // TODO is this ok, test it
775 ServerInstance->Logs->Log("USEROUTPUT", LOG_RAWIO, "C[%s] O %.*s", uuid.c_str(), (int) nlpos, text.c_str());
778 eh.AddWriteBuf(text);
780 const size_t bytessent = text.length() + 2;
781 ServerInstance->stats.Sent += bytessent;
782 this->bytes_out += bytessent;
786 void LocalUser::Send(ClientProtocol::Event& protoev)
790 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "BUG: LocalUser::Send() called on %s who does not have a serializer!",
791 GetFullRealHost().c_str());
795 // In the most common case a static LocalUser field, sendmsglist, is passed to the event to be
796 // populated. The list is cleared before returning.
797 // To handle re-enters, if sendmsglist is non-empty upon entering the method then a temporary
798 // list is used instead of the static one.
799 if (sendmsglist.empty())
801 Send(protoev, sendmsglist);
806 ClientProtocol::MessageList msglist;
807 Send(protoev, msglist);
811 void LocalUser::Send(ClientProtocol::Event& protoev, ClientProtocol::MessageList& msglist)
813 // Modules can personalize the messages sent per user for the event
814 protoev.GetMessagesForUser(this, msglist);
815 for (ClientProtocol::MessageList::const_iterator i = msglist.begin(); i != msglist.end(); ++i)
817 ClientProtocol::Message& curr = **i;
819 FIRST_MOD_RESULT(OnUserWrite, res, (this, curr));
820 if (res != MOD_RES_DENY)
821 Write(serializer->SerializeForUser(this, curr));
825 void User::WriteNumeric(const Numeric::Numeric& numeric)
827 LocalUser* const localuser = IS_LOCAL(this);
831 ModResult MOD_RESULT;
833 FIRST_MOD_RESULT(OnNumeric, MOD_RESULT, (this, numeric));
835 if (MOD_RESULT == MOD_RES_DENY)
838 ClientProtocol::Messages::Numeric numericmsg(numeric, localuser);
839 localuser->Send(ServerInstance->GetRFCEvents().numeric, numericmsg);
842 void User::WriteRemoteNotice(const std::string& text)
844 ServerInstance->PI->SendUserNotice(this, text);
847 void LocalUser::WriteRemoteNotice(const std::string& text)
854 class WriteCommonRawHandler : public User::ForEachNeighborHandler
856 ClientProtocol::Event& ev;
858 void Execute(LocalUser* user) CXX11_OVERRIDE
864 WriteCommonRawHandler(ClientProtocol::Event& protoev)
871 void User::WriteCommonRaw(ClientProtocol::Event& protoev, bool include_self)
873 WriteCommonRawHandler handler(protoev);
874 ForEachNeighbor(handler, include_self);
877 void User::ForEachNeighbor(ForEachNeighborHandler& handler, bool include_self)
879 // The basic logic for visiting the neighbors of a user is to iterate the channel list of the user
880 // and visit all users on those channels. Because two users may share more than one common channel,
881 // we must skip users that we have already visited.
882 // To do this, we make use of a global counter and an integral 'already_sent' field in LocalUser.
883 // The global counter is incremented every time we do something for each neighbor of a user. Then,
884 // before visiting a member we examine user->already_sent. If it's equal to the current counter, we
885 // skip the member. Otherwise, we set it to the current counter and visit the member.
887 // Ask modules to build a list of exceptions.
888 // Mods may also exclude entire channels by erasing them from include_chans.
889 IncludeChanList include_chans(chans.begin(), chans.end());
890 std::map<User*, bool> exceptions;
891 exceptions[this] = include_self;
892 FOREACH_MOD(OnBuildNeighborList, (this, include_chans, exceptions));
894 // Get next id, guaranteed to differ from the already_sent field of all users
895 const already_sent_t newid = ServerInstance->Users.NextAlreadySentId();
897 // Handle exceptions first
898 for (std::map<User*, bool>::const_iterator i = exceptions.begin(); i != exceptions.end(); ++i)
900 LocalUser* curr = IS_LOCAL(i->first);
903 // Mark as visited to ensure we won't visit again if there is a common channel
904 curr->already_sent = newid;
905 // Always treat quitting users as excluded
906 if ((i->second) && (!curr->quitting))
907 handler.Execute(curr);
911 // Now consider the real neighbors
912 for (IncludeChanList::const_iterator i = include_chans.begin(); i != include_chans.end(); ++i)
914 Channel* chan = (*i)->chan;
915 const Channel::MemberMap& userlist = chan->GetUsers();
916 for (Channel::MemberMap::const_iterator j = userlist.begin(); j != userlist.end(); ++j)
918 LocalUser* curr = IS_LOCAL(j->first);
919 // User not yet visited?
920 if ((curr) && (curr->already_sent != newid))
922 // Mark as visited and execute function
923 curr->already_sent = newid;
924 handler.Execute(curr);
930 void User::WriteRemoteNumeric(const Numeric::Numeric& numeric)
932 WriteNumeric(numeric);
935 /* return 0 or 1 depending if users u and u2 share one or more common channels
936 * (used by QUIT, NICK etc which arent channel specific notices)
938 * The old algorithm in 1.0 for this was relatively inefficient, iterating over
939 * the first users channels then the second users channels within the outer loop,
940 * therefore it was a maximum of x*y iterations (upon returning 0 and checking
941 * all possible iterations). However this new function instead checks against the
942 * channel's userlist in the inner loop which is a std::map<User*,User*>
943 * and saves us time as we already know what pointer value we are after.
944 * Don't quote me on the maths as i am not a mathematician or computer scientist,
945 * but i believe this algorithm is now x+(log y) maximum iterations instead.
947 bool User::SharesChannelWith(User *other)
950 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); ++i)
952 /* Eliminate the inner loop (which used to be ~equal in size to the outer loop)
953 * by replacing it with a map::find which *should* be more efficient
955 if ((*i)->chan->HasUser(other))
961 bool User::ChangeRealName(const std::string& real)
963 if (!this->realname.compare(real))
968 ModResult MOD_RESULT;
969 FIRST_MOD_RESULT(OnPreChangeRealName, MOD_RESULT, (IS_LOCAL(this), real));
970 if (MOD_RESULT == MOD_RES_DENY)
972 FOREACH_MOD(OnChangeRealName, (this, real));
974 this->realname.assign(real, 0, ServerInstance->Config->Limits.MaxReal);
979 bool User::ChangeDisplayedHost(const std::string& shost)
981 if (GetDisplayedHost() == shost)
984 LocalUser* luser = IS_LOCAL(this);
987 ModResult MOD_RESULT;
988 FIRST_MOD_RESULT(OnPreChangeHost, MOD_RESULT, (luser, shost));
989 if (MOD_RESULT == MOD_RES_DENY)
993 FOREACH_MOD(OnChangeHost, (this,shost));
995 if (realhost == shost)
996 this->displayhost.clear();
998 this->displayhost.assign(shost, 0, ServerInstance->Config->Limits.MaxHost);
1000 this->InvalidateCache();
1002 if (IS_LOCAL(this) && this->registered != REG_NONE)
1003 this->WriteNumeric(RPL_YOURDISPLAYEDHOST, this->GetDisplayedHost(), "is now your displayed host");
1008 void User::ChangeRealHost(const std::string& host, bool resetdisplay)
1010 // If the real host is the new host and we are not resetting the
1011 // display host then we have nothing to do.
1012 const bool changehost = (realhost != host);
1013 if (!changehost && !resetdisplay)
1016 // If the displayhost is not set and we are not resetting it then
1017 // we need to copy it to the displayhost field.
1018 if (displayhost.empty() && !resetdisplay)
1019 displayhost = realhost;
1021 // If the displayhost is the new host or we are resetting it then
1022 // we clear its contents to save memory.
1023 else if (displayhost == host || resetdisplay)
1024 displayhost.clear();
1026 // If we are just resetting the display host then we don't need to
1027 // do anything else.
1032 this->InvalidateCache();
1035 bool User::ChangeIdent(const std::string& newident)
1037 if (this->ident == newident)
1040 FOREACH_MOD(OnChangeIdent, (this,newident));
1042 this->ident.assign(newident, 0, ServerInstance->Config->Limits.IdentMax);
1043 this->InvalidateCache();
1049 * Sets a user's connection class.
1050 * If the class name is provided, it will be used. Otherwise, the class will be guessed using host/ip/ident/etc.
1051 * NOTE: If the <ALLOW> or <DENY> tag specifies an ip, and this user resolves,
1052 * then their ip will be taken as 'priority' anyway, so for example,
1053 * <connect allow="127.0.0.1"> will match joe!bloggs@localhost
1055 void LocalUser::SetClass(const std::string &explicit_name)
1057 ConnectClass *found = NULL;
1059 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Setting connect class for UID %s", this->uuid.c_str());
1061 if (!explicit_name.empty())
1063 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1065 ConnectClass* c = *i;
1067 if (explicit_name == c->name)
1069 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Explicitly set to %s", explicit_name.c_str());
1076 for (ServerConfig::ClassVector::const_iterator i = ServerInstance->Config->Classes.begin(); i != ServerInstance->Config->Classes.end(); ++i)
1078 ConnectClass* c = *i;
1079 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Checking %s", c->GetName().c_str());
1081 ModResult MOD_RESULT;
1082 FIRST_MOD_RESULT(OnSetConnectClass, MOD_RESULT, (this,c));
1083 if (MOD_RESULT == MOD_RES_DENY)
1085 if (MOD_RESULT == MOD_RES_ALLOW)
1087 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Class forced by module to %s", c->GetName().c_str());
1092 if (c->type == CC_NAMED)
1095 bool regdone = (registered != REG_NONE);
1096 if (c->config->getBool("registered", regdone) != regdone)
1099 /* check if host matches.. */
1100 if (!InspIRCd::MatchCIDR(this->GetIPString(), c->GetHost(), NULL) &&
1101 !InspIRCd::MatchCIDR(this->GetRealHost(), c->GetHost(), NULL))
1103 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "No host match (for %s)", c->GetHost().c_str());
1108 * deny change if change will take class over the limit check it HERE, not after we found a matching class,
1109 * because we should attempt to find another class if this one doesn't match us. -- w00t
1111 if (c->limit && (c->GetReferenceCount() >= c->limit))
1113 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "OOPS: Connect class limit (%lu) hit, denying", c->limit);
1117 /* if it requires a port ... */
1118 if (!c->ports.empty())
1120 /* and our port doesn't match, fail. */
1121 if (!c->ports.count(this->server_sa.port()))
1123 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Requires a different port, skipping");
1128 if (regdone && !c->config->getString("password").empty())
1130 if (!ServerInstance->PassCompare(this, c->config->getString("password"), password, c->config->getString("hash")))
1132 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEBUG, "Bad password, skipping");
1137 /* we stop at the first class that meets ALL critera. */
1144 * Okay, assuming we found a class that matches.. switch us into that class, keeping refcounts up to date.
1152 void User::PurgeEmptyChannels()
1154 // firstly decrement the count on each channel
1155 for (User::ChanList::iterator i = this->chans.begin(); i != this->chans.end(); )
1157 Channel* c = (*i)->chan;
1163 void User::WriteNotice(const std::string& text)
1165 LocalUser* const localuser = IS_LOCAL(this);
1169 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, localuser, text, MSG_NOTICE);
1170 localuser->Send(ServerInstance->GetRFCEvents().privmsg, msg);
1173 const std::string& FakeUser::GetFullHost()
1175 if (!ServerInstance->Config->HideServer.empty())
1176 return ServerInstance->Config->HideServer;
1177 return server->GetName();
1180 const std::string& FakeUser::GetFullRealHost()
1182 if (!ServerInstance->Config->HideServer.empty())
1183 return ServerInstance->Config->HideServer;
1184 return server->GetName();
1187 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask)
1188 : config(tag), type(t), fakelag(true), name("unnamed"), registration_timeout(0), host(mask),
1189 pingtime(0), softsendqmax(0), hardsendqmax(0), recvqmax(0),
1190 penaltythreshold(0), commandrate(0), maxlocal(0), maxglobal(0), maxconnwarn(true), maxchans(ServerInstance->Config->MaxChans),
1191 limit(0), resolvehostnames(true)
1195 ConnectClass::ConnectClass(ConfigTag* tag, char t, const std::string& mask, const ConnectClass& parent)
1202 // Connect classes can inherit from each other but this is problematic for modules which can't use
1203 // ConnectClass::Update so we build a hybrid tag containing all of the values set on this class as
1204 // well as the parent class.
1205 ConfigItems* items = NULL;
1206 config = ConfigTag::create(tag->tag, tag->src_name, tag->src_line, items);
1208 const ConfigItems& parentkeys = parent.config->getItems();
1209 for (ConfigItems::const_iterator piter = parentkeys.begin(); piter != parentkeys.end(); ++piter)
1211 // The class name and parent name are not inherited
1212 if (stdalgo::string::equalsci(piter->first, "name") || stdalgo::string::equalsci(piter->first, "parent"))
1215 // Store the item in the config tag. If this item also
1216 // exists in the child it will be overwritten.
1217 (*items)[piter->first] = piter->second;
1220 const ConfigItems& childkeys = tag->getItems();
1221 for (ConfigItems::const_iterator citer = childkeys.begin(); citer != childkeys.end(); ++citer)
1223 // This will overwrite the parent value if present.
1224 (*items)[citer->first] = citer->second;
1228 void ConnectClass::Update(const ConnectClass* src)
1230 config = src->config;
1232 fakelag = src->fakelag;
1234 registration_timeout = src->registration_timeout;
1236 pingtime = src->pingtime;
1237 softsendqmax = src->softsendqmax;
1238 hardsendqmax = src->hardsendqmax;
1239 recvqmax = src->recvqmax;
1240 penaltythreshold = src->penaltythreshold;
1241 commandrate = src->commandrate;
1242 maxlocal = src->maxlocal;
1243 maxglobal = src->maxglobal;
1244 maxconnwarn = src->maxconnwarn;
1245 maxchans = src->maxchans;
1247 resolvehostnames = src->resolvehostnames;