]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_ident.cpp
d762d42a212b3e57bfa5c12daa013045ce378a14
[user/henk/code/inspircd.git] / src / modules / m_ident.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 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->Log(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->Log(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->Log(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->Log(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                         char ident[IDENTMAX + 2];
300
301                         /* Truncate the ident at any characters we don't like, skip leading spaces */
302                         int k = 0;
303                         for (const char *j = token.c_str(); *j && (k < 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[k++] = *j;
312                                         continue;
313                                 }
314
315                                 break;
316                         }
317
318                         ident[k] = '\0';
319
320                         /* Re-check with IsIdent, in case that changes and this doesn't (paranoia!) */
321                         if (*ident && ServerInstance->IsIdent(ident))
322                         {
323                                 result = ident;
324                         }
325
326                         break;
327                 }
328
329                 /* Close (but dont delete from memory) our socket
330                  * and flag as done
331                  */
332                 Close();
333                 done = true;
334                 return;
335         }
336 };
337
338 class ModuleIdent : public Module
339 {
340  private:
341         int RequestTimeout;
342  public:
343         ModuleIdent(InspIRCd *Me)
344                 : Module(Me)
345         {
346                 OnRehash(NULL, "");
347                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnCleanup, I_OnUserDisconnect };
348                 ServerInstance->Modules->Attach(eventlist, this, 5);
349         }
350         
351         virtual Version GetVersion()
352         {
353                 return Version(1, 1, 1, 0, VF_VENDOR, API_VERSION);
354         }
355         
356         
357         virtual void OnRehash(User *user, const std::string &param)
358         {
359                 ConfigReader MyConf(ServerInstance);
360                 
361                 RequestTimeout = MyConf.ReadInteger("ident", "timeout", 0, true);
362                 if (!RequestTimeout)
363                         RequestTimeout = 5;
364         }
365         
366         virtual int OnUserRegister(User *user)
367         {
368                 /* User::ident is currently the username field from USER; with m_ident loaded, that
369                  * should be preceded by a ~. The field is actually IDENTMAX+2 characters wide. */
370                 memmove(user->ident + 1, user->ident, IDENTMAX);
371                 user->ident[0] = '~';
372                 /* Ensure that it is null terminated */
373                 user->ident[IDENTMAX + 1] = '\0';
374
375                 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
376
377                 // Get the IP that the user is connected to, and bind to that for the outgoing connection
378                 #ifndef IPV6
379                 sockaddr_in laddr;
380                 #else
381                 sockaddr_in6 laddr;
382                 #endif
383                 socklen_t laddrsz = sizeof(laddr);
384
385                 if (getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0)
386                 {
387                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", user->ident);
388                         return 0;
389                 }
390
391                 #ifndef IPV6
392                 const char *ip = inet_ntoa(laddr.sin_addr);
393                 #else
394                 char ip[INET6_ADDRSTRLEN + 1];
395                 inet_ntop(laddr.sin6_family, &laddr.sin6_addr, ip, INET6_ADDRSTRLEN);
396                 #endif
397
398                 IdentRequestSocket *isock = NULL;
399                 try
400                 {
401                         isock = new IdentRequestSocket(ServerInstance, user, ip);
402                 }
403                 catch (ModuleException &e)
404                 {
405                         ServerInstance->Log(DEBUG,"Ident exception: %s", e.GetReason());
406                         return 0;
407                 }
408
409                 user->Extend("ident_socket", isock);
410                 return 0;
411         }
412
413         /* This triggers pretty regularly, we can use it in preference to
414          * creating a Timer object and especially better than creating a
415          * Timer per ident lookup!
416          */
417         virtual bool OnCheckReady(User *user)
418         {
419                 ServerInstance->Log(DEBUG,"OnCheckReady %s", user->nick);
420
421                 /* Does user have an ident socket attached at all? */
422                 IdentRequestSocket *isock = NULL;
423                 if (!user->GetExt("ident_socket", isock))
424                 {
425                         ServerInstance->Log(DEBUG, "No ident socket :(");
426                         return true;
427                 }
428
429                 ServerInstance->Log(DEBUG, "Has ident_socket");
430
431                 time_t compare = isock->age;
432                 compare += RequestTimeout;
433
434                 /* Check for timeout of the socket */
435                 if (ServerInstance->Time() >= compare)
436                 {
437                         /* Ident timeout */
438                         user->WriteServ("NOTICE Auth :*** Ident request timed out.");
439                         ServerInstance->Log(DEBUG, "Timeout");
440                         /* The user isnt actually disconnecting,
441                          * we call this to clean up the user
442                          */
443                         OnUserDisconnect(user);
444                         return true;
445                 }
446
447                 /* Got a result yet? */
448                 if (!isock->HasResult())
449                 {
450                         ServerInstance->Log(DEBUG, "No result yet");
451                         return false;
452                 }
453
454                 ServerInstance->Log(DEBUG, "Yay, result!");
455
456                 /* wooo, got a result (it will be good, or bad) */
457                 if (*(isock->GetResult()) != '~')
458                         user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", isock->GetResult());
459                 else
460                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
461
462                 /* Copy the ident string to the user */
463                 strlcpy(user->ident, isock->GetResult(), IDENTMAX+1);
464
465                 /* The user isnt actually disconnecting, we call this to clean up the user */
466                 OnUserDisconnect(user);
467                 return true;
468         }
469
470         virtual void OnCleanup(int target_type, void *item)
471         {
472                 /* Module unloading, tidy up users */
473                 if (target_type == TYPE_USER)
474                         OnUserDisconnect((User*)item);
475         }
476
477         virtual void OnUserDisconnect(User *user)
478         {
479                 /* User disconnect (generic socket detatch event) */
480                 IdentRequestSocket *isock = NULL;
481                 if (user->GetExt("ident_socket", isock))
482                 {
483                         isock->Close();
484                         delete isock;
485                         user->Shrink("ident_socket");
486                         ServerInstance->Log(DEBUG, "Removed ident socket from %s", user->nick);
487                 }
488         }
489 };
490
491 MODULE_INIT(ModuleIdent)
492