]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_ident.cpp
Of course, it DOES help to actually initialise the Mutex objects, and delete them...
[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         User *user;                     /* User we are attached to */
81         InspIRCd* ServerInstance;       /* Server instance */
82         bool done;                      /* True if lookup is finished */
83         std::string result;             /* Holds the ident string if done */
84  public:
85
86         IdentRequestSocket(InspIRCd *Server, User* u, const std::string &bindip) : user(u), ServerInstance(Server), result(u->ident)
87         {
88                 socklen_t size = 0;
89 #ifdef IPV6
90                 /* Does this look like a v6 ip address? */
91                 bool v6 = false;
92                 if ((bindip.empty()) || bindip.find(':') != std::string::npos)
93                 v6 = true;
94
95                 if (v6)
96                         SetFd(socket(AF_INET6, SOCK_STREAM, 0));
97                 else
98 #endif
99                         SetFd(socket(AF_INET, SOCK_STREAM, 0));
100
101                 if (GetFd() == -1)
102                         throw ModuleException("Could not create socket");
103
104                 done = false;
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         ConfigReader *Conf;
341  public:
342         ModuleIdent(InspIRCd *Me) : Module(Me)
343         {
344                 Conf = new ConfigReader(ServerInstance);
345                 OnRehash(NULL, "");
346                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnCleanup, I_OnUserDisconnect };
347                 ServerInstance->Modules->Attach(eventlist, this, 5);
348         }
349
350         ~ModuleIdent()
351         {
352                 delete Conf;
353         }
354
355         virtual Version GetVersion()
356         {
357                 return Version("$Id$", VF_VENDOR, API_VERSION);
358         }
359
360         virtual void OnRehash(User *user, const std::string &param)
361         {
362                 delete Conf;
363                 Conf = new ConfigReader(ServerInstance);
364
365                 RequestTimeout = Conf->ReadInteger("ident", "timeout", 0, true);
366                 if (!RequestTimeout)
367                         RequestTimeout = 5;
368         }
369
370         virtual int OnUserRegister(User *user)
371         {
372                 for (int j = 0; j < Conf->Enumerate("connect"); j++)
373                 {
374                         std::string hostn = Conf->ReadValue("connect","allow",j);
375                         /* XXX: Fixme: does not respect port, limit, etc */
376                         if ((InspIRCd::MatchCIDR(user->GetIPString(),hostn)) || (InspIRCd::Match(user->host,hostn)))
377                         {
378                                 bool useident = Conf->ReadFlag("connect", "useident", j);
379
380                                 if (!useident)
381                                         return 0;
382                         }
383                 }
384
385                 /* User::ident is currently the username field from USER; with m_ident loaded, that
386                  * should be preceded by a ~. The field is actually IdentMax+2 characters wide. */
387                 if (user->ident.length() > ServerInstance->Config->Limits.IdentMax + 1)
388                         user->ident.assign(user->ident, 0, ServerInstance->Config->Limits.IdentMax);
389                 user->ident.insert(0, "~");
390
391                 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
392
393                 // Get the IP that the user is connected to, and bind to that for the outgoing connection
394                 #ifndef IPV6
395                 sockaddr_in laddr;
396                 #else
397                 sockaddr_in6 laddr;
398                 #endif
399                 socklen_t laddrsz = sizeof(laddr);
400
401                 if (getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0)
402                 {
403                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", user->ident.c_str());
404                         return 0;
405                 }
406
407                 #ifndef IPV6
408                 const char *ip = inet_ntoa(laddr.sin_addr);
409                 #else
410                 char ip[INET6_ADDRSTRLEN + 1];
411                 inet_ntop(laddr.sin6_family, &laddr.sin6_addr, ip, INET6_ADDRSTRLEN);
412                 #endif
413
414                 IdentRequestSocket *isock = NULL;
415                 try
416                 {
417                         isock = new IdentRequestSocket(ServerInstance, user, ip);
418                 }
419                 catch (ModuleException &e)
420                 {
421                         ServerInstance->Logs->Log("m_ident",DEBUG,"Ident exception: %s", e.GetReason());
422                         return 0;
423                 }
424
425                 user->Extend("ident_socket", isock);
426                 return 0;
427         }
428
429         /* This triggers pretty regularly, we can use it in preference to
430          * creating a Timer object and especially better than creating a
431          * Timer per ident lookup!
432          */
433         virtual bool OnCheckReady(User *user)
434         {
435                 /* Does user have an ident socket attached at all? */
436                 IdentRequestSocket *isock = NULL;
437                 if (!user->GetExt("ident_socket", isock))
438                 {
439                         ServerInstance->Logs->Log("m_ident",DEBUG, "No ident socket :(");
440                         return true;
441                 }
442
443                 ServerInstance->Logs->Log("m_ident",DEBUG, "Has ident_socket");
444
445                 time_t compare = isock->age;
446                 compare += RequestTimeout;
447
448                 /* Check for timeout of the socket */
449                 if (ServerInstance->Time() >= compare)
450                 {
451                         /* Ident timeout */
452                         user->WriteServ("NOTICE Auth :*** Ident request timed out.");
453                         ServerInstance->Logs->Log("m_ident",DEBUG, "Timeout");
454                         /* The user isnt actually disconnecting,
455                          * we call this to clean up the user
456                          */
457                         OnUserDisconnect(user);
458                         return true;
459                 }
460
461                 /* Got a result yet? */
462                 if (!isock->HasResult())
463                 {
464                         ServerInstance->Logs->Log("m_ident",DEBUG, "No result yet");
465                         return false;
466                 }
467
468                 ServerInstance->Logs->Log("m_ident",DEBUG, "Yay, result!");
469
470                 /* wooo, got a result (it will be good, or bad) */
471                 if (*(isock->GetResult()) != '~')
472                         user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", isock->GetResult());
473                 else
474                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
475
476                 /* Copy the ident string to the user */
477                 user->ident.assign(isock->GetResult(), 0, ServerInstance->Config->Limits.IdentMax + 1);
478
479                 /* The user isnt actually disconnecting, we call this to clean up the user */
480                 OnUserDisconnect(user);
481                 return true;
482         }
483
484         virtual void OnCleanup(int target_type, void *item)
485         {
486                 /* Module unloading, tidy up users */
487                 if (target_type == TYPE_USER)
488                         OnUserDisconnect((User*)item);
489         }
490
491         virtual void OnUserDisconnect(User *user)
492         {
493                 /* User disconnect (generic socket detatch event) */
494                 IdentRequestSocket *isock = NULL;
495                 if (user->GetExt("ident_socket", isock))
496                 {
497                         isock->Close();
498                         delete isock;
499                         user->Shrink("ident_socket");
500                 }
501         }
502 };
503
504 MODULE_INIT(ModuleIdent)
505