]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/usermanager.cpp
Update copyright headers.
[user/henk/code/inspircd.git] / src / usermanager.cpp
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-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>
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
43                 void Execute(LocalUser* user) CXX11_OVERRIDE
44                 {
45                         user->Send(user->IsOper() ? operquitevent : quitevent);
46                 }
47
48          public:
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
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
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
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
119 UserManager::UserManager()
120         : already_sent_id(0)
121         , unregistered_count(0)
122         , uline_count(0)
123 {
124 }
125
126 UserManager::~UserManager()
127 {
128         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); ++i)
129         {
130                 delete i->second;
131         }
132 }
133
134 void UserManager::AddUser(int socket, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
135 {
136         // User constructor allocates a new UUID for the user and inserts it into the uuidlist
137         LocalUser* const New = new LocalUser(socket, client, server);
138         UserIOHandler* eh = &New->eh;
139
140         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New user fd: %d", socket);
141
142         this->unregistered_count++;
143         this->clientlist[New->nick] = New;
144         this->AddClone(New);
145         this->local_users.push_front(New);
146         FOREACH_MOD(OnUserInit, (New));
147
148         if (!SocketEngine::AddFd(eh, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE))
149         {
150                 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Internal error on new connection");
151                 this->QuitUser(New, "Internal error handling connection");
152                 return;
153         }
154
155         // If this listener has an IO hook provider set then tell it about the connection
156         for (ListenSocket::IOHookProvList::iterator i = via->iohookprovs.begin(); i != via->iohookprovs.end(); ++i)
157         {
158                 ListenSocket::IOHookProvRef& iohookprovref = *i;
159                 if (!iohookprovref)
160                 {
161                         if (!iohookprovref.GetProvider().empty())
162                         {
163                                 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Non-existent I/O hook '%s' in <bind:%s> tag at %s",
164                                         iohookprovref.GetProvider().c_str(),
165                                         i == via->iohookprovs.begin() ? "hook" : "ssl",
166                                         via->bind_tag->getTagLocation().c_str());
167                                 this->QuitUser(New, "Internal error handling connection");
168                                 return;
169                         }
170                         continue;
171                 }
172
173                 iohookprovref->OnAccept(eh, client, server);
174
175                 // IOHook could have encountered a fatal error, e.g. if the TLS ClientHello
176                 // was already in the queue and there was no common TLS version.
177                 if (!eh->getError().empty())
178                 {
179                         QuitUser(New, eh->getError());
180                         return;
181                 }
182         }
183
184         if (this->local_users.size() > ServerInstance->Config->SoftLimit)
185         {
186                 ServerInstance->SNO->WriteToSnoMask('a', "Warning: softlimit value has been reached: %d clients", ServerInstance->Config->SoftLimit);
187                 this->QuitUser(New,"No more connections allowed");
188                 return;
189         }
190
191         // First class check. We do this again in LocalUser::FullConnect() after DNS is done, and NICK/USER is received.
192         New->SetClass();
193         // If the user doesn't have an acceptable connect class CheckClass() quits them
194         New->CheckClass(ServerInstance->Config->CCOnConnect);
195         if (New->quitting)
196                 return;
197
198         /*
199          * even with bancache, we still have to keep User::exempt current.
200          * besides that, if we get a positive bancache hit, we still won't fuck
201          * them over if they are exempt. -- w00t
202          */
203         New->exempt = (ServerInstance->XLines->MatchesLine("E",New) != NULL);
204
205         BanCacheHit* const b = ServerInstance->BanCache.GetHit(New->GetIPString());
206         if (b)
207         {
208                 if (!b->Type.empty() && !New->exempt)
209                 {
210                         /* user banned */
211                         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Positive hit for " + New->GetIPString());
212                         if (!ServerInstance->Config->XLineMessage.empty())
213                                 New->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
214
215                         if (ServerInstance->Config->HideBans)
216                                 this->QuitUser(New, b->Type + "-lined", &b->Reason);
217                         else
218                                 this->QuitUser(New, b->Reason);
219                         return;
220                 }
221                 else
222                 {
223                         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Negative hit for " + New->GetIPString());
224                 }
225         }
226         else
227         {
228                 if (!New->exempt)
229                 {
230                         XLine* r = ServerInstance->XLines->MatchesLine("Z",New);
231
232                         if (r)
233                         {
234                                 r->Apply(New);
235                                 return;
236                         }
237                 }
238         }
239
240         if (ServerInstance->Config->RawLog)
241                 New->WriteNotice("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
242
243         FOREACH_MOD(OnSetUserIP, (New));
244         if (!New->quitting)
245                 FOREACH_MOD(OnUserPostInit, (New));
246 }
247
248 void UserManager::QuitUser(User* user, const std::string& quitmessage, const std::string* operquitmessage)
249 {
250         if (user->quitting)
251         {
252                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit quitting user: " + user->nick);
253                 return;
254         }
255
256         if (IS_SERVER(user))
257         {
258                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit server user: " + user->nick);
259                 return;
260         }
261
262         std::string quitmsg(quitmessage);
263         std::string operquitmsg;
264         if (operquitmessage)
265                 operquitmsg.assign(*operquitmessage);
266
267         LocalUser* const localuser = IS_LOCAL(user);
268         if (localuser)
269         {
270                 ModResult MOD_RESULT;
271                 FIRST_MOD_RESULT(OnUserPreQuit, MOD_RESULT, (localuser, quitmsg, operquitmsg));
272                 if (MOD_RESULT == MOD_RES_DENY)
273                         return;
274         }
275
276         if (quitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
277                 quitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
278
279         if (operquitmsg.empty())
280                 operquitmsg.assign(quitmsg);
281         else if (operquitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
282                 operquitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
283
284         user->quitting = true;
285         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "QuitUser: %s=%s '%s'", user->uuid.c_str(), user->nick.c_str(), quitmessage.c_str());
286         if (localuser)
287         {
288                 ClientProtocol::Messages::Error errormsg(InspIRCd::Format("Closing link: (%s@%s) [%s]", user->ident.c_str(), user->GetRealHost().c_str(), operquitmsg.c_str()));
289                 localuser->Send(ServerInstance->GetRFCEvents().error, errormsg);
290         }
291
292         ServerInstance->GlobalCulls.AddItem(user);
293
294         if (user->registered == REG_ALL)
295         {
296                 FOREACH_MOD(OnUserQuit, (user, quitmsg, operquitmsg));
297                 WriteCommonQuit(user, quitmsg, operquitmsg);
298         }
299         else
300                 unregistered_count--;
301
302         if (IS_LOCAL(user))
303         {
304                 LocalUser* lu = IS_LOCAL(user);
305                 FOREACH_MOD(OnUserDisconnect, (lu));
306                 lu->eh.Close();
307
308                 if (lu->registered == REG_ALL)
309                         ServerInstance->SNO->WriteToSnoMask('q',"Client exiting: %s (%s) [%s]", user->GetFullRealHost().c_str(), user->GetIPString().c_str(), operquitmsg.c_str());
310                 local_users.erase(lu);
311         }
312
313         if (!clientlist.erase(user->nick))
314                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Nick not found in clientlist, cannot remove: " + user->nick);
315
316         uuidlist.erase(user->uuid);
317         user->PurgeEmptyChannels();
318         user->UnOper();
319 }
320
321 void UserManager::AddClone(User* user)
322 {
323         CloneCounts& counts = clonemap[user->GetCIDRMask()];
324         counts.global++;
325         if (IS_LOCAL(user))
326                 counts.local++;
327 }
328
329 void UserManager::RemoveCloneCounts(User *user)
330 {
331         CloneMap::iterator it = clonemap.find(user->GetCIDRMask());
332         if (it != clonemap.end())
333         {
334                 CloneCounts& counts = it->second;
335                 counts.global--;
336                 if (counts.global == 0)
337                 {
338                         // No more users from this IP, remove entry from the map
339                         clonemap.erase(it);
340                         return;
341                 }
342
343                 if (IS_LOCAL(user))
344                         counts.local--;
345         }
346 }
347
348 void UserManager::RehashCloneCounts()
349 {
350         clonemap.clear();
351
352         const user_hash& hash = ServerInstance->Users.GetUsers();
353         for (user_hash::const_iterator i = hash.begin(); i != hash.end(); ++i)
354         {
355                 User* u = i->second;
356                 AddClone(u);
357         }
358 }
359
360 const UserManager::CloneCounts& UserManager::GetCloneCounts(User* user) const
361 {
362         CloneMap::const_iterator it = clonemap.find(user->GetCIDRMask());
363         if (it != clonemap.end())
364                 return it->second;
365         else
366                 return zeroclonecounts;
367 }
368
369 void UserManager::ServerNoticeAll(const char* text, ...)
370 {
371         std::string message;
372         VAFORMAT(message, text, text);
373         ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, ServerInstance->Config->ServerName, message, MSG_NOTICE);
374         ClientProtocol::Event msgevent(ServerInstance->GetRFCEvents().privmsg, msg);
375
376         for (LocalList::const_iterator i = local_users.begin(); i != local_users.end(); ++i)
377         {
378                 LocalUser* user = *i;
379                 user->Send(msgevent);
380         }
381 }
382
383 /**
384  * This function is called once a second from the mainloop.
385  * It is intended to do background checking on all the users, e.g. do
386  * ping checks, registration timeouts, etc.
387  */
388 void UserManager::DoBackgroundUserStuff()
389 {
390         for (LocalList::iterator i = local_users.begin(); i != local_users.end(); )
391         {
392                 // It's possible that we quit the user below due to ping timeout etc. and QuitUser() removes it from the list
393                 LocalUser* curr = *i;
394                 ++i;
395
396                 if (curr->CommandFloodPenalty || curr->eh.getSendQSize())
397                 {
398                         unsigned int rate = curr->MyClass->GetCommandRate();
399                         if (curr->CommandFloodPenalty > rate)
400                                 curr->CommandFloodPenalty -= rate;
401                         else
402                                 curr->CommandFloodPenalty = 0;
403                         curr->eh.OnDataReady();
404                 }
405
406                 switch (curr->registered)
407                 {
408                         case REG_ALL:
409                                 CheckPingTimeout(curr);
410                                 break;
411
412                         case REG_NICKUSER:
413                                 CheckModulesReady(curr);
414                                 break;
415
416                         default:
417                                 CheckRegistrationTimeout(curr);
418                                 break;
419                 }
420         }
421 }
422
423 already_sent_t UserManager::NextAlreadySentId()
424 {
425         if (++already_sent_id == 0)
426         {
427                 // Wrapped around, reset the already_sent ids of all users
428                 already_sent_id = 1;
429                 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); ++i)
430                 {
431                         LocalUser* user = *i;
432                         user->already_sent = 0;
433                 }
434         }
435         return already_sent_id;
436 }