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