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 char path_query
[PATH_MAX
];
136 static struct path_info p
;
138 const char *docroot
= conf
.docroot
;
139 int docroot_len
= strlen(docroot
);
140 char *pathptr
= NULL
;
146 struct index_file
*idx
;
148 /* back out early if url is undefined */
152 memset(&p
, 0, sizeof(p
));
156 strcpy(uh_buf
, docroot
);
158 /* separate query string from url */
159 if ((pathptr
= strchr(url
, '?')) != NULL
) {
161 p
.query
= path_query
;
162 snprintf(path_query
, sizeof(path_query
), "%s",
166 /* urldecode component w/o query */
168 if (uh_urldecode(&uh_buf
[docroot_len
],
169 sizeof(uh_buf
) - docroot_len
- 1,
170 url
, pathptr
- url
) < 0)
175 /* no query string, decode all of url */
176 else if (uh_urldecode(&uh_buf
[docroot_len
],
177 sizeof(uh_buf
) - docroot_len
- 1,
178 url
, strlen(url
) ) < 0)
181 /* create canon path */
182 len
= strlen(uh_buf
);
183 slash
= len
&& uh_buf
[len
- 1] == '/';
184 len
= min(len
, sizeof(path_phys
) - 1);
186 for (i
= len
; i
>= 0; i
--) {
190 if (ch
!= 0 && ch
!= '/')
194 exists
= !!canonpath(uh_buf
, path_phys
);
200 /* test current path */
201 if (stat(path_phys
, &p
.stat
))
204 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
208 /* check whether found path is within docroot */
209 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
210 (path_phys
[docroot_len
] != 0 &&
211 path_phys
[docroot_len
] != '/'))
214 /* is a regular file */
215 if (p
.stat
.st_mode
& S_IFREG
) {
218 p
.name
= &path_phys
[docroot_len
];
219 p
.info
= path_info
[0] ? path_info
: NULL
;
223 if (!(p
.stat
.st_mode
& S_IFDIR
))
229 pathptr
= path_phys
+ strlen(path_phys
);
231 /* ensure trailing slash */
232 if (pathptr
[-1] != '/') {
238 /* if requested url resolves to a directory and a trailing slash
239 is missing in the request url, redirect the client to the same
240 url with trailing slash appended */
242 uh_http_header(cl
, 302, "Found");
243 if (!uh_use_chunked(cl
))
244 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
245 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
246 &path_phys
[docroot_len
],
248 p
.query
? p
.query
: "");
254 /* try to locate index file */
255 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
256 list_for_each_entry(idx
, &index_files
, list
) {
257 if (strlen(idx
->name
) > len
)
260 strcpy(pathptr
, idx
->name
);
261 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
262 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
271 p
.name
= &path_phys
[docroot_len
];
273 return p
.phys
? &p
: NULL
;
276 static const char * uh_file_mime_lookup(const char *path
)
278 const struct mimetype
*m
= &uh_mime_types
[0];
282 e
= &path
[strlen(path
)-1];
285 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
294 return "application/octet-stream";
297 static const char * uh_file_mktag(struct stat
*s
, char *buf
, int len
)
299 snprintf(buf
, len
, "\"%" PRIx64
"-%" PRIx64
"-%" PRIx64
"\"",
300 s
->st_ino
, s
->st_size
, (uint64_t)s
->st_mtime
);
305 static time_t uh_file_date2unix(const char *date
)
309 memset(&t
, 0, sizeof(t
));
311 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
317 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
319 struct tm
*t
= gmtime(&ts
);
321 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
326 static char *uh_file_header(struct client
*cl
, int idx
)
328 if (!cl
->dispatch
.file
.hdr
[idx
])
331 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
334 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
339 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
, sizeof(buf
)));
340 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
341 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
343 ustream_printf(cl
->us
, "Date: %s\r\n",
344 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
347 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
349 uh_http_header(cl
, 200, "OK");
350 return uh_file_response_ok_hdrs(cl
, s
);
353 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
355 uh_http_header(cl
, 304, "Not Modified");
357 return uh_file_response_ok_hdrs(cl
, s
);
360 static void uh_file_response_405(struct client
*cl
)
362 uh_http_header(cl
, 405, "Method Not Allowed");
365 static void uh_file_response_412(struct client
*cl
)
367 uh_http_header(cl
, 412, "Precondition Failed");
370 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
373 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
374 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
382 for (i
= 0; i
< strlen(hdr
); i
++)
384 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
387 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
392 uh_file_response_412(cl
);
396 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
398 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
403 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
404 uh_file_response_304(cl
, s
);
411 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
414 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
415 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
423 for (i
= 0; i
< strlen(hdr
); i
++) {
424 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
427 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
428 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
429 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
430 uh_file_response_304(cl
, s
);
432 uh_file_response_412(cl
);
441 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
443 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
446 uh_file_response_412(cl
);
453 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
455 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
457 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
458 uh_file_response_412(cl
);
465 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
467 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
468 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
470 /* directories first */
472 return dir_b
- dir_a
;
474 return alphasort(a
, b
);
477 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
478 const char *path
, char *local_path
)
480 const char *suffix
= "/";
481 const char *type
= "directory";
482 unsigned int mode
= S_IXOTH
;
489 file
= local_path
+ strlen(local_path
);
490 for (i
= 0; i
< count
; i
++) {
491 const char *name
= files
[i
]->d_name
;
492 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
494 if (name
[0] == '.' && name
[1] == 0)
497 sprintf(file
, "%s", name
);
498 if (stat(local_path
, &s
))
504 type
= uh_file_mime_lookup(local_path
);
507 if (!(s
.st_mode
& mode
))
510 escaped
= uh_htmlescape(name
);
516 "<li><strong><a href='%s%s%s'>%s</a>%s"
517 "</strong><br /><small>modified: %s"
518 "<br />%s - %.02f kbyte<br />"
519 "<br /></small></li>",
520 path
, escaped
, suffix
,
522 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
523 type
, s
.st_size
/ 1024.0);
532 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
534 struct dirent
**files
= NULL
;
535 char *escaped_path
= uh_htmlescape(pi
->name
);
540 uh_client_error(cl
, 500, "Internal Server Error", "Out of memory");
544 uh_file_response_200(cl
, NULL
);
545 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
548 "<html><head><title>Index of %s</title></head>"
549 "<body><h1>Index of %s</h1><hr /><ol>",
550 escaped_path
, escaped_path
);
552 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
554 strcpy(uh_buf
, pi
->phys
);
555 list_entries(cl
, files
, count
, escaped_path
, uh_buf
);
560 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
564 static void file_write_cb(struct client
*cl
)
566 int fd
= cl
->dispatch
.file
.fd
;
569 while (cl
->us
->w
.data_bytes
< 256) {
570 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
581 uh_chunk_write(cl
, uh_buf
, r
);
585 static void uh_file_free(struct client
*cl
)
587 close(cl
->dispatch
.file
.fd
);
590 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
592 /* test preconditions */
593 if (!cl
->dispatch
.no_cache
&&
594 (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
595 !uh_file_if_match(cl
, &pi
->stat
) ||
596 !uh_file_if_range(cl
, &pi
->stat
) ||
597 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
598 !uh_file_if_none_match(cl
, &pi
->stat
))) {
599 ustream_printf(cl
->us
, "\r\n");
606 uh_file_response_200(cl
, &pi
->stat
);
608 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
609 uh_file_mime_lookup(pi
->name
));
611 ustream_printf(cl
->us
, "Content-Length: %" PRIu64
"\r\n\r\n",
616 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
622 cl
->dispatch
.file
.fd
= fd
;
623 cl
->dispatch
.write_cb
= file_write_cb
;
624 cl
->dispatch
.free
= uh_file_free
;
625 cl
->dispatch
.close_fds
= uh_file_free
;
629 static bool __handle_file_request(struct client
*cl
, char *url
);
631 static void uh_file_request(struct client
*cl
, const char *url
,
632 struct path_info
*pi
, struct blob_attr
**tb
)
635 struct http_request
*req
= &cl
->request
;
636 char *error_handler
, *escaped_url
;
638 switch (cl
->request
.method
) {
639 case UH_HTTP_MSG_GET
:
640 case UH_HTTP_MSG_POST
:
641 case UH_HTTP_MSG_HEAD
:
642 case UH_HTTP_MSG_OPTIONS
:
646 uh_file_response_405(cl
);
647 ustream_printf(cl
->us
, "\r\n");
652 if (!(pi
->stat
.st_mode
& S_IROTH
))
655 if (pi
->stat
.st_mode
& S_IFREG
) {
656 fd
= open(pi
->phys
, O_RDONLY
);
660 req
->disable_chunked
= true;
661 cl
->dispatch
.file
.hdr
= tb
;
662 uh_file_data(cl
, pi
, fd
);
663 cl
->dispatch
.file
.hdr
= NULL
;
667 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
668 if (conf
.no_dirlists
)
671 uh_file_dirlist(cl
, pi
);
676 /* check for a previously set 403 redirect status to prevent infinite
677 recursion when the error page itself lacks sufficient permissions */
678 if (conf
.error_handler
&& req
->redirect_status
!= 403) {
679 req
->redirect_status
= 403;
680 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
681 strcpy(error_handler
, conf
.error_handler
);
682 if (__handle_file_request(cl
, error_handler
))
686 escaped_url
= uh_htmlescape(url
);
688 uh_client_error(cl
, 403, "Forbidden",
689 "You don't have permission to access %s on this server.",
690 escaped_url
? escaped_url
: "the url");
696 void uh_dispatch_add(struct dispatch_handler
*d
)
698 list_add_tail(&d
->list
, &dispatch_handlers
);
701 static struct dispatch_handler
*
702 dispatch_find(const char *url
, struct path_info
*pi
)
704 struct dispatch_handler
*d
;
706 list_for_each_entry(d
, &dispatch_handlers
, list
) {
711 if (d
->check_path(pi
, url
))
717 if (d
->check_url(url
))
726 uh_invoke_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
728 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
731 d
->handle_request(cl
, url
, pi
);
734 static void uh_complete_request(struct client
*cl
)
736 struct deferred_request
*dr
;
740 while (!list_empty(&pending_requests
)) {
741 if (n_requests
>= conf
.max_script_requests
)
744 dr
= list_first_entry(&pending_requests
, struct deferred_request
, list
);
749 cl
->dispatch
.data_blocked
= false;
750 uh_invoke_script(cl
, dr
->d
, dr
->path
? &dr
->pi
: NULL
);
751 client_poll_post_data(cl
);
757 uh_free_pending_request(struct client
*cl
)
759 struct deferred_request
*dr
= cl
->dispatch
.req_data
;
762 uh_complete_request(cl
);
768 static int field_len(const char *ptr
)
773 return strlen(ptr
) + 1;
776 #define path_info_fields \
784 uh_defer_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
786 struct deferred_request
*dr
;
787 char *_root
, *_phys
, *_name
, *_info
, *_query
;
789 cl
->dispatch
.req_free
= uh_free_pending_request
;
792 /* allocate enough memory to duplicate all path_info strings in one block */
794 #define _field(_name) &_##_name, field_len(pi->_name),
795 dr
= calloc_a(sizeof(*dr
), path_info_fields NULL
);
797 memcpy(&dr
->pi
, pi
, sizeof(*pi
));
800 /* copy all path_info strings */
802 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
805 dr
= calloc(1, sizeof(*dr
));
808 cl
->dispatch
.req_data
= dr
;
809 cl
->dispatch
.data_blocked
= true;
812 list_add(&dr
->list
, &pending_requests
);
816 uh_invoke_handler(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
819 return d
->handle_request(cl
, url
, pi
);
821 if (n_requests
>= conf
.max_script_requests
)
822 return uh_defer_script(cl
, d
, pi
);
824 cl
->dispatch
.req_free
= uh_complete_request
;
825 uh_invoke_script(cl
, d
, pi
);
828 static bool __handle_file_request(struct client
*cl
, char *url
)
830 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
831 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
832 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
833 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
834 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
835 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
836 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
838 struct dispatch_handler
*d
;
839 struct blob_attr
*tb
[__HDR_MAX
];
840 struct path_info
*pi
;
841 char *user
, *pass
, *auth
;
843 pi
= uh_path_lookup(cl
, url
);
850 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
852 auth
= tb
[HDR_AUTHORIZATION
] ? blobmsg_data(tb
[HDR_AUTHORIZATION
]) : NULL
;
854 if (!uh_auth_check(cl
, pi
->name
, auth
, &user
, &pass
))
858 blobmsg_add_string(&cl
->hdr
, "http-auth-user", user
);
859 blobmsg_add_string(&cl
->hdr
, "http-auth-pass", pass
);
862 d
= dispatch_find(url
, pi
);
864 uh_invoke_handler(cl
, d
, url
, pi
);
866 uh_file_request(cl
, url
, pi
, tb
);
871 static char *uh_handle_alias(char *old_url
)
874 static char *new_url
;
877 if (!list_empty(&conf
.cgi_alias
)) list_for_each_entry(alias
, &conf
.cgi_alias
, list
) {
882 if (!uh_path_match(alias
->alias
, old_url
))
886 path_len
= strlen(alias
->path
);
888 old_len
= strlen(old_url
) + 1;
889 new_len
= old_len
+ MAX(conf
.cgi_prefix_len
, path_len
);
891 if (new_len
> url_len
) {
892 new_url
= realloc(new_url
, new_len
);
899 strcpy(new_url
, alias
->path
);
900 else if (conf
.cgi_prefix
)
901 strcpy(new_url
, conf
.cgi_prefix
);
902 strcat(new_url
, old_url
);
909 void uh_handle_request(struct client
*cl
)
911 struct http_request
*req
= &cl
->request
;
912 struct dispatch_handler
*d
;
913 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
914 char *error_handler
, *escaped_url
;
916 blob_buf_init(&cl
->hdr_response
, 0);
917 url
= uh_handle_alias(url
);
919 uh_handler_run(cl
, &url
, false);
923 req
->redirect_status
= 200;
924 d
= dispatch_find(url
, NULL
);
926 return uh_invoke_handler(cl
, d
, url
, NULL
);
928 if (__handle_file_request(cl
, url
))
931 if (uh_handler_run(cl
, &url
, true)) {
935 uh_handler_run(cl
, &url
, false);
936 if (__handle_file_request(cl
, url
))
940 req
->redirect_status
= 404;
941 if (conf
.error_handler
) {
942 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
943 strcpy(error_handler
, conf
.error_handler
);
944 if (__handle_file_request(cl
, error_handler
))
948 escaped_url
= uh_htmlescape(url
);
950 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.",
951 escaped_url
? escaped_url
: "");