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 "uhttpd-mimetypes.h"
33 static LIST_HEAD(index_files);
36 struct list_head list;
51 HDR_IF_MODIFIED_SINCE,
52 HDR_IF_UNMODIFIED_SINCE,
59 void uh_index_add(const char *filename)
61 struct index_file *idx;
63 idx = calloc(1, sizeof(*idx));
65 list_add_tail(&idx->list, &index_files);
68 static char * canonpath(const char *path, char *path_resolved)
70 char path_copy[PATH_MAX];
71 char *path_cpy = path_copy;
72 char *path_res = path_resolved;
75 /* relative -> absolute */
77 getcwd(path_copy, PATH_MAX);
78 strncat(path_copy, "/", PATH_MAX - strlen(path_copy));
79 strncat(path_copy, path, PATH_MAX - strlen(path_copy));
81 strncpy(path_copy, path, PATH_MAX);
85 while ((*path_cpy != '\0') && (path_cpy < (path_copy + PATH_MAX - 2))) {
89 /* skip repeating / */
90 if (path_cpy[1] == '/') {
96 if (path_cpy[1] == '.') {
98 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
103 /* collapse /x/../ */
104 if ((path_cpy[2] == '.') &&
105 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
106 while ((path_res > path_resolved) && (*--path_res != '/'));
114 *path_res++ = *path_cpy++;
117 /* remove trailing slash if not root / */
118 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
120 else if (path_res == path_resolved)
126 if (!stat(path_resolved, &s) && (s.st_mode & S_IROTH))
127 return path_resolved;
132 /* Returns NULL on error.
133 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
134 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
135 struct path_info * 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 struct path_info p;
141 char buffer[UH_LIMIT_MSGHEAD];
142 char *docroot = conf.docroot;
143 char *pathptr = NULL;
146 int no_sym = conf.no_symlinks;
149 struct index_file *idx;
151 /* back out early if url is undefined */
155 memset(path_phys, 0, sizeof(path_phys));
156 memset(path_info, 0, sizeof(path_info));
157 memset(buffer, 0, sizeof(buffer));
158 memset(&p, 0, sizeof(p));
161 memcpy(buffer, docroot,
162 min(strlen(docroot), sizeof(buffer) - 1));
164 /* separate query string from url */
165 if ((pathptr = strchr(url, '?')) != NULL) {
166 p.query = pathptr[1] ? pathptr + 1 : NULL;
168 /* urldecode component w/o query */
170 if (uh_urldecode(&buffer[strlen(docroot)],
171 sizeof(buffer) - strlen(docroot) - 1,
172 url, pathptr - url ) < 0)
173 return NULL; /* bad URL */
177 /* no query string, decode all of url */
178 else if (uh_urldecode(&buffer[strlen(docroot)],
179 sizeof(buffer) - strlen(docroot) - 1,
180 url, strlen(url) ) < 0)
181 return NULL; /* bad URL */
183 /* create canon path */
184 for (i = strlen(buffer), slash = (buffer[max(0, i-1)] == '/'); i >= 0; i--) {
185 if ((buffer[i] == 0) || (buffer[i] == '/')) {
186 memset(path_info, 0, sizeof(path_info));
187 memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
189 if (no_sym ? realpath(path_info, path_phys)
190 : canonpath(path_info, path_phys)) {
191 memset(path_info, 0, sizeof(path_info));
192 memcpy(path_info, &buffer[i],
193 min(strlen(buffer) - i, sizeof(path_info) - 1));
200 /* check whether found path is within docroot */
201 if (strncmp(path_phys, docroot, strlen(docroot)) ||
202 ((path_phys[strlen(docroot)] != 0) &&
203 (path_phys[strlen(docroot)] != '/')))
206 /* test current path */
207 if (!stat(path_phys, &p.stat)) {
208 /* is a regular file */
209 if (p.stat.st_mode & S_IFREG) {
212 p.name = &path_phys[strlen(docroot)];
213 p.info = path_info[0] ? path_info : NULL;
217 else if ((p.stat.st_mode & S_IFDIR) && !strlen(path_info)) {
218 /* ensure trailing slash */
219 if (path_phys[strlen(path_phys)-1] != '/')
220 path_phys[strlen(path_phys)] = '/';
222 /* try to locate index file */
223 memset(buffer, 0, sizeof(buffer));
224 memcpy(buffer, path_phys, sizeof(buffer));
225 pathptr = &buffer[strlen(buffer)];
227 /* if requested url resolves to a directory and a trailing slash
228 is missing in the request url, redirect the client to the same
229 url with trailing slash appended */
231 uh_http_header(cl, 302, "Found");
232 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
233 &path_phys[strlen(docroot)],
235 p.query ? p.query : "");
239 list_for_each_entry(idx, &index_files, list) {
240 strncat(buffer, idx->name, sizeof(buffer));
242 if (!stat(buffer, &s) && (s.st_mode & S_IFREG)) {
243 memcpy(path_phys, buffer, sizeof(path_phys));
244 memcpy(&p.stat, &s, sizeof(p.stat));
254 p.name = &path_phys[strlen(docroot)];
258 return p.phys ? &p : NULL;
262 time_t timegm (struct tm *tm);
265 static const char * uh_file_mime_lookup(const char *path)
267 struct mimetype *m = &uh_mime_types[0];
271 e = &path[strlen(path)-1];
274 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
283 return "application/octet-stream";
286 static const char * uh_file_mktag(struct stat *s)
288 static char tag[128];
290 snprintf(tag, sizeof(tag), "\"%x-%x-%x\"",
291 (unsigned int) s->st_ino,
292 (unsigned int) s->st_size,
293 (unsigned int) s->st_mtime);
298 static time_t uh_file_date2unix(const char *date)
302 memset(&t, 0, sizeof(t));
304 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
310 static char * uh_file_unix2date(time_t ts)
312 static char str[128];
313 struct tm *t = gmtime(&ts);
315 strftime(str, sizeof(str), "%a, %d %b %Y %H:%M:%S GMT", t);
320 static char *uh_file_header(struct client *cl, int idx)
322 if (!cl->data.file.hdr[idx])
325 return (char *) blobmsg_data(cl->data.file.hdr[idx]);
328 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));
332 ustream_printf(cl->us, "Last-Modified: %s\r\n",
333 uh_file_unix2date(s->st_mtime));
335 ustream_printf(cl->us, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
338 static void uh_file_response_200(struct client *cl, struct stat *s)
340 uh_http_header(cl, 200, "OK");
341 return uh_file_response_ok_hdrs(cl, s);
344 static void uh_file_response_304(struct client *cl, struct stat *s)
346 uh_http_header(cl, 304, "Not Modified");
348 return uh_file_response_ok_hdrs(cl, s);
351 static void uh_file_response_412(struct client *cl)
353 uh_http_header(cl, 412, "Precondition Failed");
356 static bool uh_file_if_match(struct client *cl, struct stat *s)
358 const char *tag = uh_file_mktag(s);
359 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
367 for (i = 0; i < strlen(hdr); i++)
369 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
372 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
377 uh_file_response_412(cl);
381 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
383 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
388 if (uh_file_date2unix(hdr) >= s->st_mtime) {
389 uh_file_response_304(cl, s);
396 static int uh_file_if_none_match(struct client *cl, struct stat *s)
398 const char *tag = uh_file_mktag(s);
399 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
407 for (i = 0; i < strlen(hdr); i++) {
408 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
411 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
412 if ((cl->request.method == UH_HTTP_MSG_GET) ||
413 (cl->request.method == UH_HTTP_MSG_HEAD))
414 uh_file_response_304(cl, s);
416 uh_file_response_412(cl);
425 static int uh_file_if_range(struct client *cl, struct stat *s)
427 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
430 uh_file_response_412(cl);
437 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
439 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
441 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
442 uh_file_response_412(cl);
450 static int uh_file_scandir_filter_dir(const struct dirent *e)
452 return strcmp(e->d_name, ".") ? 1 : 0;
455 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
459 char filename[PATH_MAX];
461 struct dirent **files = NULL;
464 uh_file_response_200(cl, NULL);
465 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
468 "<html><head><title>Index of %s</title></head>"
469 "<body><h1>Index of %s</h1><hr /><ol>",
472 if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
475 memset(filename, 0, sizeof(filename));
476 memcpy(filename, pi->phys, sizeof(filename));
477 pathptr = &filename[strlen(filename)];
480 for (i = 0; i < count; i++) {
481 strncat(filename, files[i]->d_name,
482 sizeof(filename) - strlen(files[i]->d_name));
484 if (!stat(filename, &s) &&
485 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
487 "<li><strong><a href='%s%s'>%s</a>/"
488 "</strong><br /><small>modified: %s"
489 "<br />directory - %.02f kbyte<br />"
490 "<br /></small></li>",
491 pi->name, files[i]->d_name,
493 uh_file_unix2date(s.st_mtime),
500 for (i = 0; i < count; i++) {
501 strncat(filename, files[i]->d_name,
502 sizeof(filename) - strlen(files[i]->d_name));
504 if (!stat(filename, &s) &&
505 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
507 "<li><strong><a href='%s%s'>%s</a>"
508 "</strong><br /><small>modified: %s"
509 "<br />%s - %.02f kbyte<br />"
510 "<br /></small></li>",
511 pi->name, files[i]->d_name,
513 uh_file_unix2date(s.st_mtime),
514 uh_file_mime_lookup(filename),
521 uh_chunk_printf(cl, "</ol><hr /></body></html>");
526 for (i = 0; i < count; i++)
533 static void file_write_cb(struct client *cl)
536 int fd = cl->data.file.fd;
539 while (cl->us->w.data_bytes < 256) {
540 r = read(fd, buf, sizeof(buf));
551 uh_chunk_write(cl, buf, r);
555 static void uh_file_free(struct client *cl)
557 close(cl->data.file.fd);
560 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
562 /* test preconditions */
563 if (!uh_file_if_modified_since(cl, &pi->stat) ||
564 !uh_file_if_match(cl, &pi->stat) ||
565 !uh_file_if_range(cl, &pi->stat) ||
566 !uh_file_if_unmodified_since(cl, &pi->stat) ||
567 !uh_file_if_none_match(cl, &pi->stat)) {
574 uh_file_response_200(cl, &pi->stat);
576 ustream_printf(cl->us, "Content-Type: %s\r\n",
577 uh_file_mime_lookup(pi->name));
579 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
584 if (cl->request.method == UH_HTTP_MSG_HEAD) {
590 cl->data.file.fd = fd;
591 cl->dispatch_write_cb = file_write_cb;
592 cl->dispatch_free = uh_file_free;
596 static void uh_file_request(struct client *cl, struct path_info *pi)
598 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
599 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
600 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
601 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
602 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
603 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
605 struct blob_attr *tb[__HDR_MAX];
608 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
610 cl->data.file.hdr = tb;
611 if ((pi->stat.st_mode & S_IFREG) && ((fd = open(pi->phys, O_RDONLY)) > 0))
612 uh_file_data(cl, pi, fd);
613 else if ((pi->stat.st_mode & S_IFDIR) && !conf.no_dirlists)
614 uh_file_dirlist(cl, pi);
616 uh_client_error(cl, 403, "Forbidden",
617 "Access to this resource is forbidden");
618 cl->data.file.hdr = NULL;
621 static bool __handle_file_request(struct client *cl, const char *url)
623 struct path_info *pi;
625 pi = uh_path_lookup(cl, url);
630 uh_file_request(cl, pi);
635 void uh_handle_file_request(struct client *cl)
637 if (__handle_file_request(cl, cl->request.url) ||
638 __handle_file_request(cl, conf.error_handler))
641 uh_client_error(cl, 404, "Not Found", "No such file or directory");