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