summaryrefslogtreecommitdiff
path: root/command_service.c
blob: ce1589d5975a2e38d46347273f6e4ff9d85e0090 (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
#include "command_service.h"
#include "commands.h"
#include "conf.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);
	GDataInputStream *input = g_data_input_stream_new(g_io_stream_get_input_stream((GIOStream*)connection));
	g_data_input_stream_set_newline_type(input, G_DATA_STREAM_NEWLINE_TYPE_LF);
	gchar *line;
	gsize size;

	while(g_socket_is_connected(socket) == TRUE &&
			(line = g_data_input_stream_read_line(input, &size, NULL, &error)) != NULL) {
		commands_handle(connection, line, &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;
		}
	}

	g_object_unref(input);

	if(error != NULL) {
		g_warning(error->message);
		g_error_free(error);
	}

	return FALSE;
}

gboolean server_start() {
	GError *error = NULL;

	ss = g_threaded_socket_service_new(10);

	if(g_socket_listener_add_inet_port((GSocketListener*)ss,
				conf_get_int("audist", "command_port"), NULL,
				&error) == FALSE) {
		g_warning("failed to set port: %s", error->message);
		g_error_free(error);
		return FALSE;
	}

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

	return TRUE;
}

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