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