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.
21 #define _DARWIN_C_SOURCE
22 #define _XOPEN_SOURCE 700
24 #include <sys/types.h>
31 #include <libubox/blobmsg.h>
34 #include "mimetypes.h"
36 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
38 static LIST_HEAD(index_files
);
39 static LIST_HEAD(dispatch_handlers
);
40 static LIST_HEAD(pending_requests
);
41 static int n_requests
;
43 struct deferred_request
{
44 struct list_head list
;
45 struct dispatch_handler
*d
;
52 struct list_head list
;
58 HDR_IF_MODIFIED_SINCE
,
59 HDR_IF_UNMODIFIED_SINCE
,
66 void uh_index_add(const char *filename
)
68 struct index_file
*idx
;
70 idx
= calloc(1, sizeof(*idx
));
72 list_add_tail(&idx
->list
, &index_files
);
75 static char * canonpath(const char *path
, char *path_resolved
)
77 const char *path_cpy
= path
;
78 char *path_res
= path_resolved
;
81 return realpath(path
, path_resolved
);
84 while ((*path_cpy
!= '\0') && (path_cpy
< (path
+ PATH_MAX
- 2))) {
88 /* skip repeating / */
89 if (path_cpy
[1] == '/') {
95 if (path_cpy
[1] == '.') {
97 if ((path_cpy
[2] == '/') || (path_cpy
[2] == '\0')) {
102 /* collapse /x/../ */
103 if ((path_cpy
[2] == '.') &&
104 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))) {
105 while ((path_res
> path_resolved
) && (*--path_res
!= '/'));
113 *path_res
++ = *path_cpy
++;
116 /* remove trailing slash if not root / */
117 if ((path_res
> (path_resolved
+1)) && (path_res
[-1] == '/'))
119 else if (path_res
== path_resolved
)
124 return path_resolved
;
127 /* Returns NULL on error.
128 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
129 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
131 uh_path_lookup(struct client
*cl
, const char *url
)
133 static char path_phys
[PATH_MAX
];
134 static char path_info
[PATH_MAX
];
135 static struct path_info p
;
137 const char *docroot
= conf
.docroot
;
138 int docroot_len
= strlen(docroot
);
139 char *pathptr
= NULL
;
145 struct index_file
*idx
;
147 /* back out early if url is undefined */
151 memset(&p
, 0, sizeof(p
));
155 strcpy(uh_buf
, docroot
);
157 /* separate query string from url */
158 if ((pathptr
= strchr(url
, '?')) != NULL
) {
159 p
.query
= pathptr
[1] ? pathptr
+ 1 : NULL
;
161 /* urldecode component w/o query */
163 if (uh_urldecode(&uh_buf
[docroot_len
],
164 sizeof(uh_buf
) - docroot_len
- 1,
165 url
, pathptr
- url
) < 0)
170 /* no query string, decode all of url */
171 else if (uh_urldecode(&uh_buf
[docroot_len
],
172 sizeof(uh_buf
) - docroot_len
- 1,
173 url
, strlen(url
) ) < 0)
176 /* create canon path */
177 len
= strlen(uh_buf
);
178 slash
= len
&& uh_buf
[len
- 1] == '/';
179 len
= min(len
, sizeof(path_phys
) - 1);
181 for (i
= len
; i
>= 0; i
--) {
185 if (ch
!= 0 && ch
!= '/')
189 exists
= !!canonpath(uh_buf
, path_phys
);
195 /* test current path */
196 if (stat(path_phys
, &p
.stat
))
199 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
203 /* check whether found path is within docroot */
204 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
205 (path_phys
[docroot_len
] != 0 &&
206 path_phys
[docroot_len
] != '/'))
209 /* is a regular file */
210 if (p
.stat
.st_mode
& S_IFREG
) {
213 p
.name
= &path_phys
[docroot_len
];
214 p
.info
= path_info
[0] ? path_info
: NULL
;
218 if (!(p
.stat
.st_mode
& S_IFDIR
))
224 pathptr
= path_phys
+ strlen(path_phys
);
226 /* ensure trailing slash */
227 if (pathptr
[-1] != '/') {
233 /* if requested url resolves to a directory and a trailing slash
234 is missing in the request url, redirect the client to the same
235 url with trailing slash appended */
237 uh_http_header(cl
, 302, "Found");
238 if (!uh_use_chunked(cl
))
239 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
240 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
241 &path_phys
[docroot_len
],
243 p
.query
? p
.query
: "");
249 /* try to locate index file */
250 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
251 list_for_each_entry(idx
, &index_files
, list
) {
252 if (strlen(idx
->name
) > len
)
255 strcpy(pathptr
, idx
->name
);
256 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
257 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
266 p
.name
= &path_phys
[docroot_len
];
268 return p
.phys
? &p
: NULL
;
271 static const char * uh_file_mime_lookup(const char *path
)
273 const struct mimetype
*m
= &uh_mime_types
[0];
277 e
= &path
[strlen(path
)-1];
280 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
289 return "application/octet-stream";
292 static const char * uh_file_mktag(struct stat
*s
, char *buf
, int len
)
294 snprintf(buf
, len
, "\"%" PRIx64
"-%" PRIx64
"-%" PRIx64
"\"",
295 s
->st_ino
, s
->st_size
, (uint64_t)s
->st_mtime
);
300 static time_t uh_file_date2unix(const char *date
)
304 memset(&t
, 0, sizeof(t
));
306 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
312 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
314 struct tm
*t
= gmtime(&ts
);
316 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
321 static char *uh_file_header(struct client
*cl
, int idx
)
323 if (!cl
->dispatch
.file
.hdr
[idx
])
326 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
329 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
334 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
, sizeof(buf
)));
335 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
336 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
338 ustream_printf(cl
->us
, "Date: %s\r\n",
339 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
342 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
344 uh_http_header(cl
, 200, "OK");
345 return uh_file_response_ok_hdrs(cl
, s
);
348 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
350 uh_http_header(cl
, 304, "Not Modified");
352 return uh_file_response_ok_hdrs(cl
, s
);
355 static void uh_file_response_412(struct client
*cl
)
357 uh_http_header(cl
, 412, "Precondition Failed");
360 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
363 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
364 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
372 for (i
= 0; i
< strlen(hdr
); i
++)
374 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
377 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
382 uh_file_response_412(cl
);
386 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
388 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
393 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
394 uh_file_response_304(cl
, s
);
401 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
404 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
405 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
413 for (i
= 0; i
< strlen(hdr
); i
++) {
414 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
417 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
418 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
419 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
420 uh_file_response_304(cl
, s
);
422 uh_file_response_412(cl
);
431 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
433 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
436 uh_file_response_412(cl
);
443 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
445 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
447 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
448 uh_file_response_412(cl
);
455 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
457 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
458 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
460 /* directories first */
462 return dir_b
- dir_a
;
464 return alphasort(a
, b
);
467 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
468 const char *path
, char *local_path
)
470 const char *suffix
= "/";
471 const char *type
= "directory";
472 unsigned int mode
= S_IXOTH
;
478 file
= local_path
+ strlen(local_path
);
479 for (i
= 0; i
< count
; i
++) {
480 const char *name
= files
[i
]->d_name
;
481 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
483 if (name
[0] == '.' && name
[1] == 0)
486 sprintf(file
, "%s", name
);
487 if (stat(local_path
, &s
))
493 type
= uh_file_mime_lookup(local_path
);
496 if (!(s
.st_mode
& mode
))
500 "<li><strong><a href='%s%s%s'>%s</a>%s"
501 "</strong><br /><small>modified: %s"
502 "<br />%s - %.02f kbyte<br />"
503 "<br /></small></li>",
506 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
507 type
, s
.st_size
/ 1024.0);
515 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
517 struct dirent
**files
= NULL
;
520 uh_file_response_200(cl
, NULL
);
521 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
524 "<html><head><title>Index of %s</title></head>"
525 "<body><h1>Index of %s</h1><hr /><ol>",
528 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
530 strcpy(uh_buf
, pi
->phys
);
531 list_entries(cl
, files
, count
, pi
->name
, uh_buf
);
535 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
539 static void file_write_cb(struct client
*cl
)
541 int fd
= cl
->dispatch
.file
.fd
;
544 while (cl
->us
->w
.data_bytes
< 256) {
545 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
556 uh_chunk_write(cl
, uh_buf
, r
);
560 static void uh_file_free(struct client
*cl
)
562 close(cl
->dispatch
.file
.fd
);
565 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
567 /* test preconditions */
568 if (!cl
->dispatch
.no_cache
&&
569 (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
570 !uh_file_if_match(cl
, &pi
->stat
) ||
571 !uh_file_if_range(cl
, &pi
->stat
) ||
572 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
573 !uh_file_if_none_match(cl
, &pi
->stat
))) {
574 ustream_printf(cl
->us
, "\r\n");
581 uh_file_response_200(cl
, &pi
->stat
);
583 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
584 uh_file_mime_lookup(pi
->name
));
586 ustream_printf(cl
->us
, "Content-Length: %" PRIu64
"\r\n\r\n",
591 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
597 cl
->dispatch
.file
.fd
= fd
;
598 cl
->dispatch
.write_cb
= file_write_cb
;
599 cl
->dispatch
.free
= uh_file_free
;
600 cl
->dispatch
.close_fds
= uh_file_free
;
604 static bool __handle_file_request(struct client
*cl
, char *url
);
606 static void uh_file_request(struct client
*cl
, const char *url
,
607 struct path_info
*pi
, struct blob_attr
**tb
)
610 struct http_request
*req
= &cl
->request
;
613 if (!(pi
->stat
.st_mode
& S_IROTH
))
616 if (pi
->stat
.st_mode
& S_IFREG
) {
617 fd
= open(pi
->phys
, O_RDONLY
);
621 req
->disable_chunked
= true;
622 cl
->dispatch
.file
.hdr
= tb
;
623 uh_file_data(cl
, pi
, fd
);
624 cl
->dispatch
.file
.hdr
= NULL
;
628 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
629 if (conf
.no_dirlists
)
632 uh_file_dirlist(cl
, pi
);
637 /* check for a previously set 403 redirect status to prevent infinite
638 recursion when the error page itself lacks sufficient permissions */
639 if (conf
.error_handler
&& req
->redirect_status
!= 403) {
640 req
->redirect_status
= 403;
641 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
642 strcpy(error_handler
, conf
.error_handler
);
643 if (__handle_file_request(cl
, error_handler
))
647 uh_client_error(cl
, 403, "Forbidden",
648 "You don't have permission to access %s on this server.",
652 void uh_dispatch_add(struct dispatch_handler
*d
)
654 list_add_tail(&d
->list
, &dispatch_handlers
);
657 static struct dispatch_handler
*
658 dispatch_find(const char *url
, struct path_info
*pi
)
660 struct dispatch_handler
*d
;
662 list_for_each_entry(d
, &dispatch_handlers
, list
) {
667 if (d
->check_path(pi
, url
))
673 if (d
->check_url(url
))
682 uh_invoke_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
684 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
687 d
->handle_request(cl
, url
, pi
);
690 static void uh_complete_request(struct client
*cl
)
692 struct deferred_request
*dr
;
696 while (!list_empty(&pending_requests
)) {
697 if (n_requests
>= conf
.max_script_requests
)
700 dr
= list_first_entry(&pending_requests
, struct deferred_request
, list
);
705 cl
->dispatch
.data_blocked
= false;
706 uh_invoke_script(cl
, dr
->d
, dr
->path
? &dr
->pi
: NULL
);
707 client_poll_post_data(cl
);
713 uh_free_pending_request(struct client
*cl
)
715 struct deferred_request
*dr
= cl
->dispatch
.req_data
;
718 uh_complete_request(cl
);
724 static int field_len(const char *ptr
)
729 return strlen(ptr
) + 1;
732 #define path_info_fields \
741 uh_defer_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
743 struct deferred_request
*dr
;
744 char *_root
, *_phys
, *_name
, *_info
, *_query
, *_auth
;
746 cl
->dispatch
.req_free
= uh_free_pending_request
;
749 /* allocate enough memory to duplicate all path_info strings in one block */
751 #define _field(_name) &_##_name, field_len(pi->_name),
752 dr
= calloc_a(sizeof(*dr
), path_info_fields NULL
);
754 memcpy(&dr
->pi
, pi
, sizeof(*pi
));
757 /* copy all path_info strings */
759 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
762 dr
= calloc(1, sizeof(*dr
));
765 cl
->dispatch
.req_data
= dr
;
766 cl
->dispatch
.data_blocked
= true;
769 list_add(&dr
->list
, &pending_requests
);
773 uh_invoke_handler(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
776 return d
->handle_request(cl
, url
, pi
);
778 if (n_requests
>= conf
.max_script_requests
)
779 return uh_defer_script(cl
, d
, pi
);
781 cl
->dispatch
.req_free
= uh_complete_request
;
782 uh_invoke_script(cl
, d
, pi
);
785 static bool __handle_file_request(struct client
*cl
, char *url
)
787 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
788 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
789 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
790 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
791 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
792 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
793 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
795 struct dispatch_handler
*d
;
796 struct blob_attr
*tb
[__HDR_MAX
];
797 struct path_info
*pi
;
800 pi
= uh_path_lookup(cl
, url
);
807 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
808 if (tb
[HDR_AUTHORIZATION
]) {
809 if (!uh_auth_check(cl
, pi
->name
, blobmsg_data(tb
[HDR_AUTHORIZATION
]), &user
, &pass
))
813 blobmsg_add_string(&cl
->hdr
, "http-auth-user", user
);
814 blobmsg_add_string(&cl
->hdr
, "http-auth-pass", pass
);
818 d
= dispatch_find(url
, pi
);
820 uh_invoke_handler(cl
, d
, url
, pi
);
822 uh_file_request(cl
, url
, pi
, tb
);
827 static char *uh_handle_alias(char *old_url
)
830 static char *new_url
;
833 if (!list_empty(&conf
.cgi_alias
)) list_for_each_entry(alias
, &conf
.cgi_alias
, list
) {
838 if (!uh_path_match(alias
->alias
, old_url
))
842 path_len
= strlen(alias
->path
);
844 old_len
= strlen(old_url
) + 1;
845 new_len
= old_len
+ MAX(conf
.cgi_prefix_len
, path_len
);
847 if (new_len
> url_len
) {
848 new_url
= realloc(new_url
, new_len
);
855 strcpy(new_url
, alias
->path
);
856 else if (conf
.cgi_prefix
)
857 strcpy(new_url
, conf
.cgi_prefix
);
858 strcat(new_url
, old_url
);
865 void uh_handle_request(struct client
*cl
)
867 struct http_request
*req
= &cl
->request
;
868 struct dispatch_handler
*d
;
869 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
872 blob_buf_init(&cl
->hdr_response
, 0);
873 url
= uh_handle_alias(url
);
875 uh_handler_run(cl
, &url
, false);
879 req
->redirect_status
= 200;
880 d
= dispatch_find(url
, NULL
);
882 return uh_invoke_handler(cl
, d
, url
, NULL
);
884 if (__handle_file_request(cl
, url
))
887 if (uh_handler_run(cl
, &url
, true)) {
891 uh_handler_run(cl
, &url
, false);
892 if (__handle_file_request(cl
, url
))
896 req
->redirect_status
= 404;
897 if (conf
.error_handler
) {
898 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
899 strcpy(error_handler
, conf
.error_handler
);
900 if (__handle_file_request(cl
, error_handler
))
904 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.", url
);