1 /*
2 * InspIRCd -- Internet Relay Chat Daemon
3 *
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-2021 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>
15 *
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.
19 *
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
23 * details.
24 *
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/>.
27 */
28
29
30 #include "inspircd.h"
31 #include "xline.h"
32 #include "iohook.h"
33
34 namespace
35 {
36 class WriteCommonQuit : public User::ForEachNeighborHandler
37 {
38 ClientProtocol::Messages::Quit quitmsg;
39 ClientProtocol::Event quitevent;
40 ClientProtocol::Messages::Quit operquitmsg;
41 ClientProtocol::Event operquitevent;
42
Execute(LocalUser * user)43 void Execute(LocalUser* user) CXX11_OVERRIDE
44 {
45 user->Send(user->IsOper() ? operquitevent : quitevent);
46 }
47
48 public:
WriteCommonQuit(User * user,const std::string & msg,const std::string & opermsg)49 WriteCommonQuit(User* user, const std::string& msg, const std::string& opermsg)
50 : quitmsg(user, msg)
51 , quitevent(ServerInstance->GetRFCEvents().quit, quitmsg)
52 , operquitmsg(user, opermsg)
53 , operquitevent(ServerInstance->GetRFCEvents().quit, operquitmsg)
54 {
55 user->ForEachNeighbor(*this, false);
56 }
57 };
58
CheckPingTimeout(LocalUser * user)59 void CheckPingTimeout(LocalUser* user)
60 {
61 // Check if it is time to ping the user yet.
62 if (ServerInstance->Time() < user->nextping)
63 return;
64
65 // This user didn't answer the last ping, remove them.
66 if (!user->lastping)
67 {
68 ModResult res;
69 FIRST_MOD_RESULT(OnConnectionFail, res, (user, I_ERR_TIMEOUT));
70 if (res == MOD_RES_ALLOW)
71 {
72 // A module is preventing this user from being timed out.
73 user->lastping = 1;
74 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
75 return;
76 }
77
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);
81 return;
82 }
83
84 // Send a ping to the client.
85 ClientProtocol::Messages::Ping ping;
86 user->Send(ServerInstance->GetRFCEvents().ping, ping);
87 user->lastping = 0;
88 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
89 }
90
CheckRegistrationTimeout(LocalUser * user)91 void CheckRegistrationTimeout(LocalUser* user)
92 {
93 if (user->GetClass() && (ServerInstance->Time() > (user->signon + user->GetClass()->GetRegTimeout())))
94 {
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");
98 }
99 }
100
CheckModulesReady(LocalUser * user)101 void CheckModulesReady(LocalUser* user)
102 {
103 ModResult res;
104 FIRST_MOD_RESULT(OnCheckReady, res, (user));
105 if (res == MOD_RES_PASSTHRU)
106 {
107 // User has sent NICK/USER and modules are ready.
108 user->FullConnect();
109 return;
110 }
111
112 // If the user has been quit in OnCheckReady then we shouldn't quit
113 // them again for having a registration timeout.
114 if (!user->quitting)
115 CheckRegistrationTimeout(user);
116 }
117 }
118
UserManager()119 UserManager::UserManager()
120 : already_sent_id(0)
121 , unregistered_count(0)
122 {
123 }
124
~UserManager()125 UserManager::~UserManager()
126 {
127 for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); ++i)
128 {
129 delete i->second;
130 }
131 }
132
AddUser(int socket,ListenSocket * via,irc::sockets::sockaddrs * client,irc::sockets::sockaddrs * server)133 void UserManager::AddUser(int socket, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
134 {
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;
138
139 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New user fd: %d", socket);
140
141 this->unregistered_count++;
142 this->clientlist[New->nick] = New;
143 this->AddClone(New);
144 this->local_users.push_front(New);
145 FOREACH_MOD(OnUserInit, (New));
146
147 if (!SocketEngine::AddFd(eh, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE))
148 {
149 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Internal error on new connection");
150 this->QuitUser(New, "Internal error handling connection");
151 return;
152 }
153
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)
156 {
157 ListenSocket::IOHookProvRef& iohookprovref = *i;
158 if (!iohookprovref)
159 {
160 if (!iohookprovref.GetProvider().empty())
161 {
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" : "sslprofile",
165 via->bind_tag->getTagLocation().c_str());
166 this->QuitUser(New, "Internal error handling connection");
167 return;
168 }
169 continue;
170 }
171
172 iohookprovref->OnAccept(eh, client, server);
173
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())
177 {
178 QuitUser(New, eh->getError());
179 return;
180 }
181 }
182
183 if (this->local_users.size() > ServerInstance->Config->SoftLimit)
184 {
185 ServerInstance->SNO->WriteToSnoMask('a', "Warning: softlimit value has been reached: %d clients", ServerInstance->Config->SoftLimit);
186 this->QuitUser(New,"No more connections allowed");
187 return;
188 }
189
190 // First class check. We do this again in LocalUser::FullConnect() after DNS is done, and NICK/USER is received.
191 New->SetClass();
192 // If the user doesn't have an acceptable connect class CheckClass() quits them
193 New->CheckClass(ServerInstance->Config->CCOnConnect);
194 if (New->quitting)
195 return;
196
197 /*
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
201 */
202 New->exempt = (ServerInstance->XLines->MatchesLine("E",New) != NULL);
203
204 BanCacheHit* const b = ServerInstance->BanCache.GetHit(New->GetIPString());
205 if (b)
206 {
207 if (!b->Type.empty() && !New->exempt)
208 {
209 /* user banned */
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);
213
214 if (ServerInstance->Config->HideBans)
215 this->QuitUser(New, b->Type + "-lined", &b->Reason);
216 else
217 this->QuitUser(New, b->Reason);
218 return;
219 }
220 else
221 {
222 ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Negative hit for " + New->GetIPString());
223 }
224 }
225 else
226 {
227 if (!New->exempt)
228 {
229 XLine* r = ServerInstance->XLines->MatchesLine("Z",New);
230
231 if (r)
232 {
233 r->Apply(New);
234 return;
235 }
236 }
237 }
238
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.");
241
242 FOREACH_MOD(OnSetUserIP, (New));
243 if (!New->quitting)
244 FOREACH_MOD(OnUserPostInit, (New));
245 }
246
QuitUser(User * user,const std::string & quitmessage,const std::string * operquitmessage)247 void UserManager::QuitUser(User* user, const std::string& quitmessage, const std::string* operquitmessage)
248 {
249 if (user->quitting)
250 {
251 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit quitting user: " + user->nick);
252 return;
253 }
254
255 if (IS_SERVER(user))
256 {
257 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit server user: " + user->nick);
258 return;
259 }
260
261 std::string quitmsg(quitmessage);
262 std::string operquitmsg;
263 if (operquitmessage)
264 operquitmsg.assign(*operquitmessage);
265
266 LocalUser* const localuser = IS_LOCAL(user);
267 if (localuser)
268 {
269 ModResult MOD_RESULT;
270 FIRST_MOD_RESULT(OnUserPreQuit, MOD_RESULT, (localuser, quitmsg, operquitmsg));
271 if (MOD_RESULT == MOD_RES_DENY)
272 return;
273 }
274
275 if (quitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
276 quitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
277
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);
282
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());
285 if (localuser)
286 {
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);
289 }
290
291 ServerInstance->GlobalCulls.AddItem(user);
292
293 if (user->registered == REG_ALL)
294 {
295 FOREACH_MOD(OnUserQuit, (user, quitmsg, operquitmsg));
296 WriteCommonQuit(user, quitmsg, operquitmsg);
297 }
298 else
299 unregistered_count--;
300
301 if (IS_LOCAL(user))
302 {
303 LocalUser* lu = IS_LOCAL(user);
304 FOREACH_MOD(OnUserDisconnect, (lu));
305 lu->eh.Close();
306
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);
310 }
311
312 if (!clientlist.erase(user->nick))
313 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Nick not found in clientlist, cannot remove: " + user->nick);
314
315 uuidlist.erase(user->uuid);
316 user->PurgeEmptyChannels();
317 user->UnOper();
318 }
319
AddClone(User * user)320 void UserManager::AddClone(User* user)
321 {
322 CloneCounts& counts = clonemap[user->GetCIDRMask()];
323 counts.global++;
324 if (IS_LOCAL(user))
325 counts.local++;
326 }
327
RemoveCloneCounts(User * user)328 void UserManager::RemoveCloneCounts(User *user)
329 {
330 CloneMap::iterator it = clonemap.find(user->GetCIDRMask());
331 if (it != clonemap.end())
332 {
333 CloneCounts& counts = it->second;
334 counts.global--;
335 if (counts.global == 0)
336 {
337 // No more users from this IP, remove entry from the map
338 clonemap.erase(it);
339 return;
340 }
341
342 if (IS_LOCAL(user))
343 counts.local--;
344 }
345 }
346
RehashCloneCounts()347 void UserManager::RehashCloneCounts()
348 {
349 clonemap.clear();
350
351 const user_hash& hash = ServerInstance->Users.GetUsers();
352 for (user_hash::const_iterator i = hash.begin(); i != hash.end(); ++i)
353 {
354 User* u = i->second;
355 AddClone(u);
356 }
357 }
358
GetCloneCounts(User * user) const359 const UserManager::CloneCounts& UserManager::GetCloneCounts(User* user) const
360 {
361 CloneMap::const_iterator it = clonemap.find(user->GetCIDRMask());
362 if (it != clonemap.end())
363 return it->second;
364 else
365 return zeroclonecounts;
366 }
367
ServerNoticeAll(const char * text,...)368 void UserManager::ServerNoticeAll(const char* text, ...)
369 {
370 std::string message;
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);
374
375 for (LocalList::const_iterator i = local_users.begin(); i != local_users.end(); ++i)
376 {
377 LocalUser* user = *i;
378 user->Send(msgevent);
379 }
380 }
381
382 /**
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.
386 */
DoBackgroundUserStuff()387 void UserManager::DoBackgroundUserStuff()
388 {
389 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); )
390 {
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;
393 ++i;
394
395 if (curr->CommandFloodPenalty || curr->eh.getSendQSize())
396 {
397 unsigned int rate = curr->MyClass->GetCommandRate();
398 if (curr->CommandFloodPenalty > rate)
399 curr->CommandFloodPenalty -= rate;
400 else
401 curr->CommandFloodPenalty = 0;
402 curr->eh.OnDataReady();
403 }
404
405 switch (curr->registered)
406 {
407 case REG_ALL:
408 CheckPingTimeout(curr);
409 break;
410
411 case REG_NICKUSER:
412 CheckModulesReady(curr);
413 break;
414
415 default:
416 CheckRegistrationTimeout(curr);
417 break;
418 }
419 }
420 }
421
NextAlreadySentId()422 already_sent_t UserManager::NextAlreadySentId()
423 {
424 if (++already_sent_id == 0)
425 {
426 // Wrapped around, reset the already_sent ids of all users
427 already_sent_id = 1;
428 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); ++i)
429 {
430 LocalUser* user = *i;
431 user->already_sent = 0;
432 }
433 }
434 return already_sent_id;
435 }
436