1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
19 /* $ModDesc: Provides support for RFC1413 ident lookups */
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
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!
40 * Using this framework we have a much more stable module.
42 * A few things to note:
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
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.
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.
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.
67 * O The code in the constructor of the ident socket is taken from
68 * BufferedSocket but majorly thinned down. It works for both
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 * --------------------------------------------------------------
77 class IdentRequestSocket : public EventHandler
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 */
88 IdentRequestSocket(InspIRCd *Server, User* u, const std::string &bindip) : user(u), ServerInstance(Server), result(u->ident)
92 /* Does this look like a v6 ip address? */
94 if ((bindip.empty()) || bindip.find(':') != std::string::npos)
98 SetFd(socket(AF_INET6, SOCK_STREAM, 0));
101 SetFd(socket(AF_INET, SOCK_STREAM, 0));
104 throw ModuleException("Could not create socket");
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];
113 /* Horrid icky nasty ugly berkely socket crap. */
118 if (inet_pton(AF_INET6, user->GetIPString(), &addy) > 0)
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;
135 if (inet_aton(user->GetIPString(), &addy) > 0)
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;
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)
154 throw ModuleException("failed to bind()");
158 ServerInstance->SE->NonBlocking(GetFd());
160 /* Attempt connection (nonblocking) */
161 if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1 && errno != EINPROGRESS)
165 throw ModuleException("connect() failed");
170 /* Add fd to socket engine */
171 if (!ServerInstance->SE->AddFd(this))
174 throw ModuleException("out of fds");
177 /* Important: We set WantWrite immediately after connect()
178 * because a successful connection will trigger a writability event
180 ServerInstance->SE->WantWrite(this);
183 virtual void OnConnected()
185 ServerInstance->Logs->Log("m_ident",DEBUG,"OnConnected()");
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
191 sockaddr_in laddr, raddr;
193 sockaddr_in6 laddr, raddr;
196 socklen_t laddrsz = sizeof(laddr);
197 socklen_t raddrsz = sizeof(raddr);
199 if ((getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0) || (getpeername(user->GetFd(), (sockaddr*) &raddr, &raddrsz) != 0))
207 /* Build request in the form 'localport,remoteport\r\n' */
209 int req_size = snprintf(req, sizeof(req), "%d,%d\r\n", ntohs(raddr.sin_port), ntohs(laddr.sin_port));
211 int req_size = snprintf(req, sizeof(req), "%d,%d\r\n", ntohs(raddr.sin6_port), ntohs(laddr.sin6_port));
214 /* Send failed if we didnt write the whole ident request --
215 * might as well give up if this happens!
217 if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size)
221 virtual void HandleEvent(EventType et, int errornum = 0)
226 /* fd readable event, received ident response */
230 /* fd writeable event, successfully connected! */
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!
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.
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);
265 /* Note: if the lookup succeeded, will contain 'ident', otherwise
266 * will contain '~ident'. Use *GetResult() to determine lookup success.
268 const char* GetResult()
270 return result.c_str();
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
279 int recvresult = ServerInstance->SE->Recv(this, ibuf, MAXBUF-1, 0);
281 /* Cant possibly be a valid response shorter than 3 chars,
282 * because the shortest possible response would look like: '1,1'
291 ServerInstance->Logs->Log("m_ident",DEBUG,"ReadResponse()");
293 irc::sepstream sep(ibuf, ':');
295 for (int i = 0; sep.GetToken(token); i++)
297 /* We only really care about the 4th portion */
303 /* Truncate the ident at any characters we don't like, skip leading spaces */
305 for (const char *j = token.c_str(); *j && (k < ServerInstance->Config->Limits.IdentMax + 1); j++)
310 /* Rules taken from InspIRCd::IsIdent */
311 if (((*j >= 'A') && (*j <= '}')) || ((*j >= '0') && (*j <= '9')) || (*j == '-') || (*j == '.'))
320 /* Re-check with IsIdent, in case that changes and this doesn't (paranoia!) */
321 if (!ident.empty() && ServerInstance->IsIdent(ident.c_str()))
329 /* Close (but dont delete from memory) our socket
338 class ModuleIdent : public Module
343 ModuleIdent(InspIRCd *Me)
347 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnCleanup, I_OnUserDisconnect };
348 ServerInstance->Modules->Attach(eventlist, this, 5);
351 virtual Version GetVersion()
353 return Version("$Id$", VF_VENDOR, API_VERSION);
357 virtual void OnRehash(User *user, const std::string ¶m)
359 ConfigReader MyConf(ServerInstance);
361 RequestTimeout = MyConf.ReadInteger("ident", "timeout", 0, true);
366 virtual int OnUserRegister(User *user)
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, "~");
374 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
376 // Get the IP that the user is connected to, and bind to that for the outgoing connection
382 socklen_t laddrsz = sizeof(laddr);
384 if (getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0)
386 user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", user->ident.c_str());
391 const char *ip = inet_ntoa(laddr.sin_addr);
393 char ip[INET6_ADDRSTRLEN + 1];
394 inet_ntop(laddr.sin6_family, &laddr.sin6_addr, ip, INET6_ADDRSTRLEN);
397 IdentRequestSocket *isock = NULL;
400 isock = new IdentRequestSocket(ServerInstance, user, ip);
402 catch (ModuleException &e)
404 ServerInstance->Logs->Log("m_ident",DEBUG,"Ident exception: %s", e.GetReason());
408 user->Extend("ident_socket", isock);
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!
416 virtual bool OnCheckReady(User *user)
418 /* Does user have an ident socket attached at all? */
419 IdentRequestSocket *isock = NULL;
420 if (!user->GetExt("ident_socket", isock))
422 ServerInstance->Logs->Log("m_ident",DEBUG, "No ident socket :(");
426 ServerInstance->Logs->Log("m_ident",DEBUG, "Has ident_socket");
428 time_t compare = isock->age;
429 compare += RequestTimeout;
431 /* Check for timeout of the socket */
432 if (ServerInstance->Time() >= compare)
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
440 OnUserDisconnect(user);
444 /* Got a result yet? */
445 if (!isock->HasResult())
447 ServerInstance->Logs->Log("m_ident",DEBUG, "No result yet");
451 ServerInstance->Logs->Log("m_ident",DEBUG, "Yay, result!");
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());
457 user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
459 /* Copy the ident string to the user */
460 user->ident.assign(isock->GetResult(), 0, ServerInstance->Config->Limits.IdentMax + 1);
462 /* The user isnt actually disconnecting, we call this to clean up the user */
463 OnUserDisconnect(user);
467 virtual void OnCleanup(int target_type, void *item)
469 /* Module unloading, tidy up users */
470 if (target_type == TYPE_USER)
471 OnUserDisconnect((User*)item);
474 virtual void OnUserDisconnect(User *user)
476 /* User disconnect (generic socket detatch event) */
477 IdentRequestSocket *isock = NULL;
478 if (user->GetExt("ident_socket", isock))
482 user->Shrink("ident_socket");
487 MODULE_INIT(ModuleIdent)