xref: /freebsd/contrib/libevent/sample/http-server.c (revision 1db64f89363c97858961c4df0b7d02f3223723cf)
1 /*
2   A trivial static http webserver using Libevent's evhttp.
3 
4   This is not the best code in the world, and it does some fairly stupid stuff
5   that you would never want to do in a production webserver. Caveat hackor!
6 
7  */
8 
9 /* Compatibility for possible missing IPv6 declarations */
10 #include "../util-internal.h"
11 
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 
19 #ifdef _WIN32
20 #include <winsock2.h>
21 #include <ws2tcpip.h>
22 #include <windows.h>
23 #include <getopt.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 /* !_WIN32 */
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <dirent.h>
35 #endif /* _WIN32 */
36 #include <signal.h>
37 
38 #ifdef EVENT__HAVE_SYS_UN_H
39 #include <sys/un.h>
40 #endif
41 #ifdef EVENT__HAVE_AFUNIX_H
42 #include <afunix.h>
43 #endif
44 
45 #include <event2/event.h>
46 #include <event2/http.h>
47 #include <event2/listener.h>
48 #include <event2/buffer.h>
49 #include <event2/util.h>
50 #include <event2/keyvalq_struct.h>
51 
52 #ifdef _WIN32
53 #include <event2/thread.h>
54 #endif /* _WIN32 */
55 
56 #ifdef EVENT__HAVE_NETINET_IN_H
57 #include <netinet/in.h>
58 # ifdef _XOPEN_SOURCE_EXTENDED
59 #  include <arpa/inet.h>
60 # endif
61 #endif
62 
63 #ifdef _WIN32
64 #ifndef stat
65 #define stat _stat
66 #endif
67 #ifndef fstat
68 #define fstat _fstat
69 #endif
70 #ifndef open
71 #define open _open
72 #endif
73 #ifndef close
74 #define close _close
75 #endif
76 #ifndef O_RDONLY
77 #define O_RDONLY _O_RDONLY
78 #endif
79 #endif /* _WIN32 */
80 
81 char uri_root[512];
82 
83 static const struct table_entry {
84 	const char *extension;
85 	const char *content_type;
86 } content_type_table[] = {
87 	{ "txt", "text/plain" },
88 	{ "c", "text/plain" },
89 	{ "h", "text/plain" },
90 	{ "html", "text/html" },
91 	{ "htm", "text/htm" },
92 	{ "css", "text/css" },
93 	{ "gif", "image/gif" },
94 	{ "jpg", "image/jpeg" },
95 	{ "jpeg", "image/jpeg" },
96 	{ "png", "image/png" },
97 	{ "pdf", "application/pdf" },
98 	{ "ps", "application/postscript" },
99 	{ NULL, NULL },
100 };
101 
102 struct options {
103 	int port;
104 	int iocp;
105 	int verbose;
106 
107 	int unlink;
108 	const char *unixsock;
109 	const char *docroot;
110 };
111 
112 /* Try to guess a good content-type for 'path' */
113 static const char *
114 guess_content_type(const char *path)
115 {
116 	const char *last_period, *extension;
117 	const struct table_entry *ent;
118 	last_period = strrchr(path, '.');
119 	if (!last_period || strchr(last_period, '/'))
120 		goto not_found; /* no exension */
121 	extension = last_period + 1;
122 	for (ent = &content_type_table[0]; ent->extension; ++ent) {
123 		if (!evutil_ascii_strcasecmp(ent->extension, extension))
124 			return ent->content_type;
125 	}
126 
127 not_found:
128 	return "application/misc";
129 }
130 
131 /* Callback used for the /dump URI, and for every non-GET request:
132  * dumps all information to stdout and gives back a trivial 200 ok */
133 static void
134 dump_request_cb(struct evhttp_request *req, void *arg)
135 {
136 	const char *cmdtype;
137 	struct evkeyvalq *headers;
138 	struct evkeyval *header;
139 	struct evbuffer *buf;
140 
141 	switch (evhttp_request_get_command(req)) {
142 	case EVHTTP_REQ_GET: cmdtype = "GET"; break;
143 	case EVHTTP_REQ_POST: cmdtype = "POST"; break;
144 	case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
145 	case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
146 	case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
147 	case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
148 	case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
149 	case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
150 	case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
151 	default: cmdtype = "unknown"; break;
152 	}
153 
154 	printf("Received a %s request for %s\nHeaders:\n",
155 	    cmdtype, evhttp_request_get_uri(req));
156 
157 	headers = evhttp_request_get_input_headers(req);
158 	for (header = headers->tqh_first; header;
159 	    header = header->next.tqe_next) {
160 		printf("  %s: %s\n", header->key, header->value);
161 	}
162 
163 	buf = evhttp_request_get_input_buffer(req);
164 	puts("Input data: <<<");
165 	while (evbuffer_get_length(buf)) {
166 		int n;
167 		char cbuf[128];
168 		n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
169 		if (n > 0)
170 			(void) fwrite(cbuf, 1, n, stdout);
171 	}
172 	puts(">>>");
173 
174 	evhttp_send_reply(req, 200, "OK", NULL);
175 }
176 
177 /* This callback gets invoked when we get any http request that doesn't match
178  * any other callback.  Like any evhttp server callback, it has a simple job:
179  * it must eventually call evhttp_send_error() or evhttp_send_reply().
180  */
181 static void
182 send_document_cb(struct evhttp_request *req, void *arg)
183 {
184 	struct evbuffer *evb = NULL;
185 	struct options *o = arg;
186 	const char *uri = evhttp_request_get_uri(req);
187 	struct evhttp_uri *decoded = NULL;
188 	const char *path;
189 	char *decoded_path;
190 	char *whole_path = NULL;
191 	size_t len;
192 	int fd = -1;
193 	struct stat st;
194 
195 	if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
196 		dump_request_cb(req, arg);
197 		return;
198 	}
199 
200 	printf("Got a GET request for <%s>\n",  uri);
201 
202 	/* Decode the URI */
203 	decoded = evhttp_uri_parse(uri);
204 	if (!decoded) {
205 		printf("It's not a good URI. Sending BADREQUEST\n");
206 		evhttp_send_error(req, HTTP_BADREQUEST, 0);
207 		return;
208 	}
209 
210 	/* Let's see what path the user asked for. */
211 	path = evhttp_uri_get_path(decoded);
212 	if (!path) path = "/";
213 
214 	/* We need to decode it, to see what path the user really wanted. */
215 	decoded_path = evhttp_uridecode(path, 0, NULL);
216 	if (decoded_path == NULL)
217 		goto err;
218 	/* Don't allow any ".."s in the path, to avoid exposing stuff outside
219 	 * of the docroot.  This test is both overzealous and underzealous:
220 	 * it forbids aceptable paths like "/this/one..here", but it doesn't
221 	 * do anything to prevent symlink following." */
222 	if (strstr(decoded_path, ".."))
223 		goto err;
224 
225 	len = strlen(decoded_path)+strlen(o->docroot)+2;
226 	if (!(whole_path = malloc(len))) {
227 		perror("malloc");
228 		goto err;
229 	}
230 	evutil_snprintf(whole_path, len, "%s/%s", o->docroot, decoded_path);
231 
232 	if (stat(whole_path, &st)<0) {
233 		goto err;
234 	}
235 
236 	/* This holds the content we're sending. */
237 	evb = evbuffer_new();
238 
239 	if (S_ISDIR(st.st_mode)) {
240 		/* If it's a directory, read the comments and make a little
241 		 * index page */
242 #ifdef _WIN32
243 		HANDLE d;
244 		WIN32_FIND_DATAA ent;
245 		char *pattern;
246 		size_t dirlen;
247 #else
248 		DIR *d;
249 		struct dirent *ent;
250 #endif
251 		const char *trailing_slash = "";
252 
253 		if (!strlen(path) || path[strlen(path)-1] != '/')
254 			trailing_slash = "/";
255 
256 #ifdef _WIN32
257 		dirlen = strlen(whole_path);
258 		pattern = malloc(dirlen+3);
259 		memcpy(pattern, whole_path, dirlen);
260 		pattern[dirlen] = '\\';
261 		pattern[dirlen+1] = '*';
262 		pattern[dirlen+2] = '\0';
263 		d = FindFirstFileA(pattern, &ent);
264 		free(pattern);
265 		if (d == INVALID_HANDLE_VALUE)
266 			goto err;
267 #else
268 		if (!(d = opendir(whole_path)))
269 			goto err;
270 #endif
271 
272 		evbuffer_add_printf(evb,
273                     "<!DOCTYPE html>\n"
274                     "<html>\n <head>\n"
275                     "  <meta charset='utf-8'>\n"
276 		    "  <title>%s</title>\n"
277 		    "  <base href='%s%s'>\n"
278 		    " </head>\n"
279 		    " <body>\n"
280 		    "  <h1>%s</h1>\n"
281 		    "  <ul>\n",
282 		    decoded_path, /* XXX html-escape this. */
283 		    path, /* XXX html-escape this? */
284 		    trailing_slash,
285 		    decoded_path /* XXX html-escape this */);
286 #ifdef _WIN32
287 		do {
288 			const char *name = ent.cFileName;
289 #else
290 		while ((ent = readdir(d))) {
291 			const char *name = ent->d_name;
292 #endif
293 			evbuffer_add_printf(evb,
294 			    "    <li><a href=\"%s\">%s</a>\n",
295 			    name, name);/* XXX escape this */
296 #ifdef _WIN32
297 		} while (FindNextFileA(d, &ent));
298 #else
299 		}
300 #endif
301 		evbuffer_add_printf(evb, "</ul></body></html>\n");
302 #ifdef _WIN32
303 		FindClose(d);
304 #else
305 		closedir(d);
306 #endif
307 		evhttp_add_header(evhttp_request_get_output_headers(req),
308 		    "Content-Type", "text/html");
309 	} else {
310 		/* Otherwise it's a file; add it to the buffer to get
311 		 * sent via sendfile */
312 		const char *type = guess_content_type(decoded_path);
313 		if ((fd = open(whole_path, O_RDONLY)) < 0) {
314 			perror("open");
315 			goto err;
316 		}
317 
318 		if (fstat(fd, &st)<0) {
319 			/* Make sure the length still matches, now that we
320 			 * opened the file :/ */
321 			perror("fstat");
322 			goto err;
323 		}
324 		evhttp_add_header(evhttp_request_get_output_headers(req),
325 		    "Content-Type", type);
326 		evbuffer_add_file(evb, fd, 0, st.st_size);
327 	}
328 
329 	evhttp_send_reply(req, 200, "OK", evb);
330 	goto done;
331 err:
332 	evhttp_send_error(req, 404, "Document was not found");
333 	if (fd>=0)
334 		close(fd);
335 done:
336 	if (decoded)
337 		evhttp_uri_free(decoded);
338 	if (decoded_path)
339 		free(decoded_path);
340 	if (whole_path)
341 		free(whole_path);
342 	if (evb)
343 		evbuffer_free(evb);
344 }
345 
346 static void
347 print_usage(FILE *out, const char *prog, int exit_code)
348 {
349 	fprintf(out,
350 		"Syntax: %s [ OPTS ] <docroot>\n"
351 		" -p      - port\n"
352 		" -U      - bind to unix socket\n"
353 		" -u      - unlink unix socket before bind\n"
354 		" -I      - IOCP\n"
355 		" -v      - verbosity, enables libevent debug logging too\n", prog);
356 	exit(exit_code);
357 }
358 static struct options
359 parse_opts(int argc, char **argv)
360 {
361 	struct options o;
362 	int opt;
363 
364 	memset(&o, 0, sizeof(o));
365 
366 	while ((opt = getopt(argc, argv, "hp:U:uIv")) != -1) {
367 		switch (opt) {
368 			case 'p': o.port = atoi(optarg); break;
369 			case 'U': o.unixsock = optarg; break;
370 			case 'u': o.unlink = 1; break;
371 			case 'I': o.iocp = 1; break;
372 			case 'v': ++o.verbose; break;
373 			case 'h': print_usage(stdout, argv[0], 0); break;
374 			default : fprintf(stderr, "Unknown option %c\n", opt); break;
375 		}
376 	}
377 
378 	if (optind >= argc || (argc - optind) > 1) {
379 		print_usage(stdout, argv[0], 1);
380 	}
381 	o.docroot = argv[optind];
382 
383 	return o;
384 }
385 
386 static void
387 do_term(int sig, short events, void *arg)
388 {
389 	struct event_base *base = arg;
390 	event_base_loopbreak(base);
391 	fprintf(stderr, "Got %i, Terminating\n", sig);
392 }
393 
394 static int
395 display_listen_sock(struct evhttp_bound_socket *handle)
396 {
397 	struct sockaddr_storage ss;
398 	evutil_socket_t fd;
399 	ev_socklen_t socklen = sizeof(ss);
400 	char addrbuf[128];
401 	void *inaddr;
402 	const char *addr;
403 	int got_port = -1;
404 
405 	fd = evhttp_bound_socket_get_fd(handle);
406 	memset(&ss, 0, sizeof(ss));
407 	if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
408 		perror("getsockname() failed");
409 		return 1;
410 	}
411 
412 	if (ss.ss_family == AF_INET) {
413 		got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
414 		inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
415 	} else if (ss.ss_family == AF_INET6) {
416 		got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
417 		inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
418 	}
419 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
420 	else if (ss.ss_family == AF_UNIX) {
421 		printf("Listening on <%s>\n", ((struct sockaddr_un*)&ss)->sun_path);
422 		return 0;
423 	}
424 #endif
425 	else {
426 		fprintf(stderr, "Weird address family %d\n",
427 		    ss.ss_family);
428 		return 1;
429 	}
430 
431 	addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
432 	    sizeof(addrbuf));
433 	if (addr) {
434 		printf("Listening on %s:%d\n", addr, got_port);
435 		evutil_snprintf(uri_root, sizeof(uri_root),
436 		    "http://%s:%d",addr,got_port);
437 	} else {
438 		fprintf(stderr, "evutil_inet_ntop failed\n");
439 		return 1;
440 	}
441 
442 	return 0;
443 }
444 
445 int
446 main(int argc, char **argv)
447 {
448 	struct event_config *cfg = NULL;
449 	struct event_base *base = NULL;
450 	struct evhttp *http = NULL;
451 	struct evhttp_bound_socket *handle = NULL;
452 	struct evconnlistener *lev = NULL;
453 	struct event *term = NULL;
454 	struct options o = parse_opts(argc, argv);
455 	int ret = 0;
456 
457 #ifdef _WIN32
458 	{
459 		WORD wVersionRequested;
460 		WSADATA wsaData;
461 		wVersionRequested = MAKEWORD(2, 2);
462 		WSAStartup(wVersionRequested, &wsaData);
463 	}
464 #else
465 	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
466 		ret = 1;
467 		goto err;
468 	}
469 #endif
470 
471 	setbuf(stdout, NULL);
472 	setbuf(stderr, NULL);
473 
474 	/** Read env like in regress */
475 	if (o.verbose || getenv("EVENT_DEBUG_LOGGING_ALL"))
476 		event_enable_debug_logging(EVENT_DBG_ALL);
477 
478 	cfg = event_config_new();
479 #ifdef _WIN32
480 	if (o.iocp) {
481 #ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
482 		evthread_use_windows_threads();
483 		event_config_set_num_cpus_hint(cfg, 8);
484 #endif
485 		event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
486 	}
487 #endif
488 
489 	base = event_base_new_with_config(cfg);
490 	if (!base) {
491 		fprintf(stderr, "Couldn't create an event_base: exiting\n");
492 		ret = 1;
493 	}
494 	event_config_free(cfg);
495 	cfg = NULL;
496 
497 	/* Create a new evhttp object to handle requests. */
498 	http = evhttp_new(base);
499 	if (!http) {
500 		fprintf(stderr, "couldn't create evhttp. Exiting.\n");
501 		ret = 1;
502 	}
503 
504 	/* The /dump URI will dump all requests to stdout and say 200 ok. */
505 	evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
506 
507 	/* We want to accept arbitrary requests, so we need to set a "generic"
508 	 * cb.  We can also add callbacks for specific paths. */
509 	evhttp_set_gencb(http, send_document_cb, &o);
510 
511 	if (o.unixsock) {
512 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
513 		struct sockaddr_un addr;
514 
515 		if (o.unlink && (unlink(o.unixsock) && errno != ENOENT)) {
516 			perror(o.unixsock);
517 			ret = 1;
518 			goto err;
519 		}
520 
521 		addr.sun_family = AF_UNIX;
522 		strcpy(addr.sun_path, o.unixsock);
523 
524 		lev = evconnlistener_new_bind(base, NULL, NULL,
525 			LEV_OPT_CLOSE_ON_FREE, -1,
526 			(struct sockaddr *)&addr, sizeof(addr));
527 		if (!lev) {
528 			perror("Cannot create listener");
529 			ret = 1;
530 			goto err;
531 		}
532 
533 		handle = evhttp_bind_listener(http, lev);
534 		if (!handle) {
535 			fprintf(stderr, "couldn't bind to %s. Exiting.\n", o.unixsock);
536 			ret = 1;
537 			goto err;
538 		}
539 #else /* !EVENT__HAVE_STRUCT_SOCKADDR_UN */
540 		fprintf(stderr, "-U is not supported on this platform. Exiting.\n");
541 		ret = 1;
542 		goto err;
543 #endif /* EVENT__HAVE_STRUCT_SOCKADDR_UN */
544 	}
545 	else {
546 		handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", o.port);
547 		if (!handle) {
548 			fprintf(stderr, "couldn't bind to port %d. Exiting.\n", o.port);
549 			ret = 1;
550 			goto err;
551 		}
552 	}
553 
554 	if (display_listen_sock(handle)) {
555 		ret = 1;
556 		goto err;
557 	}
558 
559 	term = evsignal_new(base, SIGINT, do_term, base);
560 	if (!term)
561 		goto err;
562 	if (event_add(term, NULL))
563 		goto err;
564 
565 	event_base_dispatch(base);
566 
567 #ifdef _WIN32
568 	WSACleanup();
569 #endif
570 
571 err:
572 	if (cfg)
573 		event_config_free(cfg);
574 	if (http)
575 		evhttp_free(http);
576 	if (term)
577 		event_free(term);
578 	if (base)
579 		event_base_free(base);
580 
581 	return ret;
582 }
583