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