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