1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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");
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];
111 /* Horrid icky nasty ugly berkely socket crap. */
116 if (inet_pton(AF_INET6, user->GetIPString(), &addy) > 0)
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;
133 if (inet_aton(user->GetIPString(), &addy) > 0)
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;
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)
152 throw ModuleException("failed to bind()");
156 ServerInstance->SE->NonBlocking(GetFd());
158 /* Attempt connection (nonblocking) */
159 if (ServerInstance->SE->Connect(this, (sockaddr*)addr, size) == -1 && errno != EINPROGRESS)
163 throw ModuleException("connect() failed");
168 /* Add fd to socket engine */
169 if (!ServerInstance->SE->AddFd(this))
172 throw ModuleException("out of fds");
175 /* Important: We set WantWrite immediately after connect()
176 * because a successful connection will trigger a writability event
178 ServerInstance->SE->WantWrite(this);
181 virtual void OnConnected()
183 ServerInstance->Log(DEBUG,"OnConnected()");
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
189 sockaddr_in laddr, raddr;
191 sockaddr_in6 laddr, raddr;
194 socklen_t laddrsz = sizeof(laddr);
195 socklen_t raddrsz = sizeof(raddr);
197 if ((getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0) || (getpeername(user->GetFd(), (sockaddr*) &raddr, &raddrsz) != 0))
205 /* Build request in the form 'localport,remoteport\r\n' */
207 int req_size = snprintf(req, sizeof(req), "%d,%d\r\n", ntohs(raddr.sin_port), ntohs(laddr.sin_port));
209 int req_size = snprintf(req, sizeof(req), "%d,%d\r\n", ntohs(raddr.sin6_port), ntohs(laddr.sin6_port));
212 /* Send failed if we didnt write the whole ident request --
213 * might as well give up if this happens!
215 if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size)
219 virtual void HandleEvent(EventType et, int errornum = 0)
224 /* fd readable event, received ident response */
228 /* fd writeable event, successfully connected! */
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!
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.
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);
263 /* Note: if the lookup succeeded, will contain 'ident', otherwise
264 * will contain '~ident'. Use *GetResult() to determine lookup success.
266 const char* GetResult()
268 return result.c_str();
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
277 int recvresult = ServerInstance->SE->Recv(this, ibuf, MAXBUF-1, 0);
279 /* Cant possibly be a valid response shorter than 3 chars,
280 * because the shortest possible response would look like: '1,1'
289 ServerInstance->Log(DEBUG,"ReadResponse()");
291 irc::sepstream sep(ibuf, ':');
293 for (int i = 0; sep.GetToken(token); i++)
295 /* We only really care about the 4th portion */
299 char ident[IDENTMAX + 2];
301 /* Truncate the ident at any characters we don't like, skip leading spaces */
303 for (const char *j = token.c_str(); *j && (k < IDENTMAX + 1); j++)
308 /* Rules taken from InspIRCd::IsIdent */
309 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 && ServerInstance->IsIdent(ident))
329 /* Close (but dont delete from memory) our socket
338 class ModuleIdent : public Module
343 ModuleIdent(InspIRCd *Me)
349 virtual Version GetVersion()
351 return Version(1, 1, 1, 0, VF_VENDOR, API_VERSION);
354 virtual void Implements(char *List)
356 List[I_OnRehash] = List[I_OnUserRegister] = List[I_OnCheckReady] = List[I_OnCleanup] = List[I_OnUserDisconnect] = 1;
359 virtual void OnRehash(User *user, const std::string ¶m)
361 ConfigReader MyConf(ServerInstance);
363 RequestTimeout = MyConf.ReadInteger("ident", "timeout", 0, true);
368 virtual int OnUserRegister(User *user)
370 /* User::ident is currently the username field from USER; with m_ident loaded, that
371 * should be preceded by a ~. The field is actually IDENTMAX+2 characters wide. */
372 memmove(user->ident + 1, user->ident, IDENTMAX);
373 user->ident[0] = '~';
374 /* Ensure that it is null terminated */
375 user->ident[IDENTMAX + 1] = '\0';
377 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
379 // Get the IP that the user is connected to, and bind to that for the outgoing connection
385 socklen_t laddrsz = sizeof(laddr);
387 if (getsockname(user->GetFd(), (sockaddr*) &laddr, &laddrsz) != 0)
389 user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", user->ident);
394 const char *ip = inet_ntoa(laddr.sin_addr);
396 char ip[INET6_ADDRSTRLEN + 1];
397 inet_ntop(laddr.sin6_family, &laddr.sin6_addr, ip, INET6_ADDRSTRLEN);
400 IdentRequestSocket *isock = NULL;
403 isock = new IdentRequestSocket(ServerInstance, user, ip);
405 catch (ModuleException &e)
407 ServerInstance->Log(DEBUG,"Ident exception: %s", e.GetReason());
411 user->Extend("ident_socket", isock);
415 /* This triggers pretty regularly, we can use it in preference to
416 * creating a Timer object and especially better than creating a
417 * Timer per ident lookup!
419 virtual bool OnCheckReady(User *user)
421 ServerInstance->Log(DEBUG,"OnCheckReady %s", user->nick);
423 /* Does user have an ident socket attached at all? */
424 IdentRequestSocket *isock = NULL;
425 if (!user->GetExt("ident_socket", isock))
427 ServerInstance->Log(DEBUG, "No ident socket :(");
431 ServerInstance->Log(DEBUG, "Has ident_socket");
433 time_t compare = isock->age;
434 compare += RequestTimeout;
436 /* Check for timeout of the socket */
437 if (ServerInstance->Time() >= compare)
440 user->WriteServ("NOTICE Auth :*** Ident request timed out.");
441 ServerInstance->Log(DEBUG, "Timeout");
442 /* The user isnt actually disconnecting,
443 * we call this to clean up the user
445 OnUserDisconnect(user);
449 /* Got a result yet? */
450 if (!isock->HasResult())
452 ServerInstance->Log(DEBUG, "No result yet");
456 ServerInstance->Log(DEBUG, "Yay, result!");
458 /* wooo, got a result (it will be good, or bad) */
459 if (*(isock->GetResult()) != '~')
460 user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", isock->GetResult());
462 user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
464 /* Copy the ident string to the user */
465 strlcpy(user->ident, isock->GetResult(), IDENTMAX+1);
467 /* The user isnt actually disconnecting, we call this to clean up the user */
468 OnUserDisconnect(user);
472 virtual void OnCleanup(int target_type, void *item)
474 /* Module unloading, tidy up users */
475 if (target_type == TYPE_USER)
476 OnUserDisconnect((User*)item);
479 virtual void OnUserDisconnect(User *user)
481 /* User disconnect (generic socket detatch event) */
482 IdentRequestSocket *isock = NULL;
483 if (user->GetExt("ident_socket", isock))
487 user->Shrink("ident_socket");
488 ServerInstance->Log(DEBUG, "Removed ident socket from %s", user->nick);
493 MODULE_INIT(ModuleIdent)