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