2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2019 iwalkalone <iwalkalone69@gmail.com>
5 * Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
6 * Copyright (C) 2013-2016, 2018 Attila Molnar <attilamolnar@hush.com>
7 * Copyright (C) 2013, 2018-2019 Sadie Powell <sadie@witchery.services>
8 * Copyright (C) 2013, 2015 Adam <Adam@anope.org>
9 * Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
10 * Copyright (C) 2012, 2019 Robby <robby@chatbelgie.be>
11 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12 * Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
13 * Copyright (C) 2008-2010 Craig Edwards <brain@inspircd.org>
14 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
16 * This file is part of InspIRCd. InspIRCd is free software: you can
17 * redistribute it and/or modify it under the terms of the GNU General Public
18 * License as published by the Free Software Foundation, version 2.
20 * This program is distributed in the hope that it will be useful, but WITHOUT
21 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
36 class WriteCommonQuit : public User::ForEachNeighborHandler
38 ClientProtocol::Messages::Quit quitmsg;
39 ClientProtocol::Event quitevent;
40 ClientProtocol::Messages::Quit operquitmsg;
41 ClientProtocol::Event operquitevent;
43 void Execute(LocalUser* user) CXX11_OVERRIDE
45 user->Send(user->IsOper() ? operquitevent : quitevent);
49 WriteCommonQuit(User* user, const std::string& msg, const std::string& opermsg)
51 , quitevent(ServerInstance->GetRFCEvents().quit, quitmsg)
52 , operquitmsg(user, opermsg)
53 , operquitevent(ServerInstance->GetRFCEvents().quit, operquitmsg)
55 user->ForEachNeighbor(*this, false);
59 void CheckPingTimeout(LocalUser* user)
61 // Check if it is time to ping the user yet.
62 if (ServerInstance->Time() < user->nextping)
65 // This user didn't answer the last ping, remove them.
69 FIRST_MOD_RESULT(OnConnectionFail, res, (user, I_ERR_TIMEOUT));
70 if (res == MOD_RES_ALLOW)
72 // A module is preventing this user from being timed out.
74 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
78 time_t secs = ServerInstance->Time() - (user->nextping - user->MyClass->GetPingTime());
79 const std::string message = "Ping timeout: " + ConvToStr(secs) + (secs != 1 ? " seconds" : " second");
80 ServerInstance->Users.QuitUser(user, message);
84 // Send a ping to the client.
85 ClientProtocol::Messages::Ping ping;
86 user->Send(ServerInstance->GetRFCEvents().ping, ping);
88 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
91 void CheckRegistrationTimeout(LocalUser* user)
93 if (user->GetClass() && (ServerInstance->Time() > (user->signon + user->GetClass()->GetRegTimeout())))
95 // Either the user did not send NICK/USER or a module blocked registration in
96 // OnCheckReady until the client timed out.
97 ServerInstance->Users.QuitUser(user, "Registration timeout");
101 void CheckModulesReady(LocalUser* user)
104 FIRST_MOD_RESULT(OnCheckReady, res, (user));
105 if (res == MOD_RES_PASSTHRU)
107 // User has sent NICK/USER and modules are ready.
112 // If the user has been quit in OnCheckReady then we shouldn't quit
113 // them again for having a registration timeout.
115 CheckRegistrationTimeout(user);
119 UserManager::UserManager()
121 , unregistered_count(0)
125 UserManager::~UserManager()
127 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); ++i)
133 void UserManager::AddUser(int socket, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
135 // User constructor allocates a new UUID for the user and inserts it into the uuidlist
136 LocalUser* const New = new LocalUser(socket, client, server);
137 UserIOHandler* eh = &New->eh;
139 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New user fd: %d", socket);
141 this->unregistered_count++;
142 this->clientlist[New->nick] = New;
144 this->local_users.push_front(New);
145 FOREACH_MOD(OnUserInit, (New));
147 if (!SocketEngine::AddFd(eh, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE))
149 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Internal error on new connection");
150 this->QuitUser(New, "Internal error handling connection");
154 // If this listener has an IO hook provider set then tell it about the connection
155 for (ListenSocket::IOHookProvList::iterator i = via->iohookprovs.begin(); i != via->iohookprovs.end(); ++i)
157 ListenSocket::IOHookProvRef& iohookprovref = *i;
160 if (!iohookprovref.GetProvider().empty())
162 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Non-existent I/O hook '%s' in <bind:%s> tag at %s",
163 iohookprovref.GetProvider().c_str(),
164 i == via->iohookprovs.begin() ? "hook" : "ssl",
165 via->bind_tag->getTagLocation().c_str());
166 this->QuitUser(New, "Internal error handling connection");
172 iohookprovref->OnAccept(eh, client, server);
174 // IOHook could have encountered a fatal error, e.g. if the TLS ClientHello
175 // was already in the queue and there was no common TLS version.
176 if (!eh->getError().empty())
178 QuitUser(New, eh->getError());
183 if (this->local_users.size() > ServerInstance->Config->SoftLimit)
185 ServerInstance->SNO->WriteToSnoMask('a', "Warning: softlimit value has been reached: %d clients", ServerInstance->Config->SoftLimit);
186 this->QuitUser(New,"No more connections allowed");
190 // First class check. We do this again in LocalUser::FullConnect() after DNS is done, and NICK/USER is received.
192 // If the user doesn't have an acceptable connect class CheckClass() quits them
193 New->CheckClass(ServerInstance->Config->CCOnConnect);
198 * even with bancache, we still have to keep User::exempt current.
199 * besides that, if we get a positive bancache hit, we still won't fuck
200 * them over if they are exempt. -- w00t
202 New->exempt = (ServerInstance->XLines->MatchesLine("E",New) != NULL);
204 BanCacheHit* const b = ServerInstance->BanCache.GetHit(New->GetIPString());
207 if (!b->Type.empty() && !New->exempt)
210 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Positive hit for " + New->GetIPString());
211 if (!ServerInstance->Config->XLineMessage.empty())
212 New->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
214 if (ServerInstance->Config->HideBans)
215 this->QuitUser(New, b->Type + "-lined", &b->Reason);
217 this->QuitUser(New, b->Reason);
222 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Negative hit for " + New->GetIPString());
229 XLine* r = ServerInstance->XLines->MatchesLine("Z",New);
239 if (ServerInstance->Config->RawLog)
240 New->WriteNotice("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
242 FOREACH_MOD(OnSetUserIP, (New));
244 FOREACH_MOD(OnUserPostInit, (New));
247 void UserManager::QuitUser(User* user, const std::string& quitmessage, const std::string* operquitmessage)
251 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit quitting user: " + user->nick);
257 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit server user: " + user->nick);
261 std::string quitmsg(quitmessage);
262 std::string operquitmsg;
264 operquitmsg.assign(*operquitmessage);
266 LocalUser* const localuser = IS_LOCAL(user);
269 ModResult MOD_RESULT;
270 FIRST_MOD_RESULT(OnUserPreQuit, MOD_RESULT, (localuser, quitmsg, operquitmsg));
271 if (MOD_RESULT == MOD_RES_DENY)
275 if (quitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
276 quitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
278 if (operquitmsg.empty())
279 operquitmsg.assign(quitmsg);
280 else if (operquitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
281 operquitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
283 user->quitting = true;
284 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "QuitUser: %s=%s '%s'", user->uuid.c_str(), user->nick.c_str(), quitmessage.c_str());
287 ClientProtocol::Messages::Error errormsg(InspIRCd::Format("Closing link: (%s@%s) [%s]", user->ident.c_str(), user->GetRealHost().c_str(), operquitmsg.c_str()));
288 localuser->Send(ServerInstance->GetRFCEvents().error, errormsg);
291 ServerInstance->GlobalCulls.AddItem(user);
293 if (user->registered == REG_ALL)
295 FOREACH_MOD(OnUserQuit, (user, quitmsg, operquitmsg));
296 WriteCommonQuit(user, quitmsg, operquitmsg);
299 unregistered_count--;
303 LocalUser* lu = IS_LOCAL(user);
304 FOREACH_MOD(OnUserDisconnect, (lu));
307 if (lu->registered == REG_ALL)
308 ServerInstance->SNO->WriteToSnoMask('q',"Client exiting: %s (%s) [%s]", user->GetFullRealHost().c_str(), user->GetIPString().c_str(), operquitmsg.c_str());
309 local_users.erase(lu);
312 if (!clientlist.erase(user->nick))
313 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Nick not found in clientlist, cannot remove: " + user->nick);
315 uuidlist.erase(user->uuid);
316 user->PurgeEmptyChannels();
320 void UserManager::AddClone(User* user)
322 CloneCounts& counts = clonemap[user->GetCIDRMask()];
328 void UserManager::RemoveCloneCounts(User *user)
330 CloneMap::iterator it = clonemap.find(user->GetCIDRMask());
331 if (it != clonemap.end())
333 CloneCounts& counts = it->second;
335 if (counts.global == 0)
337 // No more users from this IP, remove entry from the map
347 void UserManager::RehashCloneCounts()
351 const user_hash& hash = ServerInstance->Users.GetUsers();
352 for (user_hash::const_iterator i = hash.begin(); i != hash.end(); ++i)
359 const UserManager::CloneCounts& UserManager::GetCloneCounts(User* user) const
361 CloneMap::const_iterator it = clonemap.find(user->GetCIDRMask());
362 if (it != clonemap.end())
365 return zeroclonecounts;
368 void UserManager::ServerNoticeAll(const char* text, ...)
371 VAFORMAT(message, text, text);
372 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, ServerInstance->Config->GetServerName(), message, MSG_NOTICE);
373 ClientProtocol::Event msgevent(ServerInstance->GetRFCEvents().privmsg, msg);
375 for (LocalList::const_iterator i = local_users.begin(); i != local_users.end(); ++i)
377 LocalUser* user = *i;
378 user->Send(msgevent);
383 * This function is called once a second from the mainloop.
384 * It is intended to do background checking on all the users, e.g. do
385 * ping checks, registration timeouts, etc.
387 void UserManager::DoBackgroundUserStuff()
389 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); )
391 // It's possible that we quit the user below due to ping timeout etc. and QuitUser() removes it from the list
392 LocalUser* curr = *i;
395 if (curr->CommandFloodPenalty || curr->eh.getSendQSize())
397 unsigned int rate = curr->MyClass->GetCommandRate();
398 if (curr->CommandFloodPenalty > rate)
399 curr->CommandFloodPenalty -= rate;
401 curr->CommandFloodPenalty = 0;
402 curr->eh.OnDataReady();
405 switch (curr->registered)
408 CheckPingTimeout(curr);
412 CheckModulesReady(curr);
416 CheckRegistrationTimeout(curr);
422 already_sent_t UserManager::NextAlreadySentId()
424 if (++already_sent_id == 0)
426 // Wrapped around, reset the already_sent ids of all users
428 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); ++i)
430 LocalUser* user = *i;
431 user->already_sent = 0;
434 return already_sent_id;