]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_ident.cpp
f47901123d39c71d0bff0d99c6f60755bae7fe83
[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 /* --------------------------------------------------------------
28  * Note that this is the third incarnation of m_ident. The first
29  * two attempts were pretty crashy, mainly due to the fact we tried
30  * to use InspSocket/BufferedSocket to make them work. This class
31  * is ok for more heavyweight tasks, it does a lot of things behind
32  * the scenes that are not good for ident sockets and it has a huge
33  * memory footprint!
34  *
35  * To fix all the issues that we had in the old ident modules (many
36  * nasty race conditions that would cause segfaults etc) we have
37  * rewritten this module to use a simplified socket object based
38  * directly off EventHandler. As EventHandler only has low level
39  * readability, writeability and error events tied directly to the
40  * socket engine, this makes our lives easier as nothing happens to
41  * our ident lookup class that is outside of this module, or out-
42  * side of the control of the class. There are no timers, internal
43  * events, or such, which will cause the socket to be deleted,
44  * queued for deletion, etc. In fact, theres not even any queueing!
45  *
46  * Using this framework we have a much more stable module.
47  *
48  * A few things to note:
49  *
50  *   O  The only place that may *delete* an active or inactive
51  *      ident socket is OnUserDisconnect in the module class.
52  *      Because this is out of scope of the socket class there is
53  *      no possibility that the socket may ever try to delete
54  *      itself.
55  *
56  *   O  Closure of the ident socket with the Close() method will
57  *      not cause removal of the socket from memory or detatchment
58  *      from its 'parent' User class. It will only flag it as an
59  *      inactive socket in the socket engine.
60  *
61  *   O  Timeouts are handled in OnCheckReaady at the same time as
62  *      checking if the ident socket has a result. This is done
63  *      by checking if the age the of the class (its instantiation
64  *      time) plus the timeout value is greater than the current time.
65  *
66  *  O   The ident socket is able to but should not modify its
67  *      'parent' user directly. Instead the ident socket class sets
68  *      a completion flag and during the next call to OnCheckReady,
69  *      the completion flag will be checked and any result copied to
70  *      that user's class. This again ensures a single point of socket
71  *      deletion for safer, neater code.
72  *
73  *  O   The code in the constructor of the ident socket is taken from
74  *      BufferedSocket but majorly thinned down. It works for both
75  *      IPv4 and IPv6.
76  *
77  *  O   In the event that the ident socket throws a ModuleException,
78  *      nothing is done. This is counted as total and complete
79  *      failure to create a connection.
80  * --------------------------------------------------------------
81  */
82
83 class IdentRequestSocket : public EventHandler
84 {
85  public:
86         LocalUser *user;                        /* User we are attached to */
87         std::string result;             /* Holds the ident string if done */
88         time_t age;
89         bool done;                      /* True if lookup is finished */
90
91         IdentRequestSocket(LocalUser* u) : user(u)
92         {
93                 age = ServerInstance->Time();
94
95                 SetFd(socket(user->server_sa.family(), SOCK_STREAM, 0));
96
97                 if (GetFd() == -1)
98                         throw ModuleException("Could not create socket");
99
100                 done = false;
101
102                 irc::sockets::sockaddrs bindaddr;
103                 irc::sockets::sockaddrs connaddr;
104
105                 memcpy(&bindaddr, &user->server_sa, sizeof(bindaddr));
106                 memcpy(&connaddr, &user->client_sa, sizeof(connaddr));
107
108                 if (connaddr.family() == AF_INET6)
109                 {
110                         bindaddr.in6.sin6_port = 0;
111                         connaddr.in6.sin6_port = htons(113);
112                 }
113                 else
114                 {
115                         bindaddr.in4.sin_port = 0;
116                         connaddr.in4.sin_port = htons(113);
117                 }
118
119                 /* Attempt to bind (ident requests must come from the ip the query is referring to */
120                 if (SocketEngine::Bind(GetFd(), bindaddr) < 0)
121                 {
122                         this->Close();
123                         throw ModuleException("failed to bind()");
124                 }
125
126                 SocketEngine::NonBlocking(GetFd());
127
128                 /* Attempt connection (nonblocking) */
129                 if (SocketEngine::Connect(this, connaddr) == -1 && errno != EINPROGRESS)
130                 {
131                         this->Close();
132                         throw ModuleException("connect() failed");
133                 }
134
135                 /* Add fd to socket engine */
136                 if (!SocketEngine::AddFd(this, FD_WANT_NO_READ | FD_WANT_POLL_WRITE))
137                 {
138                         this->Close();
139                         throw ModuleException("out of fds");
140                 }
141         }
142
143         void OnEventHandlerWrite() CXX11_OVERRIDE
144         {
145                 SocketEngine::ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
146
147                 char req[32];
148
149                 /* Build request in the form 'localport,remoteport\r\n' */
150                 int req_size;
151                 if (user->client_sa.family() == AF_INET6)
152                         req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
153                                 ntohs(user->client_sa.in6.sin6_port), ntohs(user->server_sa.in6.sin6_port));
154                 else
155                         req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
156                                 ntohs(user->client_sa.in4.sin_port), ntohs(user->server_sa.in4.sin_port));
157
158                 /* Send failed if we didnt write the whole ident request --
159                  * might as well give up if this happens!
160                  */
161                 if (SocketEngine::Send(this, req, req_size, 0) < req_size)
162                         done = true;
163         }
164
165         void Close()
166         {
167                 /* Remove ident socket from engine, and close it, but dont detatch it
168                  * from its parent user class, or attempt to delete its memory.
169                  */
170                 if (GetFd() > -1)
171                 {
172                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Close ident socket %d", GetFd());
173                         SocketEngine::Close(this);
174                 }
175         }
176
177         bool HasResult()
178         {
179                 return done;
180         }
181
182         void OnEventHandlerRead() CXX11_OVERRIDE
183         {
184                 /* We don't really need to buffer for incomplete replies here, since IDENT replies are
185                  * extremely short - there is *no* sane reason it'd be in more than one packet
186                  */
187                 char ibuf[256];
188                 int recvresult = SocketEngine::Recv(this, ibuf, sizeof(ibuf)-1, 0);
189
190                 /* Close (but don't delete from memory) our socket
191                  * and flag as done since the ident lookup has finished
192                  */
193                 Close();
194                 done = true;
195
196                 /* Cant possibly be a valid response shorter than 3 chars,
197                  * because the shortest possible response would look like: '1,1'
198                  */
199                 if (recvresult < 3)
200                         return;
201
202                 ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "ReadResponse()");
203
204                 /* Truncate at the first null character, but first make sure
205                  * there is at least one null char (at the end of the buffer).
206                  */
207                 ibuf[recvresult] = '\0';
208                 std::string buf(ibuf);
209
210                 /* <2 colons: invalid
211                  *  2 colons: reply is an error
212                  * >3 colons: there is a colon in the ident
213                  */
214                 if (std::count(buf.begin(), buf.end(), ':') != 3)
215                         return;
216
217                 std::string::size_type lastcolon = buf.rfind(':');
218
219                 /* Truncate the ident at any characters we don't like, skip leading spaces */
220                 for (std::string::const_iterator i = buf.begin()+lastcolon+1; i != buf.end(); ++i)
221                 {
222                         if (result.size() == ServerInstance->Config->Limits.IdentMax)
223                                 /* Ident is getting too long */
224                                 break;
225
226                         if (*i == ' ')
227                                 continue;
228
229                         /* Add the next char to the result and see if it's still a valid ident,
230                          * according to IsIdent(). If it isn't, then erase what we just added and
231                          * we're done.
232                          */
233                         result += *i;
234                         if (!ServerInstance->IsIdent(result))
235                         {
236                                 result.erase(result.end()-1);
237                                 break;
238                         }
239                 }
240         }
241
242         void OnEventHandlerError(int errornum) CXX11_OVERRIDE
243         {
244                 Close();
245                 done = true;
246         }
247
248         CullResult cull() CXX11_OVERRIDE
249         {
250                 Close();
251                 return EventHandler::cull();
252         }
253 };
254
255 class ModuleIdent : public Module
256 {
257  private:
258         unsigned int timeout;
259         bool NoLookupPrefix;
260         SimpleExtItem<IdentRequestSocket, stdalgo::culldeleter> ext;
261
262         static void PrefixIdent(LocalUser* user)
263         {
264                 // Check that they haven't been prefixed already.
265                 if (user->ident[0] == '~')
266                         return;
267                 
268                 // All invalid usernames are prefixed with a tilde.
269                 std::string newident(user->ident);
270                 newident.insert(newident.begin(), '~');
271
272                 // If the username is too long then truncate it.
273                 if (newident.length() > ServerInstance->Config->Limits.IdentMax)
274                         newident.erase(ServerInstance->Config->Limits.IdentMax);
275
276                 // Apply the new username.
277                 user->ChangeIdent(newident);
278         }
279
280  public:
281         ModuleIdent()
282                 : ext("ident_socket", ExtensionItem::EXT_USER, this)
283         {
284         }
285
286         Version GetVersion() CXX11_OVERRIDE
287         {
288                 return Version("Provides support for RFC1413 ident lookups", VF_VENDOR);
289         }
290
291         void ReadConfig(ConfigStatus& status) CXX11_OVERRIDE
292         {
293                 ConfigTag* tag = ServerInstance->Config->ConfValue("ident");
294                 timeout = tag->getDuration("timeout", 5, 1, 60);
295                 NoLookupPrefix = tag->getBool("nolookupprefix", false);
296         }
297
298         void OnSetUserIP(LocalUser* user) CXX11_OVERRIDE
299         {
300                 IdentRequestSocket* isock = ext.get(user);
301                 if (isock)
302                 {
303                         // If an ident lookup request was in progress then cancel it.
304                         isock->Close();
305                         ext.unset(user);
306                 }
307
308                 // The ident protocol requires that clients are connecting over a protocol with ports.
309                 if (user->client_sa.family() != AF_INET && user->client_sa.family() != AF_INET6)
310                         return;
311
312                 // We don't want to look this up once the user has connected.
313                 if (user->registered == REG_ALL)
314                         return;
315
316                 ConfigTag* tag = user->MyClass->config;
317                 if (!tag->getBool("useident", true))
318                         return;
319
320                 user->WriteNotice("*** Looking up your ident...");
321
322                 try
323                 {
324                         isock = new IdentRequestSocket(user);
325                         ext.set(user, isock);
326                 }
327                 catch (ModuleException &e)
328                 {
329                         ServerInstance->Logs->Log(MODNAME, LOG_DEBUG, "Ident exception: " + e.GetReason());
330                 }
331         }
332
333         /* This triggers pretty regularly, we can use it in preference to
334          * creating a Timer object and especially better than creating a
335          * Timer per ident lookup!
336          */
337         ModResult OnCheckReady(LocalUser *user) CXX11_OVERRIDE
338         {
339                 /* Does user have an ident socket attached at all? */
340                 IdentRequestSocket *isock = ext.get(user);
341                 if (!isock)
342                 {
343                         if (NoLookupPrefix)
344                                 PrefixIdent(user);
345                         return MOD_RES_PASSTHRU;
346                 }
347
348                 time_t compare = isock->age + timeout;
349
350                 /* Check for timeout of the socket */
351                 if (ServerInstance->Time() >= compare)
352                 {
353                         /* Ident timeout */
354                         PrefixIdent(user);
355                         user->WriteNotice("*** Ident lookup timed out, using " + user->ident + " instead.");
356                 }
357                 else if (!isock->HasResult())
358                 {
359                         // time still good, no result yet... hold the registration
360                         return MOD_RES_DENY;
361                 }
362
363                 /* wooo, got a result (it will be good, or bad) */
364                 else if (isock->result.empty())
365                 {
366                         PrefixIdent(user);
367                         user->WriteNotice("*** Could not find your ident, using " + user->ident + " instead.");
368                 }
369                 else
370                 {
371                         user->ChangeIdent(isock->result);
372                         user->WriteNotice("*** Found your ident, '" + user->ident + "'");
373                 }
374
375                 isock->Close();
376                 ext.unset(user);
377                 return MOD_RES_PASSTHRU;
378         }
379
380         ModResult OnSetConnectClass(LocalUser* user, ConnectClass* myclass) CXX11_OVERRIDE
381         {
382                 if (myclass->config->getBool("requireident") && user->ident[0] == '~')
383                         return MOD_RES_DENY;
384                 return MOD_RES_PASSTHRU;
385         }
386 };
387
388 MODULE_INIT(ModuleIdent)