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);
37 struct list_head list;
42 HDR_IF_MODIFIED_SINCE,
43 HDR_IF_UNMODIFIED_SINCE,
50 void uh_index_add(const char *filename)
52 struct index_file *idx;
54 idx = calloc(1, sizeof(*idx));
56 list_add_tail(&idx->list, &index_files);
59 static char * canonpath(const char *path, char *path_resolved)
61 const char *path_cpy = path;
62 char *path_res = path_resolved;
65 return realpath(path, path_resolved);
68 while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
72 /* skip repeating / */
73 if (path_cpy[1] == '/') {
79 if (path_cpy[1] == '.') {
81 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
87 if ((path_cpy[2] == '.') &&
88 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
89 while ((path_res > path_resolved) && (*--path_res != '/'));
97 *path_res++ = *path_cpy++;
100 /* remove trailing slash if not root / */
101 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
103 else if (path_res == path_resolved)
108 return path_resolved;
111 /* Returns NULL on error.
112 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
113 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
114 static struct path_info *
115 uh_path_lookup(struct client *cl, const char *url)
117 static char path_phys[PATH_MAX];
118 static char path_info[PATH_MAX];
119 static struct path_info p;
121 const char *docroot = conf.docroot;
122 int docroot_len = strlen(docroot);
123 char *pathptr = NULL;
129 struct index_file *idx;
131 /* back out early if url is undefined */
135 memset(&p, 0, sizeof(p));
139 strcpy(uh_buf, docroot);
141 /* separate query string from url */
142 if ((pathptr = strchr(url, '?')) != NULL) {
143 p.query = pathptr[1] ? pathptr + 1 : NULL;
145 /* urldecode component w/o query */
147 if (uh_urldecode(&uh_buf[docroot_len],
148 sizeof(uh_buf) - docroot_len - 1,
149 url, pathptr - url ) < 0)
154 /* no query string, decode all of url */
155 else if (uh_urldecode(&uh_buf[docroot_len],
156 sizeof(uh_buf) - docroot_len - 1,
157 url, strlen(url) ) < 0)
160 /* create canon path */
161 len = strlen(uh_buf);
162 slash = len && uh_buf[len - 1] == '/';
163 len = min(len, sizeof(path_phys) - 1);
165 for (i = len; i >= 0; i--) {
169 if (ch != 0 && ch != '/')
173 exists = !!canonpath(uh_buf, path_phys);
176 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
180 /* check whether found path is within docroot */
181 if (strncmp(path_phys, docroot, docroot_len) != 0 ||
182 (path_phys[docroot_len] != 0 &&
183 path_phys[docroot_len] != '/'))
186 /* test current path */
187 if (stat(path_phys, &p.stat))
190 /* is a regular file */
191 if (p.stat.st_mode & S_IFREG) {
194 p.name = &path_phys[docroot_len];
195 p.info = path_info[0] ? path_info : NULL;
199 if (!(p.stat.st_mode & S_IFDIR))
205 pathptr = path_phys + strlen(path_phys);
207 /* ensure trailing slash */
208 if (pathptr[-1] != '/') {
214 /* if requested url resolves to a directory and a trailing slash
215 is missing in the request url, redirect the client to the same
216 url with trailing slash appended */
218 uh_http_header(cl, 302, "Found");
219 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
220 &path_phys[docroot_len],
222 p.query ? p.query : "");
228 /* try to locate index file */
229 len = path_phys + sizeof(path_phys) - pathptr - 1;
230 list_for_each_entry(idx, &index_files, list) {
231 if (strlen(idx->name) > len)
234 strcpy(pathptr, idx->name);
235 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG))
243 p.name = &path_phys[docroot_len];
245 return p.phys ? &p : NULL;
249 time_t timegm (struct tm *tm);
252 static const char * uh_file_mime_lookup(const char *path)
254 struct mimetype *m = &uh_mime_types[0];
258 e = &path[strlen(path)-1];
261 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
270 return "application/octet-stream";
273 static const char * uh_file_mktag(struct stat *s)
275 snprintf(_tag, sizeof(_tag), "\"%x-%x-%x\"",
276 (unsigned int) s->st_ino,
277 (unsigned int) s->st_size,
278 (unsigned int) s->st_mtime);
283 static time_t uh_file_date2unix(const char *date)
287 memset(&t, 0, sizeof(t));
289 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
295 static char * uh_file_unix2date(time_t ts)
297 struct tm *t = gmtime(&ts);
299 strftime(_tag, sizeof(_tag), "%a, %d %b %Y %H:%M:%S GMT", t);
304 static char *uh_file_header(struct client *cl, int idx)
306 if (!cl->dispatch.file.hdr[idx])
309 return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
312 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
315 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s));
316 ustream_printf(cl->us, "Last-Modified: %s\r\n",
317 uh_file_unix2date(s->st_mtime));
319 ustream_printf(cl->us, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
322 static void uh_file_response_200(struct client *cl, struct stat *s)
324 uh_http_header(cl, 200, "OK");
325 return uh_file_response_ok_hdrs(cl, s);
328 static void uh_file_response_304(struct client *cl, struct stat *s)
330 uh_http_header(cl, 304, "Not Modified");
332 return uh_file_response_ok_hdrs(cl, s);
335 static void uh_file_response_412(struct client *cl)
337 uh_http_header(cl, 412, "Precondition Failed");
340 static bool uh_file_if_match(struct client *cl, struct stat *s)
342 const char *tag = uh_file_mktag(s);
343 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
351 for (i = 0; i < strlen(hdr); i++)
353 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
356 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
361 uh_file_response_412(cl);
365 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
367 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
372 if (uh_file_date2unix(hdr) >= s->st_mtime) {
373 uh_file_response_304(cl, s);
380 static int uh_file_if_none_match(struct client *cl, struct stat *s)
382 const char *tag = uh_file_mktag(s);
383 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
391 for (i = 0; i < strlen(hdr); i++) {
392 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
395 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
396 if ((cl->request.method == UH_HTTP_MSG_GET) ||
397 (cl->request.method == UH_HTTP_MSG_HEAD))
398 uh_file_response_304(cl, s);
400 uh_file_response_412(cl);
409 static int uh_file_if_range(struct client *cl, struct stat *s)
411 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
414 uh_file_response_412(cl);
421 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
423 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
425 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
426 uh_file_response_412(cl);
434 static int uh_file_scandir_filter_dir(const struct dirent *e)
436 return strcmp(e->d_name, ".") ? 1 : 0;
439 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
443 char filename[PATH_MAX];
445 struct dirent **files = NULL;
448 uh_file_response_200(cl, NULL);
449 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
452 "<html><head><title>Index of %s</title></head>"
453 "<body><h1>Index of %s</h1><hr /><ol>",
456 if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
459 memset(filename, 0, sizeof(filename));
460 memcpy(filename, pi->phys, sizeof(filename));
461 pathptr = &filename[strlen(filename)];
464 for (i = 0; i < count; i++) {
465 strncat(filename, files[i]->d_name,
466 sizeof(filename) - strlen(files[i]->d_name));
468 if (!stat(filename, &s) &&
469 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
471 "<li><strong><a href='%s%s'>%s</a>/"
472 "</strong><br /><small>modified: %s"
473 "<br />directory - %.02f kbyte<br />"
474 "<br /></small></li>",
475 pi->name, files[i]->d_name,
477 uh_file_unix2date(s.st_mtime),
484 for (i = 0; i < count; i++) {
485 strncat(filename, files[i]->d_name,
486 sizeof(filename) - strlen(files[i]->d_name));
488 if (!stat(filename, &s) &&
489 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
491 "<li><strong><a href='%s%s'>%s</a>"
492 "</strong><br /><small>modified: %s"
493 "<br />%s - %.02f kbyte<br />"
494 "<br /></small></li>",
495 pi->name, files[i]->d_name,
497 uh_file_unix2date(s.st_mtime),
498 uh_file_mime_lookup(filename),
505 uh_chunk_printf(cl, "</ol><hr /></body></html>");
510 for (i = 0; i < count; i++)
517 static void file_write_cb(struct client *cl)
519 int fd = cl->dispatch.file.fd;
522 while (cl->us->w.data_bytes < 256) {
523 r = read(fd, uh_buf, sizeof(uh_buf));
534 uh_chunk_write(cl, uh_buf, r);
538 static void uh_file_free(struct client *cl)
540 close(cl->dispatch.file.fd);
543 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
545 /* test preconditions */
546 if (!uh_file_if_modified_since(cl, &pi->stat) ||
547 !uh_file_if_match(cl, &pi->stat) ||
548 !uh_file_if_range(cl, &pi->stat) ||
549 !uh_file_if_unmodified_since(cl, &pi->stat) ||
550 !uh_file_if_none_match(cl, &pi->stat)) {
557 uh_file_response_200(cl, &pi->stat);
559 ustream_printf(cl->us, "Content-Type: %s\r\n",
560 uh_file_mime_lookup(pi->name));
562 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
567 if (cl->request.method == UH_HTTP_MSG_HEAD) {
573 cl->dispatch.file.fd = fd;
574 cl->dispatch.write_cb = file_write_cb;
575 cl->dispatch.free = uh_file_free;
576 cl->dispatch.close_fds = uh_file_free;
580 static void uh_file_request(struct client *cl, struct path_info *pi, const char *url)
582 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
583 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
584 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
585 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
586 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
587 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
589 struct blob_attr *tb[__HDR_MAX];
592 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
594 cl->dispatch.file.hdr = tb;
596 if (!(pi->stat.st_mode & S_IROTH))
599 if (pi->stat.st_mode & S_IFREG) {
600 fd = open(pi->phys, O_RDONLY);
604 uh_file_data(cl, pi, fd);
605 } else if ((pi->stat.st_mode & S_IFDIR)) {
606 if (conf.no_dirlists)
609 uh_file_dirlist(cl, pi);
617 uh_client_error(cl, 403, "Forbidden",
618 "You don't have permission to access %s on this server.",
622 static bool __handle_file_request(struct client *cl, const char *url)
624 struct path_info *pi;
626 pi = uh_path_lookup(cl, url);
630 if (!pi->redirected) {
631 uh_file_request(cl, pi, url);
632 cl->dispatch.file.hdr = NULL;
638 void uh_handle_file_request(struct client *cl)
640 if (__handle_file_request(cl, cl->request.url) ||
641 __handle_file_request(cl, conf.error_handler))
644 uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", cl->request.url);