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!
13 #include <sys/types.h>
23 #define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
27 #include <sys/socket.h>
34 #include <event2/event.h>
35 #include <event2/http.h>
36 #include <event2/buffer.h>
37 #include <event2/util.h>
38 #include <event2/keyvalq_struct.h>
40 #ifdef _EVENT_HAVE_NETINET_IN_H
41 #include <netinet/in.h>
42 # ifdef _XOPEN_SOURCE_EXTENDED
43 # include <arpa/inet.h>
47 /* Compatibility for possible missing IPv6 declarations */
48 #include "../util-internal.h"
55 #define O_RDONLY _O_RDONLY
60 static const struct table_entry {
61 const char *extension;
62 const char *content_type;
63 } content_type_table[] = {
64 { "txt", "text/plain" },
65 { "c", "text/plain" },
66 { "h", "text/plain" },
67 { "html", "text/html" },
68 { "htm", "text/htm" },
69 { "css", "text/css" },
70 { "gif", "image/gif" },
71 { "jpg", "image/jpeg" },
72 { "jpeg", "image/jpeg" },
73 { "png", "image/png" },
74 { "pdf", "application/pdf" },
75 { "ps", "application/postsript" },
79 /* Try to guess a good content-type for 'path' */
81 guess_content_type(const char *path)
83 const char *last_period, *extension;
84 const struct table_entry *ent;
85 last_period = strrchr(path, '.');
86 if (!last_period || strchr(last_period, '/'))
87 goto not_found; /* no exension */
88 extension = last_period + 1;
89 for (ent = &content_type_table[0]; ent->extension; ++ent) {
90 if (!evutil_ascii_strcasecmp(ent->extension, extension))
91 return ent->content_type;
95 return "application/misc";
98 /* Callback used for the /dump URI, and for every non-GET request:
99 * dumps all information to stdout and gives back a trivial 200 ok */
101 dump_request_cb(struct evhttp_request *req, void *arg)
104 struct evkeyvalq *headers;
105 struct evkeyval *header;
106 struct evbuffer *buf;
108 switch (evhttp_request_get_command(req)) {
109 case EVHTTP_REQ_GET: cmdtype = "GET"; break;
110 case EVHTTP_REQ_POST: cmdtype = "POST"; break;
111 case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
112 case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
113 case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
114 case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
115 case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
116 case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
117 case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
118 default: cmdtype = "unknown"; break;
121 printf("Received a %s request for %s\nHeaders:\n",
122 cmdtype, evhttp_request_get_uri(req));
124 headers = evhttp_request_get_input_headers(req);
125 for (header = headers->tqh_first; header;
126 header = header->next.tqe_next) {
127 printf(" %s: %s\n", header->key, header->value);
130 buf = evhttp_request_get_input_buffer(req);
131 puts("Input data: <<<");
132 while (evbuffer_get_length(buf)) {
135 n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
136 fwrite(cbuf, 1, n, stdout);
140 evhttp_send_reply(req, 200, "OK", NULL);
143 /* This callback gets invoked when we get any http request that doesn't match
144 * any other callback. Like any evhttp server callback, it has a simple job:
145 * it must eventually call evhttp_send_error() or evhttp_send_reply().
148 send_document_cb(struct evhttp_request *req, void *arg)
150 struct evbuffer *evb = NULL;
151 const char *docroot = arg;
152 const char *uri = evhttp_request_get_uri(req);
153 struct evhttp_uri *decoded = NULL;
156 char *whole_path = NULL;
161 if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
162 dump_request_cb(req, arg);
166 printf("Got a GET request for <%s>\n", uri);
169 decoded = evhttp_uri_parse(uri);
171 printf("It's not a good URI. Sending BADREQUEST\n");
172 evhttp_send_error(req, HTTP_BADREQUEST, 0);
176 /* Let's see what path the user asked for. */
177 path = evhttp_uri_get_path(decoded);
178 if (!path) path = "/";
180 /* We need to decode it, to see what path the user really wanted. */
181 decoded_path = evhttp_uridecode(path, 0, NULL);
182 /* Don't allow any ".."s in the path, to avoid exposing stuff outside
183 * of the docroot. This test is both overzealous and underzealous:
184 * it forbids aceptable paths like "/this/one..here", but it doesn't
185 * do anything to prevent symlink following." */
186 if (strstr(decoded_path, ".."))
189 len = strlen(decoded_path)+strlen(docroot)+2;
190 if (!(whole_path = malloc(len))) {
194 evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
196 if (stat(whole_path, &st)<0) {
200 /* This holds the content we're sending. */
201 evb = evbuffer_new();
203 if (S_ISDIR(st.st_mode)) {
204 /* If it's a directory, read the comments and make a little
208 WIN32_FIND_DATAA ent;
215 const char *trailing_slash = "";
217 if (!strlen(path) || path[strlen(path)-1] != '/')
218 trailing_slash = "/";
221 dirlen = strlen(whole_path);
222 pattern = malloc(dirlen+3);
223 memcpy(pattern, whole_path, dirlen);
224 pattern[dirlen] = '\\';
225 pattern[dirlen+1] = '*';
226 pattern[dirlen+2] = '\0';
227 d = FindFirstFileA(pattern, &ent);
229 if (d == INVALID_HANDLE_VALUE)
232 if (!(d = opendir(whole_path)))
236 evbuffer_add_printf(evb, "<html>\n <head>\n"
237 " <title>%s</title>\n"
238 " <base href='%s%s%s'>\n"
243 decoded_path, /* XXX html-escape this. */
244 uri_root, path, /* XXX html-escape this? */
246 decoded_path /* XXX html-escape this */);
249 const char *name = ent.cFileName;
251 while ((ent = readdir(d))) {
252 const char *name = ent->d_name;
254 evbuffer_add_printf(evb,
255 " <li><a href=\"%s\">%s</a>\n",
256 name, name);/* XXX escape this */
258 } while (FindNextFileA(d, &ent));
262 evbuffer_add_printf(evb, "</ul></body></html>\n");
268 evhttp_add_header(evhttp_request_get_output_headers(req),
269 "Content-Type", "text/html");
271 /* Otherwise it's a file; add it to the buffer to get
272 * sent via sendfile */
273 const char *type = guess_content_type(decoded_path);
274 if ((fd = open(whole_path, O_RDONLY)) < 0) {
279 if (fstat(fd, &st)<0) {
280 /* Make sure the length still matches, now that we
281 * opened the file :/ */
285 evhttp_add_header(evhttp_request_get_output_headers(req),
286 "Content-Type", type);
287 evbuffer_add_file(evb, fd, 0, st.st_size);
290 evhttp_send_reply(req, 200, "OK", evb);
293 evhttp_send_error(req, 404, "Document was not found");
298 evhttp_uri_free(decoded);
310 fprintf(stdout, "Syntax: http-server <docroot>\n");
314 main(int argc, char **argv)
316 struct event_base *base;
318 struct evhttp_bound_socket *handle;
320 unsigned short port = 0;
323 WSAStartup(0x101, &WSAData);
325 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
333 base = event_base_new();
335 fprintf(stderr, "Couldn't create an event_base: exiting\n");
339 /* Create a new evhttp object to handle requests. */
340 http = evhttp_new(base);
342 fprintf(stderr, "couldn't create evhttp. Exiting.\n");
346 /* The /dump URI will dump all requests to stdout and say 200 ok. */
347 evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
349 /* We want to accept arbitrary requests, so we need to set a "generic"
350 * cb. We can also add callbacks for specific paths. */
351 evhttp_set_gencb(http, send_document_cb, argv[1]);
353 /* Now we tell the evhttp what port to listen on */
354 handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
356 fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
362 /* Extract and display the address we're listening on. */
363 struct sockaddr_storage ss;
365 ev_socklen_t socklen = sizeof(ss);
370 fd = evhttp_bound_socket_get_fd(handle);
371 memset(&ss, 0, sizeof(ss));
372 if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
373 perror("getsockname() failed");
376 if (ss.ss_family == AF_INET) {
377 got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
378 inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
379 } else if (ss.ss_family == AF_INET6) {
380 got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
381 inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
383 fprintf(stderr, "Weird address family %d\n",
387 addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
390 printf("Listening on %s:%d\n", addr, got_port);
391 evutil_snprintf(uri_root, sizeof(uri_root),
392 "http://%s:%d",addr,got_port);
394 fprintf(stderr, "evutil_inet_ntop failed\n");
399 event_base_dispatch(base);