ServerSocket.cxx 8.06 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * http://www.musicpd.org
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
21
#include "ServerSocket.hxx"
22
#include "net/IPv4Address.hxx"
23
#include "net/StaticSocketAddress.hxx"
24
#include "net/AllocatedSocketAddress.hxx"
25
#include "net/SocketAddress.hxx"
26 27
#include "net/SocketUtil.hxx"
#include "net/SocketError.hxx"
28
#include "net/UniqueSocketDescriptor.hxx"
29
#include "net/Resolver.hxx"
30
#include "net/ToString.hxx"
31
#include "event/SocketMonitor.hxx"
32 33
#include "fs/AllocatedPath.hxx"
#include "fs/FileSystem.hxx"
34
#include "util/RuntimeError.hxx"
35
#include "util/Domain.hxx"
36
#include "util/ScopeExit.hxx"
37
#include "Log.hxx"
38

39
#include <string>
40
#include <algorithm>
41

42 43 44 45 46 47 48 49 50 51 52 53 54
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>

#ifdef WIN32
#include <ws2tcpip.h>
#include <winsock.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#endif

55
class OneServerSocket final : private SocketMonitor {
56
	ServerSocket &parent;
57

58
	const unsigned serial;
59

60
#ifdef HAVE_UN
61
	AllocatedPath path;
62
#endif
63

64
	const AllocatedSocketAddress address;
65

66
public:
67
	template<typename A>
68
	OneServerSocket(EventLoop &_loop, ServerSocket &_parent,
69
			unsigned _serial,
70
			A &&_address)
71 72
		:SocketMonitor(_loop),
		 parent(_parent), serial(_serial),
73
#ifdef HAVE_UN
74
		 path(AllocatedPath::Null()),
75
#endif
76
		 address(std::forward<A>(_address))
77 78 79 80 81 82 83
	{
	}

	OneServerSocket(const OneServerSocket &other) = delete;
	OneServerSocket &operator=(const OneServerSocket &other) = delete;

	~OneServerSocket() {
84 85
		if (IsDefined())
			Close();
86 87
	}

88 89 90 91
	unsigned GetSerial() const {
		return serial;
	}

92
#ifdef HAVE_UN
93 94
	void SetPath(AllocatedPath &&_path) {
		assert(path.IsNull());
95

96
		path = std::move(_path);
97
	}
98
#endif
99

100
	void Open();
101

102
	using SocketMonitor::IsDefined;
103
	using SocketMonitor::Close;
104

105
	gcc_pure
106
	std::string ToString() const noexcept {
107
		return ::ToString(address);
108
	}
109

110
	void SetFD(SocketDescriptor _fd) noexcept {
111 112 113
		SocketMonitor::Open(_fd);
		SocketMonitor::ScheduleRead();
	}
114

115
	void Accept() noexcept;
116 117

private:
118
	virtual bool OnSocketReady(unsigned flags) override;
119 120
};

121
static constexpr Domain server_socket_domain("server_socket");
122 123 124 125 126 127 128 129 130

static int
get_remote_uid(int fd)
{
#ifdef HAVE_STRUCT_UCRED
	struct ucred cred;
	socklen_t len = sizeof (cred);

	if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) < 0)
131
		return -1;
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

	return cred.uid;
#else
#ifdef HAVE_GETPEEREID
	uid_t euid;
	gid_t egid;

	if (getpeereid(fd, &euid, &egid) == 0)
		return euid;
#else
	(void)fd;
#endif
	return -1;
#endif
}

148
inline void
149
OneServerSocket::Accept() noexcept
150
{
151
	StaticSocketAddress peer_address;
152
	UniqueSocketDescriptor peer_fd(Get().AcceptNonBlock(peer_address));
153
	if (!peer_fd.IsDefined()) {
154
		const SocketErrorMessage msg;
155 156
		FormatError(server_socket_domain,
			    "accept() failed: %s", (const char *)msg);
157 158 159
		return;
	}

160
	if (!peer_fd.SetKeepAlive()) {
161
		const SocketErrorMessage msg;
162 163 164
		FormatError(server_socket_domain,
			    "Could not set TCP keepalive option: %s",
			    (const char *)msg);
165 166
	}

167
	parent.OnAccept(std::move(peer_fd), peer_address,
168
			get_remote_uid(peer_fd.Get()));
169 170
}

171
bool
172
OneServerSocket::OnSocketReady(gcc_unused unsigned flags)
173
{
174
	Accept();
175
	return true;
176 177
}

178 179
inline void
OneServerSocket::Open()
180
{
181
	assert(!IsDefined());
182

183 184 185
	auto _fd = socket_bind_listen(address.GetFamily(),
				      SOCK_STREAM, 0,
				      address, 5);
186

187
#ifdef HAVE_UN
188 189
	/* allow everybody to connect */

190 191
	if (!path.IsNull())
		chmod(path.c_str(), 0666);
192
#endif
193

194
	/* register in the EventLoop */
195

196
	SetFD(_fd.Release());
197 198
}

199 200
ServerSocket::ServerSocket(EventLoop &_loop)
	:loop(_loop), next_serial(1) {}
201 202 203 204 205

/* this is just here to allow the OneServerSocket forward
   declaration */
ServerSocket::~ServerSocket() {}

206 207
void
ServerSocket::Open()
208
{
209
	OneServerSocket *good = nullptr, *bad = nullptr;
210
	std::exception_ptr last_error;
211

212 213
	for (auto &i : sockets) {
		assert(i.GetSerial() > 0);
214
		assert(good == nullptr || i.GetSerial() >= good->GetSerial());
215

216 217
		if (bad != nullptr && i.GetSerial() != bad->GetSerial()) {
			Close();
218
			std::rethrow_exception(last_error);
219 220
		}

221 222 223
		try {
			i.Open();
		} catch (const std::runtime_error &e) {
224
			if (good != nullptr && good->GetSerial() == i.GetSerial()) {
225 226
				const auto address_string = i.ToString();
				const auto good_string = good->ToString();
227 228 229 230 231 232
				FormatError(e,
					    "bind to '%s' failed "
					    "(continuing anyway, because "
					    "binding to '%s' succeeded)",
					    address_string.c_str(),
					    good_string.c_str());
233 234
			} else if (bad == nullptr) {
				bad = &i;
235

236
				const auto address_string = i.ToString();
237

238 239 240 241 242 243
				try {
					std::throw_with_nested(FormatRuntimeError("Failed to bind to '%s'",
										  address_string.c_str()));
				} catch (...) {
					last_error = std::current_exception();
				}
244 245
			}

246 247 248 249 250 251
			continue;
		}

		/* mark this socket as "good", and clear previous
		   errors */

252
		good = &i;
253

254 255
		if (bad != nullptr) {
			bad = nullptr;
256
			last_error = nullptr;
257 258 259
		}
	}

260
	if (bad != nullptr) {
261
		Close();
262
		std::rethrow_exception(last_error);
263 264 265
	}
}

266
void
267
ServerSocket::Close()
268 269
{
	for (auto &i : sockets)
270 271
		if (i.IsDefined())
			i.Close();
272 273
}

274
OneServerSocket &
275
ServerSocket::AddAddress(SocketAddress address)
276
{
277
	sockets.emplace_back(loop, *this, next_serial,
278
			     address);
279

280
	return sockets.back();
281 282
}

283 284 285 286 287 288 289 290 291
OneServerSocket &
ServerSocket::AddAddress(AllocatedSocketAddress &&address)
{
	sockets.emplace_back(loop, *this, next_serial,
			     std::move(address));

	return sockets.back();
}

292
void
293
ServerSocket::AddFD(int _fd)
294
{
295
	assert(_fd >= 0);
296

297
	SocketDescriptor fd(_fd);
298

299 300 301
	StaticSocketAddress address = fd.GetLocalAddress();
	if (!address.IsDefined())
		throw MakeSocketError("Failed to get socket address");
302 303

	OneServerSocket &s = AddAddress(address);
304
	s.SetFD(fd);
305 306
}

307 308
#ifdef HAVE_TCP

309 310
inline void
ServerSocket::AddPortIPv4(unsigned port)
311
{
312
	AddAddress(IPv4Address(port));
313 314 315
}

#ifdef HAVE_IPV6
316

317 318
inline void
ServerSocket::AddPortIPv6(unsigned port)
319 320 321 322 323 324
{
	struct sockaddr_in6 sin;
	memset(&sin, 0, sizeof(sin));
	sin.sin6_port = htons(port);
	sin.sin6_family = AF_INET6;

325
	AddAddress({(const sockaddr *)&sin, sizeof(sin)});
326
}
327 328 329 330 331 332

/**
 * Is IPv6 supported by the kernel?
 */
gcc_pure
static bool
333
SupportsIPv6() noexcept
334 335 336 337 338 339 340 341 342
{
	int fd = socket(AF_INET6, SOCK_STREAM, 0);
	if (fd < 0)
		return false;

	close(fd);
	return true;
}

343 344 345 346
#endif /* HAVE_IPV6 */

#endif /* HAVE_TCP */

347 348
void
ServerSocket::AddPort(unsigned port)
349 350
{
#ifdef HAVE_TCP
351 352
	if (port == 0 || port > 0xffff)
		throw std::runtime_error("Invalid TCP port");
353 354

#ifdef HAVE_IPV6
355 356
	if (SupportsIPv6())
		AddPortIPv6(port);
357
#endif
358
	AddPortIPv4(port);
359

360
	++next_serial;
361 362 363
#else /* HAVE_TCP */
	(void)port;

364
	throw std::runtime_error("TCP support is disabled");
365 366 367
#endif /* HAVE_TCP */
}

368 369
void
ServerSocket::AddHost(const char *hostname, unsigned port)
370 371
{
#ifdef HAVE_TCP
372
	struct addrinfo *ai = resolve_host_port(hostname, port,
373 374
						AI_PASSIVE, SOCK_STREAM);
	AtScopeExit(ai) { freeaddrinfo(ai); };
375

376
	for (const struct addrinfo *i = ai; i != nullptr; i = i->ai_next)
377
		AddAddress(SocketAddress(i->ai_addr, i->ai_addrlen));
378

379
	++next_serial;
380 381 382 383
#else /* HAVE_TCP */
	(void)hostname;
	(void)port;

384
	throw std::runtime_error("TCP support is disabled");
385 386 387
#endif /* HAVE_TCP */
}

388 389
void
ServerSocket::AddPath(AllocatedPath &&path)
390 391
{
#ifdef HAVE_UN
392
	unlink(path.c_str());
393

394 395
	AllocatedSocketAddress address;
	address.SetLocal(path.c_str());
396

397
	OneServerSocket &s = AddAddress(std::move(address));
398
	s.SetPath(std::move(path));
399 400 401
#else /* !HAVE_UN */
	(void)path;

402
	throw std::runtime_error("UNIX domain socket support is disabled");
403 404 405
#endif /* !HAVE_UN */
}