summaryrefslogtreecommitdiff
path: root/command_service.c
blob: 562c7f43b92803974777e1faf924ad9a412c3f68 (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
#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 = g_strstr_len(buffer, size, "\r");
		if(pos == NULL) {
			pos = g_strstr_len(buffer, size, "\n");
		}
		if(pos == NULL) {
			g_warning("EOL not found");
			return FALSE;
		}
		*pos = '\0';

		commands_handle(connection, buffer);
	}

	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);
}