2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5 * Copyright (C) 2008 Dennis Friis <peavey@inspircd.org>
6 * Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
7 * Copyright (C) 2008 Craig Edwards <craigedwards@brainbox.cc>
9 * This file is part of InspIRCd. InspIRCd is free software: you can
10 * redistribute it and/or modify it under the terms of the GNU General Public
11 * License as published by the Free Software Foundation, version 2.
13 * This program is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 class WriteCommonQuit : public User::ForEachNeighborHandler
31 ClientProtocol::Messages::Quit quitmsg;
32 ClientProtocol::Event quitevent;
33 ClientProtocol::Messages::Quit operquitmsg;
34 ClientProtocol::Event operquitevent;
36 void Execute(LocalUser* user) CXX11_OVERRIDE
38 user->Send(user->IsOper() ? operquitevent : quitevent);
42 WriteCommonQuit(User* user, const std::string& msg, const std::string& opermsg)
44 , quitevent(ServerInstance->GetRFCEvents().quit, quitmsg)
45 , operquitmsg(user, opermsg)
46 , operquitevent(ServerInstance->GetRFCEvents().quit, operquitmsg)
48 user->ForEachNeighbor(*this, false);
52 void CheckPingTimeout(LocalUser* user)
54 // Check if it is time to ping the user yet.
55 if (ServerInstance->Time() < user->nextping)
58 // This user didn't answer the last ping, remove them.
62 FIRST_MOD_RESULT(OnConnectionFail, res, (user, I_ERR_TIMEOUT));
63 if (res == MOD_RES_ALLOW)
65 // A module is preventing this user from being timed out.
67 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
71 time_t secs = ServerInstance->Time() - (user->nextping - user->MyClass->GetPingTime());
72 const std::string message = "Ping timeout: " + ConvToStr(secs) + (secs != 1 ? " seconds" : " second");
73 ServerInstance->Users.QuitUser(user, message);
77 // Send a ping to the client.
78 ClientProtocol::Messages::Ping ping;
79 user->Send(ServerInstance->GetRFCEvents().ping, ping);
81 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
84 void CheckRegistrationTimeout(LocalUser* user)
86 if (user->GetClass() && (ServerInstance->Time() > (user->signon + user->GetClass()->GetRegTimeout())))
88 // Either the user did not send NICK/USER or a module blocked registration in
89 // OnCheckReady until the client timed out.
90 ServerInstance->Users.QuitUser(user, "Registration timeout");
94 void CheckModulesReady(LocalUser* user)
97 FIRST_MOD_RESULT(OnCheckReady, res, (user));
98 if (res == MOD_RES_PASSTHRU)
100 // User has sent NICK/USER and modules are ready.
105 // If the user has been quit in OnCheckReady then we shouldn't quit
106 // them again for having a registration timeout.
108 CheckRegistrationTimeout(user);
112 UserManager::UserManager()
114 , unregistered_count(0)
118 UserManager::~UserManager()
120 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); ++i)
126 void UserManager::AddUser(int socket, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
128 // User constructor allocates a new UUID for the user and inserts it into the uuidlist
129 LocalUser* const New = new LocalUser(socket, client, server);
130 UserIOHandler* eh = &New->eh;
132 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New user fd: %d", socket);
134 this->unregistered_count++;
135 this->clientlist[New->nick] = New;
137 this->local_users.push_front(New);
138 FOREACH_MOD(OnUserInit, (New));
140 if (!SocketEngine::AddFd(eh, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE))
142 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Internal error on new connection");
143 this->QuitUser(New, "Internal error handling connection");
147 // If this listener has an IO hook provider set then tell it about the connection
148 for (ListenSocket::IOHookProvList::iterator i = via->iohookprovs.begin(); i != via->iohookprovs.end(); ++i)
150 ListenSocket::IOHookProvRef& iohookprovref = *i;
154 iohookprovref->OnAccept(eh, client, server);
155 // IOHook could have encountered a fatal error, e.g. if the TLS ClientHello was already in the queue and there was no common TLS version
156 if (!eh->getError().empty())
158 QuitUser(New, eh->getError());
163 if (this->local_users.size() > ServerInstance->Config->SoftLimit)
165 ServerInstance->SNO->WriteToSnoMask('a', "Warning: softlimit value has been reached: %d clients", ServerInstance->Config->SoftLimit);
166 this->QuitUser(New,"No more connections allowed");
170 // First class check. We do this again in LocalUser::FullConnect() after DNS is done, and NICK/USER is received.
172 // If the user doesn't have an acceptable connect class CheckClass() quits them
173 New->CheckClass(ServerInstance->Config->CCOnConnect);
178 * even with bancache, we still have to keep User::exempt current.
179 * besides that, if we get a positive bancache hit, we still won't fuck
180 * them over if they are exempt. -- w00t
182 New->exempt = (ServerInstance->XLines->MatchesLine("E",New) != NULL);
184 BanCacheHit* const b = ServerInstance->BanCache.GetHit(New->GetIPString());
187 if (!b->Type.empty() && !New->exempt)
190 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Positive hit for " + New->GetIPString());
191 if (!ServerInstance->Config->XLineMessage.empty())
192 New->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
194 if (ServerInstance->Config->HideBans)
195 this->QuitUser(New, b->Type + "-lined", &b->Reason);
197 this->QuitUser(New, b->Reason);
202 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Negative hit for " + New->GetIPString());
209 XLine* r = ServerInstance->XLines->MatchesLine("Z",New);
219 if (ServerInstance->Config->RawLog)
220 New->WriteNotice("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
222 FOREACH_MOD(OnSetUserIP, (New));
224 FOREACH_MOD(OnUserPostInit, (New));
227 void UserManager::QuitUser(User* user, const std::string& quitmessage, const std::string* operquitmessage)
231 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit quitting user: " + user->nick);
237 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit server user: " + user->nick);
241 std::string quitmsg(quitmessage);
242 std::string operquitmsg;
244 operquitmsg.assign(*operquitmessage);
246 LocalUser* const localuser = IS_LOCAL(user);
249 ModResult MOD_RESULT;
250 FIRST_MOD_RESULT(OnUserPreQuit, MOD_RESULT, (localuser, quitmsg, operquitmsg));
251 if (MOD_RESULT == MOD_RES_DENY)
255 if (quitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
256 quitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
258 if (operquitmsg.empty())
259 operquitmsg.assign(quitmsg);
260 else if (operquitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
261 operquitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
263 user->quitting = true;
264 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "QuitUser: %s=%s '%s'", user->uuid.c_str(), user->nick.c_str(), quitmessage.c_str());
267 ClientProtocol::Messages::Error errormsg(InspIRCd::Format("Closing link: (%s@%s) [%s]", user->ident.c_str(), user->GetRealHost().c_str(), operquitmsg.c_str()));
268 localuser->Send(ServerInstance->GetRFCEvents().error, errormsg);
271 ServerInstance->GlobalCulls.AddItem(user);
273 if (user->registered == REG_ALL)
275 FOREACH_MOD(OnUserQuit, (user, quitmsg, operquitmsg));
276 WriteCommonQuit(user, quitmsg, operquitmsg);
279 unregistered_count--;
283 LocalUser* lu = IS_LOCAL(user);
284 FOREACH_MOD(OnUserDisconnect, (lu));
287 if (lu->registered == REG_ALL)
288 ServerInstance->SNO->WriteToSnoMask('q',"Client exiting: %s (%s) [%s]", user->GetFullRealHost().c_str(), user->GetIPString().c_str(), operquitmsg.c_str());
289 local_users.erase(lu);
292 if (!clientlist.erase(user->nick))
293 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Nick not found in clientlist, cannot remove: " + user->nick);
295 uuidlist.erase(user->uuid);
296 user->PurgeEmptyChannels();
300 void UserManager::AddClone(User* user)
302 CloneCounts& counts = clonemap[user->GetCIDRMask()];
308 void UserManager::RemoveCloneCounts(User *user)
310 CloneMap::iterator it = clonemap.find(user->GetCIDRMask());
311 if (it != clonemap.end())
313 CloneCounts& counts = it->second;
315 if (counts.global == 0)
317 // No more users from this IP, remove entry from the map
327 void UserManager::RehashCloneCounts()
331 const user_hash& hash = ServerInstance->Users.GetUsers();
332 for (user_hash::const_iterator i = hash.begin(); i != hash.end(); ++i)
339 const UserManager::CloneCounts& UserManager::GetCloneCounts(User* user) const
341 CloneMap::const_iterator it = clonemap.find(user->GetCIDRMask());
342 if (it != clonemap.end())
345 return zeroclonecounts;
348 void UserManager::ServerNoticeAll(const char* text, ...)
351 VAFORMAT(message, text, text);
352 ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, ServerInstance->Config->ServerName, message, MSG_NOTICE);
353 ClientProtocol::Event msgevent(ServerInstance->GetRFCEvents().privmsg, msg);
355 for (LocalList::const_iterator i = local_users.begin(); i != local_users.end(); ++i)
357 LocalUser* user = *i;
358 user->Send(msgevent);
363 * This function is called once a second from the mainloop.
364 * It is intended to do background checking on all the users, e.g. do
365 * ping checks, registration timeouts, etc.
367 void UserManager::DoBackgroundUserStuff()
369 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); )
371 // It's possible that we quit the user below due to ping timeout etc. and QuitUser() removes it from the list
372 LocalUser* curr = *i;
375 if (curr->CommandFloodPenalty || curr->eh.getSendQSize())
377 unsigned int rate = curr->MyClass->GetCommandRate();
378 if (curr->CommandFloodPenalty > rate)
379 curr->CommandFloodPenalty -= rate;
381 curr->CommandFloodPenalty = 0;
382 curr->eh.OnDataReady();
385 switch (curr->registered)
388 CheckPingTimeout(curr);
392 CheckModulesReady(curr);
396 CheckRegistrationTimeout(curr);
402 already_sent_t UserManager::NextAlreadySentId()
404 if (++already_sent_id == 0)
406 // Wrapped around, reset the already_sent ids of all users
408 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); ++i)
410 LocalUser* user = *i;
411 user->already_sent = 0;
414 return already_sent_id;