summaryrefslogtreecommitdiff
path: root/httpd.c
blob: 38ef8c1c9e87f54e214bc6d7360219fa1c6fa04f (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
81
82
83
84
85
86
87
88
89
90
#include "httpd.h"
#include "httpd_commands.h"
#include "conf.h"

#include <gio/gio.h>
#include <string.h>

GSocketService *ss = NULL;

static gboolean service_incoming(GSocketService *service,
		GSocketConnection *connection, GObject *source_object,
		gpointer user_data) {
	GSocket *socket;
	GError *error = NULL;

	socket = g_socket_connection_get_socket(connection);
	if(socket == NULL) {
		g_warning("g_socket_connection_get_socket() returned NULL");
		return FALSE;
	}
	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_CR_LF);

	GString *string = g_string_new(NULL);
	gchar *line;
	gsize size;
	gchar *path = NULL;

	while(g_socket_is_connected(socket) == TRUE &&
			(line = g_data_input_stream_read_line(input, &size, NULL, &error)) != NULL) {
		if(strlen(line) == 0) {
			break;
		}

		if(path == NULL) {
			gchar **firstline = g_strsplit(line, " ", 0);
			/* this sets the first character of the last string in
			 * firstline to \0 (HTTP version) */
			firstline[g_strv_length(firstline)-1] = '\0';
			/* now join from the second string to get the request path */
			gchar *path_escaped = g_strjoinv(" ", firstline + 1);
			path = g_uri_unescape_string(path_escaped, NULL);
			g_free(path_escaped);
		} else {
			g_string_append(string, line);
		}
	}

	g_object_unref(input);

	/* not yet used */
	g_string_free(string, TRUE);

	httpd_commands_handle(connection, path);

	g_free(path);

	if(g_socket_close(socket, &error) == FALSE) {
		g_warning(error->message);
		g_error_free(error);
	}

	return FALSE;
}

gboolean httpd_start() {
	gint port = conf_get_int("audist", "httpd_port");
	if(port <= 0) {
		g_warning("invalid httpd port");
		return FALSE;
	}

	ss = g_threaded_socket_service_new(10);

	if(g_socket_listener_add_inet_port((GSocketListener*)ss, port, NULL, NULL) == FALSE) {
		g_warning("httpd: failed to set port");
		return FALSE;
	}

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

	return TRUE;
}

void httpd_stop() {
	g_socket_service_stop(ss);
	g_object_unref(ss);
	ss = NULL;
}