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.
20 #ifndef _DEFAULT_SOURCE
21 # define _DEFAULT_SOURCE
25 #define _DARWIN_C_SOURCE
26 #define _XOPEN_SOURCE 700
28 #include <sys/types.h>
35 #include <libubox/blobmsg.h>
38 #include "mimetypes.h"
40 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
42 static LIST_HEAD(index_files
);
43 static LIST_HEAD(dispatch_handlers
);
44 static LIST_HEAD(pending_requests
);
45 static int n_requests
;
47 struct deferred_request
{
48 struct list_head list
;
49 struct dispatch_handler
*d
;
57 struct list_head list
;
63 HDR_IF_MODIFIED_SINCE
,
64 HDR_IF_UNMODIFIED_SINCE
,
71 void uh_index_add(const char *filename
)
73 struct index_file
*idx
;
75 idx
= calloc(1, sizeof(*idx
));
77 list_add_tail(&idx
->list
, &index_files
);
80 static char * canonpath(const char *path
, char *path_resolved
)
82 const char *path_cpy
= path
;
83 char *path_res
= path_resolved
;
86 return realpath(path
, path_resolved
);
89 while ((*path_cpy
!= '\0') && (path_cpy
< (path
+ PATH_MAX
- 2))) {
93 /* skip repeating / */
94 if (path_cpy
[1] == '/') {
100 if (path_cpy
[1] == '.') {
102 if ((path_cpy
[2] == '/') || (path_cpy
[2] == '\0')) {
107 /* collapse /x/../ */
108 if ((path_cpy
[2] == '.') &&
109 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))) {
110 while ((path_res
> path_resolved
) && (*--path_res
!= '/'));
118 *path_res
++ = *path_cpy
++;
121 /* remove trailing slash if not root / */
122 if ((path_res
> (path_resolved
+1)) && (path_res
[-1] == '/'))
124 else if (path_res
== path_resolved
)
129 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. */
136 uh_path_lookup(struct client
*cl
, const char *url
)
138 static char path_phys
[PATH_MAX
];
139 static char path_info
[PATH_MAX
];
140 static char path_query
[PATH_MAX
];
141 static struct path_info p
;
143 const char *docroot
= conf
.docroot
;
144 int docroot_len
= strlen(docroot
);
145 char *pathptr
= NULL
;
151 struct index_file
*idx
;
153 /* back out early if url is undefined */
157 memset(&p
, 0, sizeof(p
));
161 strcpy(uh_buf
, docroot
);
163 /* separate query string from url */
164 if ((pathptr
= strchr(url
, '?')) != NULL
) {
166 p
.query
= path_query
;
167 snprintf(path_query
, sizeof(path_query
), "%s",
171 /* urldecode component w/o query */
173 if (uh_urldecode(&uh_buf
[docroot_len
],
174 sizeof(uh_buf
) - docroot_len
- 1,
175 url
, pathptr
- url
) < 0)
180 /* no query string, decode all of url */
181 else if (uh_urldecode(&uh_buf
[docroot_len
],
182 sizeof(uh_buf
) - docroot_len
- 1,
183 url
, strlen(url
) ) < 0)
186 /* create canon path */
187 len
= strlen(uh_buf
);
188 slash
= len
&& uh_buf
[len
- 1] == '/';
189 len
= min(len
, sizeof(path_phys
) - 1);
191 for (i
= len
; i
>= 0; i
--) {
195 if (ch
!= 0 && ch
!= '/')
199 exists
= !!canonpath(uh_buf
, path_phys
);
205 /* test current path */
206 if (stat(path_phys
, &p
.stat
))
209 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
213 /* check whether found path is within docroot */
214 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
215 (path_phys
[docroot_len
] != 0 &&
216 path_phys
[docroot_len
] != '/'))
219 /* is a regular file */
220 if (p
.stat
.st_mode
& S_IFREG
) {
223 p
.name
= &path_phys
[docroot_len
];
224 p
.info
= path_info
[0] ? path_info
: NULL
;
228 if (!(p
.stat
.st_mode
& S_IFDIR
))
234 pathptr
= path_phys
+ strlen(path_phys
);
236 /* ensure trailing slash */
237 if (pathptr
[-1] != '/') {
243 /* if requested url resolves to a directory and a trailing slash
244 is missing in the request url, redirect the client to the same
245 url with trailing slash appended */
247 uh_http_header(cl
, 302, "Found");
248 if (!uh_use_chunked(cl
))
249 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
250 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
251 &path_phys
[docroot_len
],
253 p
.query
? p
.query
: "");
259 /* try to locate index file */
260 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
261 list_for_each_entry(idx
, &index_files
, list
) {
262 if (strlen(idx
->name
) > len
)
265 strcpy(pathptr
, idx
->name
);
266 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
267 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
276 p
.name
= &path_phys
[docroot_len
];
278 return p
.phys
? &p
: NULL
;
281 static const char * uh_file_mime_lookup(const char *path
)
283 const struct mimetype
*m
= &uh_mime_types
[0];
287 e
= &path
[strlen(path
)-1];
290 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
299 return "application/octet-stream";
302 static const char * uh_file_mktag(struct stat
*s
, char *buf
, int len
)
304 snprintf(buf
, len
, "\"%" PRIx64
"-%" PRIx64
"-%" PRIx64
"\"",
305 s
->st_ino
, s
->st_size
, (uint64_t)s
->st_mtime
);
310 static time_t uh_file_date2unix(const char *date
)
314 memset(&t
, 0, sizeof(t
));
316 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
322 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
324 struct tm
*t
= gmtime(&ts
);
326 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
331 static char *uh_file_header(struct client
*cl
, int idx
)
333 if (!cl
->dispatch
.file
.hdr
[idx
])
336 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
339 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
344 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
, sizeof(buf
)));
345 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
346 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
348 ustream_printf(cl
->us
, "Date: %s\r\n",
349 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
352 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
354 uh_http_header(cl
, 200, "OK");
355 return uh_file_response_ok_hdrs(cl
, s
);
358 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
360 uh_http_header(cl
, 304, "Not Modified");
362 return uh_file_response_ok_hdrs(cl
, s
);
365 static void uh_file_response_405(struct client
*cl
)
367 uh_http_header(cl
, 405, "Method Not Allowed");
370 static void uh_file_response_412(struct client
*cl
)
372 uh_http_header(cl
, 412, "Precondition Failed");
375 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
378 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
379 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
387 for (i
= 0; i
< strlen(hdr
); i
++)
389 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
392 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
397 uh_file_response_412(cl
);
401 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
403 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
408 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
409 uh_file_response_304(cl
, s
);
416 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
419 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
420 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
428 for (i
= 0; i
< strlen(hdr
); i
++) {
429 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
432 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
433 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
434 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
435 uh_file_response_304(cl
, s
);
437 uh_file_response_412(cl
);
446 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
448 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
451 uh_file_response_412(cl
);
458 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
460 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
462 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
463 uh_file_response_412(cl
);
470 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
472 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
473 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
475 /* directories first */
477 return dir_b
- dir_a
;
479 return alphasort(a
, b
);
482 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
483 const char *path
, char *local_path
)
485 const char *suffix
= "/";
486 const char *type
= "directory";
487 unsigned int mode
= S_IXOTH
;
494 file
= local_path
+ strlen(local_path
);
495 for (i
= 0; i
< count
; i
++) {
496 const char *name
= files
[i
]->d_name
;
497 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
499 if (name
[0] == '.' && name
[1] == 0)
502 sprintf(file
, "%s", name
);
503 if (stat(local_path
, &s
))
509 type
= uh_file_mime_lookup(local_path
);
512 if (!(s
.st_mode
& mode
))
515 escaped
= uh_htmlescape(name
);
521 "<li><strong><a href='%s%s%s'>%s</a>%s"
522 "</strong><br /><small>modified: %s"
523 "<br />%s - %.02f kbyte<br />"
524 "<br /></small></li>",
525 path
, escaped
, suffix
,
527 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
528 type
, s
.st_size
/ 1024.0);
537 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
539 struct dirent
**files
= NULL
;
540 char *escaped_path
= uh_htmlescape(pi
->name
);
545 uh_client_error(cl
, 500, "Internal Server Error", "Out of memory");
549 uh_file_response_200(cl
, NULL
);
550 ustream_printf(cl
->us
, "Content-Type: text/html; charset=%s\r\n\r\n",
551 conf
.dirlist_charset
? conf
.dirlist_charset
: "UTF-8");
554 "<html><head><title>Index of %s</title></head>"
555 "<body><h1>Index of %s</h1><hr /><ol>",
556 escaped_path
, escaped_path
);
558 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
560 strcpy(uh_buf
, pi
->phys
);
561 list_entries(cl
, files
, count
, escaped_path
, uh_buf
);
566 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
570 static void file_write_cb(struct client
*cl
)
572 int fd
= cl
->dispatch
.file
.fd
;
575 while (cl
->us
->w
.data_bytes
< 256) {
576 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
587 uh_chunk_write(cl
, uh_buf
, r
);
591 static void uh_file_free(struct client
*cl
)
593 close(cl
->dispatch
.file
.fd
);
596 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
598 /* test preconditions */
599 if (!cl
->dispatch
.no_cache
&&
600 (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
601 !uh_file_if_match(cl
, &pi
->stat
) ||
602 !uh_file_if_range(cl
, &pi
->stat
) ||
603 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
604 !uh_file_if_none_match(cl
, &pi
->stat
))) {
605 ustream_printf(cl
->us
, "\r\n");
612 uh_file_response_200(cl
, &pi
->stat
);
614 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
615 uh_file_mime_lookup(pi
->name
));
617 ustream_printf(cl
->us
, "Content-Length: %" PRIu64
"\r\n\r\n",
622 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
628 cl
->dispatch
.file
.fd
= fd
;
629 cl
->dispatch
.write_cb
= file_write_cb
;
630 cl
->dispatch
.free
= uh_file_free
;
631 cl
->dispatch
.close_fds
= uh_file_free
;
635 static bool __handle_file_request(struct client
*cl
, char *url
, bool is_error_handler
);
637 static void uh_file_request(struct client
*cl
, const char *url
,
638 struct path_info
*pi
, struct blob_attr
**tb
)
641 struct http_request
*req
= &cl
->request
;
642 char *error_handler
, *escaped_url
;
644 switch (cl
->request
.method
) {
645 case UH_HTTP_MSG_GET
:
646 case UH_HTTP_MSG_POST
:
647 case UH_HTTP_MSG_HEAD
:
648 case UH_HTTP_MSG_OPTIONS
:
652 uh_file_response_405(cl
);
653 ustream_printf(cl
->us
, "\r\n");
658 if (!(pi
->stat
.st_mode
& S_IROTH
))
661 if (pi
->stat
.st_mode
& S_IFREG
) {
662 fd
= open(pi
->phys
, O_RDONLY
);
666 req
->disable_chunked
= true;
667 cl
->dispatch
.file
.hdr
= tb
;
668 uh_file_data(cl
, pi
, fd
);
669 cl
->dispatch
.file
.hdr
= NULL
;
673 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
674 if (conf
.no_dirlists
)
677 uh_file_dirlist(cl
, pi
);
682 /* check for a previously set 403 redirect status to prevent infinite
683 recursion when the error page itself lacks sufficient permissions */
684 if (conf
.error_handler
&& req
->redirect_status
!= 403) {
685 req
->redirect_status
= 403;
686 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
687 strcpy(error_handler
, conf
.error_handler
);
688 if (__handle_file_request(cl
, error_handler
, true))
692 escaped_url
= uh_htmlescape(url
);
694 uh_client_error(cl
, 403, "Forbidden",
695 "You don't have permission to access %s on this server.",
696 escaped_url
? escaped_url
: "the url");
702 void uh_dispatch_add(struct dispatch_handler
*d
)
704 list_add_tail(&d
->list
, &dispatch_handlers
);
707 static struct dispatch_handler
*
708 dispatch_find(const char *url
, struct path_info
*pi
)
710 struct dispatch_handler
*d
;
712 list_for_each_entry(d
, &dispatch_handlers
, list
) {
717 if (d
->check_path(pi
, url
))
723 if (d
->check_url(url
))
732 uh_invoke_script(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
735 d
->handle_request(cl
, url
, pi
);
738 static void uh_complete_request(struct client
*cl
)
740 struct deferred_request
*dr
;
744 while (!list_empty(&pending_requests
)) {
745 if (n_requests
>= conf
.max_script_requests
)
748 dr
= list_first_entry(&pending_requests
, struct deferred_request
, list
);
753 cl
->dispatch
.data_blocked
= false;
754 uh_invoke_script(cl
, dr
->d
, dr
->url
, dr
->path
? &dr
->pi
: NULL
);
755 client_poll_post_data(cl
);
756 ustream_poll(cl
->us
);
762 uh_free_pending_request(struct client
*cl
)
764 struct deferred_request
*dr
= cl
->dispatch
.req_data
;
767 uh_complete_request(cl
);
773 static int field_len(const char *ptr
)
778 return strlen(ptr
) + 1;
781 #define path_info_fields \
789 uh_defer_script(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
791 struct deferred_request
*dr
;
792 char *_url
, *_root
, *_phys
, *_name
, *_info
, *_query
;
794 cl
->dispatch
.req_free
= uh_free_pending_request
;
797 /* allocate enough memory to duplicate all path_info strings in one block */
799 #define _field(_name) &_##_name, field_len(pi->_name),
800 dr
= calloc_a(sizeof(*dr
), &_url
, strlen(url
) + 1, path_info_fields NULL
);
802 memcpy(&dr
->pi
, pi
, sizeof(*pi
));
805 /* copy all path_info strings */
807 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
810 dr
= calloc_a(sizeof(*dr
), &_url
, strlen(url
) + 1, NULL
);
813 cl
->dispatch
.req_data
= dr
;
814 cl
->dispatch
.data_blocked
= true;
815 dr
->url
= strcpy(_url
, url
);
818 list_add(&dr
->list
, &pending_requests
);
822 uh_invoke_handler(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
825 return d
->handle_request(cl
, url
, pi
);
827 if (n_requests
>= conf
.max_script_requests
)
828 return uh_defer_script(cl
, d
, url
, pi
);
830 cl
->dispatch
.req_free
= uh_complete_request
;
831 uh_invoke_script(cl
, d
, url
, pi
);
834 static bool __handle_file_request(struct client
*cl
, char *url
, bool is_error_handler
)
836 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
837 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
838 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
839 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
840 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
841 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
842 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
844 struct dispatch_handler
*d
;
845 struct blob_attr
*tb
[__HDR_MAX
];
846 struct path_info
*pi
;
847 char *user
, *pass
, *auth
;
849 if (is_error_handler
) {
850 d
= dispatch_find(url
, NULL
);
853 uh_invoke_handler(cl
, d
, url
, NULL
);
859 pi
= uh_path_lookup(cl
, url
);
866 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
868 auth
= tb
[HDR_AUTHORIZATION
] ? blobmsg_data(tb
[HDR_AUTHORIZATION
]) : NULL
;
870 if (!uh_auth_check(cl
, pi
->name
, auth
, &user
, &pass
))
874 blobmsg_add_string(&cl
->hdr
, "http-auth-user", user
);
875 blobmsg_add_string(&cl
->hdr
, "http-auth-pass", pass
);
878 d
= dispatch_find(url
, pi
);
880 uh_invoke_handler(cl
, d
, url
, pi
);
882 uh_file_request(cl
, url
, pi
, tb
);
887 static char *uh_handle_alias(char *old_url
)
890 static char *new_url
;
893 if (!list_empty(&conf
.cgi_alias
)) list_for_each_entry(alias
, &conf
.cgi_alias
, list
) {
898 if (!uh_path_match(alias
->alias
, old_url
))
902 path_len
= strlen(alias
->path
);
904 old_len
= strlen(old_url
) + 1;
905 new_len
= old_len
+ MAX(conf
.cgi_prefix_len
, path_len
);
907 if (new_len
> url_len
) {
908 new_url
= realloc(new_url
, new_len
);
915 strcpy(new_url
, alias
->path
);
916 else if (conf
.cgi_prefix
)
917 strcpy(new_url
, conf
.cgi_prefix
);
918 strcat(new_url
, old_url
);
925 void uh_handle_request(struct client
*cl
)
927 struct http_request
*req
= &cl
->request
;
928 struct dispatch_handler
*d
;
929 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
930 char *error_handler
, *escaped_url
;
932 blob_buf_init(&cl
->hdr_response
, 0);
933 url
= uh_handle_alias(url
);
935 uh_handler_run(cl
, &url
, false);
939 req
->redirect_status
= 200;
940 d
= dispatch_find(url
, NULL
);
942 return uh_invoke_handler(cl
, d
, url
, NULL
);
944 if (__handle_file_request(cl
, url
, false))
947 if (uh_handler_run(cl
, &url
, true)) {
951 uh_handler_run(cl
, &url
, false);
952 if (__handle_file_request(cl
, url
, false))
956 req
->redirect_status
= 404;
957 if (conf
.error_handler
) {
958 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
959 strcpy(error_handler
, conf
.error_handler
);
960 if (__handle_file_request(cl
, error_handler
, true))
964 escaped_url
= uh_htmlescape(url
);
966 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.",
967 escaped_url
? escaped_url
: "");