2 A trivial static http webserver using Libevent's evhttp.
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!
9 /* Compatibility for possible missing IPv6 declarations */
10 #include "../util-internal.h"
16 #include <sys/types.h>
27 #define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
31 #include <sys/socket.h>
38 #ifdef EVENT__HAVE_SYS_UN_H
41 #ifdef EVENT__HAVE_AFUNIX_H
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>
53 #include <event2/thread.h>
56 #ifdef EVENT__HAVE_NETINET_IN_H
57 #include <netinet/in.h>
58 # ifdef _XOPEN_SOURCE_EXTENDED
59 # include <arpa/inet.h>
77 #define O_RDONLY _O_RDONLY
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" },
109 const char *unixsock;
112 /* Try to guess a good content-type for 'path' */
114 guess_content_type(const char *path)
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;
128 return "application/misc";
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 */
134 dump_request_cb(struct evhttp_request *req, void *arg)
137 struct evkeyvalq *headers;
138 struct evkeyval *header;
139 struct evbuffer *buf;
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;
154 printf("Received a %s request for %s\nHeaders:\n",
155 cmdtype, evhttp_request_get_uri(req));
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);
163 buf = evhttp_request_get_input_buffer(req);
164 puts("Input data: <<<");
165 while (evbuffer_get_length(buf)) {
168 n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
170 (void) fwrite(cbuf, 1, n, stdout);
174 evhttp_send_reply(req, 200, "OK", NULL);
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().
182 send_document_cb(struct evhttp_request *req, void *arg)
184 struct evbuffer *evb = NULL;
185 const char *docroot = arg;
186 const char *uri = evhttp_request_get_uri(req);
187 struct evhttp_uri *decoded = NULL;
190 char *whole_path = NULL;
195 if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
196 dump_request_cb(req, arg);
200 printf("Got a GET request for <%s>\n", uri);
203 decoded = evhttp_uri_parse(uri);
205 printf("It's not a good URI. Sending BADREQUEST\n");
206 evhttp_send_error(req, HTTP_BADREQUEST, 0);
210 /* Let's see what path the user asked for. */
211 path = evhttp_uri_get_path(decoded);
212 if (!path) path = "/";
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)
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, ".."))
225 len = strlen(decoded_path)+strlen(docroot)+2;
226 if (!(whole_path = malloc(len))) {
230 evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
232 if (stat(whole_path, &st)<0) {
236 /* This holds the content we're sending. */
237 evb = evbuffer_new();
239 if (S_ISDIR(st.st_mode)) {
240 /* If it's a directory, read the comments and make a little
244 WIN32_FIND_DATAA ent;
251 const char *trailing_slash = "";
253 if (!strlen(path) || path[strlen(path)-1] != '/')
254 trailing_slash = "/";
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);
265 if (d == INVALID_HANDLE_VALUE)
268 if (!(d = opendir(whole_path)))
272 evbuffer_add_printf(evb,
275 " <meta charset='utf-8'>\n"
276 " <title>%s</title>\n"
277 " <base href='%s%s'>\n"
282 decoded_path, /* XXX html-escape this. */
283 path, /* XXX html-escape this? */
285 decoded_path /* XXX html-escape this */);
288 const char *name = ent.cFileName;
290 while ((ent = readdir(d))) {
291 const char *name = ent->d_name;
293 evbuffer_add_printf(evb,
294 " <li><a href=\"%s\">%s</a>\n",
295 name, name);/* XXX escape this */
297 } while (FindNextFileA(d, &ent));
301 evbuffer_add_printf(evb, "</ul></body></html>\n");
307 evhttp_add_header(evhttp_request_get_output_headers(req),
308 "Content-Type", "text/html");
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) {
318 if (fstat(fd, &st)<0) {
319 /* Make sure the length still matches, now that we
320 * opened the file :/ */
324 evhttp_add_header(evhttp_request_get_output_headers(req),
325 "Content-Type", type);
326 evbuffer_add_file(evb, fd, 0, st.st_size);
329 evhttp_send_reply(req, 200, "OK", evb);
332 evhttp_send_error(req, 404, "Document was not found");
337 evhttp_uri_free(decoded);
347 print_usage(FILE *out, const char *prog, int exit_code)
349 fprintf(out, "Syntax: [ OPTS ] %s <docroot>\n", prog);
350 fprintf(out, " -p - port\n");
351 fprintf(out, " -U - bind to unix socket\n");
352 fprintf(out, " -u - unlink unix socket before bind\n");
353 fprintf(out, " -I - IOCP\n");
354 fprintf(out, " -v - verbosity, enables libevent debug logging too\n");
357 static struct options
358 parse_opts(int argc, char **argv)
363 memset(&o, 0, sizeof(o));
365 while ((opt = getopt(argc, argv, "hp:U:uIv")) != -1) {
367 case 'p': o.port = atoi(optarg); break;
368 case 'U': o.unixsock = optarg; break;
369 case 'u': o.unlink = 1; break;
370 case 'I': o.iocp = 1; break;
371 case 'v': ++o.verbose; break;
372 case 'h': print_usage(stdout, argv[0], 0); break;
373 default : fprintf(stderr, "Unknown option %c\n", opt); break;
377 if (optind >= argc || (argc-optind) > 1) {
378 print_usage(stdout, argv[0], 1);
385 do_term(int sig, short events, void *arg)
387 struct event_base *base = arg;
388 event_base_loopbreak(base);
389 fprintf(stderr, "Got %i, Terminating\n", sig);
393 display_listen_sock(struct evhttp_bound_socket *handle)
395 struct sockaddr_storage ss;
397 ev_socklen_t socklen = sizeof(ss);
403 fd = evhttp_bound_socket_get_fd(handle);
404 memset(&ss, 0, sizeof(ss));
405 if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
406 perror("getsockname() failed");
410 if (ss.ss_family == AF_INET) {
411 got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
412 inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
413 } else if (ss.ss_family == AF_INET6) {
414 got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
415 inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
417 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
418 else if (ss.ss_family == AF_UNIX) {
419 printf("Listening on <%s>\n", ((struct sockaddr_un*)&ss)->sun_path);
424 fprintf(stderr, "Weird address family %d\n",
429 addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
432 printf("Listening on %s:%d\n", addr, got_port);
433 evutil_snprintf(uri_root, sizeof(uri_root),
434 "http://%s:%d",addr,got_port);
436 fprintf(stderr, "evutil_inet_ntop failed\n");
444 main(int argc, char **argv)
446 struct event_config *cfg = NULL;
447 struct event_base *base = NULL;
448 struct evhttp *http = NULL;
449 struct evhttp_bound_socket *handle = NULL;
450 struct evconnlistener *lev = NULL;
451 struct event *term = NULL;
452 struct options o = parse_opts(argc, argv);
457 WORD wVersionRequested;
459 wVersionRequested = MAKEWORD(2, 2);
460 WSAStartup(wVersionRequested, &wsaData);
463 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
469 setbuf(stdout, NULL);
470 setbuf(stderr, NULL);
472 /** Read env like in regress */
473 if (o.verbose || getenv("EVENT_DEBUG_LOGGING_ALL"))
474 event_enable_debug_logging(EVENT_DBG_ALL);
476 cfg = event_config_new();
479 #ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
480 evthread_use_windows_threads();
481 event_config_set_num_cpus_hint(cfg, 8);
483 event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
487 base = event_base_new_with_config(cfg);
489 fprintf(stderr, "Couldn't create an event_base: exiting\n");
492 event_config_free(cfg);
495 /* Create a new evhttp object to handle requests. */
496 http = evhttp_new(base);
498 fprintf(stderr, "couldn't create evhttp. Exiting.\n");
502 /* The /dump URI will dump all requests to stdout and say 200 ok. */
503 evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
505 /* We want to accept arbitrary requests, so we need to set a "generic"
506 * cb. We can also add callbacks for specific paths. */
507 evhttp_set_gencb(http, send_document_cb, argv[1]);
510 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
511 struct sockaddr_un addr;
513 if (o.unlink && (unlink(o.unixsock) && errno != ENOENT)) {
519 addr.sun_family = AF_UNIX;
520 strcpy(addr.sun_path, o.unixsock);
522 lev = evconnlistener_new_bind(base, NULL, NULL,
523 LEV_OPT_CLOSE_ON_FREE, -1,
524 (struct sockaddr *)&addr, sizeof(addr));
526 perror("Cannot create listener");
531 handle = evhttp_bind_listener(http, lev);
533 fprintf(stderr, "couldn't bind to %s. Exiting.\n", o.unixsock);
537 #else /* !EVENT__HAVE_STRUCT_SOCKADDR_UN */
538 fprintf(stderr, "-U is not supported on this platform. Exiting.\n");
541 #endif /* EVENT__HAVE_STRUCT_SOCKADDR_UN */
544 handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", o.port);
546 fprintf(stderr, "couldn't bind to port %d. Exiting.\n", o.port);
552 if (display_listen_sock(handle)) {
557 term = evsignal_new(base, SIGINT, do_term, base);
560 if (event_add(term, NULL))
563 event_base_dispatch(base);
571 event_config_free(cfg);
577 event_base_free(base);