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