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