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

20
#include "config.h"
21
#include "Internal.hxx"
22
#include "Domain.hxx"
23
#include "List.hxx"
24
#include "Partition.hxx"
25
#include "Instance.hxx"
26
#include "net/UniqueSocketDescriptor.hxx"
27
#include "net/SocketAddress.hxx"
28
#include "net/ToString.hxx"
29
#include "Permission.hxx"
30
#include "Log.hxx"
31 32

#include <assert.h>
33
#ifdef _WIN32
34 35 36 37
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
38

39
static constexpr char GREETING[] = "OK MPD " PROTOCOL_VERSION "\n";
40

41
Client::Client(EventLoop &_loop, Partition &_partition,
42 43 44
	       UniqueSocketDescriptor _fd,
	       int _uid, unsigned _permission,
	       int _num) noexcept
45 46
	:FullyBufferedSocket(_fd.Release(), _loop,
			     16384, client_max_output_buffer_size),
47
	 timeout_event(_loop, BIND_THIS_METHOD(OnTimeout)),
48
	 partition(&_partition),
49
	 permission(_permission),
50
	 uid(_uid),
51
	 num(_num)
52
{
53
	timeout_event.Schedule(client_timeout);
54 55
}

56
void
57
client_new(EventLoop &loop, Partition &partition,
58 59
	   UniqueSocketDescriptor fd, SocketAddress address, int uid,
	   unsigned permission) noexcept
60 61
{
	static unsigned int next_client_num;
62
	const auto remote = ToString(address);
63

64
	assert(fd.IsDefined());
65

66 67
	ClientList &client_list = *partition.instance.client_list;
	if (client_list.IsFull()) {
68
		LogWarning(client_domain, "Max connections reached");
69 70 71
		return;
	}

72
	(void)fd.Write(GREETING, sizeof(GREETING) - 1);
73

74
	const unsigned num = next_client_num++;
75
	Client *client = new Client(loop, partition, std::move(fd), uid,
76
				    permission,
77
				    num);
78

79
	client_list.Add(*client);
80

81
	FormatInfo(client_domain, "[%u] opened from %s",
82
		   num, remote.c_str());
83 84 85
}

void
86
Client::Close() noexcept
87
{
88
	partition->instance.client_list->Remove(*this);
89

90
	SetExpired();
91

92
	FormatInfo(client_domain, "[%u] closed", num);
93
	delete this;
94
}