ClientNew.cxx 2.47 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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"
Max Kellermann's avatar
Max Kellermann committed
21
#include "ClientInternal.hxx"
22
#include "ClientList.hxx"
23
#include "Partition.hxx"
24
#include "Instance.hxx"
25
#include "net/UniqueSocketDescriptor.hxx"
26
#include "net/SocketAddress.hxx"
27
#include "net/ToString.hxx"
28
#include "Permission.hxx"
29
#include "Log.hxx"
30 31

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

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

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

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

63
	assert(fd.IsDefined());
64

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

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

73
	Client *client = new Client(loop, partition, std::move(fd), uid,
74
				    permission,
75 76
				    next_client_num++);

77
	client_list.Add(*client);
78

79 80
	FormatInfo(client_domain, "[%u] opened from %s",
		   client->num, remote.c_str());
81 82 83
}

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

88
	SetExpired();
89

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