]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_ident.cpp
Make this comply with the spec; that is - CAP may be requested after registration.
[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                 done = false;
107
108                 /* We allocate two of these because sizeof(sockaddr_in6) > sizeof(sockaddr_in) */
109                 sockaddr* s = new sockaddr[2];
110                 sockaddr* addr = new sockaddr[2];
111
112 #ifdef IPV6
113                 /* Horrid icky nasty ugly berkely socket crap. */
114                 if (v6)
115                 {
116                         in6_addr addy;
117                         in6_addr n;
118                         if (inet_pton(AF_INET6, user->GetIPString(), &addy) > 0)
119                         {
120                                 ((sockaddr_in6*)addr)->sin6_family = AF_INET6;
121                                 memcpy(&((sockaddr_in6*)addr)->sin6_addr, &addy, sizeof(addy));
122                                 ((sockaddr_in6*)addr)->sin6_port = htons(113);
123                                 size = sizeof(sockaddr_in6);
124                                 inet_pton(AF_INET6, bindip.c_str(), &n);
125                                 memcpy(&((sockaddr_in6*)s)->sin6_addr, &n, sizeof(sockaddr_in6));
126                                 ((sockaddr_in6*)s)->sin6_port = 0;
127                                 ((sockaddr_in6*)s)->sin6_family = AF_INET6;
128                         }
129                 }
130                 else
131 #endif
132                 {
133                         in_addr addy;
134                         in_addr n;
135                         if (inet_aton(user->GetIPString(), &addy) > 0)
136                         {
137                                 ((sockaddr_in*)addr)->sin_family = AF_INET;
138                                 ((sockaddr_in*)addr)->sin_addr = addy;
139                                 ((sockaddr_in*)addr)->sin_port = htons(113);
140                                 size = sizeof(sockaddr_in);
141                                 inet_aton(bindip.c_str(), &n);
142                                 ((sockaddr_in*)s)->sin_addr = n;
143                                 ((sockaddr_in*)s)->sin_port = 0;
144                                 ((sockaddr_in*)s)->sin_family = AF_INET;
145                         }
146                 }
147
148                 /* Attempt to bind (ident requests must come from the ip the query is referring to */
149                 if (ServerInstance->SE->Bind(GetFd(), s, size) < 0)
150                 {
151                         this->Close();
152                         delete[] s;
153                         delete[] addr;
154                         throw ModuleException("failed to bind()");
155                 }
156
157                 delete[] s;
158                 ServerInstance->SE->NonBlocking(GetFd());
159
160                 /* Attempt connection (nonblocking) */
161                 if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1 && errno != EINPROGRESS)
162                 {
163                         this->Close();
164                         delete[] addr;
165                         throw ModuleException("connect() failed");
166                 }
167
168                 delete[] addr;
169
170                 /* Add fd to socket engine */
171                 if (!ServerInstance->SE->AddFd(this))
172                 {
173                         this->Close();
174                         throw ModuleException("out of fds");
175                 }
176
177                 /* Important: We set WantWrite immediately after connect()
178                  * because a successful connection will trigger a writability event
179                  */
180                 ServerInstance->SE->WantWrite(this);
181         }
182
183         virtual void OnConnected()
184         {
185                 ServerInstance->Logs->Log("m_ident",DEBUG,"OnConnected()");
186
187                 /* Both sockaddr_in and sockaddr_in6 can be safely casted to sockaddr, especially since the
188                  * only members we use are in a part of the struct that should always be identical (at the
189                  * byte level). */
190                 #ifndef IPV6
191                 sockaddr_in laddr, raddr;
192                 #else
193                 sockaddr_in6 laddr, raddr;
194                 #endif
195
196                 socklen_t laddrsz = sizeof(laddr);
197                 socklen_t raddrsz = sizeof(raddr);
198
199                 if ((getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0) || (getpeername(user->GetFd(), (sockaddr*) &raddr, &raddrsz) != 0))
200                 {
201                         done = true;
202                         return;
203                 }
204
205                 char req[32];
206
207                 /* Build request in the form 'localport,remoteport\r\n' */
208                 #ifndef IPV6
209                 int req_size = snprintf(req, sizeof(req), "%d,%d\r\n", ntohs(raddr.sin_port), ntohs(laddr.sin_port));
210                 #else
211                 int req_size = snprintf(req, sizeof(req), "%d,%d\r\n", ntohs(raddr.sin6_port), ntohs(laddr.sin6_port));
212                 #endif
213
214                 /* Send failed if we didnt write the whole ident request --
215                  * might as well give up if this happens!
216                  */
217                 if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size)
218                         done = true;
219         }
220
221         virtual void HandleEvent(EventType et, int errornum = 0)
222         {
223                 switch (et)
224                 {
225                         case EVENT_READ:
226                                 /* fd readable event, received ident response */
227                                 ReadResponse();
228                         break;
229                         case EVENT_WRITE:
230                                 /* fd writeable event, successfully connected! */
231                                 OnConnected();
232                         break;
233                         case EVENT_ERROR:
234                                 /* fd error event, ohshi- */
235                                 ServerInstance->Logs->Log("m_ident",DEBUG,"EVENT_ERROR");
236                                 /* We *must* Close() here immediately or we get a
237                                  * huge storm of EVENT_ERROR events!
238                                  */
239                                 Close();
240                                 done = true;
241                         break;
242                 }
243         }
244
245         void Close()
246         {
247                 /* Remove ident socket from engine, and close it, but dont detatch it
248                  * from its parent user class, or attempt to delete its memory.
249                  */
250                 if (GetFd() > -1)
251                 {
252                         ServerInstance->Logs->Log("m_ident",DEBUG,"Close ident socket %d", GetFd());
253                         ServerInstance->SE->DelFd(this);
254                         ServerInstance->SE->Close(GetFd());
255                         ServerInstance->SE->Shutdown(GetFd(), SHUT_WR);
256                         this->SetFd(-1);
257                 }
258         }
259
260         bool HasResult()
261         {
262                 return done;
263         }
264
265         /* Note: if the lookup succeeded, will contain 'ident', otherwise
266          * will contain '~ident'. Use *GetResult() to determine lookup success.
267          */
268         const char* GetResult()
269         {
270                 return result.c_str();
271         }
272
273         void ReadResponse()
274         {
275                 /* We don't really need to buffer for incomplete replies here, since IDENT replies are
276                  * extremely short - there is *no* sane reason it'd be in more than one packet
277                  */
278                 char ibuf[MAXBUF];
279                 int recvresult = ServerInstance->SE->Recv(this, ibuf, MAXBUF-1, 0);
280
281                 /* Cant possibly be a valid response shorter than 3 chars,
282                  * because the shortest possible response would look like: '1,1'
283                  */
284                 if (recvresult < 3)
285                 {
286                         Close();
287                         done = true;
288                         return;
289                 }
290
291                 ServerInstance->Logs->Log("m_ident",DEBUG,"ReadResponse()");
292
293                 irc::sepstream sep(ibuf, ':');
294                 std::string token;
295                 for (int i = 0; sep.GetToken(token); i++)
296                 {
297                         /* We only really care about the 4th portion */
298                         if (i < 3)
299                                 continue;
300
301                         std::string ident;
302
303                         /* Truncate the ident at any characters we don't like, skip leading spaces */
304                         size_t k = 0;
305                         for (const char *j = token.c_str(); *j && (k < ServerInstance->Config->Limits.IdentMax + 1); j++)
306                         {
307                                 if (*j == ' ')
308                                         continue;
309
310                                 /* Rules taken from InspIRCd::IsIdent */
311                                 if (((*j >= 'A') && (*j <= '}')) || ((*j >= '0') && (*j <= '9')) || (*j == '-') || (*j == '.'))
312                                 {
313                                         ident += *j;
314                                         continue;
315                                 }
316
317                                 break;
318                         }
319
320                         /* Re-check with IsIdent, in case that changes and this doesn't (paranoia!) */
321                         if (!ident.empty() && ServerInstance->IsIdent(ident.c_str()))
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("$Id$", 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                 if (user->ident.length() > ServerInstance->Config->Limits.IdentMax + 1)
371                         user->ident.assign(user->ident, 0, ServerInstance->Config->Limits.IdentMax);
372                 user->ident.insert(0, "~");
373
374                 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
375
376                 // Get the IP that the user is connected to, and bind to that for the outgoing connection
377                 #ifndef IPV6
378                 sockaddr_in laddr;
379                 #else
380                 sockaddr_in6 laddr;
381                 #endif
382                 socklen_t laddrsz = sizeof(laddr);
383
384                 if (getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0)
385                 {
386                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", user->ident.c_str());
387                         return 0;
388                 }
389
390                 #ifndef IPV6
391                 const char *ip = inet_ntoa(laddr.sin_addr);
392                 #else
393                 char ip[INET6_ADDRSTRLEN + 1];
394                 inet_ntop(laddr.sin6_family, &laddr.sin6_addr, ip, INET6_ADDRSTRLEN);
395                 #endif
396
397                 IdentRequestSocket *isock = NULL;
398                 try
399                 {
400                         isock = new IdentRequestSocket(ServerInstance, user, ip);
401                 }
402                 catch (ModuleException &e)
403                 {
404                         ServerInstance->Logs->Log("m_ident",DEBUG,"Ident exception: %s", e.GetReason());
405                         return 0;
406                 }
407
408                 user->Extend("ident_socket", isock);
409                 return 0;
410         }
411
412         /* This triggers pretty regularly, we can use it in preference to
413          * creating a Timer object and especially better than creating a
414          * Timer per ident lookup!
415          */
416         virtual bool OnCheckReady(User *user)
417         {
418                 /* Does user have an ident socket attached at all? */
419                 IdentRequestSocket *isock = NULL;
420                 if (!user->GetExt("ident_socket", isock))
421                 {
422                         ServerInstance->Logs->Log("m_ident",DEBUG, "No ident socket :(");
423                         return true;
424                 }
425
426                 ServerInstance->Logs->Log("m_ident",DEBUG, "Has ident_socket");
427
428                 time_t compare = isock->age;
429                 compare += RequestTimeout;
430
431                 /* Check for timeout of the socket */
432                 if (ServerInstance->Time() >= compare)
433                 {
434                         /* Ident timeout */
435                         user->WriteServ("NOTICE Auth :*** Ident request timed out.");
436                         ServerInstance->Logs->Log("m_ident",DEBUG, "Timeout");
437                         /* The user isnt actually disconnecting,
438                          * we call this to clean up the user
439                          */
440                         OnUserDisconnect(user);
441                         return true;
442                 }
443
444                 /* Got a result yet? */
445                 if (!isock->HasResult())
446                 {
447                         ServerInstance->Logs->Log("m_ident",DEBUG, "No result yet");
448                         return false;
449                 }
450
451                 ServerInstance->Logs->Log("m_ident",DEBUG, "Yay, result!");
452
453                 /* wooo, got a result (it will be good, or bad) */
454                 if (*(isock->GetResult()) != '~')
455                         user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", isock->GetResult());
456                 else
457                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
458
459                 /* Copy the ident string to the user */
460                 user->ident.assign(isock->GetResult(), 0, ServerInstance->Config->Limits.IdentMax + 1);
461
462                 /* The user isnt actually disconnecting, we call this to clean up the user */
463                 OnUserDisconnect(user);
464                 return true;
465         }
466
467         virtual void OnCleanup(int target_type, void *item)
468         {
469                 /* Module unloading, tidy up users */
470                 if (target_type == TYPE_USER)
471                         OnUserDisconnect((User*)item);
472         }
473
474         virtual void OnUserDisconnect(User *user)
475         {
476                 /* User disconnect (generic socket detatch event) */
477                 IdentRequestSocket *isock = NULL;
478                 if (user->GetExt("ident_socket", isock))
479                 {
480                         isock->Close();
481                         delete isock;
482                         user->Shrink("ident_socket");
483                 }
484         }
485 };
486
487 MODULE_INIT(ModuleIdent)
488