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