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