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