]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_ident.cpp
66bd8835ade5067f23fe9470cf985cce63192f90
[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         time_t age;
83
84         IdentRequestSocket(InspIRCd *Server, User* u) : user(u), ServerInstance(Server), result(u->ident)
85         {
86                 age = ServerInstance->Time();
87                 socklen_t size = 0;
88
89                 SetFd(socket(user->server_sa.sa.sa_family, SOCK_STREAM, 0));
90
91                 if (GetFd() == -1)
92                         throw ModuleException("Could not create socket");
93
94                 done = false;
95
96                 irc::sockets::sockaddrs bindaddr;
97                 irc::sockets::sockaddrs connaddr;
98
99                 memcpy(&bindaddr, &user->server_sa, sizeof(bindaddr));
100                 memcpy(&connaddr, &user->client_sa, sizeof(connaddr));
101
102                 if (connaddr.sa.sa_family == AF_INET6)
103                 {
104                         bindaddr.in6.sin6_port = 0;
105                         connaddr.in6.sin6_port = htons(113);
106                 }
107                 else
108                 {
109                         bindaddr.in4.sin_port = 0;
110                         connaddr.in4.sin_port = htons(113);
111                 }
112
113                 /* Attempt to bind (ident requests must come from the ip the query is referring to */
114                 if (ServerInstance->SE->Bind(GetFd(), &bindaddr.sa, size) < 0)
115                 {
116                         this->Close();
117                         throw ModuleException("failed to bind()");
118                 }
119
120                 ServerInstance->SE->NonBlocking(GetFd());
121
122                 /* Attempt connection (nonblocking) */
123                 if (ServerInstance->SE->Connect(this, &connaddr.sa, size) == -1 && errno != EINPROGRESS)
124                 {
125                         this->Close();
126                         throw ModuleException("connect() failed");
127                 }
128
129                 /* Add fd to socket engine */
130                 if (!ServerInstance->SE->AddFd(this, FD_WANT_NO_READ | FD_WANT_POLL_WRITE))
131                 {
132                         this->Close();
133                         throw ModuleException("out of fds");
134                 }
135         }
136
137         virtual void OnConnected()
138         {
139                 ServerInstance->Logs->Log("m_ident",DEBUG,"OnConnected()");
140                 ServerInstance->SE->ChangeEventMask(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
141
142                 char req[32];
143
144                 /* Build request in the form 'localport,remoteport\r\n' */
145                 int req_size;
146                 if (user->client_sa.sa.sa_family == AF_INET6)
147                         req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
148                                 ntohs(user->client_sa.in6.sin6_port), ntohs(user->server_sa.in6.sin6_port));
149                 else
150                         req_size = snprintf(req, sizeof(req), "%d,%d\r\n",
151                                 ntohs(user->client_sa.in4.sin_port), ntohs(user->server_sa.in4.sin_port));
152
153                 /* Send failed if we didnt write the whole ident request --
154                  * might as well give up if this happens!
155                  */
156                 if (ServerInstance->SE->Send(this, req, req_size, 0) < req_size)
157                         done = true;
158         }
159
160         virtual void HandleEvent(EventType et, int errornum = 0)
161         {
162                 switch (et)
163                 {
164                         case EVENT_READ:
165                                 /* fd readable event, received ident response */
166                                 ReadResponse();
167                         break;
168                         case EVENT_WRITE:
169                                 /* fd writeable event, successfully connected! */
170                                 OnConnected();
171                         break;
172                         case EVENT_ERROR:
173                                 /* fd error event, ohshi- */
174                                 ServerInstance->Logs->Log("m_ident",DEBUG,"EVENT_ERROR");
175                                 /* We *must* Close() here immediately or we get a
176                                  * huge storm of EVENT_ERROR events!
177                                  */
178                                 Close();
179                                 done = true;
180                         break;
181                 }
182         }
183
184         void Close()
185         {
186                 /* Remove ident socket from engine, and close it, but dont detatch it
187                  * from its parent user class, or attempt to delete its memory.
188                  */
189                 if (GetFd() > -1)
190                 {
191                         ServerInstance->Logs->Log("m_ident",DEBUG,"Close ident socket %d", GetFd());
192                         ServerInstance->SE->DelFd(this);
193                         ServerInstance->SE->Close(GetFd());
194                         ServerInstance->SE->Shutdown(GetFd(), SHUT_WR);
195                         this->SetFd(-1);
196                 }
197         }
198
199         bool HasResult()
200         {
201                 return done;
202         }
203
204         /* Note: if the lookup succeeded, will contain 'ident', otherwise
205          * will contain '~ident'. Use *GetResult() to determine lookup success.
206          */
207         const char* GetResult()
208         {
209                 return result.c_str();
210         }
211
212         void ReadResponse()
213         {
214                 /* We don't really need to buffer for incomplete replies here, since IDENT replies are
215                  * extremely short - there is *no* sane reason it'd be in more than one packet
216                  */
217                 char ibuf[MAXBUF];
218                 int recvresult = ServerInstance->SE->Recv(this, ibuf, MAXBUF-1, 0);
219
220                 /* Cant possibly be a valid response shorter than 3 chars,
221                  * because the shortest possible response would look like: '1,1'
222                  */
223                 if (recvresult < 3)
224                 {
225                         Close();
226                         done = true;
227                         return;
228                 }
229
230                 ServerInstance->Logs->Log("m_ident",DEBUG,"ReadResponse()");
231
232                 irc::sepstream sep(ibuf, ':');
233                 std::string token;
234                 for (int i = 0; sep.GetToken(token); i++)
235                 {
236                         /* We only really care about the 4th portion */
237                         if (i < 3)
238                                 continue;
239
240                         std::string ident;
241
242                         /* Truncate the ident at any characters we don't like, skip leading spaces */
243                         size_t k = 0;
244                         for (const char *j = token.c_str(); *j && (k < ServerInstance->Config->Limits.IdentMax + 1); j++)
245                         {
246                                 if (*j == ' ')
247                                         continue;
248
249                                 /* Rules taken from InspIRCd::IsIdent */
250                                 if (((*j >= 'A') && (*j <= '}')) || ((*j >= '0') && (*j <= '9')) || (*j == '-') || (*j == '.'))
251                                 {
252                                         ident += *j;
253                                         continue;
254                                 }
255
256                                 break;
257                         }
258
259                         /* Re-check with IsIdent, in case that changes and this doesn't (paranoia!) */
260                         if (!ident.empty() && ServerInstance->IsIdent(ident.c_str()))
261                         {
262                                 result = ident;
263                         }
264
265                         break;
266                 }
267
268                 /* Close (but dont delete from memory) our socket
269                  * and flag as done
270                  */
271                 Close();
272                 done = true;
273                 return;
274         }
275 };
276
277 class ModuleIdent : public Module
278 {
279         int RequestTimeout;
280         ConfigReader *Conf;
281         SimpleExtItem<IdentRequestSocket> ext;
282  public:
283         ModuleIdent(InspIRCd *Me) : Module(Me), ext("ident_socket", this)
284         {
285                 Conf = new ConfigReader(ServerInstance);
286                 OnRehash(NULL);
287                 Implementation eventlist[] = { I_OnRehash, I_OnUserRegister, I_OnCheckReady, I_OnCleanup, I_OnUserDisconnect };
288                 ServerInstance->Modules->Attach(eventlist, this, 5);
289         }
290
291         ~ModuleIdent()
292         {
293                 delete Conf;
294         }
295
296         virtual Version GetVersion()
297         {
298                 return Version("Provides support for RFC1413 ident lookups", VF_VENDOR, API_VERSION);
299         }
300
301         virtual void OnRehash(User *user)
302         {
303                 delete Conf;
304                 Conf = new ConfigReader(ServerInstance);
305
306                 RequestTimeout = Conf->ReadInteger("ident", "timeout", 0, true);
307                 if (!RequestTimeout)
308                         RequestTimeout = 5;
309         }
310
311         virtual ModResult OnUserRegister(User *user)
312         {
313                 for (int j = 0; j < Conf->Enumerate("connect"); j++)
314                 {
315                         std::string hostn = Conf->ReadValue("connect","allow",j);
316                         /* XXX: Fixme: does not respect port, limit, etc */
317                         if ((InspIRCd::MatchCIDR(user->GetIPString(),hostn, ascii_case_insensitive_map)) || (InspIRCd::Match(user->host,hostn, ascii_case_insensitive_map)))
318                         {
319                                 bool useident = Conf->ReadFlag("connect", "useident", "yes", j);
320
321                                 if (!useident)
322                                         return MOD_RES_PASSTHRU;
323                         }
324                 }
325
326                 /* User::ident is currently the username field from USER; with m_ident loaded, that
327                  * should be preceded by a ~. The field is actually IdentMax+2 characters wide. */
328                 if (user->ident.length() > ServerInstance->Config->Limits.IdentMax + 1)
329                         user->ident.assign(user->ident, 0, ServerInstance->Config->Limits.IdentMax);
330                 user->ident.insert(0, "~");
331
332                 user->WriteServ("NOTICE Auth :*** Looking up your ident...");
333
334                 try
335                 {
336                         IdentRequestSocket *isock = new IdentRequestSocket(ServerInstance, user);
337                         ext.set(user, isock);
338                 }
339                 catch (ModuleException &e)
340                 {
341                         ServerInstance->Logs->Log("m_ident",DEBUG,"Ident exception: %s", e.GetReason());
342                 }
343
344                 return MOD_RES_PASSTHRU;
345         }
346
347         /* This triggers pretty regularly, we can use it in preference to
348          * creating a Timer object and especially better than creating a
349          * Timer per ident lookup!
350          */
351         virtual ModResult OnCheckReady(User *user)
352         {
353                 /* Does user have an ident socket attached at all? */
354                 IdentRequestSocket *isock = ext.get(user);
355                 if (!isock)
356                 {
357                         ServerInstance->Logs->Log("m_ident",DEBUG, "No ident socket :(");
358                         return MOD_RES_PASSTHRU;
359                 }
360
361                 ServerInstance->Logs->Log("m_ident",DEBUG, "Has ident_socket");
362
363                 time_t compare = isock->age;
364                 compare += RequestTimeout;
365
366                 /* Check for timeout of the socket */
367                 if (ServerInstance->Time() >= compare)
368                 {
369                         /* Ident timeout */
370                         user->WriteServ("NOTICE Auth :*** Ident request timed out.");
371                         ServerInstance->Logs->Log("m_ident",DEBUG, "Timeout");
372                         /* The user isnt actually disconnecting,
373                          * we call this to clean up the user
374                          */
375                         OnUserDisconnect(user);
376                         return MOD_RES_PASSTHRU;
377                 }
378
379                 /* Got a result yet? */
380                 if (!isock->HasResult())
381                 {
382                         ServerInstance->Logs->Log("m_ident",DEBUG, "No result yet");
383                         return MOD_RES_DENY;
384                 }
385
386                 ServerInstance->Logs->Log("m_ident",DEBUG, "Yay, result!");
387
388                 /* wooo, got a result (it will be good, or bad) */
389                 if (*(isock->GetResult()) != '~')
390                         user->WriteServ("NOTICE Auth :*** Found your ident, '%s'", isock->GetResult());
391                 else
392                         user->WriteServ("NOTICE Auth :*** Could not find your ident, using %s instead.", isock->GetResult());
393
394                 /* Copy the ident string to the user */
395                 user->ChangeIdent(isock->GetResult());
396
397                 /* The user isnt actually disconnecting, we call this to clean up the user */
398                 OnUserDisconnect(user);
399                 return MOD_RES_PASSTHRU;
400         }
401
402         virtual void OnCleanup(int target_type, void *item)
403         {
404                 /* Module unloading, tidy up users */
405                 if (target_type == TYPE_USER)
406                         OnUserDisconnect((User*)item);
407         }
408
409         virtual void OnUserDisconnect(User *user)
410         {
411                 /* User disconnect (generic socket detatch event) */
412                 IdentRequestSocket *isock = ext.get(user);
413                 if (isock)
414                 {
415                         isock->Close();
416                         ext.unset(user);
417                 }
418         }
419 };
420
421 MODULE_INIT(ModuleIdent)
422