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