2 * uhttpd - Tiny single-threaded httpd
4 * Copyright (C) 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
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
, "Location: %s%s%s\r\n\r\n",
226 &path_phys
[docroot_len
],
228 p
.query
? p
.query
: "");
234 /* try to locate index file */
235 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
236 list_for_each_entry(idx
, &index_files
, list
) {
237 if (strlen(idx
->name
) > len
)
240 strcpy(pathptr
, idx
->name
);
241 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
242 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
251 p
.name
= &path_phys
[docroot_len
];
253 return p
.phys
? &p
: NULL
;
256 static const char * uh_file_mime_lookup(const char *path
)
258 const struct mimetype
*m
= &uh_mime_types
[0];
262 e
= &path
[strlen(path
)-1];
265 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
274 return "application/octet-stream";
277 static const char * uh_file_mktag(struct stat
*s
, char *buf
)
279 snprintf(buf
, sizeof(buf
), "\"%x-%x-%x\"",
280 (unsigned int) s
->st_ino
,
281 (unsigned int) s
->st_size
,
282 (unsigned int) s
->st_mtime
);
287 static time_t uh_file_date2unix(const char *date
)
291 memset(&t
, 0, sizeof(t
));
293 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
299 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
301 struct tm
*t
= gmtime(&ts
);
303 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
308 static char *uh_file_header(struct client
*cl
, int idx
)
310 if (!cl
->dispatch
.file
.hdr
[idx
])
313 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
316 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
321 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
));
322 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
323 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
325 ustream_printf(cl
->us
, "Date: %s\r\n",
326 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
329 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
331 uh_http_header(cl
, 200, "OK");
332 return uh_file_response_ok_hdrs(cl
, s
);
335 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
337 uh_http_header(cl
, 304, "Not Modified");
339 return uh_file_response_ok_hdrs(cl
, s
);
342 static void uh_file_response_412(struct client
*cl
)
344 uh_http_header(cl
, 412, "Precondition Failed");
347 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
350 const char *tag
= uh_file_mktag(s
, buf
);
351 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
359 for (i
= 0; i
< strlen(hdr
); i
++)
361 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
364 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
369 uh_file_response_412(cl
);
373 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
375 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
380 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
381 uh_file_response_304(cl
, s
);
388 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
391 const char *tag
= uh_file_mktag(s
, buf
);
392 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
400 for (i
= 0; i
< strlen(hdr
); i
++) {
401 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
404 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
405 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
406 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
407 uh_file_response_304(cl
, s
);
409 uh_file_response_412(cl
);
418 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
420 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
423 uh_file_response_412(cl
);
430 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
432 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
434 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
435 uh_file_response_412(cl
);
442 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
444 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
445 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
447 /* directories first */
449 return dir_b
- dir_a
;
451 return alphasort(a
, b
);
454 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
455 const char *path
, char *local_path
)
457 const char *suffix
= "/";
458 const char *type
= "directory";
459 unsigned int mode
= S_IXOTH
;
465 file
= local_path
+ strlen(local_path
);
466 for (i
= 0; i
< count
; i
++) {
467 const char *name
= files
[i
]->d_name
;
468 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
470 if (name
[0] == '.' && name
[1] == 0)
473 sprintf(file
, "%s", name
);
474 if (stat(local_path
, &s
))
480 type
= uh_file_mime_lookup(local_path
);
483 if (!(s
.st_mode
& mode
))
487 "<li><strong><a href='%s%s%s'>%s</a>%s"
488 "</strong><br /><small>modified: %s"
489 "<br />%s - %.02f kbyte<br />"
490 "<br /></small></li>",
493 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
494 type
, s
.st_size
/ 1024.0);
501 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
503 struct dirent
**files
= NULL
;
506 uh_file_response_200(cl
, NULL
);
507 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
510 "<html><head><title>Index of %s</title></head>"
511 "<body><h1>Index of %s</h1><hr /><ol>",
514 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
516 strcpy(uh_buf
, pi
->phys
);
517 list_entries(cl
, files
, count
, pi
->name
, uh_buf
);
521 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
525 static void file_write_cb(struct client
*cl
)
527 int fd
= cl
->dispatch
.file
.fd
;
530 while (cl
->us
->w
.data_bytes
< 256) {
531 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
542 uh_chunk_write(cl
, uh_buf
, r
);
546 static void uh_file_free(struct client
*cl
)
548 close(cl
->dispatch
.file
.fd
);
551 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
553 /* test preconditions */
554 if (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
555 !uh_file_if_match(cl
, &pi
->stat
) ||
556 !uh_file_if_range(cl
, &pi
->stat
) ||
557 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
558 !uh_file_if_none_match(cl
, &pi
->stat
)) {
565 uh_file_response_200(cl
, &pi
->stat
);
567 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
568 uh_file_mime_lookup(pi
->name
));
570 ustream_printf(cl
->us
, "Content-Length: %i\r\n\r\n",
575 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
581 cl
->dispatch
.file
.fd
= fd
;
582 cl
->dispatch
.write_cb
= file_write_cb
;
583 cl
->dispatch
.free
= uh_file_free
;
584 cl
->dispatch
.close_fds
= uh_file_free
;
588 static void uh_file_request(struct client
*cl
, const char *url
,
589 struct path_info
*pi
, struct blob_attr
**tb
)
593 if (!(pi
->stat
.st_mode
& S_IROTH
))
596 if (pi
->stat
.st_mode
& S_IFREG
) {
597 fd
= open(pi
->phys
, O_RDONLY
);
601 cl
->dispatch
.file
.hdr
= tb
;
602 uh_file_data(cl
, pi
, fd
);
603 cl
->dispatch
.file
.hdr
= NULL
;
607 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
608 if (conf
.no_dirlists
)
611 uh_file_dirlist(cl
, pi
);
616 uh_client_error(cl
, 403, "Forbidden",
617 "You don't have permission to access %s on this server.",
621 void uh_dispatch_add(struct dispatch_handler
*d
)
623 list_add_tail(&d
->list
, &dispatch_handlers
);
626 static struct dispatch_handler
*
627 dispatch_find(const char *url
, struct path_info
*pi
)
629 struct dispatch_handler
*d
;
631 list_for_each_entry(d
, &dispatch_handlers
, list
) {
636 if (d
->check_path(pi
, url
))
642 if (d
->check_url(url
))
650 static bool __handle_file_request(struct client
*cl
, char *url
)
652 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
653 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
654 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
655 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
656 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
657 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
658 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
660 struct dispatch_handler
*d
;
661 struct blob_attr
*tb
[__HDR_MAX
];
662 struct path_info
*pi
;
664 pi
= uh_path_lookup(cl
, url
);
671 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
672 if (tb
[HDR_AUTHORIZATION
])
673 pi
->auth
= blobmsg_data(tb
[HDR_AUTHORIZATION
]);
675 if (!uh_auth_check(cl
, pi
))
678 d
= dispatch_find(url
, pi
);
680 d
->handle_request(cl
, url
, pi
);
682 uh_file_request(cl
, url
, pi
, tb
);
687 void uh_handle_request(struct client
*cl
)
689 struct dispatch_handler
*d
;
690 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));;
693 d
= dispatch_find(url
, NULL
);
695 d
->handle_request(cl
, url
, NULL
);
699 if (__handle_file_request(cl
, url
))
702 if (conf
.error_handler
) {
703 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
704 strcpy(error_handler
, conf
.error_handler
);
705 if (__handle_file_request(cl
, error_handler
))
709 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.", url
);