2 * uhttpd - Tiny single-threaded httpd
4 * Copyright (C) 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 #define _XOPEN_SOURCE 700
23 #include <sys/types.h>
28 #include <libubox/blobmsg.h>
31 #include "mimetypes.h"
33 static LIST_HEAD(index_files);
34 static LIST_HEAD(dispatch_handlers);
37 struct list_head list;
43 HDR_IF_MODIFIED_SINCE,
44 HDR_IF_UNMODIFIED_SINCE,
51 void uh_index_add(const char *filename)
53 struct index_file *idx;
55 idx = calloc(1, sizeof(*idx));
57 list_add_tail(&idx->list, &index_files);
60 static char * canonpath(const char *path, char *path_resolved)
62 const char *path_cpy = path;
63 char *path_res = path_resolved;
66 return realpath(path, path_resolved);
69 while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
73 /* skip repeating / */
74 if (path_cpy[1] == '/') {
80 if (path_cpy[1] == '.') {
82 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
88 if ((path_cpy[2] == '.') &&
89 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
90 while ((path_res > path_resolved) && (*--path_res != '/'));
98 *path_res++ = *path_cpy++;
101 /* remove trailing slash if not root / */
102 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
104 else if (path_res == path_resolved)
109 return path_resolved;
112 /* Returns NULL on error.
113 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
114 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
115 static struct path_info *
116 uh_path_lookup(struct client *cl, const char *url)
118 static char path_phys[PATH_MAX];
119 static char path_info[PATH_MAX];
120 static struct path_info p;
122 const char *docroot = conf.docroot;
123 int docroot_len = strlen(docroot);
124 char *pathptr = NULL;
130 struct index_file *idx;
132 /* back out early if url is undefined */
136 memset(&p, 0, sizeof(p));
140 strcpy(uh_buf, docroot);
142 /* separate query string from url */
143 if ((pathptr = strchr(url, '?')) != NULL) {
144 p.query = pathptr[1] ? pathptr + 1 : NULL;
146 /* urldecode component w/o query */
148 if (uh_urldecode(&uh_buf[docroot_len],
149 sizeof(uh_buf) - docroot_len - 1,
150 url, pathptr - url ) < 0)
155 /* no query string, decode all of url */
156 else if (uh_urldecode(&uh_buf[docroot_len],
157 sizeof(uh_buf) - docroot_len - 1,
158 url, strlen(url) ) < 0)
161 /* create canon path */
162 len = strlen(uh_buf);
163 slash = len && uh_buf[len - 1] == '/';
164 len = min(len, sizeof(path_phys) - 1);
166 for (i = len; i >= 0; i--) {
170 if (ch != 0 && ch != '/')
174 exists = !!canonpath(uh_buf, path_phys);
177 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
181 /* check whether found path is within docroot */
182 if (strncmp(path_phys, docroot, docroot_len) != 0 ||
183 (path_phys[docroot_len] != 0 &&
184 path_phys[docroot_len] != '/'))
187 /* test current path */
188 if (stat(path_phys, &p.stat))
191 /* is a regular file */
192 if (p.stat.st_mode & S_IFREG) {
195 p.name = &path_phys[docroot_len];
196 p.info = path_info[0] ? path_info : NULL;
200 if (!(p.stat.st_mode & S_IFDIR))
206 pathptr = path_phys + strlen(path_phys);
208 /* ensure trailing slash */
209 if (pathptr[-1] != '/') {
215 /* if requested url resolves to a directory and a trailing slash
216 is missing in the request url, redirect the client to the same
217 url with trailing slash appended */
219 uh_http_header(cl, 302, "Found");
220 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
221 &path_phys[docroot_len],
223 p.query ? p.query : "");
229 /* try to locate index file */
230 len = path_phys + sizeof(path_phys) - pathptr - 1;
231 list_for_each_entry(idx, &index_files, list) {
232 if (strlen(idx->name) > len)
235 strcpy(pathptr, idx->name);
236 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG))
244 p.name = &path_phys[docroot_len];
246 return p.phys ? &p : NULL;
250 time_t timegm (struct tm *tm);
253 static const char * uh_file_mime_lookup(const char *path)
255 struct mimetype *m = &uh_mime_types[0];
259 e = &path[strlen(path)-1];
262 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
271 return "application/octet-stream";
274 static const char * uh_file_mktag(struct stat *s, char *buf)
276 snprintf(buf, sizeof(buf), "\"%x-%x-%x\"",
277 (unsigned int) s->st_ino,
278 (unsigned int) s->st_size,
279 (unsigned int) s->st_mtime);
284 static time_t uh_file_date2unix(const char *date)
288 memset(&t, 0, sizeof(t));
290 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
296 static char * uh_file_unix2date(time_t ts, char *buf, int len)
298 struct tm *t = gmtime(&ts);
300 strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", t);
305 static char *uh_file_header(struct client *cl, int idx)
307 if (!cl->dispatch.file.hdr[idx])
310 return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
313 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
318 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s, buf));
319 ustream_printf(cl->us, "Last-Modified: %s\r\n",
320 uh_file_unix2date(s->st_mtime, buf, sizeof(buf)));
322 ustream_printf(cl->us, "Date: %s\r\n",
323 uh_file_unix2date(time(NULL), buf, sizeof(buf)));
326 static void uh_file_response_200(struct client *cl, struct stat *s)
328 uh_http_header(cl, 200, "OK");
329 return uh_file_response_ok_hdrs(cl, s);
332 static void uh_file_response_304(struct client *cl, struct stat *s)
334 uh_http_header(cl, 304, "Not Modified");
336 return uh_file_response_ok_hdrs(cl, s);
339 static void uh_file_response_412(struct client *cl)
341 uh_http_header(cl, 412, "Precondition Failed");
344 static bool uh_file_if_match(struct client *cl, struct stat *s)
347 const char *tag = uh_file_mktag(s, buf);
348 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
356 for (i = 0; i < strlen(hdr); i++)
358 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
361 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
366 uh_file_response_412(cl);
370 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
372 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
377 if (uh_file_date2unix(hdr) >= s->st_mtime) {
378 uh_file_response_304(cl, s);
385 static int uh_file_if_none_match(struct client *cl, struct stat *s)
388 const char *tag = uh_file_mktag(s, buf);
389 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
397 for (i = 0; i < strlen(hdr); i++) {
398 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
401 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
402 if ((cl->request.method == UH_HTTP_MSG_GET) ||
403 (cl->request.method == UH_HTTP_MSG_HEAD))
404 uh_file_response_304(cl, s);
406 uh_file_response_412(cl);
415 static int uh_file_if_range(struct client *cl, struct stat *s)
417 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
420 uh_file_response_412(cl);
427 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
429 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
431 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
432 uh_file_response_412(cl);
440 static int uh_file_scandir_filter_dir(const struct dirent *e)
442 return strcmp(e->d_name, ".") ? 1 : 0;
445 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
449 char *filename = uh_buf;
451 struct dirent **files = NULL;
455 uh_file_response_200(cl, NULL);
456 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
459 "<html><head><title>Index of %s</title></head>"
460 "<body><h1>Index of %s</h1><hr /><ol>",
463 if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
468 strcpy(filename, pi->phys);
469 len = strlen(filename);
470 pathptr = filename + len;
471 len = PATH_MAX - len;
474 for (i = 0; i < count; i++) {
475 snprintf(pathptr, len, "%s", files[i]->d_name);
477 if (!stat(filename, &s) &&
478 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
480 "<li><strong><a href='%s%s/'>%s</a>/"
481 "</strong><br /><small>modified: %s"
482 "<br />directory - %.02f kbyte<br />"
483 "<br /></small></li>",
484 pi->name, files[i]->d_name,
486 uh_file_unix2date(s.st_mtime, buf, sizeof(buf)),
493 for (i = 0; i < count; i++) {
494 snprintf(pathptr, len, "%s", files[i]->d_name);
496 if (!stat(filename, &s) &&
497 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
499 "<li><strong><a href='%s%s'>%s</a>"
500 "</strong><br /><small>modified: %s"
501 "<br />%s - %.02f kbyte<br />"
502 "<br /></small></li>",
503 pi->name, files[i]->d_name,
505 uh_file_unix2date(s.st_mtime, buf, sizeof(buf)),
506 uh_file_mime_lookup(filename),
513 uh_chunk_printf(cl, "</ol><hr /></body></html>");
518 for (i = 0; i < count; i++)
525 static void file_write_cb(struct client *cl)
527 int fd = cl->dispatch.file.fd;
530 while (cl->us->w.data_bytes < 256) {
531 r = read(fd, uh_buf, sizeof(uh_buf));
542 uh_chunk_write(cl, uh_buf, r);
546 static void uh_file_free(struct client *cl)
548 close(cl->dispatch.file.fd);
551 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
553 /* test preconditions */
554 if (!uh_file_if_modified_since(cl, &pi->stat) ||
555 !uh_file_if_match(cl, &pi->stat) ||
556 !uh_file_if_range(cl, &pi->stat) ||
557 !uh_file_if_unmodified_since(cl, &pi->stat) ||
558 !uh_file_if_none_match(cl, &pi->stat)) {
565 uh_file_response_200(cl, &pi->stat);
567 ustream_printf(cl->us, "Content-Type: %s\r\n",
568 uh_file_mime_lookup(pi->name));
570 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
575 if (cl->request.method == UH_HTTP_MSG_HEAD) {
581 cl->dispatch.file.fd = fd;
582 cl->dispatch.write_cb = file_write_cb;
583 cl->dispatch.free = uh_file_free;
584 cl->dispatch.close_fds = uh_file_free;
588 static void uh_file_request(struct client *cl, const char *url,
589 struct path_info *pi, struct blob_attr **tb)
593 if (!(pi->stat.st_mode & S_IROTH))
596 if (pi->stat.st_mode & S_IFREG) {
597 fd = open(pi->phys, O_RDONLY);
601 cl->dispatch.file.hdr = tb;
602 uh_file_data(cl, pi, fd);
603 cl->dispatch.file.hdr = NULL;
607 if ((pi->stat.st_mode & S_IFDIR)) {
608 if (conf.no_dirlists)
611 uh_file_dirlist(cl, pi);
616 uh_client_error(cl, 403, "Forbidden",
617 "You don't have permission to access %s on this server.",
621 void uh_dispatch_add(struct dispatch_handler *d)
623 list_add_tail(&d->list, &dispatch_handlers);
626 static struct dispatch_handler *
627 dispatch_find(const char *url, struct path_info *pi)
629 struct dispatch_handler *d;
631 list_for_each_entry(d, &dispatch_handlers, list) {
636 if (d->check_path(pi, url))
642 if (d->check_url(url))
650 static bool __handle_file_request(struct client *cl, const char *url)
652 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
653 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
654 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
655 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
656 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
657 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
658 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
660 struct dispatch_handler *d;
661 struct blob_attr *tb[__HDR_MAX];
662 struct path_info *pi;
664 pi = uh_path_lookup(cl, url);
671 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
672 if (tb[HDR_AUTHORIZATION])
673 pi->auth = blobmsg_data(tb[HDR_AUTHORIZATION]);
675 if (!uh_auth_check(cl, pi))
678 d = dispatch_find(url, pi);
680 d->handle_request(cl, url, pi);
682 uh_file_request(cl, url, pi, tb);
687 void uh_handle_request(struct client *cl)
689 struct dispatch_handler *d;
690 const char *url = cl->request.url;
692 d = dispatch_find(url, NULL);
694 d->handle_request(cl, url, NULL);
698 if (__handle_file_request(cl, url) ||
699 __handle_file_request(cl, conf.error_handler))
702 uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", cl->request.url);