]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/listensocket.cpp
CoreExport for CommandSave. fixes #1635
[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         fd = socket(bind_to.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.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         if (tag->getBool("free"))
56         {
57                 socklen_t enable = 1;
58 #if defined IP_FREEBIND // Linux 2.4+
59                 setsockopt(fd, SOL_IP, IP_FREEBIND, &enable, sizeof(enable));
60 #elif defined IP_BINDANY // FreeBSD
61                 setsockopt(fd, IPPROTO_IP, IP_BINDANY, &enable, sizeof(enable));
62 #elif defined SO_BINDANY // NetBSD/OpenBSD
63                 setsockopt(fd, SOL_SOCKET, SO_BINDANY, &enable, sizeof(enable));
64 #else
65                 (void)enable;
66 #endif
67         }
68
69         if (bind_to.family() == AF_UNIX)
70         {
71                 const std::string permissionstr = tag->getString("permissions");
72                 unsigned int permissions = strtoul(permissionstr.c_str(), NULL, 8);
73                 if (permissions && permissions <= 07777)
74                         chmod(bind_to.str().c_str(), permissions);
75         }
76
77         SocketEngine::SetReuse(fd);
78         int rv = SocketEngine::Bind(this->fd, bind_to);
79         if (rv >= 0)
80                 rv = SocketEngine::Listen(this->fd, ServerInstance->Config->MaxConn);
81
82         // Default defer to on for TLS listeners because in TLS the client always speaks first
83         int timeout = tag->getDuration("defer", (tag->getString("ssl").empty() ? 0 : 3));
84         if (timeout && !rv)
85         {
86 #if defined TCP_DEFER_ACCEPT
87                 setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(timeout));
88 #elif defined SO_ACCEPTFILTER
89                 struct accept_filter_arg afa;
90                 memset(&afa, 0, sizeof(afa));
91                 strcpy(afa.af_name, "dataready");
92                 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
93 #endif
94         }
95
96         if (rv < 0)
97         {
98                 int errstore = errno;
99                 SocketEngine::Shutdown(this, 2);
100                 SocketEngine::Close(this->GetFd());
101                 this->fd = -1;
102                 errno = errstore;
103         }
104         else
105         {
106                 SocketEngine::NonBlocking(this->fd);
107                 SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
108
109                 this->ResetIOHookProvider();
110         }
111 }
112
113 ListenSocket::~ListenSocket()
114 {
115         if (this->GetFd() > -1)
116         {
117                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Shut down listener on fd %d", this->fd);
118                 SocketEngine::Shutdown(this, 2);
119
120                 if (SocketEngine::Close(this) != 0)
121                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to cancel listener: %s", strerror(errno));
122
123                 if (bind_sa.family() == AF_UNIX && unlink(bind_sa.un.sun_path))
124                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to unlink UNIX socket: %s", strerror(errno));
125         }
126 }
127
128 void ListenSocket::OnEventHandlerRead()
129 {
130         irc::sockets::sockaddrs client;
131         irc::sockets::sockaddrs server(bind_sa);
132
133         socklen_t length = sizeof(client);
134         int incomingSockfd = SocketEngine::Accept(this, &client.sa, &length);
135
136         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Accepting connection on socket %s fd %d", bind_sa.str().c_str(), incomingSockfd);
137         if (incomingSockfd < 0)
138         {
139                 ServerInstance->stats.Refused++;
140                 return;
141         }
142
143         socklen_t sz = sizeof(server);
144         if (getsockname(incomingSockfd, &server.sa, &sz))
145         {
146                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Can't get peername: %s", strerror(errno));
147         }
148
149         if (client.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         else if (client.family() == AF_UNIX)
179         {
180                 // Clients connecting via UNIX sockets don't have paths so give them
181                 // the server path as defined in RFC 1459 section 8.1.1.
182                 //
183                 // strcpy is safe here because sizeof(sockaddr_un.sun_path) is equal on both.
184                 strcpy(client.un.sun_path, server.un.sun_path);
185         }
186
187         SocketEngine::NonBlocking(incomingSockfd);
188
189         ModResult res;
190         FIRST_MOD_RESULT(OnAcceptConnection, res, (incomingSockfd, this, &client, &server));
191         if (res == MOD_RES_PASSTHRU)
192         {
193                 std::string type = bind_tag->getString("type", "clients");
194                 if (stdalgo::string::equalsci(type, "clients"))
195                 {
196                         ServerInstance->Users->AddUser(incomingSockfd, this, &client, &server);
197                         res = MOD_RES_ALLOW;
198                 }
199         }
200         if (res == MOD_RES_ALLOW)
201         {
202                 ServerInstance->stats.Accept++;
203         }
204         else
205         {
206                 ServerInstance->stats.Refused++;
207                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Refusing connection on %s - %s",
208                         bind_sa.str().c_str(), res == MOD_RES_DENY ? "Connection refused by module" : "Module for this port not found");
209                 SocketEngine::Close(incomingSockfd);
210         }
211 }
212
213 void ListenSocket::ResetIOHookProvider()
214 {
215         iohookprovs[0].SetProvider(bind_tag->getString("hook"));
216
217         // Check that all non-last hooks support being in the middle
218         for (IOHookProvList::iterator i = iohookprovs.begin(); i != iohookprovs.end()-1; ++i)
219         {
220                 IOHookProvRef& curr = *i;
221                 // Ignore if cannot be in the middle
222                 if ((curr) && (!curr->IsMiddle()))
223                         curr.SetProvider(std::string());
224         }
225
226         std::string provname = bind_tag->getString("ssl");
227         if (!provname.empty())
228                 provname.insert(0, "ssl/");
229
230         // SSL should be the last
231         iohookprovs.back().SetProvider(provname);
232 }