xref: /netbsd-src/external/bsd/libevent/dist/sample/http-server.c (revision 404ee5b9334f618040b6cdef96a0ff35a6fc4636)
1 /*	$NetBSD: http-server.c,v 1.1.1.3 2017/01/31 21:14:53 christos Exp $	*/
2 /*
3   A trivial static http webserver using Libevent's evhttp.
4 
5   This is not the best code in the world, and it does some fairly stupid stuff
6   that you would never want to do in a production webserver. Caveat hackor!
7 
8  */
9 
10 /* Compatibility for possible missing IPv6 declarations */
11 #include "../util-internal.h"
12 
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 
20 #ifdef _WIN32
21 #include <winsock2.h>
22 #include <ws2tcpip.h>
23 #include <windows.h>
24 #include <io.h>
25 #include <fcntl.h>
26 #ifndef S_ISDIR
27 #define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
28 #endif
29 #else
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <signal.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <dirent.h>
36 #endif
37 
38 #include <event2/event.h>
39 #include <event2/http.h>
40 #include <event2/buffer.h>
41 #include <event2/util.h>
42 #include <event2/keyvalq_struct.h>
43 
44 #ifdef EVENT__HAVE_NETINET_IN_H
45 #include <netinet/in.h>
46 # ifdef _XOPEN_SOURCE_EXTENDED
47 #  include <arpa/inet.h>
48 # endif
49 #endif
50 
51 #ifdef _WIN32
52 #ifndef stat
53 #define stat _stat
54 #endif
55 #ifndef fstat
56 #define fstat _fstat
57 #endif
58 #ifndef open
59 #define open _open
60 #endif
61 #ifndef close
62 #define close _close
63 #endif
64 #ifndef O_RDONLY
65 #define O_RDONLY _O_RDONLY
66 #endif
67 #endif
68 
69 char uri_root[512];
70 
71 static const struct table_entry {
72 	const char *extension;
73 	const char *content_type;
74 } content_type_table[] = {
75 	{ "txt", "text/plain" },
76 	{ "c", "text/plain" },
77 	{ "h", "text/plain" },
78 	{ "html", "text/html" },
79 	{ "htm", "text/htm" },
80 	{ "css", "text/css" },
81 	{ "gif", "image/gif" },
82 	{ "jpg", "image/jpeg" },
83 	{ "jpeg", "image/jpeg" },
84 	{ "png", "image/png" },
85 	{ "pdf", "application/pdf" },
86 	{ "ps", "application/postscript" },
87 	{ NULL, NULL },
88 };
89 
90 /* Try to guess a good content-type for 'path' */
91 static const char *
92 guess_content_type(const char *path)
93 {
94 	const char *last_period, *extension;
95 	const struct table_entry *ent;
96 	last_period = strrchr(path, '.');
97 	if (!last_period || strchr(last_period, '/'))
98 		goto not_found; /* no exension */
99 	extension = last_period + 1;
100 	for (ent = &content_type_table[0]; ent->extension; ++ent) {
101 		if (!evutil_ascii_strcasecmp(ent->extension, extension))
102 			return ent->content_type;
103 	}
104 
105 not_found:
106 	return "application/misc";
107 }
108 
109 /* Callback used for the /dump URI, and for every non-GET request:
110  * dumps all information to stdout and gives back a trivial 200 ok */
111 static void
112 dump_request_cb(struct evhttp_request *req, void *arg)
113 {
114 	const char *cmdtype;
115 	struct evkeyvalq *headers;
116 	struct evkeyval *header;
117 	struct evbuffer *buf;
118 
119 	switch (evhttp_request_get_command(req)) {
120 	case EVHTTP_REQ_GET: cmdtype = "GET"; break;
121 	case EVHTTP_REQ_POST: cmdtype = "POST"; break;
122 	case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
123 	case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
124 	case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
125 	case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
126 	case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
127 	case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
128 	case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
129 	default: cmdtype = "unknown"; break;
130 	}
131 
132 	printf("Received a %s request for %s\nHeaders:\n",
133 	    cmdtype, evhttp_request_get_uri(req));
134 
135 	headers = evhttp_request_get_input_headers(req);
136 	for (header = headers->tqh_first; header;
137 	    header = header->next.tqe_next) {
138 		printf("  %s: %s\n", header->key, header->value);
139 	}
140 
141 	buf = evhttp_request_get_input_buffer(req);
142 	puts("Input data: <<<");
143 	while (evbuffer_get_length(buf)) {
144 		int n;
145 		char cbuf[128];
146 		n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
147 		if (n > 0)
148 			(void) fwrite(cbuf, 1, n, stdout);
149 	}
150 	puts(">>>");
151 
152 	evhttp_send_reply(req, 200, "OK", NULL);
153 }
154 
155 /* This callback gets invoked when we get any http request that doesn't match
156  * any other callback.  Like any evhttp server callback, it has a simple job:
157  * it must eventually call evhttp_send_error() or evhttp_send_reply().
158  */
159 static void
160 send_document_cb(struct evhttp_request *req, void *arg)
161 {
162 	struct evbuffer *evb = NULL;
163 	const char *docroot = arg;
164 	const char *uri = evhttp_request_get_uri(req);
165 	struct evhttp_uri *decoded = NULL;
166 	const char *path;
167 	char *decoded_path;
168 	char *whole_path = NULL;
169 	size_t len;
170 	int fd = -1;
171 	struct stat st;
172 
173 	if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
174 		dump_request_cb(req, arg);
175 		return;
176 	}
177 
178 	printf("Got a GET request for <%s>\n",  uri);
179 
180 	/* Decode the URI */
181 	decoded = evhttp_uri_parse(uri);
182 	if (!decoded) {
183 		printf("It's not a good URI. Sending BADREQUEST\n");
184 		evhttp_send_error(req, HTTP_BADREQUEST, 0);
185 		return;
186 	}
187 
188 	/* Let's see what path the user asked for. */
189 	path = evhttp_uri_get_path(decoded);
190 	if (!path) path = "/";
191 
192 	/* We need to decode it, to see what path the user really wanted. */
193 	decoded_path = evhttp_uridecode(path, 0, NULL);
194 	if (decoded_path == NULL)
195 		goto err;
196 	/* Don't allow any ".."s in the path, to avoid exposing stuff outside
197 	 * of the docroot.  This test is both overzealous and underzealous:
198 	 * it forbids aceptable paths like "/this/one..here", but it doesn't
199 	 * do anything to prevent symlink following." */
200 	if (strstr(decoded_path, ".."))
201 		goto err;
202 
203 	len = strlen(decoded_path)+strlen(docroot)+2;
204 	if (!(whole_path = malloc(len))) {
205 		perror("malloc");
206 		goto err;
207 	}
208 	evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
209 
210 	if (stat(whole_path, &st)<0) {
211 		goto err;
212 	}
213 
214 	/* This holds the content we're sending. */
215 	evb = evbuffer_new();
216 
217 	if (S_ISDIR(st.st_mode)) {
218 		/* If it's a directory, read the comments and make a little
219 		 * index page */
220 #ifdef _WIN32
221 		HANDLE d;
222 		WIN32_FIND_DATAA ent;
223 		char *pattern;
224 		size_t dirlen;
225 #else
226 		DIR *d;
227 		struct dirent *ent;
228 #endif
229 		const char *trailing_slash = "";
230 
231 		if (!strlen(path) || path[strlen(path)-1] != '/')
232 			trailing_slash = "/";
233 
234 #ifdef _WIN32
235 		dirlen = strlen(whole_path);
236 		pattern = malloc(dirlen+3);
237 		memcpy(pattern, whole_path, dirlen);
238 		pattern[dirlen] = '\\';
239 		pattern[dirlen+1] = '*';
240 		pattern[dirlen+2] = '\0';
241 		d = FindFirstFileA(pattern, &ent);
242 		free(pattern);
243 		if (d == INVALID_HANDLE_VALUE)
244 			goto err;
245 #else
246 		if (!(d = opendir(whole_path)))
247 			goto err;
248 #endif
249 
250 		evbuffer_add_printf(evb,
251                     "<!DOCTYPE html>\n"
252                     "<html>\n <head>\n"
253                     "  <meta charset='utf-8'>\n"
254 		    "  <title>%s</title>\n"
255 		    "  <base href='%s%s'>\n"
256 		    " </head>\n"
257 		    " <body>\n"
258 		    "  <h1>%s</h1>\n"
259 		    "  <ul>\n",
260 		    decoded_path, /* XXX html-escape this. */
261 		    path, /* XXX html-escape this? */
262 		    trailing_slash,
263 		    decoded_path /* XXX html-escape this */);
264 #ifdef _WIN32
265 		do {
266 			const char *name = ent.cFileName;
267 #else
268 		while ((ent = readdir(d))) {
269 			const char *name = ent->d_name;
270 #endif
271 			evbuffer_add_printf(evb,
272 			    "    <li><a href=\"%s\">%s</a>\n",
273 			    name, name);/* XXX escape this */
274 #ifdef _WIN32
275 		} while (FindNextFileA(d, &ent));
276 #else
277 		}
278 #endif
279 		evbuffer_add_printf(evb, "</ul></body></html>\n");
280 #ifdef _WIN32
281 		FindClose(d);
282 #else
283 		closedir(d);
284 #endif
285 		evhttp_add_header(evhttp_request_get_output_headers(req),
286 		    "Content-Type", "text/html");
287 	} else {
288 		/* Otherwise it's a file; add it to the buffer to get
289 		 * sent via sendfile */
290 		const char *type = guess_content_type(decoded_path);
291 		if ((fd = open(whole_path, O_RDONLY)) < 0) {
292 			perror("open");
293 			goto err;
294 		}
295 
296 		if (fstat(fd, &st)<0) {
297 			/* Make sure the length still matches, now that we
298 			 * opened the file :/ */
299 			perror("fstat");
300 			goto err;
301 		}
302 		evhttp_add_header(evhttp_request_get_output_headers(req),
303 		    "Content-Type", type);
304 		evbuffer_add_file(evb, fd, 0, st.st_size);
305 	}
306 
307 	evhttp_send_reply(req, 200, "OK", evb);
308 	goto done;
309 err:
310 	evhttp_send_error(req, 404, "Document was not found");
311 	if (fd>=0)
312 		close(fd);
313 done:
314 	if (decoded)
315 		evhttp_uri_free(decoded);
316 	if (decoded_path)
317 		free(decoded_path);
318 	if (whole_path)
319 		free(whole_path);
320 	if (evb)
321 		evbuffer_free(evb);
322 }
323 
324 static void
325 syntax(void)
326 {
327 	fprintf(stdout, "Syntax: http-server <docroot>\n");
328 }
329 
330 int
331 main(int argc, char **argv)
332 {
333 	struct event_base *base;
334 	struct evhttp *http;
335 	struct evhttp_bound_socket *handle;
336 
337 	ev_uint16_t port = 0;
338 #ifdef _WIN32
339 	WSADATA WSAData;
340 	WSAStartup(0x101, &WSAData);
341 #else
342 	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
343 		return (1);
344 #endif
345 	if (argc < 2) {
346 		syntax();
347 		return 1;
348 	}
349 
350 	base = event_base_new();
351 	if (!base) {
352 		fprintf(stderr, "Couldn't create an event_base: exiting\n");
353 		return 1;
354 	}
355 
356 	/* Create a new evhttp object to handle requests. */
357 	http = evhttp_new(base);
358 	if (!http) {
359 		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
360 		return 1;
361 	}
362 
363 	/* The /dump URI will dump all requests to stdout and say 200 ok. */
364 	evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
365 
366 	/* We want to accept arbitrary requests, so we need to set a "generic"
367 	 * cb.  We can also add callbacks for specific paths. */
368 	evhttp_set_gencb(http, send_document_cb, argv[1]);
369 
370 	/* Now we tell the evhttp what port to listen on */
371 	handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
372 	if (!handle) {
373 		fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
374 		    (int)port);
375 		return 1;
376 	}
377 
378 	{
379 		/* Extract and display the address we're listening on. */
380 		struct sockaddr_storage ss;
381 		evutil_socket_t fd;
382 		ev_socklen_t socklen = sizeof(ss);
383 		char addrbuf[128];
384 		void *inaddr;
385 		const char *addr;
386 		int got_port = -1;
387 		fd = evhttp_bound_socket_get_fd(handle);
388 		memset(&ss, 0, sizeof(ss));
389 		if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
390 			perror("getsockname() failed");
391 			return 1;
392 		}
393 		if (ss.ss_family == AF_INET) {
394 			got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
395 			inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
396 		} else if (ss.ss_family == AF_INET6) {
397 			got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
398 			inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
399 		} else {
400 			fprintf(stderr, "Weird address family %d\n",
401 			    ss.ss_family);
402 			return 1;
403 		}
404 		addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
405 		    sizeof(addrbuf));
406 		if (addr) {
407 			printf("Listening on %s:%d\n", addr, got_port);
408 			evutil_snprintf(uri_root, sizeof(uri_root),
409 			    "http://%s:%d",addr,got_port);
410 		} else {
411 			fprintf(stderr, "evutil_inet_ntop failed\n");
412 			return 1;
413 		}
414 	}
415 
416 	event_base_dispatch(base);
417 
418 	return 0;
419 }
420