summaryrefslogtreecommitdiff
path: root/minecctl/mc-commands.c
blob: fb87430c6132c96ad2b8ef9a0eded3f674b0ea2b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* SPDX-License-Identifier: GPL-2.0 */
#include <unistd.h>

#include "shared/utils.h"
#include "minecctl.h"
#include "server.h"
#include "mc-commands.h"
#include "misc.h"
#include "shared/mc-protocol.h"

bool do_mc_pcount(_unused_ struct cfg *cfg, struct server *server,
		  unsigned *online, unsigned *max, const char **error)
{
	struct saddr *saddr;
	char buf[4096];
	size_t plen, off;
	ssize_t r;
	bool rv = false;
	int fd;

	fd = connect_any(&server->scfg.remotes, &saddr, error);
	if (fd < 0)
		return false;

	if (!mc_protocol_create_status_request(buf, sizeof(buf), &plen,
					       saddr)) {
		*error = "failed to create request";
		goto out;
	}

	/* FIXME: do proper checks for EINTR etc */
	off = 0;
	while (off < plen) {
		r = write(fd, buf + off, plen - off);
		if (r <= 0) {
			*error = "write failed";
			goto out;
		}
		off += r;
	}

	off = 0;
	while (off < sizeof(buf)) {
		r = read(fd, buf + off, sizeof(buf) - off);
		if (r <= 0) {
			*error = "read failed";
			goto out;
		}

		off += r;

		if (mc_is_handshake_complete(buf, off))
			break;
	}

	if (!mc_protocol_parse_status_reply(buf, off, online, max)) {
		*error = "failed to get player count";
		goto out;
	}

	rv = true;

out:
	close(fd);
	return rv;
}