summaryrefslogtreecommitdiff
path: root/idle.c
blob: e0eb525ab363c0f7cb706a62ea5f595c5e2b8a2d (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#define _GNU_SOURCE
#include <inttypes.h>
#include <sys/timerfd.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>

#include "main.h"
#include "uring.h"
#include "server.h"
#include "idle.h"

struct idle {
	struct uring_task task;
	uint64_t value;
};

static inline void
write_byte(char **pos, char byte)
{
	assert_return(pos && *pos);

	**pos = byte;
	(*pos)++;
}

#define MC_HELO 0x00
#define MC_NEXT_STATE_STATUS 0x01
#define MC_GET_STATUS 0x00
#define MC_VARINT_MAX_BYTES 5
#define MC_STATUS_REPLY 0x00

static inline void
write_varint(char **pos, int32_t orig)
{
	assert_return(pos && *pos);

	uint32_t val = (uint32_t)orig;

	while (val) {
		**pos = val & 0x7f;
		val >>= 7;
		if (val > 0)
			**pos |= 0x80;
		(*pos)++;
	}
}

/*
 * return value:
 * positive = varint parsed
 * zero = need more bytes
 * negative = error
 */
static inline int
read_varint(char **pos, size_t *remain, int32_t *res)
{
	unsigned consumed;
	uint32_t val = 0;

	assert_return(pos && *pos && remain && res, -1);

	for (consumed = 1; consumed <= *remain; consumed++) {
		uint32_t tmp;

		tmp = **pos & 0x7f;
		val += (tmp << (7 * (consumed - 1)));
		(*pos)++;

		if (!(tmp & 0x80))
			break;
	}

	if (consumed > *remain)
		return 0;
	else if (consumed > MC_VARINT_MAX_BYTES)
		return -1;

	*remain -= consumed;
	*res = (int32_t)val;
	return 1;
}

static inline void
write_bytes(char **pos, const char *bytes, size_t n)
{
	assert_return(pos && *pos && bytes && n > 0);

	memcpy(*pos, bytes, n);
	*pos += n;
}

static inline void
write_str(char **pos, const char *str)
{
	size_t len;

	assert_return(pos && *pos && !empty_str(str));

	len = strlen(str);
	write_varint(pos, len);
	write_bytes(pos, str, len);
}

static inline void
write_cmd(char **pos, const char *begin, const char *end)
{
	assert_return(pos && *pos && begin && end && end > begin);

	write_varint(pos, end - begin);
	write_bytes(pos, begin, end - begin);
}

static int
idle_check_handshake_complete(struct uring_task *task, int res)
{
	size_t remain;
	char *pos;
	int32_t mclen;
	int r;

	assert_return(task, -EINVAL);
	assert_task_alive_or(DBG_IDLE, task, return -EINTR);

	remain = task->tbuf->len;
	pos = task->tbuf->buf;

	r = read_varint(&pos, &remain, &mclen);
	if (r < 0) {
		error("failed to parse message length");
		return -EINVAL;
	} else if (r == 0) {
		return 0;
	} else if (mclen < 2) {
		error("short MC message");
		return -EINVAL;
	}

	if (mclen < remain) {
		debug(DBG_IDLE, "short MC message - len: %" PRIi32 ", remain: %zu",
		      mclen, remain);
		return 0;
	} 

	debug(DBG_IDLE, "Complete message");
	return 1;
}

#define ONLINE_NEEDLE "\"online\""
static int
get_player_count(const char *pos, size_t remain)
{
	/*
	 * Example JSON (line breaks added):
	 * {"description":{
	 *	"text":"A Minecraft Server"},
	 *	"players":{"max":20,"online":0},
	 *	"version":{"name":"1.15.2","protocol":578}
	 * }
	 */
	char *online;
	char *end;
	unsigned count;

	assert_return(pos && remain > 0, -1);

	online = memmem(pos, remain, ONLINE_NEEDLE, strlen(ONLINE_NEEDLE));
	if (!online) {
		error("could not find online count in JSON");
		return -1;
	}

	remain -= (online - pos);

	end = memchr(online, '}', remain);
	if (!end) {
		error("could not parse JSON (no end)");
		return -1;
	}
	*end = '\0';

	if (sscanf(online, ONLINE_NEEDLE " : %u", &count) != 1) {
		error("could not parse JSON (online count)");
		return -1;
	}

	return count;
}

static void
idle_check_handshake_reply(struct uring_task *task, int res)
{
	struct server *server = container_of(task, struct server, idle_task);
	int32_t mclen;
	int32_t jsonlen;
	char *pos;
	size_t remain;
	int player_count = -1;
	int r;

	assert_return(task);
	assert_task_alive(DBG_IDLE, task);

	debug(DBG_IDLE, "res: %i", res);
	if (res < 0)
		goto out;

	/*
	fprintf(stderr, "Received MC message (%i bytes):", res);
	for (int i = 0; i < res; i++)
		fprintf(stderr, "0x%02hhx ", idle->remotebuf[i]);
	fprintf(stderr, "n");
	*/

	remain = server->idle_buf.len;
	pos = server->idle_buf.buf;

	r = read_varint(&pos, &remain, &mclen);
	if (r <= 0 || mclen < 2 || mclen < remain) {
		/* Should not happen since the msg has been checked already */
		error("invalid message");
		goto out;
	}

	debug(DBG_IDLE, "MC message - len: %" PRIi32 ", remain: %zu",
	      mclen, remain);

	if (*pos != MC_STATUS_REPLY) {
		error("unknown server reply (0x%02hhx)", *pos);
		goto out;
	}

	pos++;
	remain--;

	r = read_varint(&pos, &remain, &jsonlen);
	if (r <= 0) {
		error("could not read JSON length");
		goto out;
	}

	debug(DBG_IDLE, "MC - json len: %" PRIi32 ", remain: %zu",
	      jsonlen, remain);

	if (jsonlen < remain) {
		error("invalid JSON length");
		goto out;
	}

	/*
	fprintf(stderr, "JSON: ");
	for (int i = 0; i < jsonlen; i++)
		fprintf(stderr, "%c", pos[i]);
	*/

	player_count = get_player_count(pos, remain);

out:
	uring_task_close_fd(task);
	server_set_active_players(server, player_count);
	return;
}

static void
idle_check_handshake_sent(struct uring_task *task, int res)
{
	assert_return(task);
	assert_task_alive(DBG_IDLE, task);

	debug(DBG_IDLE, "sent %i bytes", res);
	if (res < 0) {
		uring_task_close_fd(task);
		return;
	}

	uring_tbuf_read_until(task,
			      idle_check_handshake_complete,
			      idle_check_handshake_reply);
}

void
idle_check_get_player_count(struct server *server, struct connection *conn)
{
	char buf[1024];
	char *pos;
	char *cmdbuf = server->idle_buf.buf;
	uint16_t port;
	char hostname[INET6_ADDRSTRLEN];

	assert_return(server && conn && server->idle_task.priv);

	port = saddr_port(&conn->remote);
	saddr_addr(&conn->remote, hostname, sizeof(hostname));

	pos = buf;
	write_byte(&pos, MC_HELO);
	write_varint(&pos, -1); /* Protocol version, -1 = undefined */
	write_str(&pos, hostname);
	write_byte(&pos, (port >> 8) & 0xff);
	write_byte(&pos, (port >> 0) & 0xff);
	write_byte(&pos, MC_NEXT_STATE_STATUS);
	write_cmd(&cmdbuf, buf, pos);

	pos = buf;
	write_byte(&pos, MC_GET_STATUS);
	write_cmd(&cmdbuf, buf, pos);

	server->idle_buf.len = (cmdbuf - server->idle_buf.buf);
	debug(DBG_IDLE, "sending MC message (%zu bytes)", server->idle_buf.len);

	uring_tbuf_write(&server->idle_task, idle_check_handshake_sent);
}

static void
idle_cb(struct uring_task *task, int res)
{
	struct idle *idle = container_of(task, struct idle, task);
	struct server *server;

	assert_return(task);
	assert_task_alive(DBG_IDLE, task);

	if (res != sizeof(idle->value)) {
		error("timerfd_read: %i", res);
		return;
	}

	debug(DBG_IDLE, "timer fired (value: %" PRIu64 ")", idle->value);

	list_for_each_entry(server, &cfg->servers, list)
		server_idle_check(server);

	uring_read(&idle->task, &idle->value, sizeof(idle->value), idle_cb);
}

static void
idle_free(struct uring_task *task)
{
	struct idle *idle = container_of(task, struct idle, task);

	assert_return(task);
	debug(DBG_IDLE, "task %p, idle %p", task, idle);
	xfree(idle);
}

void
idle_refdump()
{
	assert_return_silent(cfg->idle);

	uring_task_refdump(&cfg->idle->task);
}

void
idle_delete()
{
	assert_return(cfg->idle);

	debug(DBG_IDLE, "closing fd %i", cfg->idle->task.fd);
	uring_task_destroy(&cfg->idle->task);
	cfg->idle = NULL;
}

void
idle_init()
{
	struct idle *idle;
	int ifd;
	struct itimerspec tspec = {
		.it_interval = {
			.tv_sec  = 60,
			.tv_nsec = 0
		},
		.it_value = {
			/* FIXME: change to 60 */
			.tv_sec  = 4,
			.tv_nsec = 0
		}
	};

	assert_return(!cfg->idle);

	idle = zmalloc(sizeof(*idle));
	if (!idle)
		die("malloc: %m");

	ifd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
	if (ifd < 0)
		die("timerfd_create: %m");

	if (timerfd_settime(ifd, 0, &tspec, NULL) != 0)
		die("timerfd_settime: %m");

	uring_task_init(&idle->task, "idle", uring_parent(), idle_free);
	uring_task_set_fd(&idle->task, ifd);
	cfg->idle = idle;

	uring_read(&idle->task, &idle->value, sizeof(idle->value), idle_cb);
}