fa37155e7159ffcded7f8aca8c78c3fa692d30c2
[project/uhttpd.git] / file.c
1 /*
2 * uhttpd - Tiny single-threaded httpd
3 *
4 * Copyright (C) 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
6 *
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
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
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.
18 */
19
20 #define _BSD_SOURCE
21 #define _XOPEN_SOURCE 700
22
23 #include <sys/types.h>
24 #include <sys/dir.h>
25 #include <time.h>
26 #include <strings.h>
27
28 #include <libubox/blobmsg.h>
29
30 #include "uhttpd.h"
31 #include "uhttpd-mimetypes.h"
32
33 static LIST_HEAD(index_files);
34
35 struct index_file {
36 struct list_head list;
37 const char *name;
38 };
39
40 struct path_info {
41 char *root;
42 char *phys;
43 char *name;
44 char *info;
45 char *query;
46 int redirected;
47 struct stat stat;
48 };
49
50 enum file_hdr {
51 HDR_IF_MODIFIED_SINCE,
52 HDR_IF_UNMODIFIED_SINCE,
53 HDR_IF_MATCH,
54 HDR_IF_NONE_MATCH,
55 HDR_IF_RANGE,
56 __HDR_MAX
57 };
58
59 void uh_index_add(const char *filename)
60 {
61 struct index_file *idx;
62
63 idx = calloc(1, sizeof(*idx));
64 idx->name = filename;
65 list_add_tail(&idx->list, &index_files);
66 }
67
68 static char * canonpath(const char *path, char *path_resolved)
69 {
70 char path_copy[PATH_MAX];
71 char *path_cpy = path_copy;
72 char *path_res = path_resolved;
73 struct stat s;
74
75 /* relative -> absolute */
76 if (*path != '/') {
77 getcwd(path_copy, PATH_MAX);
78 strncat(path_copy, "/", PATH_MAX - strlen(path_copy));
79 strncat(path_copy, path, PATH_MAX - strlen(path_copy));
80 } else {
81 strncpy(path_copy, path, PATH_MAX);
82 }
83
84 /* normalize */
85 while ((*path_cpy != '\0') && (path_cpy < (path_copy + PATH_MAX - 2))) {
86 if (*path_cpy != '/')
87 goto next;
88
89 /* skip repeating / */
90 if (path_cpy[1] == '/') {
91 path_cpy++;
92 continue;
93 }
94
95 /* /./ or /../ */
96 if (path_cpy[1] == '.') {
97 /* skip /./ */
98 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
99 path_cpy += 2;
100 continue;
101 }
102
103 /* collapse /x/../ */
104 if ((path_cpy[2] == '.') &&
105 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
106 while ((path_res > path_resolved) && (*--path_res != '/'));
107
108 path_cpy += 3;
109 continue;
110 }
111 }
112
113 next:
114 *path_res++ = *path_cpy++;
115 }
116
117 /* remove trailing slash if not root / */
118 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
119 path_res--;
120 else if (path_res == path_resolved)
121 *path_res++ = '/';
122
123 *path_res = '\0';
124
125 /* test access */
126 if (!stat(path_resolved, &s) && (s.st_mode & S_IROTH))
127 return path_resolved;
128
129 return NULL;
130 }
131
132 /* Returns NULL on error.
133 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
134 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
135 struct path_info * uh_path_lookup(struct client *cl, const char *url)
136 {
137 static char path_phys[PATH_MAX];
138 static char path_info[PATH_MAX];
139 static struct path_info p;
140
141 char buffer[UH_LIMIT_MSGHEAD];
142 char *docroot = conf.docroot;
143 char *pathptr = NULL;
144
145 int slash = 0;
146 int no_sym = conf.no_symlinks;
147 int i = 0;
148 struct stat s;
149 struct index_file *idx;
150
151 /* back out early if url is undefined */
152 if (url == NULL)
153 return NULL;
154
155 memset(path_phys, 0, sizeof(path_phys));
156 memset(path_info, 0, sizeof(path_info));
157 memset(buffer, 0, sizeof(buffer));
158 memset(&p, 0, sizeof(p));
159
160 /* copy docroot */
161 memcpy(buffer, docroot,
162 min(strlen(docroot), sizeof(buffer) - 1));
163
164 /* separate query string from url */
165 if ((pathptr = strchr(url, '?')) != NULL) {
166 p.query = pathptr[1] ? pathptr + 1 : NULL;
167
168 /* urldecode component w/o query */
169 if (pathptr > url) {
170 if (uh_urldecode(&buffer[strlen(docroot)],
171 sizeof(buffer) - strlen(docroot) - 1,
172 url, pathptr - url ) < 0)
173 return NULL; /* bad URL */
174 }
175 }
176
177 /* no query string, decode all of url */
178 else if (uh_urldecode(&buffer[strlen(docroot)],
179 sizeof(buffer) - strlen(docroot) - 1,
180 url, strlen(url) ) < 0)
181 return NULL; /* bad URL */
182
183 /* create canon path */
184 for (i = strlen(buffer), slash = (buffer[max(0, i-1)] == '/'); i >= 0; i--) {
185 if ((buffer[i] == 0) || (buffer[i] == '/')) {
186 memset(path_info, 0, sizeof(path_info));
187 memcpy(path_info, buffer, min(i + 1, sizeof(path_info) - 1));
188
189 if (no_sym ? realpath(path_info, path_phys)
190 : canonpath(path_info, path_phys)) {
191 memset(path_info, 0, sizeof(path_info));
192 memcpy(path_info, &buffer[i],
193 min(strlen(buffer) - i, sizeof(path_info) - 1));
194
195 break;
196 }
197 }
198 }
199
200 /* check whether found path is within docroot */
201 if (strncmp(path_phys, docroot, strlen(docroot)) ||
202 ((path_phys[strlen(docroot)] != 0) &&
203 (path_phys[strlen(docroot)] != '/')))
204 return NULL;
205
206 /* test current path */
207 if (!stat(path_phys, &p.stat)) {
208 /* is a regular file */
209 if (p.stat.st_mode & S_IFREG) {
210 p.root = docroot;
211 p.phys = path_phys;
212 p.name = &path_phys[strlen(docroot)];
213 p.info = path_info[0] ? path_info : NULL;
214 }
215
216 /* is a directory */
217 else if ((p.stat.st_mode & S_IFDIR) && !strlen(path_info)) {
218 /* ensure trailing slash */
219 if (path_phys[strlen(path_phys)-1] != '/')
220 path_phys[strlen(path_phys)] = '/';
221
222 /* try to locate index file */
223 memset(buffer, 0, sizeof(buffer));
224 memcpy(buffer, path_phys, sizeof(buffer));
225 pathptr = &buffer[strlen(buffer)];
226
227 /* if requested url resolves to a directory and a trailing slash
228 is missing in the request url, redirect the client to the same
229 url with trailing slash appended */
230 if (!slash) {
231 uh_http_header(cl, 302, "Found");
232 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
233 &path_phys[strlen(docroot)],
234 p.query ? "?" : "",
235 p.query ? p.query : "");
236 uh_request_done(cl);
237 p.redirected = 1;
238 } else {
239 list_for_each_entry(idx, &index_files, list) {
240 strncat(buffer, idx->name, sizeof(buffer));
241
242 if (!stat(buffer, &s) && (s.st_mode & S_IFREG)) {
243 memcpy(path_phys, buffer, sizeof(path_phys));
244 memcpy(&p.stat, &s, sizeof(p.stat));
245 break;
246 }
247
248 *pathptr = 0;
249 }
250 }
251
252 p.root = docroot;
253 p.phys = path_phys;
254 p.name = &path_phys[strlen(docroot)];
255 }
256 }
257
258 return p.phys ? &p : NULL;
259 }
260
261 #ifdef __APPLE__
262 time_t timegm (struct tm *tm);
263 #endif
264
265 static const char * uh_file_mime_lookup(const char *path)
266 {
267 struct mimetype *m = &uh_mime_types[0];
268 const char *e;
269
270 while (m->extn) {
271 e = &path[strlen(path)-1];
272
273 while (e >= path) {
274 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
275 return m->mime;
276
277 e--;
278 }
279
280 m++;
281 }
282
283 return "application/octet-stream";
284 }
285
286 static const char * uh_file_mktag(struct stat *s)
287 {
288 static char tag[128];
289
290 snprintf(tag, sizeof(tag), "\"%x-%x-%x\"",
291 (unsigned int) s->st_ino,
292 (unsigned int) s->st_size,
293 (unsigned int) s->st_mtime);
294
295 return tag;
296 }
297
298 static time_t uh_file_date2unix(const char *date)
299 {
300 struct tm t;
301
302 memset(&t, 0, sizeof(t));
303
304 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
305 return timegm(&t);
306
307 return 0;
308 }
309
310 static char * uh_file_unix2date(time_t ts)
311 {
312 static char str[128];
313 struct tm *t = gmtime(&ts);
314
315 strftime(str, sizeof(str), "%a, %d %b %Y %H:%M:%S GMT", t);
316
317 return str;
318 }
319
320 static char *uh_file_header(struct client *cl, int idx)
321 {
322 if (!cl->data.file.hdr[idx])
323 return NULL;
324
325 return (char *) blobmsg_data(cl->data.file.hdr[idx]);
326 }
327
328 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
329 {
330 if (s) {
331 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s));
332 ustream_printf(cl->us, "Last-Modified: %s\r\n",
333 uh_file_unix2date(s->st_mtime));
334 }
335 ustream_printf(cl->us, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
336 }
337
338 static void uh_file_response_200(struct client *cl, struct stat *s)
339 {
340 uh_http_header(cl, 200, "OK");
341 return uh_file_response_ok_hdrs(cl, s);
342 }
343
344 static void uh_file_response_304(struct client *cl, struct stat *s)
345 {
346 uh_http_header(cl, 304, "Not Modified");
347
348 return uh_file_response_ok_hdrs(cl, s);
349 }
350
351 static void uh_file_response_412(struct client *cl)
352 {
353 uh_http_header(cl, 412, "Precondition Failed");
354 }
355
356 static bool uh_file_if_match(struct client *cl, struct stat *s)
357 {
358 const char *tag = uh_file_mktag(s);
359 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
360 char *p;
361 int i;
362
363 if (!hdr)
364 return true;
365
366 p = &hdr[0];
367 for (i = 0; i < strlen(hdr); i++)
368 {
369 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
370 hdr[i++] = 0;
371 p = &hdr[i];
372 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
373 return true;
374 }
375 }
376
377 uh_file_response_412(cl);
378 return false;
379 }
380
381 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
382 {
383 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
384
385 if (!hdr)
386 return true;
387
388 if (uh_file_date2unix(hdr) >= s->st_mtime) {
389 uh_file_response_304(cl, s);
390 return false;
391 }
392
393 return true;
394 }
395
396 static int uh_file_if_none_match(struct client *cl, struct stat *s)
397 {
398 const char *tag = uh_file_mktag(s);
399 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
400 char *p;
401 int i;
402
403 if (!hdr)
404 return true;
405
406 p = &hdr[0];
407 for (i = 0; i < strlen(hdr); i++) {
408 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
409 hdr[i++] = 0;
410 p = &hdr[i];
411 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
412 if ((cl->request.method == UH_HTTP_MSG_GET) ||
413 (cl->request.method == UH_HTTP_MSG_HEAD))
414 uh_file_response_304(cl, s);
415 else
416 uh_file_response_412(cl);
417
418 return false;
419 }
420 }
421
422 return true;
423 }
424
425 static int uh_file_if_range(struct client *cl, struct stat *s)
426 {
427 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
428
429 if (hdr) {
430 uh_file_response_412(cl);
431 return false;
432 }
433
434 return true;
435 }
436
437 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
438 {
439 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
440
441 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
442 uh_file_response_412(cl);
443 return false;
444 }
445
446 return true;
447 }
448
449
450 static int uh_file_scandir_filter_dir(const struct dirent *e)
451 {
452 return strcmp(e->d_name, ".") ? 1 : 0;
453 }
454
455 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
456 {
457 int i;
458 int count = 0;
459 char filename[PATH_MAX];
460 char *pathptr;
461 struct dirent **files = NULL;
462 struct stat s;
463
464 uh_file_response_200(cl, NULL);
465 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
466
467 uh_chunk_printf(cl,
468 "<html><head><title>Index of %s</title></head>"
469 "<body><h1>Index of %s</h1><hr /><ol>",
470 pi->name, pi->name);
471
472 if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
473 alphasort)) > 0)
474 {
475 memset(filename, 0, sizeof(filename));
476 memcpy(filename, pi->phys, sizeof(filename));
477 pathptr = &filename[strlen(filename)];
478
479 /* list subdirs */
480 for (i = 0; i < count; i++) {
481 strncat(filename, files[i]->d_name,
482 sizeof(filename) - strlen(files[i]->d_name));
483
484 if (!stat(filename, &s) &&
485 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
486 uh_chunk_printf(cl,
487 "<li><strong><a href='%s%s'>%s</a>/"
488 "</strong><br /><small>modified: %s"
489 "<br />directory - %.02f kbyte<br />"
490 "<br /></small></li>",
491 pi->name, files[i]->d_name,
492 files[i]->d_name,
493 uh_file_unix2date(s.st_mtime),
494 s.st_size / 1024.0);
495
496 *pathptr = 0;
497 }
498
499 /* list files */
500 for (i = 0; i < count; i++) {
501 strncat(filename, files[i]->d_name,
502 sizeof(filename) - strlen(files[i]->d_name));
503
504 if (!stat(filename, &s) &&
505 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
506 uh_chunk_printf(cl,
507 "<li><strong><a href='%s%s'>%s</a>"
508 "</strong><br /><small>modified: %s"
509 "<br />%s - %.02f kbyte<br />"
510 "<br /></small></li>",
511 pi->name, files[i]->d_name,
512 files[i]->d_name,
513 uh_file_unix2date(s.st_mtime),
514 uh_file_mime_lookup(filename),
515 s.st_size / 1024.0);
516
517 *pathptr = 0;
518 }
519 }
520
521 uh_chunk_printf(cl, "</ol><hr /></body></html>");
522 uh_request_done(cl);
523
524 if (files)
525 {
526 for (i = 0; i < count; i++)
527 free(files[i]);
528
529 free(files);
530 }
531 }
532
533 static void file_write_cb(struct client *cl)
534 {
535 char buf[512];
536 int fd = cl->data.file.fd;
537 int r;
538
539 while (cl->us->w.data_bytes < 256) {
540 r = read(fd, buf, sizeof(buf));
541 if (r < 0) {
542 if (errno == EINTR)
543 continue;
544 }
545
546 if (!r) {
547 uh_request_done(cl);
548 return;
549 }
550
551 uh_chunk_write(cl, buf, r);
552 }
553 }
554
555 static void uh_file_free(struct client *cl)
556 {
557 close(cl->data.file.fd);
558 }
559
560 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
561 {
562 /* test preconditions */
563 if (!uh_file_if_modified_since(cl, &pi->stat) ||
564 !uh_file_if_match(cl, &pi->stat) ||
565 !uh_file_if_range(cl, &pi->stat) ||
566 !uh_file_if_unmodified_since(cl, &pi->stat) ||
567 !uh_file_if_none_match(cl, &pi->stat)) {
568 uh_request_done(cl);
569 close(fd);
570 return;
571 }
572
573 /* write status */
574 uh_file_response_200(cl, &pi->stat);
575
576 ustream_printf(cl->us, "Content-Type: %s\r\n",
577 uh_file_mime_lookup(pi->name));
578
579 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
580 pi->stat.st_size);
581
582
583 /* send body */
584 if (cl->request.method == UH_HTTP_MSG_HEAD) {
585 uh_request_done(cl);
586 close(fd);
587 return;
588 }
589
590 cl->data.file.fd = fd;
591 cl->dispatch_write_cb = file_write_cb;
592 cl->dispatch_free = uh_file_free;
593 file_write_cb(cl);
594 }
595
596 static void uh_file_request(struct client *cl, struct path_info *pi)
597 {
598 static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
599 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
600 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
601 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
602 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
603 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
604 };
605 struct blob_attr *tb[__HDR_MAX];
606 int fd;
607
608 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
609
610 cl->data.file.hdr = tb;
611 if ((pi->stat.st_mode & S_IFREG) && ((fd = open(pi->phys, O_RDONLY)) > 0))
612 uh_file_data(cl, pi, fd);
613 else if ((pi->stat.st_mode & S_IFDIR) && !conf.no_dirlists)
614 uh_file_dirlist(cl, pi);
615 else
616 uh_client_error(cl, 403, "Forbidden",
617 "Access to this resource is forbidden");
618 cl->data.file.hdr = NULL;
619 }
620
621 static bool __handle_file_request(struct client *cl, const char *url)
622 {
623 struct path_info *pi;
624
625 pi = uh_path_lookup(cl, url);
626 if (!pi)
627 return false;
628
629 if (!pi->redirected)
630 uh_file_request(cl, pi);
631
632 return true;
633 }
634
635 void uh_handle_file_request(struct client *cl)
636 {
637 if (__handle_file_request(cl, cl->request.url) ||
638 __handle_file_request(cl, conf.error_handler))
639 return;
640
641 uh_client_error(cl, 404, "Not Found", "No such file or directory");
642 }