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