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.
21 #define _DARWIN_C_SOURCE
22 #define _XOPEN_SOURCE 700
24 #include <sys/types.h>
31 #include <libubox/blobmsg.h>
34 #include "mimetypes.h"
36 static LIST_HEAD(index_files);
37 static LIST_HEAD(dispatch_handlers);
38 static LIST_HEAD(pending_requests);
39 static int n_requests;
41 struct deferred_request {
42 struct list_head list;
43 struct dispatch_handler *d;
50 struct list_head list;
56 HDR_IF_MODIFIED_SINCE,
57 HDR_IF_UNMODIFIED_SINCE,
64 void uh_index_add(const char *filename)
66 struct index_file *idx;
68 idx = calloc(1, sizeof(*idx));
70 list_add_tail(&idx->list, &index_files);
73 static char * canonpath(const char *path, char *path_resolved)
75 const char *path_cpy = path;
76 char *path_res = path_resolved;
79 return realpath(path, path_resolved);
82 while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
86 /* skip repeating / */
87 if (path_cpy[1] == '/') {
93 if (path_cpy[1] == '.') {
95 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
100 /* collapse /x/../ */
101 if ((path_cpy[2] == '.') &&
102 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
103 while ((path_res > path_resolved) && (*--path_res != '/'));
111 *path_res++ = *path_cpy++;
114 /* remove trailing slash if not root / */
115 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
117 else if (path_res == path_resolved)
122 return path_resolved;
125 /* Returns NULL on error.
126 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
127 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
128 static struct path_info *
129 uh_path_lookup(struct client *cl, const char *url)
131 static char path_phys[PATH_MAX];
132 static char path_info[PATH_MAX];
133 static struct path_info p;
135 const char *docroot = conf.docroot;
136 int docroot_len = strlen(docroot);
137 char *pathptr = NULL;
143 struct index_file *idx;
145 /* back out early if url is undefined */
149 memset(&p, 0, sizeof(p));
153 strcpy(uh_buf, docroot);
155 /* separate query string from url */
156 if ((pathptr = strchr(url, '?')) != NULL) {
157 p.query = pathptr[1] ? pathptr + 1 : NULL;
159 /* urldecode component w/o query */
161 if (uh_urldecode(&uh_buf[docroot_len],
162 sizeof(uh_buf) - docroot_len - 1,
163 url, pathptr - url ) < 0)
168 /* no query string, decode all of url */
169 else if (uh_urldecode(&uh_buf[docroot_len],
170 sizeof(uh_buf) - docroot_len - 1,
171 url, strlen(url) ) < 0)
174 /* create canon path */
175 len = strlen(uh_buf);
176 slash = len && uh_buf[len - 1] == '/';
177 len = min(len, sizeof(path_phys) - 1);
179 for (i = len; i >= 0; i--) {
183 if (ch != 0 && ch != '/')
187 exists = !!canonpath(uh_buf, path_phys);
193 /* test current path */
194 if (stat(path_phys, &p.stat))
197 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
201 /* check whether found path is within docroot */
202 if (strncmp(path_phys, docroot, docroot_len) != 0 ||
203 (path_phys[docroot_len] != 0 &&
204 path_phys[docroot_len] != '/'))
207 /* is a regular file */
208 if (p.stat.st_mode & S_IFREG) {
211 p.name = &path_phys[docroot_len];
212 p.info = path_info[0] ? path_info : NULL;
216 if (!(p.stat.st_mode & S_IFDIR))
222 pathptr = path_phys + strlen(path_phys);
224 /* ensure trailing slash */
225 if (pathptr[-1] != '/') {
231 /* if requested url resolves to a directory and a trailing slash
232 is missing in the request url, redirect the client to the same
233 url with trailing slash appended */
235 uh_http_header(cl, 302, "Found");
236 ustream_printf(cl->us, "Content-Length: 0\r\n");
237 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
238 &path_phys[docroot_len],
240 p.query ? p.query : "");
246 /* try to locate index file */
247 len = path_phys + sizeof(path_phys) - pathptr - 1;
248 list_for_each_entry(idx, &index_files, list) {
249 if (strlen(idx->name) > len)
252 strcpy(pathptr, idx->name);
253 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG)) {
254 memcpy(&p.stat, &s, sizeof(p.stat));
263 p.name = &path_phys[docroot_len];
265 return p.phys ? &p : NULL;
268 static const char * uh_file_mime_lookup(const char *path)
270 const struct mimetype *m = &uh_mime_types[0];
274 e = &path[strlen(path)-1];
277 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
286 return "application/octet-stream";
289 static const char * uh_file_mktag(struct stat *s, char *buf, int len)
291 snprintf(buf, len, "\"%" PRIx64 "-%" PRIx64 "-%" PRIx64 "\"",
292 s->st_ino, s->st_size, s->st_mtime);
297 static time_t uh_file_date2unix(const char *date)
301 memset(&t, 0, sizeof(t));
303 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
309 static char * uh_file_unix2date(time_t ts, char *buf, int len)
311 struct tm *t = gmtime(&ts);
313 strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", t);
318 static char *uh_file_header(struct client *cl, int idx)
320 if (!cl->dispatch.file.hdr[idx])
323 return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
326 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
331 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s, buf, sizeof(buf)));
332 ustream_printf(cl->us, "Last-Modified: %s\r\n",
333 uh_file_unix2date(s->st_mtime, buf, sizeof(buf)));
335 ustream_printf(cl->us, "Date: %s\r\n",
336 uh_file_unix2date(time(NULL), buf, sizeof(buf)));
339 static void uh_file_response_200(struct client *cl, struct stat *s)
341 uh_http_header(cl, 200, "OK");
342 return uh_file_response_ok_hdrs(cl, s);
345 static void uh_file_response_304(struct client *cl, struct stat *s)
347 uh_http_header(cl, 304, "Not Modified");
349 return uh_file_response_ok_hdrs(cl, s);
352 static void uh_file_response_412(struct client *cl)
354 uh_http_header(cl, 412, "Precondition Failed");
357 static bool uh_file_if_match(struct client *cl, struct stat *s)
360 const char *tag = uh_file_mktag(s, buf, sizeof(buf));
361 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
369 for (i = 0; i < strlen(hdr); i++)
371 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
374 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
379 uh_file_response_412(cl);
383 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
385 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
390 if (uh_file_date2unix(hdr) >= s->st_mtime) {
391 uh_file_response_304(cl, s);
398 static int uh_file_if_none_match(struct client *cl, struct stat *s)
401 const char *tag = uh_file_mktag(s, buf, sizeof(buf));
402 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
410 for (i = 0; i < strlen(hdr); i++) {
411 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
414 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
415 if ((cl->request.method == UH_HTTP_MSG_GET) ||
416 (cl->request.method == UH_HTTP_MSG_HEAD))
417 uh_file_response_304(cl, s);
419 uh_file_response_412(cl);
428 static int uh_file_if_range(struct client *cl, struct stat *s)
430 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
433 uh_file_response_412(cl);
440 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
442 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
444 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
445 uh_file_response_412(cl);
452 static int dirent_cmp(const struct dirent **a, const struct dirent **b)
454 bool dir_a = !!((*a)->d_type & DT_DIR);
455 bool dir_b = !!((*b)->d_type & DT_DIR);
457 /* directories first */
459 return dir_b - dir_a;
461 return alphasort(a, b);
464 static void list_entries(struct client *cl, struct dirent **files, int count,
465 const char *path, char *local_path)
467 const char *suffix = "/";
468 const char *type = "directory";
469 unsigned int mode = S_IXOTH;
475 file = local_path + strlen(local_path);
476 for (i = 0; i < count; i++) {
477 const char *name = files[i]->d_name;
478 bool dir = !!(files[i]->d_type & DT_DIR);
480 if (name[0] == '.' && name[1] == 0)
483 sprintf(file, "%s", name);
484 if (stat(local_path, &s))
490 type = uh_file_mime_lookup(local_path);
493 if (!(s.st_mode & mode))
497 "<li><strong><a href='%s%s%s'>%s</a>%s"
498 "</strong><br /><small>modified: %s"
499 "<br />%s - %.02f kbyte<br />"
500 "<br /></small></li>",
503 uh_file_unix2date(s.st_mtime, buf, sizeof(buf)),
504 type, s.st_size / 1024.0);
512 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
514 struct dirent **files = NULL;
517 uh_file_response_200(cl, NULL);
518 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
521 "<html><head><title>Index of %s</title></head>"
522 "<body><h1>Index of %s</h1><hr /><ol>",
525 count = scandir(pi->phys, &files, NULL, dirent_cmp);
527 strcpy(uh_buf, pi->phys);
528 list_entries(cl, files, count, pi->name, uh_buf);
532 uh_chunk_printf(cl, "</ol><hr /></body></html>");
536 static void file_write_cb(struct client *cl)
538 int fd = cl->dispatch.file.fd;
541 while (cl->us->w.data_bytes < 256) {
542 r = read(fd, uh_buf, sizeof(uh_buf));
553 uh_chunk_write(cl, uh_buf, r);
557 static void uh_file_free(struct client *cl)
559 close(cl->dispatch.file.fd);
562 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
564 /* test preconditions */
565 if (!uh_file_if_modified_since(cl, &pi->stat) ||
566 !uh_file_if_match(cl, &pi->stat) ||
567 !uh_file_if_range(cl, &pi->stat) ||
568 !uh_file_if_unmodified_since(cl, &pi->stat) ||
569 !uh_file_if_none_match(cl, &pi->stat)) {
570 ustream_printf(cl->us, "\r\n");
577 uh_file_response_200(cl, &pi->stat);
579 ustream_printf(cl->us, "Content-Type: %s\r\n",
580 uh_file_mime_lookup(pi->name));
582 ustream_printf(cl->us, "Content-Length: %" PRIu64 "\r\n\r\n",
587 if (cl->request.method == UH_HTTP_MSG_HEAD) {
593 cl->dispatch.file.fd = fd;
594 cl->dispatch.write_cb = file_write_cb;
595 cl->dispatch.free = uh_file_free;
596 cl->dispatch.close_fds = uh_file_free;
600 static bool __handle_file_request(struct client *cl, char *url);
602 static void uh_file_request(struct client *cl, const char *url,
603 struct path_info *pi, struct blob_attr **tb)
606 struct http_request *req = &cl->request;
609 if (!(pi->stat.st_mode & S_IROTH))
612 if (pi->stat.st_mode & S_IFREG) {
613 fd = open(pi->phys, O_RDONLY);
617 cl->dispatch.file.hdr = tb;
618 uh_file_data(cl, pi, fd);
619 cl->dispatch.file.hdr = NULL;
623 if ((pi->stat.st_mode & S_IFDIR)) {
624 if (conf.no_dirlists)
627 uh_file_dirlist(cl, pi);
632 /* check for a previously set 403 redirect status to prevent infinite
633 recursion when the error page itself lacks sufficient permissions */
634 if (conf.error_handler && req->redirect_status != 403) {
635 req->redirect_status = 403;
636 error_handler = alloca(strlen(conf.error_handler) + 1);
637 strcpy(error_handler, conf.error_handler);
638 if (__handle_file_request(cl, error_handler))
642 uh_client_error(cl, 403, "Forbidden",
643 "You don't have permission to access %s on this server.",
647 void uh_dispatch_add(struct dispatch_handler *d)
649 list_add_tail(&d->list, &dispatch_handlers);
652 static struct dispatch_handler *
653 dispatch_find(const char *url, struct path_info *pi)
655 struct dispatch_handler *d;
657 list_for_each_entry(d, &dispatch_handlers, list) {
662 if (d->check_path(pi, url))
668 if (d->check_url(url))
677 uh_invoke_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
679 char *url = blobmsg_data(blob_data(cl->hdr.head));
682 d->handle_request(cl, url, pi);
685 static void uh_complete_request(struct client *cl)
687 struct deferred_request *dr;
691 while (!list_empty(&pending_requests)) {
692 if (n_requests >= conf.max_script_requests)
695 dr = list_first_entry(&pending_requests, struct deferred_request, list);
699 uh_invoke_script(dr->cl, dr->d, dr->path ? &dr->pi : NULL);
705 uh_free_pending_request(struct client *cl)
707 struct deferred_request *dr = cl->dispatch.req_data;
710 uh_complete_request(cl);
716 static int field_len(const char *ptr)
721 return strlen(ptr) + 1;
724 #define path_info_fields \
733 uh_defer_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
735 struct deferred_request *dr;
736 char *_root, *_phys, *_name, *_info, *_query, *_auth;
738 cl->dispatch.req_free = uh_free_pending_request;
741 /* allocate enough memory to duplicate all path_info strings in one block */
743 #define _field(_name) &_##_name, field_len(pi->_name),
744 dr = calloc_a(sizeof(*dr), path_info_fields NULL);
746 memcpy(&dr->pi, pi, sizeof(*pi));
749 /* copy all path_info strings */
751 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
754 dr = calloc(1, sizeof(*dr));
757 cl->dispatch.req_data = dr;
760 list_add(&dr->list, &pending_requests);
764 uh_invoke_handler(struct client *cl, struct dispatch_handler *d, char *url, struct path_info *pi)
767 return d->handle_request(cl, url, pi);
769 if (n_requests >= conf.max_script_requests)
770 return uh_defer_script(cl, d, pi);
772 cl->dispatch.req_free = uh_complete_request;
773 uh_invoke_script(cl, d, pi);
776 static bool __handle_file_request(struct client *cl, char *url)
778 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
779 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
780 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
781 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
782 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
783 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
784 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
786 struct dispatch_handler *d;
787 struct blob_attr *tb[__HDR_MAX];
788 struct path_info *pi;
790 pi = uh_path_lookup(cl, url);
797 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
798 if (tb[HDR_AUTHORIZATION])
799 pi->auth = blobmsg_data(tb[HDR_AUTHORIZATION]);
801 if (!uh_auth_check(cl, pi))
804 d = dispatch_find(url, pi);
806 uh_invoke_handler(cl, d, url, pi);
808 uh_file_request(cl, url, pi, tb);
813 void uh_handle_request(struct client *cl)
815 struct http_request *req = &cl->request;
816 struct dispatch_handler *d;
817 char *url = blobmsg_data(blob_data(cl->hdr.head));
820 req->redirect_status = 200;
821 d = dispatch_find(url, NULL);
823 return uh_invoke_handler(cl, d, url, NULL);
825 if (__handle_file_request(cl, url))
828 req->redirect_status = 404;
829 if (conf.error_handler) {
830 error_handler = alloca(strlen(conf.error_handler) + 1);
831 strcpy(error_handler, conf.error_handler);
832 if (__handle_file_request(cl, error_handler))
836 uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", url);