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.
20 #include <sys/types.h>
23 #include <libubox/blobmsg.h>
26 #include "uhttpd-mimetypes.h"
28 static LIST_HEAD(index_files
);
31 struct list_head list
;
46 HDR_IF_MODIFIED_SINCE
,
47 HDR_IF_UNMODIFIED_SINCE
,
54 void uh_index_add(const char *filename
)
56 struct index_file
*idx
;
58 idx
= calloc(1, sizeof(*idx
));
60 list_add_tail(&idx
->list
, &index_files
);
63 static char * canonpath(const char *path
, char *path_resolved
)
65 char path_copy
[PATH_MAX
];
66 char *path_cpy
= path_copy
;
67 char *path_res
= path_resolved
;
70 /* relative -> absolute */
72 getcwd(path_copy
, PATH_MAX
);
73 strncat(path_copy
, "/", PATH_MAX
- strlen(path_copy
));
74 strncat(path_copy
, path
, PATH_MAX
- strlen(path_copy
));
76 strncpy(path_copy
, path
, PATH_MAX
);
80 while ((*path_cpy
!= '\0') && (path_cpy
< (path_copy
+ PATH_MAX
- 2))) {
84 /* skip repeating / */
85 if (path_cpy
[1] == '/') {
91 if (path_cpy
[1] == '.') {
93 if ((path_cpy
[2] == '/') || (path_cpy
[2] == '\0')) {
99 if ((path_cpy
[2] == '.') &&
100 ((path_cpy
[3] == '/') || (path_cpy
[3] == '\0'))) {
101 while ((path_res
> path_resolved
) && (*--path_res
!= '/'));
109 *path_res
++ = *path_cpy
++;
112 /* remove trailing slash if not root / */
113 if ((path_res
> (path_resolved
+1)) && (path_res
[-1] == '/'))
115 else if (path_res
== path_resolved
)
121 if (!stat(path_resolved
, &s
) && (s
.st_mode
& S_IROTH
))
122 return path_resolved
;
127 /* Returns NULL on error.
128 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
129 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
130 struct path_info
* uh_path_lookup(struct client
*cl
, const char *url
)
132 static char path_phys
[PATH_MAX
];
133 static char path_info
[PATH_MAX
];
134 static struct path_info p
;
136 char buffer
[UH_LIMIT_MSGHEAD
];
137 char *docroot
= conf
.docroot
;
138 char *pathptr
= NULL
;
141 int no_sym
= conf
.no_symlinks
;
144 struct index_file
*idx
;
146 /* back out early if url is undefined */
150 memset(path_phys
, 0, sizeof(path_phys
));
151 memset(path_info
, 0, sizeof(path_info
));
152 memset(buffer
, 0, sizeof(buffer
));
153 memset(&p
, 0, sizeof(p
));
156 memcpy(buffer
, docroot
,
157 min(strlen(docroot
), sizeof(buffer
) - 1));
159 /* separate query string from url */
160 if ((pathptr
= strchr(url
, '?')) != NULL
) {
161 p
.query
= pathptr
[1] ? pathptr
+ 1 : NULL
;
163 /* urldecode component w/o query */
165 if (uh_urldecode(&buffer
[strlen(docroot
)],
166 sizeof(buffer
) - strlen(docroot
) - 1,
167 url
, pathptr
- url
) < 0)
168 return NULL
; /* bad URL */
172 /* no query string, decode all of url */
173 else if (uh_urldecode(&buffer
[strlen(docroot
)],
174 sizeof(buffer
) - strlen(docroot
) - 1,
175 url
, strlen(url
) ) < 0)
176 return NULL
; /* bad URL */
178 /* create canon path */
179 for (i
= strlen(buffer
), slash
= (buffer
[max(0, i
-1)] == '/'); i
>= 0; i
--) {
180 if ((buffer
[i
] == 0) || (buffer
[i
] == '/')) {
181 memset(path_info
, 0, sizeof(path_info
));
182 memcpy(path_info
, buffer
, min(i
+ 1, sizeof(path_info
) - 1));
184 if (no_sym
? realpath(path_info
, path_phys
)
185 : canonpath(path_info
, path_phys
)) {
186 memset(path_info
, 0, sizeof(path_info
));
187 memcpy(path_info
, &buffer
[i
],
188 min(strlen(buffer
) - i
, sizeof(path_info
) - 1));
195 /* check whether found path is within docroot */
196 if (strncmp(path_phys
, docroot
, strlen(docroot
)) ||
197 ((path_phys
[strlen(docroot
)] != 0) &&
198 (path_phys
[strlen(docroot
)] != '/')))
201 /* test current path */
202 if (!stat(path_phys
, &p
.stat
)) {
203 /* is a regular file */
204 if (p
.stat
.st_mode
& S_IFREG
) {
207 p
.name
= &path_phys
[strlen(docroot
)];
208 p
.info
= path_info
[0] ? path_info
: NULL
;
212 else if ((p
.stat
.st_mode
& S_IFDIR
) && !strlen(path_info
)) {
213 /* ensure trailing slash */
214 if (path_phys
[strlen(path_phys
)-1] != '/')
215 path_phys
[strlen(path_phys
)] = '/';
217 /* try to locate index file */
218 memset(buffer
, 0, sizeof(buffer
));
219 memcpy(buffer
, path_phys
, sizeof(buffer
));
220 pathptr
= &buffer
[strlen(buffer
)];
222 /* if requested url resolves to a directory and a trailing slash
223 is missing in the request url, redirect the client to the same
224 url with trailing slash appended */
226 uh_http_header(cl
, 302, "Found");
227 ustream_printf(cl
->us
, "Location: %s%s%s\r\n\r\n",
228 &path_phys
[strlen(docroot
)],
230 p
.query
? p
.query
: "");
234 list_for_each_entry(idx
, &index_files
, list
) {
235 strncat(buffer
, idx
->name
, sizeof(buffer
));
237 if (!stat(buffer
, &s
) && (s
.st_mode
& S_IFREG
)) {
238 memcpy(path_phys
, buffer
, sizeof(path_phys
));
239 memcpy(&p
.stat
, &s
, sizeof(p
.stat
));
249 p
.name
= &path_phys
[strlen(docroot
)];
253 return p
.phys
? &p
: NULL
;
257 time_t timegm (struct tm
*tm
);
260 static const char * uh_file_mime_lookup(const char *path
)
262 struct mimetype
*m
= &uh_mime_types
[0];
266 e
= &path
[strlen(path
)-1];
269 if ((*e
== '.' || *e
== '/') && !strcasecmp(&e
[1], m
->extn
))
278 return "application/octet-stream";
281 static const char * uh_file_mktag(struct stat
*s
)
283 static char tag
[128];
285 snprintf(tag
, sizeof(tag
), "\"%x-%x-%x\"",
286 (unsigned int) s
->st_ino
,
287 (unsigned int) s
->st_size
,
288 (unsigned int) s
->st_mtime
);
293 static time_t uh_file_date2unix(const char *date
)
297 memset(&t
, 0, sizeof(t
));
299 if (strptime(date
, "%a, %d %b %Y %H:%M:%S %Z", &t
) != NULL
)
305 static char * uh_file_unix2date(time_t ts
)
307 static char str
[128];
308 struct tm
*t
= gmtime(&ts
);
310 strftime(str
, sizeof(str
), "%a, %d %b %Y %H:%M:%S GMT", t
);
315 static char *uh_file_header(struct client
*cl
, int idx
)
317 if (!cl
->data
.file
.hdr
[idx
])
320 return (char *) blobmsg_data(cl
->data
.file
.hdr
[idx
]);
323 static void uh_file_response_ok_hdrs(struct client
*cl
, struct stat
*s
)
326 ustream_printf(cl
->us
, "ETag: %s\r\n", uh_file_mktag(s
));
327 ustream_printf(cl
->us
, "Last-Modified: %s\r\n",
328 uh_file_unix2date(s
->st_mtime
));
330 ustream_printf(cl
->us
, "Date: %s\r\n", uh_file_unix2date(time(NULL
)));
333 static void uh_file_response_200(struct client
*cl
, struct stat
*s
)
335 uh_http_header(cl
, 200, "OK");
336 return uh_file_response_ok_hdrs(cl
, s
);
339 static void uh_file_response_304(struct client
*cl
, struct stat
*s
)
341 uh_http_header(cl
, 304, "Not Modified");
343 return uh_file_response_ok_hdrs(cl
, s
);
346 static void uh_file_response_412(struct client
*cl
)
348 uh_http_header(cl
, 412, "Precondition Failed");
351 static bool uh_file_if_match(struct client
*cl
, struct stat
*s
)
353 const char *tag
= uh_file_mktag(s
);
354 char *hdr
= uh_file_header(cl
, HDR_IF_MATCH
);
362 for (i
= 0; i
< strlen(hdr
); i
++)
364 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
367 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
372 uh_file_response_412(cl
);
376 static int uh_file_if_modified_since(struct client
*cl
, struct stat
*s
)
378 char *hdr
= uh_file_header(cl
, HDR_IF_MODIFIED_SINCE
);
383 if (uh_file_date2unix(hdr
) >= s
->st_mtime
) {
384 uh_file_response_304(cl
, s
);
391 static int uh_file_if_none_match(struct client
*cl
, struct stat
*s
)
393 const char *tag
= uh_file_mktag(s
);
394 char *hdr
= uh_file_header(cl
, HDR_IF_NONE_MATCH
);
402 for (i
= 0; i
< strlen(hdr
); i
++) {
403 if ((hdr
[i
] == ' ') || (hdr
[i
] == ',')) {
406 } else if (!strcmp(p
, "*") || !strcmp(p
, tag
)) {
407 if ((cl
->request
.method
== UH_HTTP_MSG_GET
) ||
408 (cl
->request
.method
== UH_HTTP_MSG_HEAD
))
409 uh_file_response_304(cl
, s
);
411 uh_file_response_412(cl
);
420 static int uh_file_if_range(struct client
*cl
, struct stat
*s
)
422 char *hdr
= uh_file_header(cl
, HDR_IF_RANGE
);
425 uh_file_response_412(cl
);
432 static int uh_file_if_unmodified_since(struct client
*cl
, struct stat
*s
)
434 char *hdr
= uh_file_header(cl
, HDR_IF_UNMODIFIED_SINCE
);
436 if (hdr
&& uh_file_date2unix(hdr
) <= s
->st_mtime
) {
437 uh_file_response_412(cl
);
445 static int uh_file_scandir_filter_dir(const struct dirent
*e
)
447 return strcmp(e
->d_name
, ".") ? 1 : 0;
450 static void uh_file_dirlist(struct client
*cl
, struct path_info
*pi
)
454 char filename
[PATH_MAX
];
456 struct dirent
**files
= NULL
;
459 uh_file_response_200(cl
, NULL
);
460 ustream_printf(cl
->us
, "Content-Type: text/html\r\n\r\n");
463 "<html><head><title>Index of %s</title></head>"
464 "<body><h1>Index of %s</h1><hr /><ol>",
467 if ((count
= scandir(pi
->phys
, &files
, uh_file_scandir_filter_dir
,
470 memset(filename
, 0, sizeof(filename
));
471 memcpy(filename
, pi
->phys
, sizeof(filename
));
472 pathptr
= &filename
[strlen(filename
)];
475 for (i
= 0; i
< count
; i
++) {
476 strncat(filename
, files
[i
]->d_name
,
477 sizeof(filename
) - strlen(files
[i
]->d_name
));
479 if (!stat(filename
, &s
) &&
480 (s
.st_mode
& S_IFDIR
) && (s
.st_mode
& S_IXOTH
))
482 "<li><strong><a href='%s%s'>%s</a>/"
483 "</strong><br /><small>modified: %s"
484 "<br />directory - %.02f kbyte<br />"
485 "<br /></small></li>",
486 pi
->name
, files
[i
]->d_name
,
488 uh_file_unix2date(s
.st_mtime
),
495 for (i
= 0; i
< count
; i
++) {
496 strncat(filename
, files
[i
]->d_name
,
497 sizeof(filename
) - strlen(files
[i
]->d_name
));
499 if (!stat(filename
, &s
) &&
500 !(s
.st_mode
& S_IFDIR
) && (s
.st_mode
& S_IROTH
))
502 "<li><strong><a href='%s%s'>%s</a>"
503 "</strong><br /><small>modified: %s"
504 "<br />%s - %.02f kbyte<br />"
505 "<br /></small></li>",
506 pi
->name
, files
[i
]->d_name
,
508 uh_file_unix2date(s
.st_mtime
),
509 uh_file_mime_lookup(filename
),
516 uh_chunk_printf(cl
, "</ol><hr /></body></html>");
521 for (i
= 0; i
< count
; i
++)
528 static void file_write_cb(struct client
*cl
)
531 int fd
= cl
->data
.file
.fd
;
534 while (cl
->us
->w
.data_bytes
< 256) {
535 r
= read(fd
, buf
, sizeof(buf
));
546 uh_chunk_write(cl
, buf
, r
);
550 static void uh_file_free(struct client
*cl
)
552 close(cl
->data
.file
.fd
);
555 static void uh_file_data(struct client
*cl
, struct path_info
*pi
, int fd
)
557 /* test preconditions */
558 if (!uh_file_if_modified_since(cl
, &pi
->stat
) ||
559 !uh_file_if_match(cl
, &pi
->stat
) ||
560 !uh_file_if_range(cl
, &pi
->stat
) ||
561 !uh_file_if_unmodified_since(cl
, &pi
->stat
) ||
562 !uh_file_if_none_match(cl
, &pi
->stat
)) {
569 uh_file_response_200(cl
, &pi
->stat
);
571 ustream_printf(cl
->us
, "Content-Type: %s\r\n",
572 uh_file_mime_lookup(pi
->name
));
574 ustream_printf(cl
->us
, "Content-Length: %i\r\n\r\n",
579 if (cl
->request
.method
== UH_HTTP_MSG_HEAD
) {
585 cl
->data
.file
.fd
= fd
;
586 cl
->dispatch_write_cb
= file_write_cb
;
587 cl
->dispatch_free
= uh_file_free
;
591 static void uh_file_request(struct client
*cl
, struct path_info
*pi
)
593 static const struct blobmsg_policy hdr_policy
[__HDR_MAX
] = {
594 [HDR_IF_MODIFIED_SINCE
] = { "if-modified-since", BLOBMSG_TYPE_STRING
},
595 [HDR_IF_UNMODIFIED_SINCE
] = { "if-unmodified-since", BLOBMSG_TYPE_STRING
},
596 [HDR_IF_MATCH
] = { "if-match", BLOBMSG_TYPE_STRING
},
597 [HDR_IF_NONE_MATCH
] = { "if-none-match", BLOBMSG_TYPE_STRING
},
598 [HDR_IF_RANGE
] = { "if-range", BLOBMSG_TYPE_STRING
},
600 struct blob_attr
*tb
[__HDR_MAX
];
603 blobmsg_parse(hdr_policy
, __HDR_MAX
, tb
, blob_data(cl
->hdr
.head
), blob_len(cl
->hdr
.head
));
605 cl
->data
.file
.hdr
= tb
;
606 if ((pi
->stat
.st_mode
& S_IFREG
) && ((fd
= open(pi
->phys
, O_RDONLY
)) > 0))
607 uh_file_data(cl
, pi
, fd
);
608 else if ((pi
->stat
.st_mode
& S_IFDIR
) && !conf
.no_dirlists
)
609 uh_file_dirlist(cl
, pi
);
611 uh_client_error(cl
, 403, "Forbidden",
612 "Access to this resource is forbidden");
613 cl
->data
.file
.hdr
= NULL
;
616 void uh_handle_file_request(struct client
*cl
)
618 struct path_info
*pi
;
620 pi
= uh_path_lookup(cl
, cl
->request
.url
);
629 uh_file_request(cl
, pi
);