summaryrefslogtreecommitdiff
path: root/src/cmd/httpd.c
blob: 2e0b6d0f138794a3ab88cb5a6b3ffe1fe05c363d (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* garbage httpd, just to see if it works
 * easily DoSable (like the rest of the network stack), vulnerable to path traversal, etc */
#include <camellia.h>
#include <camellia/flags.h>
#include <camellia/syscalls.h>
#include <dirent.h>
#include <err.h>
#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

const char *sockpath = "/net/listen/0.0.0.0/tcp/80";
const char *webroot  = "/usr/www";
size_t webrootl;

static void status(FILE *c, const char *code) {
	fprintf(c, "HTTP/1.1 %s\r\n\r\n", code);
}

static void handle(FILE *c) {
	char buf[2048];
	fgets(buf, sizeof buf, c);
	printf("%s", buf);

	if (memcmp(buf, "GET /", 5) != 0) {
		status(c, "400 Bad Request");
		return;
	}
	char *path = buf + 4;
	char *end = strchr(path, ' ');
	if (end) *end = '\0';

	if (strlen(webroot) + strlen(path) + 1 <= sizeof(buf)) {
		memmove(buf + strlen(webroot), path, strlen(path) + 1);
		memcpy(buf, webroot, strlen(webroot));
	}

	hid_t h = camellia_open(buf, OPEN_READ);
	printf("%s, %d\n", buf, h);
	if (h < 0) {
		status(c, "404 Not Found");
		return;
	}

	if (path[strlen(path) - 1] != '/') {
		FILE *f = fdopen(h, "r");
		if (!f) {
			status(c, "500 Internal Server Error");
			return;
		}

		/* regular file */
		status(c, "200 OK");
		for (;;) {
			int len = fread(buf, 1, sizeof buf, f);
			if (len <= 0) break;
			fwrite(buf, 1, len, c);
		}

		fclose(f);
	} else {
		/* directory listing */
		DIR *dir = opendir_f(fdopen(h, "r"));
		if (!dir) {
			status(c, "500 Internal Server Error");
			return;
		}

		fprintf(c,
			"HTTP/1.1 200 OK\r\n"
			"Content-Type: text/html; charset=UTF-8\r\n"
			"\r\n"
			"<h1>directory listing for %s</h1><hr>"
			"<ul><li><a href=..>..</a></li>",
			buf
		);

		struct dirent *d;
		while ((d = readdir(dir))) {
			fprintf(c, "<li><a href=\"%s\">%s</a></li>", d->d_name, d->d_name);
		}
		closedir(dir);
	}
}

int main(int argc, char **argv) {
	int c;
	optind = 0;

	while ((c = getopt(argc, argv, "a:r:")) != -1) {
		switch (c) {
		case 'a':
			sockpath = optarg;
			break;
		case 'r':
			webroot = optarg;
			break;
		default:
			fprintf(stderr, "usage: httpd [-a /net/listen/IP/tcp/PORT] [-r path]\n");
			return 1;
		}
	}

	for (;;) {
		hid_t conn = camellia_open(sockpath, OPEN_RW);
		if (conn < 0) {
			errx(1, "open('%s') failed, errno %d", sockpath, -conn);
		}
		FILE *f = fdopen(conn, "a+");
		handle(f);
		fclose(f);
	}
}