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
);
39 struct list_head list
;
45 HDR_IF_MODIFIED_SINCE
,
46 HDR_IF_UNMODIFIED_SINCE
,
53 void uh_index_add(const char *filename
)
55 struct index_file
*idx
;
57 idx
= calloc(1, sizeof(*idx
));
59 list_add_tail(&idx
->list
, &index_files
);
62 static char * canonpath(const char *path
, char *path_resolved
)
64 const char *path_cpy
= path
;
65 char *path_res
= path_resolved
;
68 return realpath(path
, path_resolved
);
71 while ((*path_cpy
!= '\0') && (path_cpy
< (path
+ PATH_MAX
- 2))) {
75 /* skip repeating / */
76 if (path_cpy
[1] == '/') {
82 if (path_cpy
[1] == '.') {
84 if ((path_cpy
[2] == '/') || (path_cpy
[2] == '\0')) {
90 if ((path_cpy
[2] == '.') &&
91 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))) {
92 while ((path_res
> path_resolved
) && (*--path_res
!= '/'));
100 *path_res
++ = *path_cpy
++;
103 /* remove trailing slash if not root / */
104 if ((path_res
> (path_resolved
+1)) && (path_res
[-1] == '/'))
106 else if (path_res
== path_resolved
)
111 return path_resolved
;
114 /* Returns NULL on error.
115 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
116 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
117 static struct path_info
*
118 uh_path_lookup(struct client
*cl
, const char *url
)
120 static char path_phys
[PATH_MAX
];
121 static char path_info
[PATH_MAX
];
122 static struct path_info p
;
124 const char *docroot
= conf
.docroot
;
125 int docroot_len
= strlen(docroot
);
126 char *pathptr
= NULL
;
132 struct index_file
*idx
;
134 /* back out early if url is undefined */
138 memset(&p
, 0, sizeof(p
));
142 strcpy(uh_buf
, docroot
);
144 /* separate query string from url */
145 if ((pathptr
= strchr(url
, '?')) != NULL
) {
146 p
.query
= pathptr
[1] ? pathptr
+ 1 : NULL
;
148 /* urldecode component w/o query */
150 if (uh_urldecode(&uh_buf
[docroot_len
],
151 sizeof(uh_buf
) - docroot_len
- 1,
152 url
, pathptr
- url
) < 0)
157 /* no query string, decode all of url */
158 else if (uh_urldecode(&uh_buf
[docroot_len
],
159 sizeof(uh_buf
) - docroot_len
- 1,
160 url
, strlen(url
) ) < 0)
163 /* create canon path */
164 len
= strlen(uh_buf
);
165 slash
= len
&& uh_buf
[len
- 1] == '/';
166 len
= min(len
, sizeof(path_phys
) - 1);
168 for (i
= len
; i
>= 0; i
--) {
172 if (ch
!= 0 && ch
!= '/')
176 exists
= !!canonpath(uh_buf
, path_phys
);
182 /* test current path */
183 if (stat(path_phys
, &p
.stat
))
186 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
190 /* check whether found path is within docroot */
191 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
192 (path_phys
[docroot_len
] != 0 &&
193 path_phys
[docroot_len
] != '/'))
196 /* is a regular file */
197 if (p
.stat
.st_mode
& S_IFREG
) {
200 p
.name
= &path_phys
[docroot_len
];
201 p
.info
= path_info
[0] ? path_info
: NULL
;
205 if (!(p
.stat
.st_mode
& S_IFDIR
))
211 pathptr
= path_phys
+ strlen(path_phys
);
213 /* ensure trailing slash */
214 if (pathptr
[-1] != '/') {
220 /* if requested url resolves to a directory and a trailing slash
221 is missing in the request url, redirect the client to the same
222 url with trailing slash appended */
224 uh_http_header(cl
, 302, "Found");
225 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
226 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
227 &path_phys
[docroot_len
],
229 p
.query
? p
.query
: "");
235 /* try to locate index file */
236 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
237 list_for_each_entry(idx
, &index_files
, list
) {
238 if (strlen(idx
->name
) > len
)
241 strcpy(pathptr
, idx
->name
);
242 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
243 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
252 p
.name
= &path_phys
[docroot_len
];
254 return p
.phys
? &p
: NULL
;
257 static const char * uh_file_mime_lookup(const char *path
)
259 const struct mimetype
*m
= &uh_mime_types
[0];
263 e
= &path
[strlen(path
)-1];
266 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
275 return "application/octet-stream";
278 static const char * uh_file_mktag(struct stat
*s
, char *buf
, int len
)
280 snprintf(buf
, len
, "\"%x-%x-%x\"",
281 (unsigned int) s
->st_ino
,
282 (unsigned int) s
->st_size
,
283 (unsigned int) s
->st_mtime
);
288 static time_t uh_file_date2unix(const char *date
)
292 memset(&t
, 0, sizeof(t
));
294 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
300 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
302 struct tm
*t
= gmtime(&ts
);
304 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
309 static char *uh_file_header(struct client
*cl
, int idx
)
311 if (!cl
->dispatch
.file
.hdr
[idx
])
314 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
317 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
322 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
, sizeof(buf
)));
323 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
324 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
326 ustream_printf(cl
->us
, "Date: %s\r\n",
327 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
330 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
332 uh_http_header(cl
, 200, "OK");
333 return uh_file_response_ok_hdrs(cl
, s
);
336 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
338 uh_http_header(cl
, 304, "Not Modified");
340 return uh_file_response_ok_hdrs(cl
, s
);
343 static void uh_file_response_412(struct client
*cl
)
345 uh_http_header(cl
, 412, "Precondition Failed");
348 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
351 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
352 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
360 for (i
= 0; i
< strlen(hdr
); i
++)
362 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
365 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
370 uh_file_response_412(cl
);
374 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
376 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
381 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
382 uh_file_response_304(cl
, s
);
389 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
392 const char *tag
= uh_file_mktag(s
, buf
, sizeof(buf
));
393 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
401 for (i
= 0; i
< strlen(hdr
); i
++) {
402 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
405 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
406 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
407 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
408 uh_file_response_304(cl
, s
);
410 uh_file_response_412(cl
);
419 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
421 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
424 uh_file_response_412(cl
);
431 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
433 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
435 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
436 uh_file_response_412(cl
);
443 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
445 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
446 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
448 /* directories first */
450 return dir_b
- dir_a
;
452 return alphasort(a
, b
);
455 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
456 const char *path
, char *local_path
)
458 const char *suffix
= "/";
459 const char *type
= "directory";
460 unsigned int mode
= S_IXOTH
;
466 file
= local_path
+ strlen(local_path
);
467 for (i
= 0; i
< count
; i
++) {
468 const char *name
= files
[i
]->d_name
;
469 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
471 if (name
[0] == '.' && name
[1] == 0)
474 sprintf(file
, "%s", name
);
475 if (stat(local_path
, &s
))
481 type
= uh_file_mime_lookup(local_path
);
484 if (!(s
.st_mode
& mode
))
488 "<li><strong><a href='%s%s%s'>%s</a>%s"
489 "</strong><br /><small>modified: %s"
490 "<br />%s - %.02f kbyte<br />"
491 "<br /></small></li>",
494 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
495 type
, s
.st_size
/ 1024.0);
502 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
504 struct dirent
**files
= NULL
;
507 uh_file_response_200(cl
, NULL
);
508 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
511 "<html><head><title>Index of %s</title></head>"
512 "<body><h1>Index of %s</h1><hr /><ol>",
515 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
517 strcpy(uh_buf
, pi
->phys
);
518 list_entries(cl
, files
, count
, pi
->name
, uh_buf
);
522 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
526 static void file_write_cb(struct client
*cl
)
528 int fd
= cl
->dispatch
.file
.fd
;
531 while (cl
->us
->w
.data_bytes
< 256) {
532 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
543 uh_chunk_write(cl
, uh_buf
, r
);
547 static void uh_file_free(struct client
*cl
)
549 close(cl
->dispatch
.file
.fd
);
552 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
554 /* test preconditions */
555 if (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
556 !uh_file_if_match(cl
, &pi
->stat
) ||
557 !uh_file_if_range(cl
, &pi
->stat
) ||
558 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
559 !uh_file_if_none_match(cl
, &pi
->stat
)) {
560 ustream_printf(cl
->us
, "Content-Length: 0\r\n");
561 ustream_printf(cl
->us
, "\r\n");
568 uh_file_response_200(cl
, &pi
->stat
);
570 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
571 uh_file_mime_lookup(pi
->name
));
573 ustream_printf(cl
->us
, "Content-Length: %i\r\n\r\n",
578 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
584 cl
->dispatch
.file
.fd
= fd
;
585 cl
->dispatch
.write_cb
= file_write_cb
;
586 cl
->dispatch
.free
= uh_file_free
;
587 cl
->dispatch
.close_fds
= uh_file_free
;
591 static void uh_file_request(struct client
*cl
, const char *url
,
592 struct path_info
*pi
, struct blob_attr
**tb
)
596 if (!(pi
->stat
.st_mode
& S_IROTH
))
599 if (pi
->stat
.st_mode
& S_IFREG
) {
600 fd
= open(pi
->phys
, O_RDONLY
);
604 cl
->dispatch
.file
.hdr
= tb
;
605 uh_file_data(cl
, pi
, fd
);
606 cl
->dispatch
.file
.hdr
= NULL
;
610 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
611 if (conf
.no_dirlists
)
614 uh_file_dirlist(cl
, pi
);
619 uh_client_error(cl
, 403, "Forbidden",
620 "You don't have permission to access %s on this server.",
624 void uh_dispatch_add(struct dispatch_handler
*d
)
626 list_add_tail(&d
->list
, &dispatch_handlers
);
629 static struct dispatch_handler
*
630 dispatch_find(const char *url
, struct path_info
*pi
)
632 struct dispatch_handler
*d
;
634 list_for_each_entry(d
, &dispatch_handlers
, list
) {
639 if (d
->check_path(pi
, url
))
645 if (d
->check_url(url
))
653 static bool __handle_file_request(struct client
*cl
, char *url
)
655 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
656 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
657 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
658 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
659 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
660 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
661 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
663 struct dispatch_handler
*d
;
664 struct blob_attr
*tb
[__HDR_MAX
];
665 struct path_info
*pi
;
667 pi
= uh_path_lookup(cl
, url
);
674 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
675 if (tb
[HDR_AUTHORIZATION
])
676 pi
->auth
= blobmsg_data(tb
[HDR_AUTHORIZATION
]);
678 if (!uh_auth_check(cl
, pi
))
681 d
= dispatch_find(url
, pi
);
683 d
->handle_request(cl
, url
, pi
);
685 uh_file_request(cl
, url
, pi
, tb
);
690 void uh_handle_request(struct client
*cl
)
692 struct http_request
*req
= &cl
->request
;
693 struct dispatch_handler
*d
;
694 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));;
697 req
->redirect_status
= 200;
698 d
= dispatch_find(url
, NULL
);
700 d
->handle_request(cl
, url
, NULL
);
704 if (__handle_file_request(cl
, url
))
707 req
->redirect_status
= 404;
708 if (conf
.error_handler
) {
709 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
710 strcpy(error_handler
, conf
.error_handler
);
711 if (__handle_file_request(cl
, error_handler
))
715 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.", url
);