1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019-2020 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
6  *   Copyright (C) 2013, 2016-2021 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
8  *   Copyright (C) 2013 Adam <Adam@anope.org>
9  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
10  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
11  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12  *   Copyright (C) 2009-2010 Craig Edwards <brain@inspircd.org>
13  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
14  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
15  *
16  * This file is part of InspIRCd.  InspIRCd is free software: you can
17  * redistribute it and/or modify it under the terms of the GNU General Public
18  * License as published by the Free Software Foundation, version 2.
19  *
20  * This program is distributed in the hope that it will be useful, but WITHOUT
21  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
22  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
23  * details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27  */
28 
29 
30 #include "inspircd.h"
31 #include "iohook.h"
32 
33 #ifndef _WIN32
34 #include <netinet/tcp.h>
35 #endif
36 
ListenSocket(ConfigTag * tag,const irc::sockets::sockaddrs & bind_to)37 ListenSocket::ListenSocket(ConfigTag* tag, const irc::sockets::sockaddrs& bind_to)
38 	: bind_tag(tag)
39 	, bind_sa(bind_to)
40 {
41 	// Are we creating a UNIX socket?
42 	if (bind_to.family() == AF_UNIX)
43 	{
44 		// Is 'replace' enabled?
45 		const bool replace = tag->getBool("replace");
46 		if (replace && irc::sockets::isunix(bind_to.str()))
47 			unlink(bind_to.str().c_str());
48 	}
49 
50 	fd = socket(bind_to.family(), SOCK_STREAM, 0);
51 	if (!HasFd())
52 		return;
53 
54 #ifdef IPV6_V6ONLY
55 	/* This OS supports IPv6 sockets that can also listen for IPv4
56 	 * connections. If our address is "*" or empty, enable both v4 and v6 to
57 	 * allow for simpler configuration on dual-stack hosts. Otherwise, if it
58 	 * is "::" or an IPv6 address, disable support so that an IPv4 bind will
59 	 * work on the port (by us or another application).
60 	 */
61 	if (bind_to.family() == AF_INET6)
62 	{
63 		std::string addr = tag->getString("address");
64 		/* This must be >= sizeof(DWORD) on Windows */
65 		const int enable = (addr.empty() || addr == "*") ? 0 : 1;
66 		/* This must be before bind() */
67 		setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&enable), sizeof(enable));
68 		// errors ignored intentionally
69 	}
70 #endif
71 
72 	if (tag->getBool("free"))
73 	{
74 		socklen_t enable = 1;
75 #if defined IP_FREEBIND // Linux 2.4+
76 		setsockopt(fd, SOL_IP, IP_FREEBIND, &enable, sizeof(enable));
77 #elif defined IP_BINDANY // FreeBSD
78 		setsockopt(fd, IPPROTO_IP, IP_BINDANY, &enable, sizeof(enable));
79 #elif defined SO_BINDANY // NetBSD/OpenBSD
80 		setsockopt(fd, SOL_SOCKET, SO_BINDANY, &enable, sizeof(enable));
81 #else
82 		(void)enable;
83 #endif
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 	if (bind_to.family() == AF_UNIX)
92 	{
93 		const std::string permissionstr = tag->getString("permissions");
94 		unsigned int permissions = strtoul(permissionstr.c_str(), NULL, 8);
95 		if (permissions && permissions <= 07777)
96 			chmod(bind_to.str().c_str(), permissions);
97 	}
98 
99 	// Default defer to on for TLS listeners because in TLS the client always speaks first
100 	unsigned int timeoutdef = tag->getString("sslprofile", tag->getString("ssl")).empty() ? 0 : 3;
101 	int timeout = tag->getDuration("defer", timeoutdef, 0, 60);
102 	if (timeout && !rv)
103 	{
104 #if defined TCP_DEFER_ACCEPT
105 		setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(timeout));
106 #elif defined SO_ACCEPTFILTER
107 		struct accept_filter_arg afa;
108 		memset(&afa, 0, sizeof(afa));
109 		strcpy(afa.af_name, "dataready");
110 		setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
111 #endif
112 	}
113 
114 	if (rv < 0)
115 	{
116 		int errstore = errno;
117 		SocketEngine::Shutdown(this, 2);
118 		SocketEngine::Close(this->GetFd());
119 		this->fd = -1;
120 		errno = errstore;
121 	}
122 	else
123 	{
124 		SocketEngine::NonBlocking(this->fd);
125 		SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
126 
127 		this->ResetIOHookProvider();
128 	}
129 }
130 
~ListenSocket()131 ListenSocket::~ListenSocket()
132 {
133 	if (this->HasFd())
134 	{
135 		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Shut down listener on fd %d", this->fd);
136 		SocketEngine::Shutdown(this, 2);
137 
138 		if (SocketEngine::Close(this) != 0)
139 			ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to cancel listener: %s", strerror(errno));
140 
141 		if (bind_sa.family() == AF_UNIX && unlink(bind_sa.un.sun_path))
142 			ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to unlink UNIX socket: %s", strerror(errno));
143 	}
144 }
145 
OnEventHandlerRead()146 void ListenSocket::OnEventHandlerRead()
147 {
148 	irc::sockets::sockaddrs client;
149 	irc::sockets::sockaddrs server(bind_sa);
150 
151 	socklen_t length = sizeof(client);
152 	int incomingSockfd = SocketEngine::Accept(this, &client.sa, &length);
153 
154 	ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Accepting connection on socket %s fd %d", bind_sa.str().c_str(), incomingSockfd);
155 	if (incomingSockfd < 0)
156 	{
157 		ServerInstance->stats.Refused++;
158 		return;
159 	}
160 
161 	socklen_t sz = sizeof(server);
162 	if (getsockname(incomingSockfd, &server.sa, &sz))
163 	{
164 		ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Can't get peername: %s", strerror(errno));
165 	}
166 
167 	if (client.family() == AF_INET6)
168 	{
169 		/*
170 		 * This case is the be all and end all patch to catch and nuke 4in6
171 		 * instead of special-casing shit all over the place and wreaking merry
172 		 * havoc with crap, instead, we just recreate sockaddr and strip ::ffff: prefix
173 		 * if it's a 4in6 IP.
174 		 *
175 		 * This is, of course, much improved over the older way of handling this
176 		 * (pretend it doesn't exist + hack around it -- yes, both were done!)
177 		 *
178 		 * Big, big thanks to danieldg for his work on this.
179 		 * -- w00t
180 		 */
181 		static const unsigned char prefix4in6[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xFF,0xFF };
182 		if (!memcmp(prefix4in6, &client.in6.sin6_addr, 12))
183 		{
184 			// recreate as a sockaddr_in using the IPv4 IP
185 			uint16_t sport = client.in6.sin6_port;
186 			client.in4.sin_family = AF_INET;
187 			client.in4.sin_port = sport;
188 			memcpy(&client.in4.sin_addr.s_addr, client.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
189 
190 			sport = server.in6.sin6_port;
191 			server.in4.sin_family = AF_INET;
192 			server.in4.sin_port = sport;
193 			memcpy(&server.in4.sin_addr.s_addr, server.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
194 		}
195 	}
196 	else if (client.family() == AF_UNIX)
197 	{
198 		// Clients connecting via UNIX sockets don't have paths so give them
199 		// the server path as defined in RFC 1459 section 8.1.1.
200 		//
201 		// strcpy is safe here because sizeof(sockaddr_un.sun_path) is equal on both.
202 		strcpy(client.un.sun_path, server.un.sun_path);
203 	}
204 
205 	SocketEngine::NonBlocking(incomingSockfd);
206 
207 	ModResult res;
208 	FIRST_MOD_RESULT(OnAcceptConnection, res, (incomingSockfd, this, &client, &server));
209 	if (res == MOD_RES_PASSTHRU)
210 	{
211 		const std::string type = bind_tag->getString("type", "clients", 1);
212 		if (stdalgo::string::equalsci(type, "clients"))
213 		{
214 			ServerInstance->Users->AddUser(incomingSockfd, this, &client, &server);
215 			res = MOD_RES_ALLOW;
216 		}
217 	}
218 	if (res == MOD_RES_ALLOW)
219 	{
220 		ServerInstance->stats.Accept++;
221 	}
222 	else
223 	{
224 		ServerInstance->stats.Refused++;
225 		ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Refusing connection on %s - %s",
226 			bind_sa.str().c_str(), res == MOD_RES_DENY ? "Connection refused by module" : "Module for this port not found");
227 		SocketEngine::Close(incomingSockfd);
228 	}
229 }
230 
ResetIOHookProvider()231 void ListenSocket::ResetIOHookProvider()
232 {
233 	iohookprovs[0].SetProvider(bind_tag->getString("hook"));
234 
235 	// Check that all non-last hooks support being in the middle
236 	for (IOHookProvList::iterator i = iohookprovs.begin(); i != iohookprovs.end()-1; ++i)
237 	{
238 		IOHookProvRef& curr = *i;
239 		// Ignore if cannot be in the middle
240 		if ((curr) && (!curr->IsMiddle()))
241 			curr.SetProvider(std::string());
242 	}
243 
244 	std::string provname = bind_tag->getString("sslprofile",  bind_tag->getString("ssl"));
245 	if (!provname.empty())
246 		provname.insert(0, "ssl/");
247 
248 	// TLS (SSL) should be the last
249 	iohookprovs.back().SetProvider(provname);
250 }
251