2 * uhttpd - Tiny single-threaded httpd
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #ifndef _DEFAULT_SOURCE
21 # define _DEFAULT_SOURCE
25 #define _DARWIN_C_SOURCE
26 #define _XOPEN_SOURCE 700
28 #include <sys/types.h>
35 #include <libubox/blobmsg.h>
38 #include "mimetypes.h"
40 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
42 static LIST_HEAD(index_files);
43 static LIST_HEAD(dispatch_handlers);
44 static LIST_HEAD(pending_requests);
45 static int n_requests;
47 struct deferred_request {
48 struct list_head list;
49 struct dispatch_handler *d;
56 struct list_head list;
62 HDR_IF_MODIFIED_SINCE,
63 HDR_IF_UNMODIFIED_SINCE,
70 void uh_index_add(const char *filename)
72 struct index_file *idx;
74 idx = calloc(1, sizeof(*idx));
76 list_add_tail(&idx->list, &index_files);
79 static char * canonpath(const char *path, char *path_resolved)
81 const char *path_cpy = path;
82 char *path_res = path_resolved;
85 return realpath(path, path_resolved);
88 while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
92 /* skip repeating / */
93 if (path_cpy[1] == '/') {
99 if (path_cpy[1] == '.') {
101 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
106 /* collapse /x/../ */
107 if ((path_cpy[2] == '.') &&
108 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
109 while ((path_res > path_resolved) && (*--path_res != '/'));
117 *path_res++ = *path_cpy++;
120 /* remove trailing slash if not root / */
121 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
123 else if (path_res == path_resolved)
128 return path_resolved;
131 /* Returns NULL on error.
132 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
133 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
135 uh_path_lookup(struct client *cl, const char *url)
137 static char path_phys[PATH_MAX];
138 static char path_info[PATH_MAX];
139 static char path_query[PATH_MAX];
140 static struct path_info p;
142 const char *docroot = conf.docroot;
143 int docroot_len = strlen(docroot);
144 char *pathptr = NULL;
150 struct index_file *idx;
152 /* back out early if url is undefined */
156 memset(&p, 0, sizeof(p));
160 strcpy(uh_buf, docroot);
162 /* separate query string from url */
163 if ((pathptr = strchr(url, '?')) != NULL) {
165 p.query = path_query;
166 snprintf(path_query, sizeof(path_query), "%s",
170 /* urldecode component w/o query */
172 if (uh_urldecode(&uh_buf[docroot_len],
173 sizeof(uh_buf) - docroot_len - 1,
174 url, pathptr - url ) < 0)
179 /* no query string, decode all of url */
180 else if (uh_urldecode(&uh_buf[docroot_len],
181 sizeof(uh_buf) - docroot_len - 1,
182 url, strlen(url) ) < 0)
185 /* create canon path */
186 len = strlen(uh_buf);
187 slash = len && uh_buf[len - 1] == '/';
188 len = min(len, sizeof(path_phys) - 1);
190 for (i = len; i >= 0; i--) {
194 if (ch != 0 && ch != '/')
198 exists = !!canonpath(uh_buf, path_phys);
204 /* test current path */
205 if (stat(path_phys, &p.stat))
208 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
212 /* check whether found path is within docroot */
213 if (strncmp(path_phys, docroot, docroot_len) != 0 ||
214 (path_phys[docroot_len] != 0 &&
215 path_phys[docroot_len] != '/'))
218 /* is a regular file */
219 if (p.stat.st_mode & S_IFREG) {
222 p.name = &path_phys[docroot_len];
223 p.info = path_info[0] ? path_info : NULL;
227 if (!(p.stat.st_mode & S_IFDIR))
233 pathptr = path_phys + strlen(path_phys);
235 /* ensure trailing slash */
236 if (pathptr[-1] != '/') {
242 /* if requested url resolves to a directory and a trailing slash
243 is missing in the request url, redirect the client to the same
244 url with trailing slash appended */
246 uh_http_header(cl, 302, "Found");
247 if (!uh_use_chunked(cl))
248 ustream_printf(cl->us, "Content-Length: 0\r\n");
249 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
250 &path_phys[docroot_len],
252 p.query ? p.query : "");
258 /* try to locate index file */
259 len = path_phys + sizeof(path_phys) - pathptr - 1;
260 list_for_each_entry(idx, &index_files, list) {
261 if (strlen(idx->name) > len)
264 strcpy(pathptr, idx->name);
265 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG)) {
266 memcpy(&p.stat, &s, sizeof(p.stat));
275 p.name = &path_phys[docroot_len];
277 return p.phys ? &p : NULL;
280 static const char * uh_file_mime_lookup(const char *path)
282 const struct mimetype *m = &uh_mime_types[0];
286 e = &path[strlen(path)-1];
289 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
298 return "application/octet-stream";
301 static const char * uh_file_mktag(struct stat *s, char *buf, int len)
303 snprintf(buf, len, "\"%" PRIx64 "-%" PRIx64 "-%" PRIx64 "\"",
304 s->st_ino, s->st_size, (uint64_t)s->st_mtime);
309 static time_t uh_file_date2unix(const char *date)
313 memset(&t, 0, sizeof(t));
315 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
321 static char * uh_file_unix2date(time_t ts, char *buf, int len)
323 struct tm *t = gmtime(&ts);
325 strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", t);
330 static char *uh_file_header(struct client *cl, int idx)
332 if (!cl->dispatch.file.hdr[idx])
335 return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
338 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
343 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s, buf, sizeof(buf)));
344 ustream_printf(cl->us, "Last-Modified: %s\r\n",
345 uh_file_unix2date(s->st_mtime, buf, sizeof(buf)));
347 ustream_printf(cl->us, "Date: %s\r\n",
348 uh_file_unix2date(time(NULL), buf, sizeof(buf)));
351 static void uh_file_response_200(struct client *cl, struct stat *s)
353 uh_http_header(cl, 200, "OK");
354 return uh_file_response_ok_hdrs(cl, s);
357 static void uh_file_response_304(struct client *cl, struct stat *s)
359 uh_http_header(cl, 304, "Not Modified");
361 return uh_file_response_ok_hdrs(cl, s);
364 static void uh_file_response_405(struct client *cl)
366 uh_http_header(cl, 405, "Method Not Allowed");
369 static void uh_file_response_412(struct client *cl)
371 uh_http_header(cl, 412, "Precondition Failed");
374 static bool uh_file_if_match(struct client *cl, struct stat *s)
377 const char *tag = uh_file_mktag(s, buf, sizeof(buf));
378 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
386 for (i = 0; i < strlen(hdr); i++)
388 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
391 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
396 uh_file_response_412(cl);
400 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
402 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
407 if (uh_file_date2unix(hdr) >= s->st_mtime) {
408 uh_file_response_304(cl, s);
415 static int uh_file_if_none_match(struct client *cl, struct stat *s)
418 const char *tag = uh_file_mktag(s, buf, sizeof(buf));
419 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
427 for (i = 0; i < strlen(hdr); i++) {
428 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
431 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
432 if ((cl->request.method == UH_HTTP_MSG_GET) ||
433 (cl->request.method == UH_HTTP_MSG_HEAD))
434 uh_file_response_304(cl, s);
436 uh_file_response_412(cl);
445 static int uh_file_if_range(struct client *cl, struct stat *s)
447 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
450 uh_file_response_412(cl);
457 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
459 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
461 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
462 uh_file_response_412(cl);
469 static int dirent_cmp(const struct dirent **a, const struct dirent **b)
471 bool dir_a = !!((*a)->d_type & DT_DIR);
472 bool dir_b = !!((*b)->d_type & DT_DIR);
474 /* directories first */
476 return dir_b - dir_a;
478 return alphasort(a, b);
481 static void list_entries(struct client *cl, struct dirent **files, int count,
482 const char *path, char *local_path)
484 const char *suffix = "/";
485 const char *type = "directory";
486 unsigned int mode = S_IXOTH;
493 file = local_path + strlen(local_path);
494 for (i = 0; i < count; i++) {
495 const char *name = files[i]->d_name;
496 bool dir = !!(files[i]->d_type & DT_DIR);
498 if (name[0] == '.' && name[1] == 0)
501 sprintf(file, "%s", name);
502 if (stat(local_path, &s))
508 type = uh_file_mime_lookup(local_path);
511 if (!(s.st_mode & mode))
514 escaped = uh_htmlescape(name);
520 "<li><strong><a href='%s%s%s'>%s</a>%s"
521 "</strong><br /><small>modified: %s"
522 "<br />%s - %.02f kbyte<br />"
523 "<br /></small></li>",
524 path, escaped, suffix,
526 uh_file_unix2date(s.st_mtime, buf, sizeof(buf)),
527 type, s.st_size / 1024.0);
536 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
538 struct dirent **files = NULL;
539 char *escaped_path = uh_htmlescape(pi->name);
544 uh_client_error(cl, 500, "Internal Server Error", "Out of memory");
548 uh_file_response_200(cl, NULL);
549 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
552 "<html><head><title>Index of %s</title></head>"
553 "<body><h1>Index of %s</h1><hr /><ol>",
554 escaped_path, escaped_path);
556 count = scandir(pi->phys, &files, NULL, dirent_cmp);
558 strcpy(uh_buf, pi->phys);
559 list_entries(cl, files, count, escaped_path, uh_buf);
564 uh_chunk_printf(cl, "</ol><hr /></body></html>");
568 static void file_write_cb(struct client *cl)
570 int fd = cl->dispatch.file.fd;
573 while (cl->us->w.data_bytes < 256) {
574 r = read(fd, uh_buf, sizeof(uh_buf));
585 uh_chunk_write(cl, uh_buf, r);
589 static void uh_file_free(struct client *cl)
591 close(cl->dispatch.file.fd);
594 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
596 /* test preconditions */
597 if (!cl->dispatch.no_cache &&
598 (!uh_file_if_modified_since(cl, &pi->stat) ||
599 !uh_file_if_match(cl, &pi->stat) ||
600 !uh_file_if_range(cl, &pi->stat) ||
601 !uh_file_if_unmodified_since(cl, &pi->stat) ||
602 !uh_file_if_none_match(cl, &pi->stat))) {
603 ustream_printf(cl->us, "\r\n");
610 uh_file_response_200(cl, &pi->stat);
612 ustream_printf(cl->us, "Content-Type: %s\r\n",
613 uh_file_mime_lookup(pi->name));
615 ustream_printf(cl->us, "Content-Length: %" PRIu64 "\r\n\r\n",
620 if (cl->request.method == UH_HTTP_MSG_HEAD) {
626 cl->dispatch.file.fd = fd;
627 cl->dispatch.write_cb = file_write_cb;
628 cl->dispatch.free = uh_file_free;
629 cl->dispatch.close_fds = uh_file_free;
633 static bool __handle_file_request(struct client *cl, char *url);
635 static void uh_file_request(struct client *cl, const char *url,
636 struct path_info *pi, struct blob_attr **tb)
639 struct http_request *req = &cl->request;
640 char *error_handler, *escaped_url;
642 switch (cl->request.method) {
643 case UH_HTTP_MSG_GET:
644 case UH_HTTP_MSG_POST:
645 case UH_HTTP_MSG_HEAD:
646 case UH_HTTP_MSG_OPTIONS:
650 uh_file_response_405(cl);
651 ustream_printf(cl->us, "\r\n");
656 if (!(pi->stat.st_mode & S_IROTH))
659 if (pi->stat.st_mode & S_IFREG) {
660 fd = open(pi->phys, O_RDONLY);
664 req->disable_chunked = true;
665 cl->dispatch.file.hdr = tb;
666 uh_file_data(cl, pi, fd);
667 cl->dispatch.file.hdr = NULL;
671 if ((pi->stat.st_mode & S_IFDIR)) {
672 if (conf.no_dirlists)
675 uh_file_dirlist(cl, pi);
680 /* check for a previously set 403 redirect status to prevent infinite
681 recursion when the error page itself lacks sufficient permissions */
682 if (conf.error_handler && req->redirect_status != 403) {
683 req->redirect_status = 403;
684 error_handler = alloca(strlen(conf.error_handler) + 1);
685 strcpy(error_handler, conf.error_handler);
686 if (__handle_file_request(cl, error_handler))
690 escaped_url = uh_htmlescape(url);
692 uh_client_error(cl, 403, "Forbidden",
693 "You don't have permission to access %s on this server.",
694 escaped_url ? escaped_url : "the url");
700 void uh_dispatch_add(struct dispatch_handler *d)
702 list_add_tail(&d->list, &dispatch_handlers);
705 static struct dispatch_handler *
706 dispatch_find(const char *url, struct path_info *pi)
708 struct dispatch_handler *d;
710 list_for_each_entry(d, &dispatch_handlers, list) {
715 if (d->check_path(pi, url))
721 if (d->check_url(url))
730 uh_invoke_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
732 char *url = blobmsg_data(blob_data(cl->hdr.head));
735 d->handle_request(cl, url, pi);
738 static void uh_complete_request(struct client *cl)
740 struct deferred_request *dr;
744 while (!list_empty(&pending_requests)) {
745 if (n_requests >= conf.max_script_requests)
748 dr = list_first_entry(&pending_requests, struct deferred_request, list);
753 cl->dispatch.data_blocked = false;
754 uh_invoke_script(cl, dr->d, dr->path ? &dr->pi : NULL);
755 client_poll_post_data(cl);
756 ustream_poll(cl->us);
762 uh_free_pending_request(struct client *cl)
764 struct deferred_request *dr = cl->dispatch.req_data;
767 uh_complete_request(cl);
773 static int field_len(const char *ptr)
778 return strlen(ptr) + 1;
781 #define path_info_fields \
789 uh_defer_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
791 struct deferred_request *dr;
792 char *_root, *_phys, *_name, *_info, *_query;
794 cl->dispatch.req_free = uh_free_pending_request;
797 /* allocate enough memory to duplicate all path_info strings in one block */
799 #define _field(_name) &_##_name, field_len(pi->_name),
800 dr = calloc_a(sizeof(*dr), path_info_fields NULL);
802 memcpy(&dr->pi, pi, sizeof(*pi));
805 /* copy all path_info strings */
807 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
810 dr = calloc(1, sizeof(*dr));
813 cl->dispatch.req_data = dr;
814 cl->dispatch.data_blocked = true;
817 list_add(&dr->list, &pending_requests);
821 uh_invoke_handler(struct client *cl, struct dispatch_handler *d, char *url, struct path_info *pi)
824 return d->handle_request(cl, url, pi);
826 if (n_requests >= conf.max_script_requests)
827 return uh_defer_script(cl, d, pi);
829 cl->dispatch.req_free = uh_complete_request;
830 uh_invoke_script(cl, d, pi);
833 static bool __handle_file_request(struct client *cl, char *url)
835 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
836 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
837 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
838 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
839 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
840 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
841 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
843 struct dispatch_handler *d;
844 struct blob_attr *tb[__HDR_MAX];
845 struct path_info *pi;
846 char *user, *pass, *auth;
848 pi = uh_path_lookup(cl, url);
855 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
857 auth = tb[HDR_AUTHORIZATION] ? blobmsg_data(tb[HDR_AUTHORIZATION]) : NULL;
859 if (!uh_auth_check(cl, pi->name, auth, &user, &pass))
863 blobmsg_add_string(&cl->hdr, "http-auth-user", user);
864 blobmsg_add_string(&cl->hdr, "http-auth-pass", pass);
867 d = dispatch_find(url, pi);
869 uh_invoke_handler(cl, d, url, pi);
871 uh_file_request(cl, url, pi, tb);
876 static char *uh_handle_alias(char *old_url)
879 static char *new_url;
882 if (!list_empty(&conf.cgi_alias)) list_for_each_entry(alias, &conf.cgi_alias, list) {
887 if (!uh_path_match(alias->alias, old_url))
891 path_len = strlen(alias->path);
893 old_len = strlen(old_url) + 1;
894 new_len = old_len + MAX(conf.cgi_prefix_len, path_len);
896 if (new_len > url_len) {
897 new_url = realloc(new_url, new_len);
904 strcpy(new_url, alias->path);
905 else if (conf.cgi_prefix)
906 strcpy(new_url, conf.cgi_prefix);
907 strcat(new_url, old_url);
914 void uh_handle_request(struct client *cl)
916 struct http_request *req = &cl->request;
917 struct dispatch_handler *d;
918 char *url = blobmsg_data(blob_data(cl->hdr.head));
919 char *error_handler, *escaped_url;
921 blob_buf_init(&cl->hdr_response, 0);
922 url = uh_handle_alias(url);
924 uh_handler_run(cl, &url, false);
928 req->redirect_status = 200;
929 d = dispatch_find(url, NULL);
931 return uh_invoke_handler(cl, d, url, NULL);
933 if (__handle_file_request(cl, url))
936 if (uh_handler_run(cl, &url, true)) {
940 uh_handler_run(cl, &url, false);
941 if (__handle_file_request(cl, url))
945 req->redirect_status = 404;
946 if (conf.error_handler) {
947 error_handler = alloca(strlen(conf.error_handler) + 1);
948 strcpy(error_handler, conf.error_handler);
949 if (__handle_file_request(cl, error_handler))
953 escaped_url = uh_htmlescape(url);
955 uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.",
956 escaped_url ? escaped_url : "");