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