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