]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/listensocket.cpp
Convert a bunch of time-related config options to getDuration.
[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 "iohook.h"
23
24 #ifndef _WIN32
25 #include <netinet/tcp.h>
26 #endif
27
28 ListenSocket::ListenSocket(ConfigTag* tag, const irc::sockets::sockaddrs& bind_to)
29         : bind_tag(tag)
30 {
31         irc::sockets::satoap(bind_to, bind_addr, bind_port);
32         bind_desc = bind_to.str();
33
34         fd = socket(bind_to.sa.sa_family, SOCK_STREAM, 0);
35
36         if (this->fd == -1)
37                 return;
38
39 #ifdef IPV6_V6ONLY
40         /* This OS supports IPv6 sockets that can also listen for IPv4
41          * connections. If our address is "*" or empty, enable both v4 and v6 to
42          * allow for simpler configuration on dual-stack hosts. Otherwise, if it
43          * is "::" or an IPv6 address, disable support so that an IPv4 bind will
44          * work on the port (by us or another application).
45          */
46         if (bind_to.sa.sa_family == AF_INET6)
47         {
48                 std::string addr = tag->getString("address");
49                 /* This must be >= sizeof(DWORD) on Windows */
50                 const int enable = (addr.empty() || addr == "*") ? 0 : 1;
51                 /* This must be before bind() */
52                 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&enable), sizeof(enable));
53                 // errors ignored intentionally
54         }
55 #endif
56
57         if (tag->getBool("free"))
58         {
59                 socklen_t enable = 1;
60 #if defined IP_FREEBIND // Linux 2.4+
61                 setsockopt(fd, SOL_IP, IP_FREEBIND, &enable, sizeof(enable));
62 #elif defined IP_BINDANY // FreeBSD
63                 setsockopt(fd, IPPROTO_IP, IP_BINDANY, &enable, sizeof(enable));
64 #elif defined SO_BINDANY // NetBSD/OpenBSD
65                 setsockopt(fd, SOL_SOCKET, SO_BINDANY, &enable, sizeof(enable));
66 #else
67                 (void)enable;
68 #endif
69         }
70
71         SocketEngine::SetReuse(fd);
72         int rv = SocketEngine::Bind(this->fd, bind_to);
73         if (rv >= 0)
74                 rv = SocketEngine::Listen(this->fd, ServerInstance->Config->MaxConn);
75
76         // Default defer to on for TLS listeners because in TLS the client always speaks first
77         int timeout = tag->getDuration("defer", (tag->getString("ssl").empty() ? 0 : 3));
78         if (timeout && !rv)
79         {
80 #if defined TCP_DEFER_ACCEPT
81                 setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(timeout));
82 #elif defined SO_ACCEPTFILTER
83                 struct accept_filter_arg afa;
84                 memset(&afa, 0, sizeof(afa));
85                 strcpy(afa.af_name, "dataready");
86                 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
87 #endif
88         }
89
90         if (rv < 0)
91         {
92                 int errstore = errno;
93                 SocketEngine::Shutdown(this, 2);
94                 SocketEngine::Close(this->GetFd());
95                 this->fd = -1;
96                 errno = errstore;
97         }
98         else
99         {
100                 SocketEngine::NonBlocking(this->fd);
101                 SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
102
103                 this->ResetIOHookProvider();
104         }
105 }
106
107 ListenSocket::~ListenSocket()
108 {
109         if (this->GetFd() > -1)
110         {
111                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Shut down listener on fd %d", this->fd);
112                 SocketEngine::Shutdown(this, 2);
113                 if (SocketEngine::Close(this) != 0)
114                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to cancel listener: %s", strerror(errno));
115         }
116 }
117
118 void ListenSocket::OnEventHandlerRead()
119 {
120         irc::sockets::sockaddrs client;
121         irc::sockets::sockaddrs server;
122
123         socklen_t length = sizeof(client);
124         int incomingSockfd = SocketEngine::Accept(this, &client.sa, &length);
125
126         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Accepting connection on socket %s fd %d", bind_desc.c_str(), incomingSockfd);
127         if (incomingSockfd < 0)
128         {
129                 ServerInstance->stats.Refused++;
130                 return;
131         }
132
133         socklen_t sz = sizeof(server);
134         if (getsockname(incomingSockfd, &server.sa, &sz))
135         {
136                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Can't get peername: %s", strerror(errno));
137                 irc::sockets::aptosa(bind_addr, bind_port, server);
138         }
139
140         if (client.sa.sa_family == AF_INET6)
141         {
142                 /*
143                  * This case is the be all and end all patch to catch and nuke 4in6
144                  * instead of special-casing shit all over the place and wreaking merry
145                  * havoc with crap, instead, we just recreate sockaddr and strip ::ffff: prefix
146                  * if it's a 4in6 IP.
147                  *
148                  * This is, of course, much improved over the older way of handling this
149                  * (pretend it doesn't exist + hack around it -- yes, both were done!)
150                  *
151                  * Big, big thanks to danieldg for his work on this.
152                  * -- w00t
153                  */
154                 static const unsigned char prefix4in6[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xFF,0xFF };
155                 if (!memcmp(prefix4in6, &client.in6.sin6_addr, 12))
156                 {
157                         // recreate as a sockaddr_in using the IPv4 IP
158                         uint16_t sport = client.in6.sin6_port;
159                         client.in4.sin_family = AF_INET;
160                         client.in4.sin_port = sport;
161                         memcpy(&client.in4.sin_addr.s_addr, client.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
162
163                         sport = server.in6.sin6_port;
164                         server.in4.sin_family = AF_INET;
165                         server.in4.sin_port = sport;
166                         memcpy(&server.in4.sin_addr.s_addr, server.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
167                 }
168         }
169
170         SocketEngine::NonBlocking(incomingSockfd);
171
172         ModResult res;
173         FIRST_MOD_RESULT(OnAcceptConnection, res, (incomingSockfd, this, &client, &server));
174         if (res == MOD_RES_PASSTHRU)
175         {
176                 std::string type = bind_tag->getString("type", "clients");
177                 if (type == "clients")
178                 {
179                         ServerInstance->Users->AddUser(incomingSockfd, this, &client, &server);
180                         res = MOD_RES_ALLOW;
181                 }
182         }
183         if (res == MOD_RES_ALLOW)
184         {
185                 ServerInstance->stats.Accept++;
186         }
187         else
188         {
189                 ServerInstance->stats.Refused++;
190                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Refusing connection on %s - %s",
191                         bind_desc.c_str(), res == MOD_RES_DENY ? "Connection refused by module" : "Module for this port not found");
192                 SocketEngine::Close(incomingSockfd);
193         }
194 }
195
196 void ListenSocket::ResetIOHookProvider()
197 {
198         iohookprovs[0].SetProvider(bind_tag->getString("hook"));
199
200         // Check that all non-last hooks support being in the middle
201         for (IOHookProvList::iterator i = iohookprovs.begin(); i != iohookprovs.end()-1; ++i)
202         {
203                 IOHookProvRef& curr = *i;
204                 // Ignore if cannot be in the middle
205                 if ((curr) && (!curr->IsMiddle()))
206                         curr.SetProvider(std::string());
207         }
208
209         std::string provname = bind_tag->getString("ssl");
210         if (!provname.empty())
211                 provname.insert(0, "ssl/");
212
213         // SSL should be the last
214         iohookprovs.back().SetProvider(provname);
215 }