summaryrefslogtreecommitdiff
path: root/control_service.c
blob: 127beeec74b6fb9e2483e52614280664961ea152 (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
#include "control_service.h"
#include "commands.h"
#include "conf.h"

#include <glib.h>
#include <glib/gstdio.h>
#include <gio/gio.h>
#include <gio/gunixsocketaddress.h>
#include <string.h>

static GSocketService *ss = NULL;
static GSocketAddress *address;

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 control_service_start() {
	GError *error = NULL;

	gchar *sockname = conf_get_string("audist", "control_socket");
	if(sockname == NULL) {
		g_warning("control_socket not set in config, can't start control service");
		return FALSE;
	}
	address = g_unix_socket_address_new(sockname);

	ss = g_threaded_socket_service_new(2);

	if(g_socket_listener_add_address((GSocketListener*)ss, address,
			G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, NULL,
			NULL, &error) == FALSE) {
		g_warning("failed to set socket address: %s", error->message);
		g_error_free(error);
		return FALSE;
	}

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

	g_socket_service_start((GSocketService*)ss);

	return TRUE;
}

void control_service_stop() {
	g_socket_service_stop((GSocketService*)ss);
	g_unlink(g_unix_socket_address_get_path((GUnixSocketAddress*)address));
	g_object_unref(ss);
	g_object_unref(address);
}