]> arthur.barton.de Git - netatalk.git/blob - libevent/sample/http-server.c
Add libevent
[netatalk.git] / libevent / 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 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12
13 #include <sys/types.h>
14 #include <sys/stat.h>
15
16 #ifdef WIN32
17 #include <winsock2.h>
18 #include <ws2tcpip.h>
19 #include <windows.h>
20 #include <io.h>
21 #include <fcntl.h>
22 #else
23 #include <sys/stat.h>
24 #include <sys/socket.h>
25 #include <signal.h>
26 #include <fcntl.h>
27 #include <unistd.h>
28 #include <dirent.h>
29 #endif
30
31 #include <event2/event.h>
32 #include <event2/http.h>
33 #include <event2/buffer.h>
34 #include <event2/util.h>
35 #include <event2/keyvalq_struct.h>
36
37 #ifdef _EVENT_HAVE_NETINET_IN_H
38 #include <netinet/in.h>
39 #endif
40
41 #ifdef WIN32
42 #define stat _stat
43 #define fstat _fstat
44 #define open _open
45 #define close _close
46 #define O_RDONLY _O_RDONLY
47 #endif
48
49 char uri_root[512];
50
51 static const struct table_entry {
52         const char *extension;
53         const char *content_type;
54 } content_type_table[] = {
55         { "txt", "text/plain" },
56         { "c", "text/plain" },
57         { "h", "text/plain" },
58         { "html", "text/html" },
59         { "htm", "text/htm" },
60         { "css", "text/css" },
61         { "gif", "image/gif" },
62         { "jpg", "image/jpeg" },
63         { "jpeg", "image/jpeg" },
64         { "png", "image/png" },
65         { "pdf", "application/pdf" },
66         { "ps", "application/postsript" },
67         { NULL, NULL },
68 };
69
70 /* Try to guess a good content-type for 'path' */
71 static const char *
72 guess_content_type(const char *path)
73 {
74         const char *last_period, *extension;
75         const struct table_entry *ent;
76         last_period = strrchr(path, '.');
77         if (!last_period || strchr(last_period, '/'))
78                 goto not_found; /* no exension */
79         extension = last_period + 1;
80         for (ent = &content_type_table[0]; ent->extension; ++ent) {
81                 if (!evutil_ascii_strcasecmp(ent->extension, extension))
82                         return ent->content_type;
83         }
84
85 not_found:
86         return "application/misc";
87 }
88
89 /* Callback used for the /dump URI, and for every non-GET request:
90  * dumps all information to stdout and gives back a trivial 200 ok */
91 static void
92 dump_request_cb(struct evhttp_request *req, void *arg)
93 {
94         const char *cmdtype;
95         struct evkeyvalq *headers;
96         struct evkeyval *header;
97         struct evbuffer *buf;
98
99         switch (evhttp_request_get_command(req)) {
100         case EVHTTP_REQ_GET: cmdtype = "GET"; break;
101         case EVHTTP_REQ_POST: cmdtype = "POST"; break;
102         case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
103         case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
104         case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
105         case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
106         case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
107         case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
108         case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
109         default: cmdtype = "unknown"; break;
110         }
111
112         printf("Received a %s request for %s\nHeaders:\n",
113             cmdtype, evhttp_request_get_uri(req));
114
115         headers = evhttp_request_get_input_headers(req);
116         for (header = headers->tqh_first; header;
117             header = header->next.tqe_next) {
118                 printf("  %s: %s\n", header->key, header->value);
119         }
120
121         buf = evhttp_request_get_input_buffer(req);
122         puts("Input data: <<<");
123         while (evbuffer_get_length(buf)) {
124                 int n;
125                 char cbuf[128];
126                 n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
127                 fwrite(cbuf, 1, n, stdout);
128         }
129         puts(">>>");
130
131         evhttp_send_reply(req, 200, "OK", NULL);
132 }
133
134 /* This callback gets invoked when we get any http request that doesn't match
135  * any other callback.  Like any evhttp server callback, it has a simple job:
136  * it must eventually call evhttp_send_error() or evhttp_send_reply().
137  */
138 static void
139 send_document_cb(struct evhttp_request *req, void *arg)
140 {
141         struct evbuffer *evb;
142         const char *docroot = arg;
143         const char *uri = evhttp_request_get_uri(req);
144         struct evhttp_uri *decoded = NULL;
145         const char *path;
146         char *decoded_path;
147         char *whole_path = NULL;
148         size_t len;
149         int fd = -1;
150         struct stat st;
151
152         if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
153                 dump_request_cb(req, arg);
154                 return;
155         }
156
157         printf("Got a GET request for <%s>\n",  uri);
158
159         /* Decode the URI */
160         decoded = evhttp_uri_parse(uri);
161         if (!decoded) {
162                 printf("It's not a good URI. Sending BADREQUEST\n");
163                 evhttp_send_error(req, HTTP_BADREQUEST, 0);
164                 return;
165         }
166
167         /* Let's see what path the user asked for. */
168         path = evhttp_uri_get_path(decoded);
169         if (!path) path = "/";
170
171         /* We need to decode it, to see what path the user really wanted. */
172         decoded_path = evhttp_uridecode(path, 0, NULL);
173         /* Don't allow any ".."s in the path, to avoid exposing stuff outside
174          * of the docroot.  This test is both overzealous and underzealous:
175          * it forbids aceptable paths like "/this/one..here", but it doesn't
176          * do anything to prevent symlink following." */
177         if (strstr(decoded_path, ".."))
178                 goto err;
179
180         len = strlen(decoded_path)+strlen(docroot)+2;
181         if (!(whole_path = malloc(len))) {
182                 perror("malloc");
183                 goto err;
184         }
185         evutil_snprintf(whole_path, len, "%s/%s", docroot, decoded_path);
186
187         if (stat(whole_path, &st)<0) {
188                 goto err;
189         }
190
191         /* This holds the content we're sending. */
192         evb = evbuffer_new();
193
194         if (S_ISDIR(st.st_mode)) {
195                 /* If it's a directory, read the comments and make a little
196                  * index page */
197 #ifdef WIN32
198                 HANDLE d;
199                 WIN32_FIND_DATAA ent;
200                 char *pattern;
201                 size_t dirlen;
202 #else
203                 DIR *d;
204                 struct dirent *ent;
205 #endif
206                 const char *trailing_slash = "";
207
208                 if (!strlen(path) || path[strlen(path)-1] != '/')
209                         trailing_slash = "/";
210
211 #ifdef WIN32
212                 dirlen = strlen(whole_path);
213                 pattern = malloc(dirlen+3);
214                 memcpy(pattern, whole_path, dirlen);
215                 pattern[dirlen] = '\\';
216                 pattern[dirlen+1] = '*';
217                 pattern[dirlen+2] = '\0';
218                 d = FindFirstFileA(pattern, &ent);
219                 free(pattern);
220                 if (d == INVALID_HANDLE_VALUE)
221                         goto err;
222 #else
223                 if (!(d = opendir(whole_path)))
224                         goto err;
225 #endif
226                 close(fd);
227
228                 evbuffer_add_printf(evb, "<html>\n <head>\n"
229                     "  <title>%s</title>\n"
230                     "  <base href='%s%s%s'>\n"
231                     " </head>\n"
232                     " <body>\n"
233                     "  <h1>%s</h1>\n"
234                     "  <ul>\n",
235                     decoded_path, /* XXX html-escape this. */
236                     uri_root, path, /* XXX html-escape this? */
237                     trailing_slash,
238                     decoded_path /* XXX html-escape this */);
239 #ifdef WIN32
240                 do {
241                         const char *name = ent.cFileName;
242 #else
243                 while ((ent = readdir(d))) {
244                         const char *name = ent->d_name;
245 #endif
246                         evbuffer_add_printf(evb,
247                             "    <li><a href=\"%s\">%s</a>\n",
248                             name, name);/* XXX escape this */
249 #ifdef WIN32
250                 } while (FindNextFileA(d, &ent));
251 #else
252                 }
253 #endif
254                 evbuffer_add_printf(evb, "</ul></body></html>\n");
255 #ifdef WIN32
256                 CloseHandle(d);
257 #else
258                 closedir(d);
259 #endif
260                 evhttp_add_header(evhttp_request_get_output_headers(req),
261                     "Content-Type", "text/html");
262         } else {
263                 /* Otherwise it's a file; add it to the buffer to get
264                  * sent via sendfile */
265                 const char *type = guess_content_type(decoded_path);
266                 if ((fd = open(whole_path, O_RDONLY)) < 0) {
267                         perror("open");
268                         goto err;
269                 }
270
271                 if (fstat(fd, &st)<0) {
272                         /* Make sure the length still matches, now that we
273                          * opened the file :/ */
274                         perror("fstat");
275                         goto err;
276                 }
277                 evhttp_add_header(evhttp_request_get_output_headers(req),
278                     "Content-Type", type);
279                 evbuffer_add_file(evb, fd, 0, st.st_size);
280         }
281
282         evhttp_send_reply(req, 200, "OK", evb);
283         evbuffer_free(evb);
284         return;
285 err:
286         evhttp_send_error(req, 404, "Document was not found");
287         if (fd>=0)
288                 close(fd);
289         if (decoded)
290                 evhttp_uri_free(decoded);
291         if (decoded_path)
292                 free(decoded_path);
293         if (whole_path)
294                 free(whole_path);
295 }
296
297 static void
298 syntax(void)
299 {
300         fprintf(stdout, "Syntax: http-server <docroot>\n");
301 }
302
303 int
304 main(int argc, char **argv)
305 {
306         struct event_base *base;
307         struct evhttp *http;
308         struct evhttp_bound_socket *handle;
309
310         unsigned short port = 0;
311 #ifdef WIN32
312         WSADATA WSAData;
313         WSAStartup(0x101, &WSAData);
314 #else
315         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
316                 return (1);
317 #endif
318         if (argc < 2) {
319                 syntax();
320                 return 1;
321         }
322
323         base = event_base_new();
324         if (!base) {
325                 fprintf(stderr, "Couldn't create an event_base: exiting\n");
326                 return 1;
327         }
328
329         /* Create a new evhttp object to handle requests. */
330         http = evhttp_new(base);
331         if (!http) {
332                 fprintf(stderr, "couldn't create evhttp. Exiting.\n");
333                 return 1;
334         }
335
336         /* The /dump URI will dump all requests to stdout and say 200 ok. */
337         evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
338
339         /* We want to accept arbitrary requests, so we need to set a "generic"
340          * cb.  We can also add callbacks for specific paths. */
341         evhttp_set_gencb(http, send_document_cb, argv[1]);
342
343         /* Now we tell the evhttp what port to listen on */
344         handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", port);
345         if (!handle) {
346                 fprintf(stderr, "couldn't bind to port %d. Exiting.\n",
347                     (int)port);
348                 return 1;
349         }
350
351         {
352                 /* Extract and display the address we're listening on. */
353                 struct sockaddr_storage ss;
354                 evutil_socket_t fd;
355                 ev_socklen_t socklen = sizeof(ss);
356                 char addrbuf[128];
357                 void *inaddr;
358                 const char *addr;
359                 int got_port = -1;
360                 fd = evhttp_bound_socket_get_fd(handle);
361                 memset(&ss, 0, sizeof(ss));
362                 if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
363                         perror("getsockname() failed");
364                         return 1;
365                 }
366                 if (ss.ss_family == AF_INET) {
367                         got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
368                         inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
369                 } else if (ss.ss_family == AF_INET6) {
370                         got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
371                         inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
372                 } else {
373                         fprintf(stderr, "Weird address family %d\n",
374                             ss.ss_family);
375                         return 1;
376                 }
377                 addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
378                     sizeof(addrbuf));
379                 if (addr) {
380                         printf("Listening on %s:%d\n", addr, got_port);
381                         evutil_snprintf(uri_root, sizeof(uri_root),
382                             "http://%s:%d",addr,got_port);
383                 } else {
384                         fprintf(stderr, "evutil_inet_ntop failed\n");
385                         return 1;
386                 }
387         }
388
389         event_base_dispatch(base);
390
391         return 0;
392 }