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