Imported Upstream version 2.1.10
[platform/upstream/libevent.git] / sample / http-server.c
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 {
104         int port;
105         int iocp;
106         int verbose;
107
108         int unlink;
109         const char *unixsock;
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         const char *docroot = 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(docroot)+2;
226         if (!(whole_path = malloc(len))) {
227                 perror("malloc");
228                 goto err;
229         }
230         evutil_snprintf(whole_path, len, "%s/%s", 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, "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");
355         exit(exit_code);
356 }
357 static struct options
358 parse_opts(int argc, char **argv)
359 {
360         struct options o;
361         int opt;
362
363         memset(&o, 0, sizeof(o));
364
365         while ((opt = getopt(argc, argv, "hp:U:uIv")) != -1) {
366                 switch (opt) {
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;
374                 }
375         }
376
377         if (optind >= argc || (argc-optind) > 1) {
378                 print_usage(stdout, argv[0], 1);
379         }
380
381         return o;
382 }
383
384 static void
385 do_term(int sig, short events, void *arg)
386 {
387         struct event_base *base = arg;
388         event_base_loopbreak(base);
389         fprintf(stderr, "Got %i, Terminating\n", sig);
390 }
391
392 static int
393 display_listen_sock(struct evhttp_bound_socket *handle)
394 {
395         struct sockaddr_storage ss;
396         evutil_socket_t fd;
397         ev_socklen_t socklen = sizeof(ss);
398         char addrbuf[128];
399         void *inaddr;
400         const char *addr;
401         int got_port = -1;
402
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");
407                 return 1;
408         }
409
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;
416         }
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);
420                 return 0;
421         }
422 #endif
423         else {
424                 fprintf(stderr, "Weird address family %d\n",
425                     ss.ss_family);
426                 return 1;
427         }
428
429         addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
430             sizeof(addrbuf));
431         if (addr) {
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);
435         } else {
436                 fprintf(stderr, "evutil_inet_ntop failed\n");
437                 return 1;
438         }
439
440         return 0;
441 }
442
443 int
444 main(int argc, char **argv)
445 {
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);
453         int ret = 0;
454
455 #ifdef _WIN32
456         {
457                 WORD wVersionRequested;
458                 WSADATA wsaData;
459                 wVersionRequested = MAKEWORD(2, 2);
460                 WSAStartup(wVersionRequested, &wsaData);
461         }
462 #else
463         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
464                 ret = 1;
465                 goto err;
466         }
467 #endif
468
469         setbuf(stdout, NULL);
470         setbuf(stderr, NULL);
471
472         /** Read env like in regress */
473         if (o.verbose || getenv("EVENT_DEBUG_LOGGING_ALL"))
474                 event_enable_debug_logging(EVENT_DBG_ALL);
475
476         cfg = event_config_new();
477 #ifdef _WIN32
478         if (o.iocp) {
479 #ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
480                 evthread_use_windows_threads();
481                 event_config_set_num_cpus_hint(cfg, 8);
482 #endif
483                 event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
484         }
485 #endif
486
487         base = event_base_new_with_config(cfg);
488         if (!base) {
489                 fprintf(stderr, "Couldn't create an event_base: exiting\n");
490                 ret = 1;
491         }
492         event_config_free(cfg);
493         cfg = NULL;
494
495         /* Create a new evhttp object to handle requests. */
496         http = evhttp_new(base);
497         if (!http) {
498                 fprintf(stderr, "couldn't create evhttp. Exiting.\n");
499                 ret = 1;
500         }
501
502         /* The /dump URI will dump all requests to stdout and say 200 ok. */
503         evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
504
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]);
508
509         if (o.unixsock) {
510 #ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
511                 struct sockaddr_un addr;
512
513                 if (o.unlink && (unlink(o.unixsock) && errno != ENOENT)) {
514                         perror(o.unixsock);
515                         ret = 1;
516                         goto err;
517                 }
518
519                 addr.sun_family = AF_UNIX;
520                 strcpy(addr.sun_path, o.unixsock);
521
522                 lev = evconnlistener_new_bind(base, NULL, NULL,
523                         LEV_OPT_CLOSE_ON_FREE, -1,
524                         (struct sockaddr *)&addr, sizeof(addr));
525                 if (!lev) {
526                         perror("Cannot create listener");
527                         ret = 1;
528                         goto err;
529                 }
530
531                 handle = evhttp_bind_listener(http, lev);
532                 if (!handle) {
533                         fprintf(stderr, "couldn't bind to %s. Exiting.\n", o.unixsock);
534                         ret = 1;
535                         goto err;
536                 }
537 #else /* !EVENT__HAVE_STRUCT_SOCKADDR_UN */
538                 fprintf(stderr, "-U is not supported on this platform. Exiting.\n");
539                 ret = 1;
540                 goto err;
541 #endif /* EVENT__HAVE_STRUCT_SOCKADDR_UN */
542         }
543         else {
544                 handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", o.port);
545                 if (!handle) {
546                         fprintf(stderr, "couldn't bind to port %d. Exiting.\n", o.port);
547                         ret = 1;
548                         goto err;
549                 }
550         }
551
552         if (display_listen_sock(handle)) {
553                 ret = 1;
554                 goto err;
555         }
556
557         term = evsignal_new(base, SIGINT, do_term, base);
558         if (!term)
559                 goto err;
560         if (event_add(term, NULL))
561                 goto err;
562
563         event_base_dispatch(base);
564
565 #ifdef _WIN32
566         WSACleanup();
567 #endif
568
569 err:
570         if (cfg)
571                 event_config_free(cfg);
572         if (http)
573                 evhttp_free(http);
574         if (term)
575                 event_free(term);
576         if (base)
577                 event_base_free(base);
578
579         return ret;
580 }