]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/usermanager.cpp
Change allocation of UserManager::clientlist to be physically part of the object...
[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 "bancache.h"
26 #include "iohook.h"
27
28 UserManager::UserManager()
29         : unregistered_count(0)
30 {
31 }
32
33 UserManager::~UserManager()
34 {
35         for (user_hash::iterator i = clientlist.begin(); i != clientlist.end(); ++i)
36         {
37                 delete i->second;
38         }
39 }
40
41 /* add a client connection to the sockets list */
42 void UserManager::AddUser(int socket, ListenSocket* via, irc::sockets::sockaddrs* client, irc::sockets::sockaddrs* server)
43 {
44         /* NOTE: Calling this one parameter constructor for User automatically
45          * allocates a new UUID and places it in the hash_map.
46          */
47         LocalUser* New = NULL;
48         try
49         {
50                 New = new LocalUser(socket, client, server);
51         }
52         catch (...)
53         {
54                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "*** WTF *** Duplicated UUID! -- Crack smoking monkeys have been unleashed.");
55                 ServerInstance->SNO->WriteToSnoMask('a', "WARNING *** Duplicate UUID allocated!");
56                 return;
57         }
58         UserIOHandler* eh = &New->eh;
59
60         // If this listener has an IO hook provider set then tell it about the connection
61         if (via->iohookprov)
62                 via->iohookprov->OnAccept(eh, client, server);
63
64         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "New user fd: %d", socket);
65
66         this->unregistered_count++;
67
68         /* The users default nick is their UUID */
69         New->nick = New->uuid;
70         this->clientlist[New->nick] = New;
71
72         New->registered = REG_NONE;
73         New->signon = ServerInstance->Time() + ServerInstance->Config->dns_timeout;
74         New->lastping = 1;
75
76         ServerInstance->Users->AddLocalClone(New);
77         ServerInstance->Users->AddGlobalClone(New);
78
79         this->local_users.push_front(New);
80
81         if ((this->local_users.size() > ServerInstance->Config->SoftLimit) || (this->local_users.size() >= (unsigned int)SocketEngine::GetMaxFds()))
82         {
83                 ServerInstance->SNO->WriteToSnoMask('a', "Warning: softlimit value has been reached: %d clients", ServerInstance->Config->SoftLimit);
84                 this->QuitUser(New,"No more connections allowed");
85                 return;
86         }
87
88         /*
89          * First class check. We do this again in FullConnect after DNS is done, and NICK/USER is recieved.
90          * See my note down there for why this is required. DO NOT REMOVE. :) -- w00t
91          */
92         New->SetClass();
93
94         /*
95          * Check connect class settings and initialise settings into User.
96          * This will be done again after DNS resolution. -- w00t
97          */
98         New->CheckClass(ServerInstance->Config->CCOnConnect);
99         if (New->quitting)
100                 return;
101
102         /*
103          * even with bancache, we still have to keep User::exempt current.
104          * besides that, if we get a positive bancache hit, we still won't fuck
105          * them over if they are exempt. -- w00t
106          */
107         New->exempt = (ServerInstance->XLines->MatchesLine("E",New) != NULL);
108
109         if (BanCacheHit *b = ServerInstance->BanCache->GetHit(New->GetIPString()))
110         {
111                 if (!b->Type.empty() && !New->exempt)
112                 {
113                         /* user banned */
114                         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Positive hit for " + New->GetIPString());
115                         if (!ServerInstance->Config->XLineMessage.empty())
116                                 New->WriteNotice("*** " +  ServerInstance->Config->XLineMessage);
117                         this->QuitUser(New, b->Reason);
118                         return;
119                 }
120                 else
121                 {
122                         ServerInstance->Logs->Log("BANCACHE", LOG_DEBUG, "BanCache: Negative hit for " + New->GetIPString());
123                 }
124         }
125         else
126         {
127                 if (!New->exempt)
128                 {
129                         XLine* r = ServerInstance->XLines->MatchesLine("Z",New);
130
131                         if (r)
132                         {
133                                 r->Apply(New);
134                                 return;
135                         }
136                 }
137         }
138
139         if (!SocketEngine::AddFd(eh, FD_WANT_FAST_READ | FD_WANT_EDGE_WRITE))
140         {
141                 ServerInstance->Logs->Log("USERS", LOG_DEBUG, "Internal error on new connection");
142                 this->QuitUser(New, "Internal error handling connection");
143         }
144
145         if (ServerInstance->Config->RawLog)
146                 New->WriteNotice("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
147
148         FOREACH_MOD(OnSetUserIP, (New));
149         if (New->quitting)
150                 return;
151
152         FOREACH_MOD(OnUserInit, (New));
153 }
154
155 void UserManager::QuitUser(User* user, const std::string& quitreason, const std::string* operreason)
156 {
157         if (user->quitting)
158         {
159                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit quitting user: " + user->nick);
160                 return;
161         }
162
163         if (IS_SERVER(user))
164         {
165                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Tried to quit server user: " + user->nick);
166                 return;
167         }
168
169         user->quitting = true;
170
171         ServerInstance->Logs->Log("USERS", LOG_DEBUG, "QuitUser: %s=%s '%s'", user->uuid.c_str(), user->nick.c_str(), quitreason.c_str());
172         user->Write("ERROR :Closing link: (%s@%s) [%s]", user->ident.c_str(), user->host.c_str(), operreason ? operreason->c_str() : quitreason.c_str());
173
174         std::string reason;
175         reason.assign(quitreason, 0, ServerInstance->Config->Limits.MaxQuit);
176         if (!operreason)
177                 operreason = &reason;
178
179         ServerInstance->GlobalCulls.AddItem(user);
180
181         if (user->registered == REG_ALL)
182         {
183                 FOREACH_MOD(OnUserQuit, (user, reason, *operreason));
184                 user->WriteCommonQuit(reason, *operreason);
185         }
186         else
187                 unregistered_count--;
188
189         if (IS_LOCAL(user))
190         {
191                 LocalUser* lu = IS_LOCAL(user);
192                 FOREACH_MOD(OnUserDisconnect, (lu));
193                 lu->eh.Close();
194
195                 if (lu->registered == REG_ALL)
196                         ServerInstance->SNO->WriteToSnoMask('q',"Client exiting: %s (%s) [%s]", user->GetFullRealHost().c_str(), user->GetIPString().c_str(), operreason->c_str());
197         }
198
199         if (!clientlist.erase(user->nick))
200                 ServerInstance->Logs->Log("USERS", LOG_DEFAULT, "ERROR: Nick not found in clientlist, cannot remove: " + user->nick);
201
202         uuidlist.erase(user->uuid);
203         user->PurgeEmptyChannels();
204 }
205
206 void UserManager::AddLocalClone(User *user)
207 {
208         local_clones[user->GetCIDRMask()]++;
209 }
210
211 void UserManager::AddGlobalClone(User *user)
212 {
213         global_clones[user->GetCIDRMask()]++;
214 }
215
216 void UserManager::RemoveCloneCounts(User *user)
217 {
218         if (IS_LOCAL(user))
219         {
220                 clonemap::iterator x = local_clones.find(user->GetCIDRMask());
221                 if (x != local_clones.end())
222                 {
223                         x->second--;
224                         if (!x->second)
225                         {
226                                 local_clones.erase(x);
227                         }
228                 }
229         }
230
231         clonemap::iterator y = global_clones.find(user->GetCIDRMask());
232         if (y != global_clones.end())
233         {
234                 y->second--;
235                 if (!y->second)
236                 {
237                         global_clones.erase(y);
238                 }
239         }
240 }
241
242 unsigned long UserManager::GlobalCloneCount(User *user)
243 {
244         clonemap::iterator x = global_clones.find(user->GetCIDRMask());
245         if (x != global_clones.end())
246                 return x->second;
247         else
248                 return 0;
249 }
250
251 unsigned long UserManager::LocalCloneCount(User *user)
252 {
253         clonemap::iterator x = local_clones.find(user->GetCIDRMask());
254         if (x != local_clones.end())
255                 return x->second;
256         else
257                 return 0;
258 }
259
260 void UserManager::ServerNoticeAll(const char* text, ...)
261 {
262         std::string message;
263         VAFORMAT(message, text, text);
264         message = "NOTICE $" + ServerInstance->Config->ServerName + " :" + message;
265
266         for (LocalUserList::const_iterator i = local_users.begin(); i != local_users.end(); i++)
267         {
268                 User* t = *i;
269                 t->WriteServ(message);
270         }
271 }
272
273 void UserManager::GarbageCollect()
274 {
275         // Reset the already_sent IDs so we don't wrap it around and drop a message
276         LocalUser::already_sent_id = 0;
277         for (LocalUserList::const_iterator i = this->local_users.begin(); i != this->local_users.end(); i++)
278         {
279                 (**i).already_sent = 0;
280                 (**i).RemoveExpiredInvites();
281         }
282 }
283
284 /* this returns true when all modules are satisfied that the user should be allowed onto the irc server
285  * (until this returns true, a user will block in the waiting state, waiting to connect up to the
286  * registration timeout maximum seconds)
287  */
288 bool UserManager::AllModulesReportReady(LocalUser* user)
289 {
290         ModResult res;
291         FIRST_MOD_RESULT(OnCheckReady, res, (user));
292         return (res == MOD_RES_PASSTHRU);
293 }
294
295 /**
296  * This function is called once a second from the mainloop.
297  * It is intended to do background checking on all the user structs, e.g.
298  * stuff like ping checks, registration timeouts, etc.
299  */
300 void UserManager::DoBackgroundUserStuff()
301 {
302         /*
303          * loop over all local users..
304          */
305         for (LocalUserList::iterator i = local_users.begin(); i != local_users.end(); ++i)
306         {
307                 LocalUser* curr = *i;
308
309                 if (curr->quitting)
310                         continue;
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
336                                         curr->Write("PING :" + ServerInstance->Config->ServerName);
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                                 break;
349                 }
350
351                 if (curr->registered != REG_ALL && (ServerInstance->Time() > (curr->age + 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 }