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>
30 #include <libubox/blobmsg.h>
33 #include "mimetypes.h"
35 static LIST_HEAD(index_files
);
36 static LIST_HEAD(dispatch_handlers
);
37 static LIST_HEAD(pending_requests
);
38 static int n_requests
;
40 struct deferred_request
{
41 struct list_head list
;
42 struct dispatch_handler
*d
;
49 struct list_head list
;
55 HDR_IF_MODIFIED_SINCE
,
56 HDR_IF_UNMODIFIED_SINCE
,
63 void uh_index_add(const char *filename
)
65 struct index_file
*idx
;
67 idx
= calloc(1, sizeof(*idx
));
69 list_add_tail(&idx
->list
, &index_files
);
72 static char * canonpath(const char *path
, char *path_resolved
)
74 const char *path_cpy
= path
;
75 char *path_res
= path_resolved
;
78 return realpath(path
, path_resolved
);
81 while ((*path_cpy
!= '\0') && (path_cpy
< (path
+ PATH_MAX
- 2))) {
85 /* skip repeating / */
86 if (path_cpy
[1] == '/') {
92 if (path_cpy
[1] == '.') {
94 if ((path_cpy
[2] == '/') || (path_cpy
[2] == '\0')) {
100 if ((path_cpy
[2] == '.') &&
101 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))) {
102 while ((path_res
> path_resolved
) && (*--path_res
!= '/'));
110 *path_res
++ = *path_cpy
++;
113 /* remove trailing slash if not root / */
114 if ((path_res
> (path_resolved
+1)) && (path_res
[-1] == '/'))
116 else if (path_res
== path_resolved
)
121 return path_resolved
;
124 /* Returns NULL on error.
125 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
126 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
127 static struct path_info
*
128 uh_path_lookup(struct client
*cl
, const char *url
)
130 static char path_phys
[PATH_MAX
];
131 static char path_info
[PATH_MAX
];
132 static struct path_info p
;
134 const char *docroot
= conf
.docroot
;
135 int docroot_len
= strlen(docroot
);
136 char *pathptr
= NULL
;
142 struct index_file
*idx
;
144 /* back out early if url is undefined */
148 memset(&p
, 0, sizeof(p
));
152 strcpy(uh_buf
, docroot
);
154 /* separate query string from url */
155 if ((pathptr
= strchr(url
, '?')) != NULL
) {
156 p
.query
= pathptr
[1] ? pathptr
+ 1 : NULL
;
158 /* urldecode component w/o query */
160 if (uh_urldecode(&uh_buf
[docroot_len
],
161 sizeof(uh_buf
) - docroot_len
- 1,
162 url
, pathptr
- url
) < 0)
167 /* no query string, decode all of url */
168 else if (uh_urldecode(&uh_buf
[docroot_len
],
169 sizeof(uh_buf
) - docroot_len
- 1,
170 url
, strlen(url
) ) < 0)
173 /* create canon path */
174 len
= strlen(uh_buf
);
175 slash
= len
&& uh_buf
[len
- 1] == '/';
176 len
= min(len
, sizeof(path_phys
) - 1);
178 for (i
= len
; i
>= 0; i
--) {
182 if (ch
!= 0 && ch
!= '/')
186 exists
= !!canonpath(uh_buf
, path_phys
);
192 /* test current path */
193 if (stat(path_phys
, &p
.stat
))
196 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
200 /* check whether found path is within docroot */
201 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
202 (path_phys
[docroot_len
] != 0 &&
203 path_phys
[docroot_len
] != '/'))
206 /* is a regular file */
207 if (p
.stat
.st_mode
& S_IFREG
) {
210 p
.name
= &path_phys
[docroot_len
];
211 p
.info
= path_info
[0] ? path_info
: NULL
;
215 if (!(p
.stat
.st_mode
& S_IFDIR
))
221 pathptr
= path_phys
+ strlen(path_phys
);
223 /* ensure trailing slash */
224 if (pathptr
[-1] != '/') {
230 /* if requested url resolves to a directory and a trailing slash
231 is missing in the request url, redirect the client to the same
232 url with trailing slash appended */
234 uh_http_header(cl
, 302, "Found");
235 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
236 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
237 &path_phys
[docroot_len
],
239 p
.query
? p
.query
: "");
245 /* try to locate index file */
246 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
247 list_for_each_entry(idx
, &index_files
, list
) {
248 if (strlen(idx
->name
) > len
)
251 strcpy(pathptr
, idx
->name
);
252 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
253 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
262 p
.name
= &path_phys
[docroot_len
];
264 return p
.phys
? &p
: NULL
;
267 static const char * uh_file_mime_lookup(const char *path
)
269 const struct mimetype
*m
= &uh_mime_types
[0];
273 e
= &path
[strlen(path
)-1];
276 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
285 return "application/octet-stream";
288 static const char * uh_file_mktag(struct stat
*s
, char *buf
, int len
)
290 snprintf(buf
, len
, "\"%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
, char *buf
, int len
)
312 struct tm
*t
= gmtime(&ts
);
314 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
319 static char *uh_file_header(struct client
*cl
, int idx
)
321 if (!cl
->dispatch
.file
.hdr
[idx
])
324 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
327 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
332 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
, sizeof(buf
)));
333 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
334 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
336 ustream_printf(cl
->us
, "Date: %s\r\n",
337 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
340 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
342 uh_http_header(cl
, 200, "OK");
343 return uh_file_response_ok_hdrs(cl
, s
);
346 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
348 uh_http_header(cl
, 304, "Not Modified");
350 return uh_file_response_ok_hdrs(cl
, s
);
353 static void uh_file_response_412(struct client
*cl
)
355 uh_http_header(cl
, 412, "Precondition Failed");
358 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
361 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
362 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
370 for (i
= 0; i
< strlen(hdr
); i
++)
372 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
375 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
380 uh_file_response_412(cl
);
384 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
386 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
391 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
392 uh_file_response_304(cl
, s
);
399 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
402 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
403 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
411 for (i
= 0; i
< strlen(hdr
); i
++) {
412 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
415 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
416 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
417 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
418 uh_file_response_304(cl
, s
);
420 uh_file_response_412(cl
);
429 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
431 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
434 uh_file_response_412(cl
);
441 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
443 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
445 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
446 uh_file_response_412(cl
);
453 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
455 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
456 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
458 /* directories first */
460 return dir_b
- dir_a
;
462 return alphasort(a
, b
);
465 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
466 const char *path
, char *local_path
)
468 const char *suffix
= "/";
469 const char *type
= "directory";
470 unsigned int mode
= S_IXOTH
;
476 file
= local_path
+ strlen(local_path
);
477 for (i
= 0; i
< count
; i
++) {
478 const char *name
= files
[i
]->d_name
;
479 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
481 if (name
[0] == '.' && name
[1] == 0)
484 sprintf(file
, "%s", name
);
485 if (stat(local_path
, &s
))
491 type
= uh_file_mime_lookup(local_path
);
494 if (!(s
.st_mode
& mode
))
498 "<li><strong><a href='%s%s%s'>%s</a>%s"
499 "</strong><br /><small>modified: %s"
500 "<br />%s - %.02f kbyte<br />"
501 "<br /></small></li>",
504 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
505 type
, s
.st_size
/ 1024.0);
512 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
514 struct dirent
**files
= NULL
;
517 uh_file_response_200(cl
, NULL
);
518 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
521 "<html><head><title>Index of %s</title></head>"
522 "<body><h1>Index of %s</h1><hr /><ol>",
525 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
527 strcpy(uh_buf
, pi
->phys
);
528 list_entries(cl
, files
, count
, pi
->name
, uh_buf
);
532 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
536 static void file_write_cb(struct client
*cl
)
538 int fd
= cl
->dispatch
.file
.fd
;
541 while (cl
->us
->w
.data_bytes
< 256) {
542 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
553 uh_chunk_write(cl
, uh_buf
, r
);
557 static void uh_file_free(struct client
*cl
)
559 close(cl
->dispatch
.file
.fd
);
562 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
564 /* test preconditions */
565 if (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
566 !uh_file_if_match(cl
, &pi
->stat
) ||
567 !uh_file_if_range(cl
, &pi
->stat
) ||
568 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
569 !uh_file_if_none_match(cl
, &pi
->stat
)) {
570 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
571 ustream_printf(cl
->us
, "\r\n");
578 uh_file_response_200(cl
, &pi
->stat
);
580 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
581 uh_file_mime_lookup(pi
->name
));
583 ustream_printf(cl
->us
, "Content-Length: %i\r\n\r\n",
588 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
594 cl
->dispatch
.file
.fd
= fd
;
595 cl
->dispatch
.write_cb
= file_write_cb
;
596 cl
->dispatch
.free
= uh_file_free
;
597 cl
->dispatch
.close_fds
= uh_file_free
;
601 static bool __handle_file_request(struct client
*cl
, char *url
);
603 static void uh_file_request(struct client
*cl
, const char *url
,
604 struct path_info
*pi
, struct blob_attr
**tb
)
607 struct http_request
*req
= &cl
->request
;
610 if (!(pi
->stat
.st_mode
& S_IROTH
))
613 if (pi
->stat
.st_mode
& S_IFREG
) {
614 fd
= open(pi
->phys
, O_RDONLY
);
618 cl
->dispatch
.file
.hdr
= tb
;
619 uh_file_data(cl
, pi
, fd
);
620 cl
->dispatch
.file
.hdr
= NULL
;
624 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
625 if (conf
.no_dirlists
)
628 uh_file_dirlist(cl
, pi
);
633 /* check for a previously set 403 redirect status to prevent infinite
634 recursion when the error page itself lacks sufficient permissions */
635 if (conf
.error_handler
&& req
->redirect_status
!= 403) {
636 req
->redirect_status
= 403;
637 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
638 strcpy(error_handler
, conf
.error_handler
);
639 if (__handle_file_request(cl
, error_handler
))
643 uh_client_error(cl
, 403, "Forbidden",
644 "You don't have permission to access %s on this server.",
648 void uh_dispatch_add(struct dispatch_handler
*d
)
650 list_add_tail(&d
->list
, &dispatch_handlers
);
653 static struct dispatch_handler
*
654 dispatch_find(const char *url
, struct path_info
*pi
)
656 struct dispatch_handler
*d
;
658 list_for_each_entry(d
, &dispatch_handlers
, list
) {
663 if (d
->check_path(pi
, url
))
669 if (d
->check_url(url
))
678 uh_invoke_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
680 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
683 d
->handle_request(cl
, url
, pi
);
686 static void uh_complete_request(struct client
*cl
)
688 struct deferred_request
*dr
;
692 while (!list_empty(&pending_requests
)) {
693 if (n_requests
>= conf
.max_script_requests
)
696 dr
= list_first_entry(&pending_requests
, struct deferred_request
, list
);
700 uh_invoke_script(dr
->cl
, dr
->d
, dr
->path
? &dr
->pi
: NULL
);
706 uh_free_pending_request(struct client
*cl
)
708 struct deferred_request
*dr
= cl
->dispatch
.req_data
;
711 uh_complete_request(cl
);
717 static int field_len(const char *ptr
)
722 return strlen(ptr
) + 1;
725 #define path_info_fields \
734 uh_defer_script(struct client
*cl
, struct dispatch_handler
*d
, struct path_info
*pi
)
736 struct deferred_request
*dr
;
737 char *_root
, *_phys
, *_name
, *_info
, *_query
, *_auth
;
739 cl
->dispatch
.req_free
= uh_free_pending_request
;
742 /* allocate enough memory to duplicate all path_info strings in one block */
744 #define _field(_name) &_##_name, field_len(pi->_name),
745 dr
= calloc_a(sizeof(*dr
), path_info_fields NULL
);
747 memcpy(&dr
->pi
, pi
, sizeof(*pi
));
750 /* copy all path_info strings */
752 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
755 dr
= calloc(1, sizeof(*dr
));
758 cl
->dispatch
.req_data
= dr
;
761 list_add(&dr
->list
, &pending_requests
);
765 uh_invoke_handler(struct client
*cl
, struct dispatch_handler
*d
, char *url
, struct path_info
*pi
)
768 return d
->handle_request(cl
, url
, pi
);
770 if (n_requests
>= conf
.max_script_requests
)
771 return uh_defer_script(cl
, d
, pi
);
773 cl
->dispatch
.req_free
= uh_complete_request
;
774 uh_invoke_script(cl
, d
, pi
);
777 static bool __handle_file_request(struct client
*cl
, char *url
)
779 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
780 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
781 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
782 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
783 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
784 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
785 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
787 struct dispatch_handler
*d
;
788 struct blob_attr
*tb
[__HDR_MAX
];
789 struct path_info
*pi
;
791 pi
= uh_path_lookup(cl
, url
);
798 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
799 if (tb
[HDR_AUTHORIZATION
])
800 pi
->auth
= blobmsg_data(tb
[HDR_AUTHORIZATION
]);
802 if (!uh_auth_check(cl
, pi
))
805 d
= dispatch_find(url
, pi
);
807 uh_invoke_handler(cl
, d
, url
, pi
);
809 uh_file_request(cl
, url
, pi
, tb
);
814 void uh_handle_request(struct client
*cl
)
816 struct http_request
*req
= &cl
->request
;
817 struct dispatch_handler
*d
;
818 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));
821 req
->redirect_status
= 200;
822 d
= dispatch_find(url
, NULL
);
824 return uh_invoke_handler(cl
, d
, url
, NULL
);
826 if (__handle_file_request(cl
, url
))
829 req
->redirect_status
= 404;
830 if (conf
.error_handler
) {
831 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
832 strcpy(error_handler
, conf
.error_handler
);
833 if (__handle_file_request(cl
, error_handler
))
837 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.", url
);