]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/listensocket.cpp
Merge pull request #587 from SaberUK/master+defer-preprocessor
[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 #include <netinet/tcp.h>
25
26 ListenSocket::ListenSocket(ConfigTag* tag, const irc::sockets::sockaddrs& bind_to)
27         : bind_tag(tag)
28 {
29         irc::sockets::satoap(bind_to, bind_addr, bind_port);
30         bind_desc = irc::sockets::satouser(bind_to);
31
32         fd = socket(bind_to.sa.sa_family, SOCK_STREAM, 0);
33
34         if (this->fd == -1)
35                 return;
36
37 #ifdef IPV6_V6ONLY
38         /* This OS supports IPv6 sockets that can also listen for IPv4
39          * connections. If our address is "*" or empty, enable both v4 and v6 to
40          * allow for simpler configuration on dual-stack hosts. Otherwise, if it
41          * is "::" or an IPv6 address, disable support so that an IPv4 bind will
42          * work on the port (by us or another application).
43          */
44         if (bind_to.sa.sa_family == AF_INET6)
45         {
46                 std::string addr = tag->getString("address");
47                 /* This must be >= sizeof(DWORD) on Windows */
48                 const int enable = (addr.empty() || addr == "*") ? 0 : 1;
49                 /* This must be before bind() */
50                 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&enable), sizeof(enable));
51                 // errors ignored intentionally
52         }
53 #endif
54
55         ServerInstance->SE->SetReuse(fd);
56         int rv = ServerInstance->SE->Bind(this->fd, bind_to);
57         if (rv >= 0)
58                 rv = ServerInstance->SE->Listen(this->fd, ServerInstance->Config->MaxConn);
59
60         int timeout = tag->getInt("defer", 0);
61         if (timeout && !rv)
62         {
63 #if defined TCP_DEFER_ACCEPT
64                 setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(timeout));
65 #elif defined SO_ACCEPTFILTER
66                 struct accept_filter_arg afa;
67                 memset(&afa, 0, sizeof(afa));
68                 strcpy(afa.af_name, "dataready");
69                 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
70 #endif
71         }
72
73         if (rv < 0)
74         {
75                 int errstore = errno;
76                 ServerInstance->SE->Shutdown(this, 2);
77                 ServerInstance->SE->Close(this);
78                 this->fd = -1;
79                 errno = errstore;
80         }
81         else
82         {
83                 ServerInstance->SE->NonBlocking(this->fd);
84                 ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
85         }
86 }
87
88 ListenSocket::~ListenSocket()
89 {
90         if (this->GetFd() > -1)
91         {
92                 ServerInstance->SE->DelFd(this);
93                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Shut down listener on fd %d", this->fd);
94                 ServerInstance->SE->Shutdown(this, 2);
95                 if (ServerInstance->SE->Close(this) != 0)
96                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to cancel listener: %s", strerror(errno));
97                 this->fd = -1;
98         }
99 }
100
101 /* Just seperated into another func for tidiness really.. */
102 void ListenSocket::AcceptInternal()
103 {
104         irc::sockets::sockaddrs client;
105         irc::sockets::sockaddrs server;
106
107         socklen_t length = sizeof(client);
108         int incomingSockfd = ServerInstance->SE->Accept(this, &client.sa, &length);
109
110         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "HandleEvent for Listensocket %s nfd=%d", bind_desc.c_str(), incomingSockfd);
111         if (incomingSockfd < 0)
112         {
113                 ServerInstance->stats->statsRefused++;
114                 return;
115         }
116
117         socklen_t sz = sizeof(server);
118         if (getsockname(incomingSockfd, &server.sa, &sz))
119         {
120                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Can't get peername: %s", strerror(errno));
121                 irc::sockets::aptosa(bind_addr, bind_port, server);
122         }
123
124         /*
125          * XXX -
126          * this is done as a safety check to keep the file descriptors within range of fd_ref_table.
127          * its a pretty big but for the moment valid assumption:
128          * file descriptors are handed out starting at 0, and are recycled as theyre freed.
129          * therefore if there is ever an fd over 65535, 65536 clients must be connected to the
130          * irc server at once (or the irc server otherwise initiating this many connections, files etc)
131          * which for the time being is a physical impossibility (even the largest networks dont have more
132          * than about 10,000 users on ONE server!)
133          */
134         if (incomingSockfd >= ServerInstance->SE->GetMaxFds())
135         {
136                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Server is full");
137                 ServerInstance->SE->Shutdown(incomingSockfd, 2);
138                 ServerInstance->SE->Close(incomingSockfd);
139                 ServerInstance->stats->statsRefused++;
140                 return;
141         }
142
143         if (client.sa.sa_family == AF_INET6)
144         {
145                 /*
146                  * This case is the be all and end all patch to catch and nuke 4in6
147                  * instead of special-casing shit all over the place and wreaking merry
148                  * havoc with crap, instead, we just recreate sockaddr and strip ::ffff: prefix
149                  * if it's a 4in6 IP.
150                  *
151                  * This is, of course, much improved over the older way of handling this
152                  * (pretend it doesn't exist + hack around it -- yes, both were done!)
153                  *
154                  * Big, big thanks to danieldg for his work on this.
155                  * -- w00t
156                  */
157                 static const unsigned char prefix4in6[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xFF,0xFF };
158                 if (!memcmp(prefix4in6, &client.in6.sin6_addr, 12))
159                 {
160                         // recreate as a sockaddr_in using the IPv4 IP
161                         uint16_t sport = client.in6.sin6_port;
162                         client.in4.sin_family = AF_INET;
163                         client.in4.sin_port = sport;
164                         memcpy(&client.in4.sin_addr.s_addr, client.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
165
166                         sport = server.in6.sin6_port;
167                         server.in4.sin_family = AF_INET;
168                         server.in4.sin_port = sport;
169                         memcpy(&server.in4.sin_addr.s_addr, server.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
170                 }
171         }
172
173         ServerInstance->SE->NonBlocking(incomingSockfd);
174
175         ModResult res;
176         FIRST_MOD_RESULT(OnAcceptConnection, res, (incomingSockfd, this, &client, &server));
177         if (res == MOD_RES_PASSTHRU)
178         {
179                 std::string type = bind_tag->getString("type", "clients");
180                 if (type == "clients")
181                 {
182                         ServerInstance->Users->AddUser(incomingSockfd, this, &client, &server);
183                         res = MOD_RES_ALLOW;
184                 }
185         }
186         if (res == MOD_RES_ALLOW)
187         {
188                 ServerInstance->stats->statsAccept++;
189         }
190         else
191         {
192                 ServerInstance->stats->statsRefused++;
193                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Refusing connection on %s - %s",
194                         bind_desc.c_str(), res == MOD_RES_DENY ? "Connection refused by module" : "Module for this port not found");
195                 ServerInstance->SE->Close(incomingSockfd);
196         }
197 }
198
199 void ListenSocket::HandleEvent(EventType e, int err)
200 {
201         switch (e)
202         {
203                 case EVENT_ERROR:
204                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ListenSocket::HandleEvent() received a socket engine error event! well shit! '%s'", strerror(err));
205                         break;
206                 case EVENT_WRITE:
207                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "*** BUG *** ListenSocket::HandleEvent() got a WRITE event!!!");
208                         break;
209                 case EVENT_READ:
210                         this->AcceptInternal();
211                         break;
212         }
213 }