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

#include <gio/gio.h>
#include <string.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, &error);

			if(error != NULL) {
				g_warning(error->message);
				gchar *error_buffer = g_strdup_printf("%s\n", error->message);
				g_socket_send(socket, error_buffer, strlen(error_buffer), NULL, NULL);
				g_free(error_buffer);
				g_error_free(error);
				error = NULL;
			}

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