]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_ident.cpp
Merge pull request #544 from SaberUK/master+kill-maxbuf
[user/henk/code/inspircd.git] / src / modules / m_ident.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007, 2009 John Brooks <john.brooks@dereferenced.net>
6  *   Copyright (C) 2006-2008 Robin Burchell <robin+git@viroteck.net>
7  *   Copyright (C) 2005-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "inspircd.h"
26
27 /* $ModDesc: Provides support for RFC1413 ident lookups */
28
29 /* --------------------------------------------------------------
30  * Note that this is the third incarnation of m_ident. The first
31  * two attempts were pretty crashy, mainly due to the fact we tried
32  * to use InspSocket/BufferedSocket to make them work. This class
33  * is ok for more heavyweight tasks, it does a lot of things behind
34  * the scenes that are not good for ident sockets and it has a huge
35  * memory footprint!
36  *
37  * To fix all the issues that we had in the old ident modules (many
38  * nasty race conditions that would cause segfaults etc) we have
39  * rewritten this module to use a simplified socket object based
40  * directly off EventHandler. As EventHandler only has low level
41  * readability, writeability and error events tied directly to the
42  * socket engine, this makes our lives easier as nothing happens to
43  * our ident lookup class that is outside of this module, or out-
44  * side of the control of the class. There are no timers, internal
45  * events, or such, which will cause the socket to be deleted,
46  * queued for deletion, etc. In fact, theres not even any queueing!
47  *
48  * Using this framework we have a much more stable module.
49  *
50  * A few things to note:
51  *
52  *   O  The only place that may *delete* an active or inactive
53  *      ident socket is OnUserDisconnect in the module class.
54  *      Because this is out of scope of the socket class there is
55  *      no possibility that the socket may ever try to delete
56  *      itself.
57  *
58  *   O  Closure of the ident socket with the Close() method will
59  *      not cause removal of the socket from memory or detatchment
60  *      from its 'parent' User class. It will only flag it as an
61  *      inactive socket in the socket engine.
62  *
63  *   O  Timeouts are handled in OnCheckReaady at the same time as
64  *      checking if the ident socket has a result. This is done
65  *      by checking if the age the of the class (its instantiation
66  *      time) plus the timeout value is greater than the current time.
67  *
68  *  O   The ident socket is able to but should not modify its
69  *      'parent' user directly. Instead the ident socket class sets
70  *      a completion flag and during the next call to OnCheckReady,
71  *      the completion flag will be checked and any result copied to
72  *      that user's class. This again ensures a single point of socket
73  *      deletion for safer, neater code.
74  *
75  *  O   The code in the constructor of the ident socket is taken from
76  *      BufferedSocket but majorly thinned down. It works for both
77  *      IPv4 and IPv6.
78  *
79  *  O   In the event that the ident socket throws a ModuleException,
80  *      nothing is done. This is counted as total and complete
81  *      failure to create a connection.
82  * --------------------------------------------------------------
83  */
84
85 class IdentRequestSocket : public EventHandler
86 {
87  public:
88         LocalUser *user;                        /* User we are attached to */
89         std::string result;             /* Holds the ident string if done */
90         time_t age;
91         bool done;                      /* True if lookup is finished */
92
93         IdentRequestSocket(LocalUser* u) : user(u)
94         {
95                 age = ServerInstance->Time();
96
97                 SetFd(socket(user->server_sa.sa.sa_family, SOCK_STREAM, 0));
98
99                 if (GetFd() == -1)
100                         throw ModuleException("Could not create socket");
101
102                 done = false;
103
104                 irc::sockets::sockaddrs bindaddr;
105                 irc::sockets::sockaddrs connaddr;
106
107                 memcpy(&bindaddr, &user->server_sa, sizeof(bindaddr));
108                 memcpy(&connaddr, &user->client_sa, sizeof(connaddr));
109
110                 if (connaddr.sa.sa_family == AF_INET6)
111                 {
112                         bindaddr.in6.sin6_port = 0;
113                         connaddr.in6.sin6_port = htons(113);
114                 }
115                 else
116                 {
117                         bindaddr.in4.sin_port = 0;
118                         connaddr.in4.sin_port = htons(113);
119                 }
120
121                 /* Attempt to bind (ident requests must come from the ip the query is referring to */
122                 if (ServerInstance->SE->Bind(GetFd(), bindaddr) < 0)
123                 {
124                         this->Close();
125                         throw ModuleException("failed to bind()");
126                 }
127
128                 ServerInstance->SE->NonBlocking(GetFd());
129
130                 /* Attempt connection (nonblocking) */
131                 if (ServerInstance->SE->Connect(this, &connaddr.sa, connaddr.sa_size()) == -1 && errno != EINPROGRESS)
132                 {
133                         this->Close();
134                         throw ModuleException("connect() failed");
135                 }
136
137                 /* Add fd to socket engine */
138                 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_POLL_WRITE))
139                 {
140                         this->Close();
141                         throw ModuleException("out of fds");
142                 }
143         }
144
145         void OnConnected()
146         {
147                 ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "OnConnected()");
148                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
149
150                 char req[32];
151
152                 /* Build request in the form 'localport,remoteport\r\n' */
153                 int req_size;
154                 if (user->client_sa.sa.sa_family == AF_INET6)
155                         req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
156                                 ntohs(user->client_sa.in6.sin6_port), ntohs(user->server_sa.in6.sin6_port));
157                 else
158                         req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
159                                 ntohs(user->client_sa.in4.sin_port), ntohs(user->server_sa.in4.sin_port));
160
161                 /* Send failed if we didnt write the whole ident request --
162                  * might as well give up if this happens!
163                  */
164                 if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size)
165                         done = true;
166         }
167
168         void HandleEvent(EventType et, int errornum = 0)
169         {
170                 switch (et)
171                 {
172                         case EVENT_READ:
173                                 /* fd readable event, received ident response */
174                                 ReadResponse();
175                         break;
176                         case EVENT_WRITE:
177                                 /* fd writeable event, successfully connected! */
178                                 OnConnected();
179                         break;
180                         case EVENT_ERROR:
181                                 /* fd error event, ohshi- */
182                                 ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "EVENT_ERROR");
183                                 /* We *must* Close() here immediately or we get a
184                                  * huge storm of EVENT_ERROR events!
185                                  */
186                                 Close();
187                                 done = true;
188                         break;
189                 }
190         }
191
192         void Close()
193         {
194                 /* Remove ident socket from engine, and close it, but dont detatch it
195                  * from its parent user class, or attempt to delete its memory.
196                  */
197                 if (GetFd() > -1)
198                 {
199                         ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "Close ident socket %d", GetFd());
200                         ServerInstance->SE->DelFd(this);
201                         ServerInstance->SE->Close(GetFd());
202                         this->SetFd(-1);
203                 }
204         }
205
206         bool HasResult()
207         {
208                 return done;
209         }
210
211         void ReadResponse()
212         {
213                 /* We don't really need to buffer for incomplete replies here, since IDENT replies are
214                  * extremely short - there is *no* sane reason it'd be in more than one packet
215                  */
216                 char ibuf[256];
217                 int recvresult = ServerInstance->SE->Recv(this, ibuf, sizeof(ibuf)-1, 0);
218
219                 /* Close (but don't delete from memory) our socket
220                  * and flag as done since the ident lookup has finished
221                  */
222                 Close();
223                 done = true;
224
225                 /* Cant possibly be a valid response shorter than 3 chars,
226                  * because the shortest possible response would look like: '1,1'
227                  */
228                 if (recvresult < 3)
229                         return;
230
231                 ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "ReadResponse()");
232
233                 /* Truncate at the first null character, but first make sure
234                  * there is at least one null char (at the end of the buffer).
235                  */
236                 ibuf[recvresult] = '\0';
237                 std::string buf(ibuf);
238
239                 /* <2 colons: invalid
240                  *  2 colons: reply is an error
241                  * >3 colons: there is a colon in the ident
242                  */
243                 if (std::count(buf.begin(), buf.end(), ':') != 3)
244                         return;
245
246                 std::string::size_type lastcolon = buf.rfind(':');
247
248                 /* Truncate the ident at any characters we don't like, skip leading spaces */
249                 for (std::string::const_iterator i = buf.begin()+lastcolon+1; i != buf.end(); ++i)
250                 {
251                         if (result.size() == ServerInstance->Config->Limits.IdentMax)
252                                 /* Ident is getting too long */
253                                 break;
254
255                         if (*i == ' ')
256                                 continue;
257
258                         /* Add the next char to the result and see if it's still a valid ident,
259                          * according to IsIdent(). If it isn't, then erase what we just added and
260                          * we're done.
261                          */
262                         result += *i;
263                         if (!ServerInstance->IsIdent(result.c_str()))
264                         {
265                                 result.erase(result.end()-1);
266                                 break;
267                         }
268                 }
269         }
270 };
271
272 class ModuleIdent : public Module
273 {
274         int RequestTimeout;
275         SimpleExtItem<IdentRequestSocket> ext;
276  public:
277         ModuleIdent() : ext("ident_socket", this)
278         {
279         }
280
281         void init() CXX11_OVERRIDE
282         {
283                 ServerInstance->Modules->AddService(ext);
284                 OnRehash(NULL);
285                 Implementation eventlist[] = {
286                         I_OnRehash, I_OnUserInit, I_OnCheckReady,
287                         I_OnUserDisconnect, I_OnSetConnectClass
288                 };
289                 ServerInstance->Modules->Attach(eventlist, this, sizeof(eventlist)/sizeof(Implementation));
290         }
291
292         Version GetVersion() CXX11_OVERRIDE
293         {
294                 return Version("Provides support for RFC1413 ident lookups", VF_VENDOR);
295         }
296
297         void OnRehash(User *user) CXX11_OVERRIDE
298         {
299                 RequestTimeout = ServerInstance->Config->ConfValue("ident")->getInt("timeout", 5);
300                 if (!RequestTimeout)
301                         RequestTimeout = 5;
302         }
303
304         void OnUserInit(LocalUser *user) CXX11_OVERRIDE
305         {
306                 ConfigTag* tag = user->MyClass->config;
307                 if (!tag->getBool("useident", true))
308                         return;
309
310                 user->WriteNotice("*** Looking up your ident...");
311
312                 try
313                 {
314                         IdentRequestSocket *isock = new IdentRequestSocket(IS_LOCAL(user));
315                         ext.set(user, isock);
316                 }
317                 catch (ModuleException &e)
318                 {
319                         ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "Ident exception: %s", e.GetReason());
320                 }
321         }
322
323         /* This triggers pretty regularly, we can use it in preference to
324          * creating a Timer object and especially better than creating a
325          * Timer per ident lookup!
326          */
327         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
328         {
329                 /* Does user have an ident socket attached at all? */
330                 IdentRequestSocket *isock = ext.get(user);
331                 if (!isock)
332                 {
333                         ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "No ident socket :(");
334                         return MOD_RES_PASSTHRU;
335                 }
336
337                 ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "Has ident_socket");
338
339                 time_t compare = isock->age;
340                 compare += RequestTimeout;
341
342                 /* Check for timeout of the socket */
343                 if (ServerInstance->Time() >= compare)
344                 {
345                         /* Ident timeout */
346                         user->WriteNotice("*** Ident request timed out.");
347                         ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "Timeout");
348                 }
349                 else if (!isock->HasResult())
350                 {
351                         // time still good, no result yet... hold the registration
352                         ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "No result yet");
353                         return MOD_RES_DENY;
354                 }
355
356                 ServerInstance->Logs->Log("m_ident", LOG_DEBUG, "Yay, result!");
357
358                 /* wooo, got a result (it will be good, or bad) */
359                 if (isock->result.empty())
360                 {
361                         user->ident.insert(0, 1, '~');
362                         user->WriteNotice("*** Could not find your ident, using " + user->ident + " instead.");
363                 }
364                 else
365                 {
366                         user->ident = isock->result;
367                         user->WriteNotice("*** Found your ident, '" + user->ident + "'");
368                 }
369
370                 user->InvalidateCache();
371                 isock->Close();
372                 ext.unset(user);
373                 return MOD_RES_PASSTHRU;
374         }
375
376         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
377         {
378                 if (myclass->config->getBool("requireident") && user->ident[0] == '~')
379                         return MOD_RES_DENY;
380                 return MOD_RES_PASSTHRU;
381         }
382
383         void OnCleanup(int target_type, void *item) CXX11_OVERRIDE
384         {
385                 /* Module unloading, tidy up users */
386                 if (target_type == TYPE_USER)
387                 {
388                         LocalUser* user = IS_LOCAL((User*) item);
389                         if (user)
390                                 OnUserDisconnect(user);
391                 }
392         }
393
394         void OnUserDisconnect(LocalUser *user) CXX11_OVERRIDE
395         {
396                 /* User disconnect (generic socket detatch event) */
397                 IdentRequestSocket *isock = ext.get(user);
398                 if (isock)
399                 {
400                         isock->Close();
401                         ext.unset(user);
402                 }
403         }
404 };
405
406 MODULE_INIT(ModuleIdent)