summaryrefslogtreecommitdiff
path: root/command_service.c
blob: 5d357dac75915ed17abe93ae54ed4d7a895d3feb (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
#include "command_service.h"
#include "commands.h"

#include <gio/gio.h>

static GSocketService *ss = NULL;

static gboolean service_incoming(GSocketService *service,
		GSocketConnection *connection, GObject *source_object,
		gpointer user_data) {
	GError *error = NULL;
	GSocket *socket = g_socket_connection_get_socket(connection);
	gchar buffer[0x400];

	while(g_socket_is_connected(socket) == TRUE) {
		gssize size = g_socket_receive(socket, buffer, 0x400, NULL, &error);

		if(size < 0) {
			g_warning(error->message);
			return FALSE;
		} else if(size == 0) {
			break;
		}

		g_debug("size == %ld", size);
		g_debug(buffer);

		gchar *pos, *eol;
		pos = buffer;
		while((eol = g_strstr_len(pos, size, "\n")) != NULL || (eol = g_strstr_len(pos, size, "\r")) != NULL) {
			*eol = '\0';

			commands_handle(connection, pos);

			size -= eol - pos + 1;
			pos = eol + 1;
		}
	}

	return FALSE;
}

gboolean server_start() {
	ss = g_threaded_socket_service_new(10);

	g_socket_listener_add_inet_port((GSocketListener*)ss, 7681, NULL, NULL);

	g_signal_connect(ss, "incoming", (GCallback)service_incoming, NULL);
	g_socket_service_start(ss);

	return TRUE;
}

void server_stop() {
	g_socket_service_stop(ss);
	g_object_unref(ss);
}