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