]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/usermanager.cpp
Add OnUserPreQuit event to allow modules to change quit messages (#1629).
[user/henk/code/inspircd.git] / src / usermanager.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
8  *
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.
12  *
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
16  * details.
17  *
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/>.
20  */
21
22
23 #include "inspircd.h"
24 #include "xline.h"
25 #include "iohook.h"
26
27 namespace
28 {
29         class WriteCommonQuit : public User::ForEachNeighborHandler
30         {
31                 ClientProtocol::Messages::Quit quitmsg;
32                 ClientProtocol::Event quitevent;
33                 ClientProtocol::Messages::Quit operquitmsg;
34                 ClientProtocol::Event operquitevent;
35
36                 void Execute(LocalUser* user) CXX11_OVERRIDE
37                 {
38                         user->Send(user->IsOper() ? operquitevent : quitevent);
39                 }
40
41          public:
42                 WriteCommonQuit(User* user, const std::string& msg, const std::string& opermsg)
43                         : quitmsg(user, msg)
44                         , quitevent(ServerInstance->GetRFCEvents().quit, quitmsg)
45                         , operquitmsg(user, opermsg)
46                         , operquitevent(ServerInstance->GetRFCEvents().quit, operquitmsg)
47                 {
48                         user->ForEachNeighbor(*this, false);
49                 }
50         };
51
52         void CheckPingTimeout(LocalUser* user)
53         {
54                 // Check if it is time to ping the user yet.
55                 if (ServerInstance->Time() < user->nextping)
56                         return;
57
58                 // This user didn't answer the last ping, remove them.
59                 if (!user->lastping)
60                 {
61                         time_t secs = ServerInstance->Time() - (user->nextping - user->MyClass->GetPingTime());
62                         const std::string message = "Ping timeout: " + ConvToStr(secs) + (secs != 1 ? " seconds" : " second");
63                         ServerInstance->Users.QuitUser(user, message);
64                         return;
65                 }
66
67                 // Send a ping to the client.
68                 ClientProtocol::Messages::Ping ping;
69                 user->Send(ServerInstance->GetRFCEvents().ping, ping);
70                 user->lastping = 0;
71                 user->nextping = ServerInstance->Time() + user->MyClass->GetPingTime();
72         }
73
74         void CheckRegistrationTimeout(LocalUser* user)
75         {
76                 if (user->GetClass() && (ServerInstance->Time() > (user->signon + user->GetClass()->GetRegTimeout())))
77                 {
78                         // Either the user did not send NICK/USER or a module blocked registration in
79                         // OnCheckReady until the client timed out.
80                         ServerInstance->Users.QuitUser(user, "Registration timeout");
81                 }
82         }
83
84         void CheckModulesReady(LocalUser* user)
85         {
86                 ModResult res;
87                 FIRST_MOD_RESULT(OnCheckReady, res, (user));
88                 if (res == MOD_RES_PASSTHRU)
89                 {
90                         // User has sent NICK/USER and modules are ready.
91                         user->FullConnect();
92                         return;
93                 }
94
95                 // If the user has been quit in OnCheckReady then we shouldn't quit
96                 // them again for having a registration timeout.
97                 if (!user->quitting)
98                         CheckRegistrationTimeout(user);
99         }
100 }
101
102 UserManager::UserManager()
103         : already_sent_id(0)
104         , unregistered_count(0)
105 {
106 }
107
108 UserManager::~UserManager()
109 {
110         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); ++i)
111         {
112                 delete i->second;
113         }
114 }
115
116 void UserManager::AddUser(int socket, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
117 {
118         // User constructor allocates a new UUID for the user and inserts it into the uuidlist
119         LocalUser* const New = new LocalUser(socket, client, server);
120         UserIOHandler* eh = &New->eh;
121
122         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New user fd: %d", socket);
123
124         this->unregistered_count++;
125         this->clientlist[New->nick] = New;
126         this->AddClone(New);
127         this->local_users.push_front(New);
128         FOREACH_MOD(OnUserInit, (New));
129
130         if (!SocketEngine::AddFd(eh, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE))
131         {
132                 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Internal error on new connection");
133                 this->QuitUser(New, "Internal error handling connection");
134                 return;
135         }
136
137         // If this listener has an IO hook provider set then tell it about the connection
138         for (ListenSocket::IOHookProvList::iterator i = via->iohookprovs.begin(); i != via->iohookprovs.end(); ++i)
139         {
140                 ListenSocket::IOHookProvRef& iohookprovref = *i;
141                 if (!iohookprovref)
142                         continue;
143
144                 iohookprovref->OnAccept(eh, client, server);
145                 // 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
146                 if (!eh->getError().empty())
147                 {
148                         QuitUser(New, eh->getError());
149                         return;
150                 }
151         }
152
153         if (this->local_users.size() > ServerInstance->Config->SoftLimit)
154         {
155                 ServerInstance->SNO->WriteToSnoMask('a', "Warning: softlimit value has been reached: %d clients", ServerInstance->Config->SoftLimit);
156                 this->QuitUser(New,"No more connections allowed");
157                 return;
158         }
159
160         // First class check. We do this again in LocalUser::FullConnect() after DNS is done, and NICK/USER is received.
161         New->SetClass();
162         // If the user doesn't have an acceptable connect class CheckClass() quits them
163         New->CheckClass(ServerInstance->Config->CCOnConnect);
164         if (New->quitting)
165                 return;
166
167         /*
168          * even with bancache, we still have to keep User::exempt current.
169          * besides that, if we get a positive bancache hit, we still won't fuck
170          * them over if they are exempt. -- w00t
171          */
172         New->exempt = (ServerInstance->XLines->MatchesLine("E",New) != NULL);
173
174         BanCacheHit* const b = ServerInstance->BanCache.GetHit(New->GetIPString());
175         if (b)
176         {
177                 if (!b->Type.empty() && !New->exempt)
178                 {
179                         /* user banned */
180                         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Positive hit for " + New->GetIPString());
181                         if (!ServerInstance->Config->XLineMessage.empty())
182                                 New->WriteNumeric(ERR_YOUREBANNEDCREEP, ServerInstance->Config->XLineMessage);
183
184                         if (ServerInstance->Config->HideBans)
185                                 this->QuitUser(New, b->Type + "-lined", &b->Reason);
186                         else
187                                 this->QuitUser(New, b->Reason);
188                         return;
189                 }
190                 else
191                 {
192                         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Negative hit for " + New->GetIPString());
193                 }
194         }
195         else
196         {
197                 if (!New->exempt)
198                 {
199                         XLine* r = ServerInstance->XLines->MatchesLine("Z",New);
200
201                         if (r)
202                         {
203                                 r->Apply(New);
204                                 return;
205                         }
206                 }
207         }
208
209         if (ServerInstance->Config->RawLog)
210                 New->WriteNotice("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
211
212         FOREACH_MOD(OnSetUserIP, (New));
213         if (!New->quitting)
214                 FOREACH_MOD(OnUserPostInit, (New));
215 }
216
217 void UserManager::QuitUser(User* user, const std::string& quitmessage, const std::string* operquitmessage)
218 {
219         if (user->quitting)
220         {
221                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit quitting user: " + user->nick);
222                 return;
223         }
224
225         if (IS_SERVER(user))
226         {
227                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit server user: " + user->nick);
228                 return;
229         }
230
231         std::string quitmsg(quitmessage);
232         std::string operquitmsg;
233         if (operquitmessage)
234                 operquitmsg.assign(*operquitmessage);
235
236         LocalUser* const localuser = IS_LOCAL(user);
237         if (localuser)
238         {
239                 ModResult MOD_RESULT;
240                 FIRST_MOD_RESULT(OnUserPreQuit, MOD_RESULT, (localuser, quitmsg, operquitmsg));
241                 if (MOD_RESULT == MOD_RES_DENY)
242                         return;
243         }
244
245         if (quitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
246                 quitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
247
248         if (operquitmsg.empty())
249                 operquitmsg.assign(quitmsg);
250         else if (operquitmsg.length() > ServerInstance->Config->Limits.MaxQuit)
251                 operquitmsg.erase(ServerInstance->Config->Limits.MaxQuit + 1);
252
253         user->quitting = true;
254         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "QuitUser: %s=%s '%s'", user->uuid.c_str(), user->nick.c_str(), quitmessage.c_str());
255         if (localuser)
256         {
257                 ClientProtocol::Messages::Error errormsg(InspIRCd::Format("Closing link: (%s@%s) [%s]", user->ident.c_str(), user->GetRealHost().c_str(), operquitmsg.c_str()));
258                 localuser->Send(ServerInstance->GetRFCEvents().error, errormsg);
259         }
260
261         ServerInstance->GlobalCulls.AddItem(user);
262
263         if (user->registered == REG_ALL)
264         {
265                 FOREACH_MOD(OnUserQuit, (user, quitmsg, operquitmsg));
266                 WriteCommonQuit(user, quitmsg, operquitmsg);
267         }
268         else
269                 unregistered_count--;
270
271         if (IS_LOCAL(user))
272         {
273                 LocalUser* lu = IS_LOCAL(user);
274                 FOREACH_MOD(OnUserDisconnect, (lu));
275                 lu->eh.Close();
276
277                 if (lu->registered == REG_ALL)
278                         ServerInstance->SNO->WriteToSnoMask('q',"Client exiting: %s (%s) [%s]", user->GetFullRealHost().c_str(), user->GetIPString().c_str(), operquitmsg.c_str());
279                 local_users.erase(lu);
280         }
281
282         if (!clientlist.erase(user->nick))
283                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Nick not found in clientlist, cannot remove: " + user->nick);
284
285         uuidlist.erase(user->uuid);
286         user->PurgeEmptyChannels();
287         user->UnOper();
288 }
289
290 void UserManager::AddClone(User* user)
291 {
292         CloneCounts& counts = clonemap[user->GetCIDRMask()];
293         counts.global++;
294         if (IS_LOCAL(user))
295                 counts.local++;
296 }
297
298 void UserManager::RemoveCloneCounts(User *user)
299 {
300         CloneMap::iterator it = clonemap.find(user->GetCIDRMask());
301         if (it != clonemap.end())
302         {
303                 CloneCounts& counts = it->second;
304                 counts.global--;
305                 if (counts.global == 0)
306                 {
307                         // No more users from this IP, remove entry from the map
308                         clonemap.erase(it);
309                         return;
310                 }
311
312                 if (IS_LOCAL(user))
313                         counts.local--;
314         }
315 }
316
317 void UserManager::RehashCloneCounts()
318 {
319         clonemap.clear();
320
321         const user_hash& hash = ServerInstance->Users.GetUsers();
322         for (user_hash::const_iterator i = hash.begin(); i != hash.end(); ++i)
323         {
324                 User* u = i->second;
325                 AddClone(u);
326         }
327 }
328
329 const UserManager::CloneCounts& UserManager::GetCloneCounts(User* user) const
330 {
331         CloneMap::const_iterator it = clonemap.find(user->GetCIDRMask());
332         if (it != clonemap.end())
333                 return it->second;
334         else
335                 return zeroclonecounts;
336 }
337
338 void UserManager::ServerNoticeAll(const char* text, ...)
339 {
340         std::string message;
341         VAFORMAT(message, text, text);
342         ClientProtocol::Messages::Privmsg msg(ClientProtocol::Messages::Privmsg::nocopy, ServerInstance->FakeClient, ServerInstance->Config->ServerName, message, MSG_NOTICE);
343         ClientProtocol::Event msgevent(ServerInstance->GetRFCEvents().privmsg, msg);
344
345         for (LocalList::const_iterator i = local_users.begin(); i != local_users.end(); ++i)
346         {
347                 LocalUser* user = *i;
348                 user->Send(msgevent);
349         }
350 }
351
352 /**
353  * This function is called once a second from the mainloop.
354  * It is intended to do background checking on all the users, e.g. do
355  * ping checks, registration timeouts, etc.
356  */
357 void UserManager::DoBackgroundUserStuff()
358 {
359         for (LocalList::iterator i = local_users.begin(); i != local_users.end(); )
360         {
361                 // It's possible that we quit the user below due to ping timeout etc. and QuitUser() removes it from the list
362                 LocalUser* curr = *i;
363                 ++i;
364
365                 if (curr->CommandFloodPenalty || curr->eh.getSendQSize())
366                 {
367                         unsigned int rate = curr->MyClass->GetCommandRate();
368                         if (curr->CommandFloodPenalty > rate)
369                                 curr->CommandFloodPenalty -= rate;
370                         else
371                                 curr->CommandFloodPenalty = 0;
372                         curr->eh.OnDataReady();
373                 }
374
375                 switch (curr->registered)
376                 {
377                         case REG_ALL:
378                                 CheckPingTimeout(curr);
379                                 break;
380
381                         case REG_NICKUSER:
382                                 CheckModulesReady(curr);
383                                 break;
384
385                         default:
386                                 CheckRegistrationTimeout(curr);
387                                 break;
388                 }
389         }
390 }
391
392 already_sent_t UserManager::NextAlreadySentId()
393 {
394         if (++already_sent_id == 0)
395         {
396                 // Wrapped around, reset the already_sent ids of all users
397                 already_sent_id = 1;
398                 for (LocalList::iterator i = local_users.begin(); i != local_users.end(); ++i)
399                 {
400                         LocalUser* user = *i;
401                         user->already_sent = 0;
402                 }
403         }
404         return already_sent_id;
405 }