SocketUtil.cxx 1.68 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13
 * 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.
14 15 16 17
 *
 * 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.
18 19
 */

20
#include "config.h"
21
#include "SocketUtil.hxx"
22
#include "SocketAddress.hxx"
23
#include "SocketError.hxx"
24
#include "UniqueSocketDescriptor.hxx"
25

26 27
#include <sys/stat.h>

28
UniqueSocketDescriptor
29
socket_bind_listen(int domain, int type, int protocol,
30
		   SocketAddress address,
31
		   int backlog)
32
{
33 34
	UniqueSocketDescriptor fd;
	if (!fd.CreateNonBlock(domain, type, protocol))
35
		throw MakeSocketError("Failed to create socket");
36

37
#ifdef HAVE_UN
38
	if (domain == AF_LOCAL) {
39 40
		/* Prevent access until right permissions are set */
		fchmod(fd.Get(), 0);
41 42 43
	}
#endif

44 45
	if (!fd.SetReuseAddress())
		throw MakeSocketError("setsockopt() failed");
46

47 48
	if (!fd.Bind(address))
		throw MakeSocketError("Failed to bind socket");
49

50 51
	if (!fd.Listen(backlog))
		throw MakeSocketError("Failed to listen on socket");
52

53
#if defined(HAVE_STRUCT_UCRED) && defined(SO_PASSCRED)
54
	fd.SetBoolOption(SOL_SOCKET, SO_PASSCRED, true);
55 56 57 58
#endif

	return fd;
}