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
);
179 snprintf(path_info
, sizeof(path_info
), "%s", uh_buf
+ i
);
183 /* check whether found path is within docroot */
184 if (strncmp(path_phys
, docroot
, docroot_len
) != 0 ||
185 (path_phys
[docroot_len
] != 0 &&
186 path_phys
[docroot_len
] != '/'))
189 /* test current path */
190 if (stat(path_phys
, &p
.stat
))
193 /* is a regular file */
194 if (p
.stat
.st_mode
& S_IFREG
) {
197 p
.name
= &path_phys
[docroot_len
];
198 p
.info
= path_info
[0] ? path_info
: NULL
;
202 if (!(p
.stat
.st_mode
& S_IFDIR
))
208 pathptr
= path_phys
+ strlen(path_phys
);
210 /* ensure trailing slash */
211 if (pathptr
[-1] != '/') {
217 /* if requested url resolves to a directory and a trailing slash
218 is missing in the request url, redirect the client to the same
219 url with trailing slash appended */
221 uh_http_header(cl
, 302, "Found");
222 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
223 &path_phys
[docroot_len
],
225 p
.query
? p
.query
: "");
231 /* try to locate index file */
232 len
= path_phys
+ sizeof(path_phys
) - pathptr
- 1;
233 list_for_each_entry(idx
, &index_files
, list
) {
234 if (strlen(idx
->name
) > len
)
237 strcpy(pathptr
, idx
->name
);
238 if (!stat(path_phys
, &s
) && (s
.st_mode
& S_IFREG
)) {
239 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
248 p
.name
= &path_phys
[docroot_len
];
250 return p
.phys
? &p
: NULL
;
253 static const char * uh_file_mime_lookup(const char *path
)
255 const struct mimetype
*m
= &uh_mime_types
[0];
259 e
= &path
[strlen(path
)-1];
262 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
271 return "application/octet-stream";
274 static const char * uh_file_mktag(struct stat
*s
, char *buf
)
276 snprintf(buf
, sizeof(buf
), "\"%x-%x-%x\"",
277 (unsigned int) s
->st_ino
,
278 (unsigned int) s
->st_size
,
279 (unsigned int) s
->st_mtime
);
284 static time_t uh_file_date2unix(const char *date
)
288 memset(&t
, 0, sizeof(t
));
290 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
296 static char * uh_file_unix2date(time_t ts
, char *buf
, int len
)
298 struct tm
*t
= gmtime(&ts
);
300 strftime(buf
, len
, "%a, %d %b %Y %H:%M:%S GMT", t
);
305 static char *uh_file_header(struct client
*cl
, int idx
)
307 if (!cl
->dispatch
.file
.hdr
[idx
])
310 return (char *) blobmsg_data(cl
->dispatch
.file
.hdr
[idx
]);
313 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
318 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
, buf
));
319 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
320 uh_file_unix2date(s
->st_mtime
, buf
, sizeof(buf
)));
322 ustream_printf(cl
->us
, "Date: %s\r\n",
323 uh_file_unix2date(time(NULL
), buf
, sizeof(buf
)));
326 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
328 uh_http_header(cl
, 200, "OK");
329 return uh_file_response_ok_hdrs(cl
, s
);
332 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
334 uh_http_header(cl
, 304, "Not Modified");
336 return uh_file_response_ok_hdrs(cl
, s
);
339 static void uh_file_response_412(struct client
*cl
)
341 uh_http_header(cl
, 412, "Precondition Failed");
344 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
347 const char *tag
= uh_file_mktag(s
, buf
);
348 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
356 for (i
= 0; i
< strlen(hdr
); i
++)
358 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
361 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
366 uh_file_response_412(cl
);
370 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
372 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
377 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
378 uh_file_response_304(cl
, s
);
385 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
388 const char *tag
= uh_file_mktag(s
, buf
);
389 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
397 for (i
= 0; i
< strlen(hdr
); i
++) {
398 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
401 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
402 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
403 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
404 uh_file_response_304(cl
, s
);
406 uh_file_response_412(cl
);
415 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
417 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
420 uh_file_response_412(cl
);
427 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
429 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
431 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
432 uh_file_response_412(cl
);
439 static int dirent_cmp(const struct dirent
**a
, const struct dirent
**b
)
441 bool dir_a
= !!((*a
)->d_type
& DT_DIR
);
442 bool dir_b
= !!((*b
)->d_type
& DT_DIR
);
444 /* directories first */
446 return dir_b
- dir_a
;
448 return alphasort(a
, b
);
451 static void list_entries(struct client
*cl
, struct dirent
**files
, int count
,
452 const char *path
, char *local_path
)
454 const char *suffix
= "/";
455 const char *type
= "directory";
456 unsigned int mode
= S_IXOTH
;
462 file
= local_path
+ strlen(local_path
);
463 for (i
= 0; i
< count
; i
++) {
464 const char *name
= files
[i
]->d_name
;
465 bool dir
= !!(files
[i
]->d_type
& DT_DIR
);
467 if (name
[0] == '.' && name
[1] == 0)
470 sprintf(file
, "%s", name
);
471 if (stat(local_path
, &s
))
477 type
= uh_file_mime_lookup(local_path
);
480 if (!(s
.st_mode
& mode
))
484 "<li><strong><a href='%s%s%s'>%s</a>%s"
485 "</strong><br /><small>modified: %s"
486 "<br />%s - %.02f kbyte<br />"
487 "<br /></small></li>",
490 uh_file_unix2date(s
.st_mtime
, buf
, sizeof(buf
)),
491 type
, s
.st_size
/ 1024.0);
498 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
500 struct dirent
**files
= NULL
;
503 uh_file_response_200(cl
, NULL
);
504 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
507 "<html><head><title>Index of %s</title></head>"
508 "<body><h1>Index of %s</h1><hr /><ol>",
511 count
= scandir(pi
->phys
, &files
, NULL
, dirent_cmp
);
513 strcpy(uh_buf
, pi
->phys
);
514 list_entries(cl
, files
, count
, pi
->name
, uh_buf
);
518 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
522 static void file_write_cb(struct client
*cl
)
524 int fd
= cl
->dispatch
.file
.fd
;
527 while (cl
->us
->w
.data_bytes
< 256) {
528 r
= read(fd
, uh_buf
, sizeof(uh_buf
));
539 uh_chunk_write(cl
, uh_buf
, r
);
543 static void uh_file_free(struct client
*cl
)
545 close(cl
->dispatch
.file
.fd
);
548 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
550 /* test preconditions */
551 if (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
552 !uh_file_if_match(cl
, &pi
->stat
) ||
553 !uh_file_if_range(cl
, &pi
->stat
) ||
554 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
555 !uh_file_if_none_match(cl
, &pi
->stat
)) {
562 uh_file_response_200(cl
, &pi
->stat
);
564 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
565 uh_file_mime_lookup(pi
->name
));
567 ustream_printf(cl
->us
, "Content-Length: %i\r\n\r\n",
572 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
578 cl
->dispatch
.file
.fd
= fd
;
579 cl
->dispatch
.write_cb
= file_write_cb
;
580 cl
->dispatch
.free
= uh_file_free
;
581 cl
->dispatch
.close_fds
= uh_file_free
;
585 static void uh_file_request(struct client
*cl
, const char *url
,
586 struct path_info
*pi
, struct blob_attr
**tb
)
590 if (!(pi
->stat
.st_mode
& S_IROTH
))
593 if (pi
->stat
.st_mode
& S_IFREG
) {
594 fd
= open(pi
->phys
, O_RDONLY
);
598 cl
->dispatch
.file
.hdr
= tb
;
599 uh_file_data(cl
, pi
, fd
);
600 cl
->dispatch
.file
.hdr
= NULL
;
604 if ((pi
->stat
.st_mode
& S_IFDIR
)) {
605 if (conf
.no_dirlists
)
608 uh_file_dirlist(cl
, pi
);
613 uh_client_error(cl
, 403, "Forbidden",
614 "You don't have permission to access %s on this server.",
618 void uh_dispatch_add(struct dispatch_handler
*d
)
620 list_add_tail(&d
->list
, &dispatch_handlers
);
623 static struct dispatch_handler
*
624 dispatch_find(const char *url
, struct path_info
*pi
)
626 struct dispatch_handler
*d
;
628 list_for_each_entry(d
, &dispatch_handlers
, list
) {
633 if (d
->check_path(pi
, url
))
639 if (d
->check_url(url
))
647 static bool __handle_file_request(struct client
*cl
, char *url
)
649 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
650 [HDR_AUTHORIZATION
] = { "authorization", BLOBMSG_TYPE_STRING
},
651 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
652 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
653 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
654 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
655 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
657 struct dispatch_handler
*d
;
658 struct blob_attr
*tb
[__HDR_MAX
];
659 struct path_info
*pi
;
661 pi
= uh_path_lookup(cl
, url
);
668 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
669 if (tb
[HDR_AUTHORIZATION
])
670 pi
->auth
= blobmsg_data(tb
[HDR_AUTHORIZATION
]);
672 if (!uh_auth_check(cl
, pi
))
675 d
= dispatch_find(url
, pi
);
677 d
->handle_request(cl
, url
, pi
);
679 uh_file_request(cl
, url
, pi
, tb
);
684 void uh_handle_request(struct client
*cl
)
686 struct dispatch_handler
*d
;
687 char *url
= blobmsg_data(blob_data(cl
->hdr
.head
));;
690 d
= dispatch_find(url
, NULL
);
692 d
->handle_request(cl
, url
, NULL
);
696 if (__handle_file_request(cl
, url
))
699 error_handler
= alloca(strlen(conf
.error_handler
) + 1);
700 strcpy(error_handler
, conf
.error_handler
);
701 if (__handle_file_request(cl
, error_handler
))
704 uh_client_error(cl
, 404, "Not Found", "The requested URL %s was not found on this server.", url
);