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 #define _DEFAULT_SOURCE
22 #define _DARWIN_C_SOURCE
23 #define _XOPEN_SOURCE 700
25 #include <sys/types.h>
32 #include <libubox/blobmsg.h>
35 #include "mimetypes.h"
37 #define MAX(a, b) (((a) > (b)) ? (a) : (b))
39 static LIST_HEAD(index_files
);
40 static LIST_HEAD(dispatch_handlers
);
41 static LIST_HEAD(pending_requests
);
42 static int n_requests
;
44 struct deferred_request
{
45 struct list_head list
;
46 struct dispatch_handler
*d
;
53 struct list_head list
;
59 HDR_IF_MODIFIED_SINCE
,
60 HDR_IF_UNMODIFIED_SINCE
,
67 void uh_index_add(const char *filename
)
69 struct index_file
*idx
;
71 idx
= calloc(1, sizeof(*idx
));
73 list_add_tail(&idx
->list
, &index_files
);
76 static char * canonpath(const char *path
, char *path_resolved
)
78 const char *path_cpy
= path
;
79 char *path_res
= path_resolved
;
82 return realpath(path
, path_resolved
);
85 while ((*path_cpy
!= '\0') && (path_cpy
< (path
+ 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
)
125 return path_resolved
;
128 /* Returns NULL on error.
129 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
130 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
132 uh_path_lookup(struct client
*cl
, const char *url
)
134 static char path_phys
[PATH_MAX
];
135 static char path_info
[PATH_MAX
];
136 static char path_query
[PATH_MAX
];
137 static struct path_info p
;
139 const char *docroot
= conf
.docroot
;
140 int docroot_len
= strlen(docroot
);
141 char *pathptr
= NULL
;
147 struct index_file
*idx
;
149 /* back out early if url is undefined */
153 memset(&p
, 0, sizeof(p
));
157 strcpy(uh_buf
, docroot
);
159 /* separate query string from url */
160 if ((pathptr
= strchr(url
, '?')) != NULL
) {
162 p
.query
= path_query
;
163 snprintf(path_query
, sizeof(path_query
), "%s",
167 /* urldecode component w/o query */
169 if (uh_urldecode(&uh_buf
[docroot_len
],
170 sizeof(uh_buf
) - docroot_len
- 1,
171 url
, pathptr
- url
) < 0)
176 /* no query string, decode all of url */
177 else if (uh_urldecode(&uh_buf
[docroot_len
],
178 sizeof(uh_buf
) - docroot_len
- 1,
179 url
, strlen(url
) ) < 0)
182 /* create canon path */
183 len
= strlen(uh_buf
);
184 slash
= len
&& uh_buf
[len
- 1] == '/';
185 len
= min(len
, sizeof(path_phys
) - 1);
187 for (i
= len
; i
>= 0; i
--) {
191 if (ch
!= 0 && ch
!= '/')
195 exists
= !!canonpath(uh_buf
, path_phys
);
201 /* test current path */
202 if (stat(path_phys
, &p
.stat
))
205 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
209 /* check whether found path is within docroot */
210 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
211 (path_phys
[docroot_len
] != 0 &&
212 path_phys
[docroot_len
] != '/'))
215 /* is a regular file */
216 if (p
.stat
.st_mode
& S_IFREG
) {
219 p
.name
= &path_phys
[docroot_len
];
220 p
.info
= path_info
[0] ? path_info
: NULL
;
224 if (!(p
.stat
.st_mode
& S_IFDIR
))
230 pathptr
= path_phys
+ strlen(path_phys
);
232 /* ensure trailing slash */
233 if (pathptr
[-1] != '/') {
239 /* if requested url resolves to a directory and a trailing slash
240 is missing in the request url, redirect the client to the same
241 url with trailing slash appended */
243 uh_http_header(cl
, 302, "Found");
244 if (!uh_use_chunked(cl
))
245 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
246 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
247 &path_phys
[docroot_len
],
249 p
.query
? p
.query
: "");
255 /* try to locate index file */
256 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
257 list_for_each_entry(idx
, &index_files
, list
) {
258 if (strlen(idx
->name
) > len
)
261 strcpy(pathptr
, idx
->name
);
262 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
263 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
272 p
.name
= &path_phys
[docroot_len
];
274 return p
.phys
? &p
: NULL
;
277 static const char * uh_file_mime_lookup(const char *path
)
279 const struct mimetype
*m
= &uh_mime_types
[0];
283 e
= &path
[strlen(path
)-1];
286 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
295 return "application/octet-stream";
298 static const char * uh_file_mktag(struct stat
*s
, char *buf
, int len
)
300 snprintf(buf
, len
, "\"%" PRIx64
"-%" PRIx64
"-%" PRIx64
"\"",
301 s
->st_ino
, s
->st_size
, (uint64_t)s
->st_mtime
);
306 static time_t uh_file_date2unix(const char *date
)
310 memset(&t
, 0, sizeof(t
));
312 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
318 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
320 struct tm
*t
= gmtime(&ts
);
322 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
327 static char *uh_file_header(struct client
*cl
, int idx
)
329 if (!cl
->dispatch
.file
.hdr
[idx
])
332 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
335 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
340 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
, sizeof(buf
)));
341 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
342 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
344 ustream_printf(cl
->us
, "Date: %s\r\n",
345 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
348 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
350 uh_http_header(cl
, 200, "OK");
351 return uh_file_response_ok_hdrs(cl
, s
);
354 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
356 uh_http_header(cl
, 304, "Not Modified");
358 return uh_file_response_ok_hdrs(cl
, s
);
361 static void uh_file_response_405(struct client
*cl
)
363 uh_http_header(cl
, 405, "Method Not Allowed");
366 static void uh_file_response_412(struct client
*cl
)
368 uh_http_header(cl
, 412, "Precondition Failed");
371 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
374 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
375 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
383 for (i
= 0; i
< strlen(hdr
); i
++)
385 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
388 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
393 uh_file_response_412(cl
);
397 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
399 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
404 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
405 uh_file_response_304(cl
, s
);
412 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
415 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
416 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
424 for (i
= 0; i
< strlen(hdr
); i
++) {
425 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
428 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
429 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
430 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
431 uh_file_response_304(cl
, s
);
433 uh_file_response_412(cl
);
442 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
444 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
447 uh_file_response_412(cl
);
454 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
456 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
458 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
459 uh_file_response_412(cl
);
466 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
468 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
469 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
471 /* directories first */
473 return dir_b
- dir_a
;
475 return alphasort(a
, b
);
478 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
479 const char *path
, char *local_path
)
481 const char *suffix
= "/";
482 const char *type
= "directory";
483 unsigned int mode
= S_IXOTH
;
490 file
= local_path
+ strlen(local_path
);
491 for (i
= 0; i
< count
; i
++) {
492 const char *name
= files
[i
]->d_name
;
493 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
495 if (name
[0] == '.' && name
[1] == 0)
498 sprintf(file
, "%s", name
);
499 if (stat(local_path
, &s
))
505 type
= uh_file_mime_lookup(local_path
);
508 if (!(s
.st_mode
& mode
))
511 escaped
= uh_htmlescape(name
);
517 "<li><strong><a href='%s%s%s'>%s</a>%s"
518 "</strong><br /><small>modified: %s"
519 "<br />%s - %.02f kbyte<br />"
520 "<br /></small></li>",
521 path
, escaped
, suffix
,
523 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
524 type
, s
.st_size
/ 1024.0);
533 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
535 struct dirent
**files
= NULL
;
536 char *escaped_path
= uh_htmlescape(pi
->name
);
541 uh_client_error(cl
, 500, "Internal Server Error", "Out of memory");
545 uh_file_response_200(cl
, NULL
);
546 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
549 "<html><head><title>Index of %s</title></head>"
550 "<body><h1>Index of %s</h1><hr /><ol>",
551 escaped_path
, escaped_path
);
553 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
555 strcpy(uh_buf
, pi
->phys
);
556 list_entries(cl
, files
, count
, escaped_path
, uh_buf
);
561 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
565 static void file_write_cb(struct client
*cl
)
567 int fd
= cl
->dispatch
.file
.fd
;
570 while (cl
->us
->w
.data_bytes
< 256) {
571 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
582 uh_chunk_write(cl
, uh_buf
, r
);
586 static void uh_file_free(struct client
*cl
)
588 close(cl
->dispatch
.file
.fd
);
591 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
593 /* test preconditions */
594 if (!cl
->dispatch
.no_cache
&&
595 (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
596 !uh_file_if_match(cl
, &pi
->stat
) ||
597 !uh_file_if_range(cl
, &pi
->stat
) ||
598 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
599 !uh_file_if_none_match(cl
, &pi
->stat
))) {
600 ustream_printf(cl
->us
, "\r\n");
607 uh_file_response_200(cl
, &pi
->stat
);
609 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
610 uh_file_mime_lookup(pi
->name
));
612 ustream_printf(cl
->us
, "Content-Length: %" PRIu64
"\r\n\r\n",
617 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
623 cl
->dispatch
.file
.fd
= fd
;
624 cl
->dispatch
.write_cb
= file_write_cb
;
625 cl
->dispatch
.free
= uh_file_free
;
626 cl
->dispatch
.close_fds
= uh_file_free
;
630 static bool __handle_file_request(struct client
*cl
, char *url
);
632 static void uh_file_request(struct client
*cl
, const char *url
,
633 struct path_info
*pi
, struct blob_attr
**tb
)
636 struct http_request
*req
= &cl
->request
;
637 char *error_handler
, *escaped_url
;
639 switch (cl
->request
.method
) {
640 case UH_HTTP_MSG_GET
:
641 case UH_HTTP_MSG_POST
:
642 case UH_HTTP_MSG_HEAD
:
643 case UH_HTTP_MSG_OPTIONS
:
647 uh_file_response_405(cl
);
648 ustream_printf(cl
->us
, "\r\n");
653 if (!(pi
->stat
.st_mode
& S_IROTH
))
656 if (pi
->stat
.st_mode
& S_IFREG
) {
657 fd
= open(pi
->phys
, O_RDONLY
);
661 req
->disable_chunked
= true;
662 cl
->dispatch
.file
.hdr
= tb
;
663 uh_file_data(cl
, pi
, fd
);
664 cl
->dispatch
.file
.hdr
= NULL
;
668 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
669 if (conf
.no_dirlists
)
672 uh_file_dirlist(cl
, pi
);
677 /* check for a previously set 403 redirect status to prevent infinite
678 recursion when the error page itself lacks sufficient permissions */
679 if (conf
.error_handler
&& req
->redirect_status
!= 403) {
680 req
->redirect_status
= 403;
681 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
682 strcpy(error_handler
, conf
.error_handler
);
683 if (__handle_file_request(cl
, error_handler
))
687 escaped_url
= uh_htmlescape(url
);
689 uh_client_error(cl
, 403, "Forbidden",
690 "You don't have permission to access %s on this server.",
691 escaped_url
? escaped_url
: "the url");
697 void uh_dispatch_add(struct dispatch_handler
*d
)
699 list_add_tail(&d
->list
, &dispatch_handlers
);
702 static struct dispatch_handler
*
703 dispatch_find(const char *url
, struct path_info
*pi
)
705 struct dispatch_handler
*d
;
707 list_for_each_entry(d
, &dispatch_handlers
, list
) {
712 if (d
->check_path(pi
, url
))
718 if (d
->check_url(url
))
727 uh_invoke_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
729 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
732 d
->handle_request(cl
, url
, pi
);
735 static void uh_complete_request(struct client
*cl
)
737 struct deferred_request
*dr
;
741 while (!list_empty(&pending_requests
)) {
742 if (n_requests
>= conf
.max_script_requests
)
745 dr
= list_first_entry(&pending_requests
, struct deferred_request
, list
);
750 cl
->dispatch
.data_blocked
= false;
751 uh_invoke_script(cl
, dr
->d
, dr
->path
? &dr
->pi
: NULL
);
752 client_poll_post_data(cl
);
758 uh_free_pending_request(struct client
*cl
)
760 struct deferred_request
*dr
= cl
->dispatch
.req_data
;
763 uh_complete_request(cl
);
769 static int field_len(const char *ptr
)
774 return strlen(ptr
) + 1;
777 #define path_info_fields \
785 uh_defer_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
787 struct deferred_request
*dr
;
788 char *_root
, *_phys
, *_name
, *_info
, *_query
;
790 cl
->dispatch
.req_free
= uh_free_pending_request
;
793 /* allocate enough memory to duplicate all path_info strings in one block */
795 #define _field(_name) &_##_name, field_len(pi->_name),
796 dr
= calloc_a(sizeof(*dr
), path_info_fields NULL
);
798 memcpy(&dr
->pi
, pi
, sizeof(*pi
));
801 /* copy all path_info strings */
803 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
806 dr
= calloc(1, sizeof(*dr
));
809 cl
->dispatch
.req_data
= dr
;
810 cl
->dispatch
.data_blocked
= true;
813 list_add(&dr
->list
, &pending_requests
);
817 uh_invoke_handler(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
820 return d
->handle_request(cl
, url
, pi
);
822 if (n_requests
>= conf
.max_script_requests
)
823 return uh_defer_script(cl
, d
, pi
);
825 cl
->dispatch
.req_free
= uh_complete_request
;
826 uh_invoke_script(cl
, d
, pi
);
829 static bool __handle_file_request(struct client
*cl
, char *url
)
831 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
832 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
833 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
834 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
835 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
836 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
837 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
839 struct dispatch_handler
*d
;
840 struct blob_attr
*tb
[__HDR_MAX
];
841 struct path_info
*pi
;
842 char *user
, *pass
, *auth
;
844 pi
= uh_path_lookup(cl
, url
);
851 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
853 auth
= tb
[HDR_AUTHORIZATION
] ? blobmsg_data(tb
[HDR_AUTHORIZATION
]) : NULL
;
855 if (!uh_auth_check(cl
, pi
->name
, auth
, &user
, &pass
))
859 blobmsg_add_string(&cl
->hdr
, "http-auth-user", user
);
860 blobmsg_add_string(&cl
->hdr
, "http-auth-pass", pass
);
863 d
= dispatch_find(url
, pi
);
865 uh_invoke_handler(cl
, d
, url
, pi
);
867 uh_file_request(cl
, url
, pi
, tb
);
872 static char *uh_handle_alias(char *old_url
)
875 static char *new_url
;
878 if (!list_empty(&conf
.cgi_alias
)) list_for_each_entry(alias
, &conf
.cgi_alias
, list
) {
883 if (!uh_path_match(alias
->alias
, old_url
))
887 path_len
= strlen(alias
->path
);
889 old_len
= strlen(old_url
) + 1;
890 new_len
= old_len
+ MAX(conf
.cgi_prefix_len
, path_len
);
892 if (new_len
> url_len
) {
893 new_url
= realloc(new_url
, new_len
);
900 strcpy(new_url
, alias
->path
);
901 else if (conf
.cgi_prefix
)
902 strcpy(new_url
, conf
.cgi_prefix
);
903 strcat(new_url
, old_url
);
910 void uh_handle_request(struct client
*cl
)
912 struct http_request
*req
= &cl
->request
;
913 struct dispatch_handler
*d
;
914 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
915 char *error_handler
, *escaped_url
;
917 blob_buf_init(&cl
->hdr_response
, 0);
918 url
= uh_handle_alias(url
);
920 uh_handler_run(cl
, &url
, false);
924 req
->redirect_status
= 200;
925 d
= dispatch_find(url
, NULL
);
927 return uh_invoke_handler(cl
, d
, url
, NULL
);
929 if (__handle_file_request(cl
, url
))
932 if (uh_handler_run(cl
, &url
, true)) {
936 uh_handler_run(cl
, &url
, false);
937 if (__handle_file_request(cl
, url
))
941 req
->redirect_status
= 404;
942 if (conf
.error_handler
) {
943 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
944 strcpy(error_handler
, conf
.error_handler
);
945 if (__handle_file_request(cl
, error_handler
))
949 escaped_url
= uh_htmlescape(url
);
951 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.",
952 escaped_url
? escaped_url
: "");