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