]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/listensocket.cpp
Split IOHook into IOHook and IOHookProvider
[user/henk/code/inspircd.git] / src / listensocket.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
6  *
7  * This file is part of InspIRCd.  InspIRCd is free software: you can
8  * redistribute it and/or modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation, version 2.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #include "inspircd.h"
22 #include "socket.h"
23 #include "socketengine.h"
24
25 #ifndef _WIN32
26 #include <netinet/tcp.h>
27 #endif
28
29 ListenSocket::ListenSocket(ConfigTag* tag, const irc::sockets::sockaddrs& bind_to)
30         : bind_tag(tag)
31         , iohookprov(NULL, std::string())
32 {
33         irc::sockets::satoap(bind_to, bind_addr, bind_port);
34         bind_desc = bind_to.str();
35
36         fd = socket(bind_to.sa.sa_family, SOCK_STREAM, 0);
37
38         if (this->fd == -1)
39                 return;
40
41 #ifdef IPV6_V6ONLY
42         /* This OS supports IPv6 sockets that can also listen for IPv4
43          * connections. If our address is "*" or empty, enable both v4 and v6 to
44          * allow for simpler configuration on dual-stack hosts. Otherwise, if it
45          * is "::" or an IPv6 address, disable support so that an IPv4 bind will
46          * work on the port (by us or another application).
47          */
48         if (bind_to.sa.sa_family == AF_INET6)
49         {
50                 std::string addr = tag->getString("address");
51                 /* This must be >= sizeof(DWORD) on Windows */
52                 const int enable = (addr.empty() || addr == "*") ? 0 : 1;
53                 /* This must be before bind() */
54                 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&enable), sizeof(enable));
55                 // errors ignored intentionally
56         }
57 #endif
58
59         ServerInstance->SE->SetReuse(fd);
60         int rv = ServerInstance->SE->Bind(this->fd, bind_to);
61         if (rv >= 0)
62                 rv = ServerInstance->SE->Listen(this->fd, ServerInstance->Config->MaxConn);
63
64         int timeout = tag->getInt("defer", 0);
65         if (timeout && !rv)
66         {
67 #if defined TCP_DEFER_ACCEPT
68                 setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(timeout));
69 #elif defined SO_ACCEPTFILTER
70                 struct accept_filter_arg afa;
71                 memset(&afa, 0, sizeof(afa));
72                 strcpy(afa.af_name, "dataready");
73                 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
74 #endif
75         }
76
77         if (rv < 0)
78         {
79                 int errstore = errno;
80                 ServerInstance->SE->Shutdown(this, 2);
81                 ServerInstance->SE->Close(this);
82                 this->fd = -1;
83                 errno = errstore;
84         }
85         else
86         {
87                 ServerInstance->SE->NonBlocking(this->fd);
88                 ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
89
90                 this->ResetIOHookProvider();
91         }
92 }
93
94 ListenSocket::~ListenSocket()
95 {
96         if (this->GetFd() > -1)
97         {
98                 ServerInstance->SE->DelFd(this);
99                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Shut down listener on fd %d", this->fd);
100                 ServerInstance->SE->Shutdown(this, 2);
101                 if (ServerInstance->SE->Close(this) != 0)
102                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to cancel listener: %s", strerror(errno));
103                 this->fd = -1;
104         }
105 }
106
107 /* Just seperated into another func for tidiness really.. */
108 void ListenSocket::AcceptInternal()
109 {
110         irc::sockets::sockaddrs client;
111         irc::sockets::sockaddrs server;
112
113         socklen_t length = sizeof(client);
114         int incomingSockfd = ServerInstance->SE->Accept(this, &client.sa, &length);
115
116         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "HandleEvent for Listensocket %s nfd=%d", bind_desc.c_str(), incomingSockfd);
117         if (incomingSockfd < 0)
118         {
119                 ServerInstance->stats->statsRefused++;
120                 return;
121         }
122
123         socklen_t sz = sizeof(server);
124         if (getsockname(incomingSockfd, &server.sa, &sz))
125         {
126                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Can't get peername: %s", strerror(errno));
127                 irc::sockets::aptosa(bind_addr, bind_port, server);
128         }
129
130         /*
131          * XXX -
132          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
133          * its a pretty big but for the moment valid assumption:
134          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
135          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
136          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
137          * which for the time being is a physical impossibility (even the largest networks dont have more
138          * than about 10,000 users on ONE server!)
139          */
140         if (incomingSockfd >= ServerInstance->SE->GetMaxFds())
141         {
142                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Server is full");
143                 ServerInstance->SE->Shutdown(incomingSockfd, 2);
144                 ServerInstance->SE->Close(incomingSockfd);
145                 ServerInstance->stats->statsRefused++;
146                 return;
147         }
148
149         if (client.sa.sa_family == AF_INET6)
150         {
151                 /*
152                  * This case is the be all and end all patch to catch and nuke 4in6
153                  * instead of special-casing shit all over the place and wreaking merry
154                  * havoc with crap, instead, we just recreate sockaddr and strip ::ffff: prefix
155                  * if it's a 4in6 IP.
156                  *
157                  * This is, of course, much improved over the older way of handling this
158                  * (pretend it doesn't exist + hack around it -- yes, both were done!)
159                  *
160                  * Big, big thanks to danieldg for his work on this.
161                  * -- w00t
162                  */
163                 static const unsigned char prefix4in6[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xFF,0xFF };
164                 if (!memcmp(prefix4in6, &client.in6.sin6_addr, 12))
165                 {
166                         // recreate as a sockaddr_in using the IPv4 IP
167                         uint16_t sport = client.in6.sin6_port;
168                         client.in4.sin_family = AF_INET;
169                         client.in4.sin_port = sport;
170                         memcpy(&client.in4.sin_addr.s_addr, client.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
171
172                         sport = server.in6.sin6_port;
173                         server.in4.sin_family = AF_INET;
174                         server.in4.sin_port = sport;
175                         memcpy(&server.in4.sin_addr.s_addr, server.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
176                 }
177         }
178
179         ServerInstance->SE->NonBlocking(incomingSockfd);
180
181         ModResult res;
182         FIRST_MOD_RESULT(OnAcceptConnection, res, (incomingSockfd, this, &client, &server));
183         if (res == MOD_RES_PASSTHRU)
184         {
185                 std::string type = bind_tag->getString("type", "clients");
186                 if (type == "clients")
187                 {
188                         ServerInstance->Users->AddUser(incomingSockfd, this, &client, &server);
189                         res = MOD_RES_ALLOW;
190                 }
191         }
192         if (res == MOD_RES_ALLOW)
193         {
194                 ServerInstance->stats->statsAccept++;
195         }
196         else
197         {
198                 ServerInstance->stats->statsRefused++;
199                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Refusing connection on %s - %s",
200                         bind_desc.c_str(), res == MOD_RES_DENY ? "Connection refused by module" : "Module for this port not found");
201                 ServerInstance->SE->Close(incomingSockfd);
202         }
203 }
204
205 void ListenSocket::HandleEvent(EventType e, int err)
206 {
207         switch (e)
208         {
209                 case EVENT_ERROR:
210                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ListenSocket::HandleEvent() received a socket engine error event! well shit! '%s'", strerror(err));
211                         break;
212                 case EVENT_WRITE:
213                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "*** BUG *** ListenSocket::HandleEvent() got a WRITE event!!!");
214                         break;
215                 case EVENT_READ:
216                         this->AcceptInternal();
217                         break;
218         }
219 }
220
221 bool ListenSocket::ResetIOHookProvider()
222 {
223         std::string provname = bind_tag->getString("ssl");
224         if (!provname.empty())
225                 provname.insert(0, "ssl/");
226
227         // Set the new provider name, dynref handles the rest
228         iohookprov.SetProvider(provname);
229
230         // Return true if no provider was set, or one was set and it was also found
231         return (provname.empty() || iohookprov);
232 }