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 char _tag[128];
34 static LIST_HEAD(index_files);
35 static LIST_HEAD(dispatch_handlers);
38 struct list_head list;
44 HDR_IF_MODIFIED_SINCE,
45 HDR_IF_UNMODIFIED_SINCE,
52 void uh_index_add(const char *filename)
54 struct index_file *idx;
56 idx = calloc(1, sizeof(*idx));
58 list_add_tail(&idx->list, &index_files);
61 static char * canonpath(const char *path, char *path_resolved)
63 const char *path_cpy = path;
64 char *path_res = path_resolved;
67 return realpath(path, path_resolved);
70 while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
74 /* skip repeating / */
75 if (path_cpy[1] == '/') {
81 if (path_cpy[1] == '.') {
83 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
89 if ((path_cpy[2] == '.') &&
90 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
91 while ((path_res > path_resolved) && (*--path_res != '/'));
99 *path_res++ = *path_cpy++;
102 /* remove trailing slash if not root / */
103 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
105 else if (path_res == path_resolved)
110 return path_resolved;
113 /* Returns NULL on error.
114 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
115 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
116 static struct path_info *
117 uh_path_lookup(struct client *cl, const char *url)
119 static char path_phys[PATH_MAX];
120 static char path_info[PATH_MAX];
121 static struct path_info p;
123 const char *docroot = conf.docroot;
124 int docroot_len = strlen(docroot);
125 char *pathptr = NULL;
131 struct index_file *idx;
133 /* back out early if url is undefined */
137 memset(&p, 0, sizeof(p));
141 strcpy(uh_buf, docroot);
143 /* separate query string from url */
144 if ((pathptr = strchr(url, '?')) != NULL) {
145 p.query = pathptr[1] ? pathptr + 1 : NULL;
147 /* urldecode component w/o query */
149 if (uh_urldecode(&uh_buf[docroot_len],
150 sizeof(uh_buf) - docroot_len - 1,
151 url, pathptr - url ) < 0)
156 /* no query string, decode all of url */
157 else if (uh_urldecode(&uh_buf[docroot_len],
158 sizeof(uh_buf) - docroot_len - 1,
159 url, strlen(url) ) < 0)
162 /* create canon path */
163 len = strlen(uh_buf);
164 slash = len && uh_buf[len - 1] == '/';
165 len = min(len, sizeof(path_phys) - 1);
167 for (i = len; i >= 0; i--) {
171 if (ch != 0 && ch != '/')
175 exists = !!canonpath(uh_buf, path_phys);
178 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
182 /* check whether found path is within docroot */
183 if (strncmp(path_phys, docroot, docroot_len) != 0 ||
184 (path_phys[docroot_len] != 0 &&
185 path_phys[docroot_len] != '/'))
188 /* test current path */
189 if (stat(path_phys, &p.stat))
192 /* is a regular file */
193 if (p.stat.st_mode & S_IFREG) {
196 p.name = &path_phys[docroot_len];
197 p.info = path_info[0] ? path_info : NULL;
201 if (!(p.stat.st_mode & S_IFDIR))
207 pathptr = path_phys + strlen(path_phys);
209 /* ensure trailing slash */
210 if (pathptr[-1] != '/') {
216 /* if requested url resolves to a directory and a trailing slash
217 is missing in the request url, redirect the client to the same
218 url with trailing slash appended */
220 uh_http_header(cl, 302, "Found");
221 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
222 &path_phys[docroot_len],
224 p.query ? p.query : "");
230 /* try to locate index file */
231 len = path_phys + sizeof(path_phys) - pathptr - 1;
232 list_for_each_entry(idx, &index_files, list) {
233 if (strlen(idx->name) > len)
236 strcpy(pathptr, idx->name);
237 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG))
245 p.name = &path_phys[docroot_len];
247 return p.phys ? &p : NULL;
251 time_t timegm (struct tm *tm);
254 static const char * uh_file_mime_lookup(const char *path)
256 struct mimetype *m = &uh_mime_types[0];
260 e = &path[strlen(path)-1];
263 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
272 return "application/octet-stream";
275 static const char * uh_file_mktag(struct stat *s)
277 snprintf(_tag, sizeof(_tag), "\"%x-%x-%x\"",
278 (unsigned int) s->st_ino,
279 (unsigned int) s->st_size,
280 (unsigned int) s->st_mtime);
285 static time_t uh_file_date2unix(const char *date)
289 memset(&t, 0, sizeof(t));
291 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
297 static char * uh_file_unix2date(time_t ts)
299 struct tm *t = gmtime(&ts);
301 strftime(_tag, sizeof(_tag), "%a, %d %b %Y %H:%M:%S GMT", t);
306 static char *uh_file_header(struct client *cl, int idx)
308 if (!cl->dispatch.file.hdr[idx])
311 return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
314 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
317 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s));
318 ustream_printf(cl->us, "Last-Modified: %s\r\n",
319 uh_file_unix2date(s->st_mtime));
321 ustream_printf(cl->us, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
324 static void uh_file_response_200(struct client *cl, struct stat *s)
326 uh_http_header(cl, 200, "OK");
327 return uh_file_response_ok_hdrs(cl, s);
330 static void uh_file_response_304(struct client *cl, struct stat *s)
332 uh_http_header(cl, 304, "Not Modified");
334 return uh_file_response_ok_hdrs(cl, s);
337 static void uh_file_response_412(struct client *cl)
339 uh_http_header(cl, 412, "Precondition Failed");
342 static bool uh_file_if_match(struct client *cl, struct stat *s)
344 const char *tag = uh_file_mktag(s);
345 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
353 for (i = 0; i < strlen(hdr); i++)
355 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
358 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
363 uh_file_response_412(cl);
367 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
369 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
374 if (uh_file_date2unix(hdr) >= s->st_mtime) {
375 uh_file_response_304(cl, s);
382 static int uh_file_if_none_match(struct client *cl, struct stat *s)
384 const char *tag = uh_file_mktag(s);
385 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
393 for (i = 0; i < strlen(hdr); i++) {
394 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
397 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
398 if ((cl->request.method == UH_HTTP_MSG_GET) ||
399 (cl->request.method == UH_HTTP_MSG_HEAD))
400 uh_file_response_304(cl, s);
402 uh_file_response_412(cl);
411 static int uh_file_if_range(struct client *cl, struct stat *s)
413 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
416 uh_file_response_412(cl);
423 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
425 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
427 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
428 uh_file_response_412(cl);
436 static int uh_file_scandir_filter_dir(const struct dirent *e)
438 return strcmp(e->d_name, ".") ? 1 : 0;
441 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
445 char filename[PATH_MAX];
447 struct dirent **files = NULL;
450 uh_file_response_200(cl, NULL);
451 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
454 "<html><head><title>Index of %s</title></head>"
455 "<body><h1>Index of %s</h1><hr /><ol>",
458 if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
461 memset(filename, 0, sizeof(filename));
462 memcpy(filename, pi->phys, sizeof(filename));
463 pathptr = &filename[strlen(filename)];
466 for (i = 0; i < count; i++) {
467 strncat(filename, files[i]->d_name,
468 sizeof(filename) - strlen(files[i]->d_name));
470 if (!stat(filename, &s) &&
471 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
473 "<li><strong><a href='%s%s/'>%s</a>/"
474 "</strong><br /><small>modified: %s"
475 "<br />directory - %.02f kbyte<br />"
476 "<br /></small></li>",
477 pi->name, files[i]->d_name,
479 uh_file_unix2date(s.st_mtime),
486 for (i = 0; i < count; i++) {
487 strncat(filename, files[i]->d_name,
488 sizeof(filename) - strlen(files[i]->d_name));
490 if (!stat(filename, &s) &&
491 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
493 "<li><strong><a href='%s%s'>%s</a>"
494 "</strong><br /><small>modified: %s"
495 "<br />%s - %.02f kbyte<br />"
496 "<br /></small></li>",
497 pi->name, files[i]->d_name,
499 uh_file_unix2date(s.st_mtime),
500 uh_file_mime_lookup(filename),
507 uh_chunk_printf(cl, "</ol><hr /></body></html>");
512 for (i = 0; i < count; i++)
519 static void file_write_cb(struct client *cl)
521 int fd = cl->dispatch.file.fd;
524 while (cl->us->w.data_bytes < 256) {
525 r = read(fd, uh_buf, sizeof(uh_buf));
536 uh_chunk_write(cl, uh_buf, r);
540 static void uh_file_free(struct client *cl)
542 close(cl->dispatch.file.fd);
545 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
547 /* test preconditions */
548 if (!uh_file_if_modified_since(cl, &pi->stat) ||
549 !uh_file_if_match(cl, &pi->stat) ||
550 !uh_file_if_range(cl, &pi->stat) ||
551 !uh_file_if_unmodified_since(cl, &pi->stat) ||
552 !uh_file_if_none_match(cl, &pi->stat)) {
559 uh_file_response_200(cl, &pi->stat);
561 ustream_printf(cl->us, "Content-Type: %s\r\n",
562 uh_file_mime_lookup(pi->name));
564 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
569 if (cl->request.method == UH_HTTP_MSG_HEAD) {
575 cl->dispatch.file.fd = fd;
576 cl->dispatch.write_cb = file_write_cb;
577 cl->dispatch.free = uh_file_free;
578 cl->dispatch.close_fds = uh_file_free;
582 static void uh_file_request(struct client *cl, const char *url,
583 struct path_info *pi, struct blob_attr **tb)
587 if (!(pi->stat.st_mode & S_IROTH))
590 if (pi->stat.st_mode & S_IFREG) {
591 fd = open(pi->phys, O_RDONLY);
595 cl->dispatch.file.hdr = tb;
596 uh_file_data(cl, pi, fd);
597 cl->dispatch.file.hdr = NULL;
601 if ((pi->stat.st_mode & S_IFDIR)) {
602 if (conf.no_dirlists)
605 uh_file_dirlist(cl, pi);
610 uh_client_error(cl, 403, "Forbidden",
611 "You don't have permission to access %s on this server.",
615 void uh_dispatch_add(struct dispatch_handler *d)
617 list_add_tail(&d->list, &dispatch_handlers);
620 static struct dispatch_handler *
621 dispatch_find(const char *url, struct path_info *pi)
623 struct dispatch_handler *d;
625 list_for_each_entry(d, &dispatch_handlers, list) {
630 if (d->check_path(pi, url))
636 if (d->check_url(url))
644 static bool __handle_file_request(struct client *cl, const char *url)
646 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
647 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
648 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
649 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
650 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
651 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
652 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
654 struct dispatch_handler *d;
655 struct blob_attr *tb[__HDR_MAX];
656 struct path_info *pi;
658 pi = uh_path_lookup(cl, url);
665 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
666 if (tb[HDR_AUTHORIZATION])
667 pi->auth = blobmsg_data(tb[HDR_AUTHORIZATION]);
669 if (!uh_auth_check(cl, pi))
672 d = dispatch_find(url, pi);
674 d->handle_request(cl, url, pi);
676 uh_file_request(cl, url, pi, tb);
681 void uh_handle_request(struct client *cl)
683 struct dispatch_handler *d;
684 const char *url = cl->request.url;
686 d = dispatch_find(url, NULL);
688 d->handle_request(cl, url, NULL);
692 if (__handle_file_request(cl, url) ||
693 __handle_file_request(cl, conf.error_handler))
696 uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", cl->request.url);