1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
16 /* $ModDesc: Provides support for RFC1413 ident lookups */
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
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!
37 * Using this framework we have a much more stable module.
39 * A few things to note:
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
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.
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.
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.
64 * O The code in the constructor of the ident socket is taken from
65 * BufferedSocket but majorly thinned down. It works for both
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 * --------------------------------------------------------------
74 class IdentRequestSocket : public EventHandler
77 LocalUser *user; /* User we are attached to */
78 bool done; /* True if lookup is finished */
79 std::string result; /* Holds the ident string if done */
83 IdentRequestSocket(LocalUser* u) : user(u), result(u->ident)
85 age = ServerInstance->Time();
88 SetFd(socket(user->server_sa.sa.sa_family, SOCK_STREAM, 0));
91 throw ModuleException("Could not create socket");
95 irc::sockets::sockaddrs bindaddr;
96 irc::sockets::sockaddrs connaddr;
98 memcpy(&bindaddr, &user->server_sa, sizeof(bindaddr));
99 memcpy(&connaddr, &user->client_sa, sizeof(connaddr));
101 if (connaddr.sa.sa_family == AF_INET6)
103 bindaddr.in6.sin6_port = 0;
104 connaddr.in6.sin6_port = htons(113);
108 bindaddr.in4.sin_port = 0;
109 connaddr.in4.sin_port = htons(113);
112 /* Attempt to bind (ident requests must come from the ip the query is referring to */
113 if (ServerInstance->SE->Bind(GetFd(), &bindaddr.sa, size) < 0)
116 throw ModuleException("failed to bind()");
119 ServerInstance->SE->NonBlocking(GetFd());
121 /* Attempt connection (nonblocking) */
122 if (ServerInstance->SE->Connect(this, &connaddr.sa, size) == -1 && errno != EINPROGRESS)
125 throw ModuleException("connect() failed");
128 /* Add fd to socket engine */
129 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_POLL_WRITE))
132 throw ModuleException("out of fds");
136 virtual void OnConnected()
138 ServerInstance->Logs->Log("m_ident",DEBUG,"OnConnected()");
139 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
143 /* Build request in the form 'localport,remoteport\r\n' */
145 if (user->client_sa.sa.sa_family == AF_INET6)
146 req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
147 ntohs(user->client_sa.in6.sin6_port), ntohs(user->server_sa.in6.sin6_port));
149 req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
150 ntohs(user->client_sa.in4.sin_port), ntohs(user->server_sa.in4.sin_port));
152 /* Send failed if we didnt write the whole ident request --
153 * might as well give up if this happens!
155 if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size)
159 virtual void HandleEvent(EventType et, int errornum = 0)
164 /* fd readable event, received ident response */
168 /* fd writeable event, successfully connected! */
172 /* fd error event, ohshi- */
173 ServerInstance->Logs->Log("m_ident",DEBUG,"EVENT_ERROR");
174 /* We *must* Close() here immediately or we get a
175 * huge storm of EVENT_ERROR events!
185 /* Remove ident socket from engine, and close it, but dont detatch it
186 * from its parent user class, or attempt to delete its memory.
190 ServerInstance->Logs->Log("m_ident",DEBUG,"Close ident socket %d", GetFd());
191 ServerInstance->SE->DelFd(this);
192 ServerInstance->SE->Close(GetFd());
193 ServerInstance->SE->Shutdown(GetFd(), SHUT_WR);
203 /* Note: if the lookup succeeded, will contain 'ident', otherwise
204 * will contain '~ident'. Use *GetResult() to determine lookup success.
206 const char* GetResult()
208 return result.c_str();
213 /* We don't really need to buffer for incomplete replies here, since IDENT replies are
214 * extremely short - there is *no* sane reason it'd be in more than one packet
217 int recvresult = ServerInstance->SE->Recv(this, ibuf, MAXBUF-1, 0);
219 /* Cant possibly be a valid response shorter than 3 chars,
220 * because the shortest possible response would look like: '1,1'
229 ServerInstance->Logs->Log("m_ident",DEBUG,"ReadResponse()");
231 irc::sepstream sep(ibuf, ':');
233 for (int i = 0; sep.GetToken(token); i++)
235 /* We only really care about the 4th portion */
241 /* Truncate the ident at any characters we don't like, skip leading spaces */
243 for (const char *j = token.c_str(); *j && (k < ServerInstance->Config->Limits.IdentMax + 1); j++)
248 /* Rules taken from InspIRCd::IsIdent */
249 if (((*j >= 'A') && (*j <= '}')) || ((*j >= '0') && (*j <= '9')) || (*j == '-') || (*j == '.'))
258 /* Re-check with IsIdent, in case that changes and this doesn't (paranoia!) */
259 if (!ident.empty() && ServerInstance->IsIdent(ident.c_str()))
267 /* Close (but dont delete from memory) our socket
276 class ModuleIdent : public Module
279 SimpleExtItem<IdentRequestSocket> ext;
281 ModuleIdent() : ext("ident_socket", this)
284 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnUserDisconnect };
285 ServerInstance->Modules->Attach(eventlist, this, 4);
292 virtual Version GetVersion()
294 return Version("Provides support for RFC1413 ident lookups", VF_VENDOR);
297 virtual void OnRehash(User *user)
301 RequestTimeout = Conf.ReadInteger("ident", "timeout", 0, true);
306 virtual ModResult OnUserRegister(LocalUser *user)
308 ConfigTag* tag = user->MyClass->config;
309 if (!tag->getBool("useident", true))
310 return MOD_RES_PASSTHRU;
312 /* User::ident is currently the username field from USER; with m_ident loaded, that
313 * should be preceded by a ~. The field is actually IdentMax+2 characters wide. */
314 if (user->ident.length() > ServerInstance->Config->Limits.IdentMax + 1)
315 user->ident.assign(user->ident, 0, ServerInstance->Config->Limits.IdentMax);
316 user->ident.insert(0, "~");
318 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
322 IdentRequestSocket *isock = new IdentRequestSocket(IS_LOCAL(user));
323 ext.set(user, isock);
325 catch (ModuleException &e)
327 ServerInstance->Logs->Log("m_ident",DEBUG,"Ident exception: %s", e.GetReason());
330 return MOD_RES_PASSTHRU;
333 /* This triggers pretty regularly, we can use it in preference to
334 * creating a Timer object and especially better than creating a
335 * Timer per ident lookup!
337 virtual ModResult OnCheckReady(LocalUser *user)
339 /* Does user have an ident socket attached at all? */
340 IdentRequestSocket *isock = ext.get(user);
343 ServerInstance->Logs->Log("m_ident",DEBUG, "No ident socket :(");
344 return MOD_RES_PASSTHRU;
347 ServerInstance->Logs->Log("m_ident",DEBUG, "Has ident_socket");
349 time_t compare = isock->age;
350 compare += RequestTimeout;
352 /* Check for timeout of the socket */
353 if (ServerInstance->Time() >= compare)
356 user->WriteServ("NOTICE Auth :*** Ident request timed out.");
357 ServerInstance->Logs->Log("m_ident",DEBUG, "Timeout");
358 /* The user isnt actually disconnecting,
359 * we call this to clean up the user
361 OnUserDisconnect(user);
362 return MOD_RES_PASSTHRU;
365 /* Got a result yet? */
366 if (!isock->HasResult())
368 ServerInstance->Logs->Log("m_ident",DEBUG, "No result yet");
372 ServerInstance->Logs->Log("m_ident",DEBUG, "Yay, result!");
374 /* wooo, got a result (it will be good, or bad) */
375 if (*(isock->GetResult()) != '~')
376 user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", isock->GetResult());
378 user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
380 /* Copy the ident string to the user */
381 user->ChangeIdent(isock->GetResult());
383 /* The user isnt actually disconnecting, we call this to clean up the user */
384 OnUserDisconnect(user);
385 return MOD_RES_PASSTHRU;
388 virtual void OnCleanup(int target_type, void *item)
390 /* Module unloading, tidy up users */
391 if (target_type == TYPE_USER)
392 OnUserDisconnect((LocalUser*)item);
395 virtual void OnUserDisconnect(LocalUser *user)
397 /* User disconnect (generic socket detatch event) */
398 IdentRequestSocket *isock = ext.get(user);
407 MODULE_INIT(ModuleIdent)