properly terminate headers of http responses without data, add Content-Length: 0
[project/uhttpd.git] / file.c
1 /*
2 * uhttpd - Tiny single-threaded httpd
3 *
4 * Copyright (C) 2010-2013 Jo-Philipp Wich <xm@subsignal.org>
5 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
6 *
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.
10 *
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.
18 */
19
20 #define _BSD_SOURCE
21 #define _DARWIN_C_SOURCE
22 #define _XOPEN_SOURCE 700
23
24 #include <sys/types.h>
25 #include <sys/dir.h>
26 #include <time.h>
27 #include <strings.h>
28 #include <dirent.h>
29
30 #include <libubox/blobmsg.h>
31
32 #include "uhttpd.h"
33 #include "mimetypes.h"
34
35 static LIST_HEAD(index_files);
36 static LIST_HEAD(dispatch_handlers);
37
38 struct index_file {
39 struct list_head list;
40 const char *name;
41 };
42
43 enum file_hdr {
44 HDR_AUTHORIZATION,
45 HDR_IF_MODIFIED_SINCE,
46 HDR_IF_UNMODIFIED_SINCE,
47 HDR_IF_MATCH,
48 HDR_IF_NONE_MATCH,
49 HDR_IF_RANGE,
50 __HDR_MAX
51 };
52
53 void uh_index_add(const char *filename)
54 {
55 struct index_file *idx;
56
57 idx = calloc(1, sizeof(*idx));
58 idx->name = filename;
59 list_add_tail(&idx->list, &index_files);
60 }
61
62 static char * canonpath(const char *path, char *path_resolved)
63 {
64 const char *path_cpy = path;
65 char *path_res = path_resolved;
66
67 if (conf.no_symlinks)
68 return realpath(path, path_resolved);
69
70 /* normalize */
71 while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
72 if (*path_cpy != '/')
73 goto next;
74
75 /* skip repeating / */
76 if (path_cpy[1] == '/') {
77 path_cpy++;
78 continue;
79 }
80
81 /* /./ or /../ */
82 if (path_cpy[1] == '.') {
83 /* skip /./ */
84 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
85 path_cpy += 2;
86 continue;
87 }
88
89 /* collapse /x/../ */
90 if ((path_cpy[2] == '.') &&
91 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
92 while ((path_res > path_resolved) && (*--path_res != '/'));
93
94 path_cpy += 3;
95 continue;
96 }
97 }
98
99 next:
100 *path_res++ = *path_cpy++;
101 }
102
103 /* remove trailing slash if not root / */
104 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
105 path_res--;
106 else if (path_res == path_resolved)
107 *path_res++ = '/';
108
109 *path_res = '\0';
110
111 return path_resolved;
112 }
113
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)
119 {
120 static char path_phys[PATH_MAX];
121 static char path_info[PATH_MAX];
122 static struct path_info p;
123
124 const char *docroot = conf.docroot;
125 int docroot_len = strlen(docroot);
126 char *pathptr = NULL;
127 bool slash;
128
129 int i = 0;
130 int len;
131 struct stat s;
132 struct index_file *idx;
133
134 /* back out early if url is undefined */
135 if (url == NULL)
136 return NULL;
137
138 memset(&p, 0, sizeof(p));
139 path_phys[0] = 0;
140 path_info[0] = 0;
141
142 strcpy(uh_buf, docroot);
143
144 /* separate query string from url */
145 if ((pathptr = strchr(url, '?')) != NULL) {
146 p.query = pathptr[1] ? pathptr + 1 : NULL;
147
148 /* urldecode component w/o query */
149 if (pathptr > url) {
150 if (uh_urldecode(&uh_buf[docroot_len],
151 sizeof(uh_buf) - docroot_len - 1,
152 url, pathptr - url ) < 0)
153 return NULL;
154 }
155 }
156
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)
161 return NULL;
162
163 /* create canon path */
164 len = strlen(uh_buf);
165 slash = len && uh_buf[len - 1] == '/';
166 len = min(len, sizeof(path_phys) - 1);
167
168 for (i = len; i >= 0; i--) {
169 char ch = uh_buf[i];
170 bool exists;
171
172 if (ch != 0 && ch != '/')
173 continue;
174
175 uh_buf[i] = 0;
176 exists = !!canonpath(uh_buf, path_phys);
177 uh_buf[i] = ch;
178
179 if (!exists)
180 continue;
181
182 /* test current path */
183 if (stat(path_phys, &p.stat))
184 continue;
185
186 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
187 break;
188 }
189
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] != '/'))
194 return NULL;
195
196 /* is a regular file */
197 if (p.stat.st_mode & S_IFREG) {
198 p.root = docroot;
199 p.phys = path_phys;
200 p.name = &path_phys[docroot_len];
201 p.info = path_info[0] ? path_info : NULL;
202 return &p;
203 }
204
205 if (!(p.stat.st_mode & S_IFDIR))
206 return NULL;
207
208 if (path_info[0])
209 return NULL;
210
211 pathptr = path_phys + strlen(path_phys);
212
213 /* ensure trailing slash */
214 if (pathptr[-1] != '/') {
215 pathptr[0] = '/';
216 pathptr[1] = 0;
217 pathptr++;
218 }
219
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 */
223 if (!slash) {
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],
228 p.query ? "?" : "",
229 p.query ? p.query : "");
230 uh_request_done(cl);
231 p.redirected = 1;
232 return &p;
233 }
234
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)
239 continue;
240
241 strcpy(pathptr, idx->name);
242 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG)) {
243 memcpy(&p.stat, &s, sizeof(p.stat));
244 break;
245 }
246
247 *pathptr = 0;
248 }
249
250 p.root = docroot;
251 p.phys = path_phys;
252 p.name = &path_phys[docroot_len];
253
254 return p.phys ? &p : NULL;
255 }
256
257 static const char * uh_file_mime_lookup(const char *path)
258 {
259 const struct mimetype *m = &uh_mime_types[0];
260 const char *e;
261
262 while (m->extn) {
263 e = &path[strlen(path)-1];
264
265 while (e >= path) {
266 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
267 return m->mime;
268
269 e--;
270 }
271
272 m++;
273 }
274
275 return "application/octet-stream";
276 }
277
278 static const char * uh_file_mktag(struct stat *s, char *buf, int len)
279 {
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);
284
285 return buf;
286 }
287
288 static time_t uh_file_date2unix(const char *date)
289 {
290 struct tm t;
291
292 memset(&t, 0, sizeof(t));
293
294 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
295 return timegm(&t);
296
297 return 0;
298 }
299
300 static char * uh_file_unix2date(time_t ts, char *buf, int len)
301 {
302 struct tm *t = gmtime(&ts);
303
304 strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", t);
305
306 return buf;
307 }
308
309 static char *uh_file_header(struct client *cl, int idx)
310 {
311 if (!cl->dispatch.file.hdr[idx])
312 return NULL;
313
314 return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
315 }
316
317 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
318 {
319 char buf[128];
320
321 if (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)));
325 }
326 ustream_printf(cl->us, "Date: %s\r\n",
327 uh_file_unix2date(time(NULL), buf, sizeof(buf)));
328 }
329
330 static void uh_file_response_200(struct client *cl, struct stat *s)
331 {
332 uh_http_header(cl, 200, "OK");
333 return uh_file_response_ok_hdrs(cl, s);
334 }
335
336 static void uh_file_response_304(struct client *cl, struct stat *s)
337 {
338 uh_http_header(cl, 304, "Not Modified");
339
340 return uh_file_response_ok_hdrs(cl, s);
341 }
342
343 static void uh_file_response_412(struct client *cl)
344 {
345 uh_http_header(cl, 412, "Precondition Failed");
346 }
347
348 static bool uh_file_if_match(struct client *cl, struct stat *s)
349 {
350 char buf[128];
351 const char *tag = uh_file_mktag(s, buf, sizeof(buf));
352 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
353 char *p;
354 int i;
355
356 if (!hdr)
357 return true;
358
359 p = &hdr[0];
360 for (i = 0; i < strlen(hdr); i++)
361 {
362 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
363 hdr[i++] = 0;
364 p = &hdr[i];
365 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
366 return true;
367 }
368 }
369
370 uh_file_response_412(cl);
371 return false;
372 }
373
374 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
375 {
376 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
377
378 if (!hdr)
379 return true;
380
381 if (uh_file_date2unix(hdr) >= s->st_mtime) {
382 uh_file_response_304(cl, s);
383 return false;
384 }
385
386 return true;
387 }
388
389 static int uh_file_if_none_match(struct client *cl, struct stat *s)
390 {
391 char buf[128];
392 const char *tag = uh_file_mktag(s, buf, sizeof(buf));
393 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
394 char *p;
395 int i;
396
397 if (!hdr)
398 return true;
399
400 p = &hdr[0];
401 for (i = 0; i < strlen(hdr); i++) {
402 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
403 hdr[i++] = 0;
404 p = &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);
409 else
410 uh_file_response_412(cl);
411
412 return false;
413 }
414 }
415
416 return true;
417 }
418
419 static int uh_file_if_range(struct client *cl, struct stat *s)
420 {
421 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
422
423 if (hdr) {
424 uh_file_response_412(cl);
425 return false;
426 }
427
428 return true;
429 }
430
431 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
432 {
433 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
434
435 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
436 uh_file_response_412(cl);
437 return false;
438 }
439
440 return true;
441 }
442
443 static int dirent_cmp(const struct dirent **a, const struct dirent **b)
444 {
445 bool dir_a = !!((*a)->d_type & DT_DIR);
446 bool dir_b = !!((*b)->d_type & DT_DIR);
447
448 /* directories first */
449 if (dir_a != dir_b)
450 return dir_b - dir_a;
451
452 return alphasort(a, b);
453 }
454
455 static void list_entries(struct client *cl, struct dirent **files, int count,
456 const char *path, char *local_path)
457 {
458 const char *suffix = "/";
459 const char *type = "directory";
460 unsigned int mode = S_IXOTH;
461 struct stat s;
462 char *file;
463 char buf[128];
464 int i;
465
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);
470
471 if (name[0] == '.' && name[1] == 0)
472 continue;
473
474 sprintf(file, "%s", name);
475 if (stat(local_path, &s))
476 continue;
477
478 if (!dir) {
479 suffix = "";
480 mode = S_IROTH;
481 type = uh_file_mime_lookup(local_path);
482 }
483
484 if (!(s.st_mode & mode))
485 continue;
486
487 uh_chunk_printf(cl,
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>",
492 path, name, suffix,
493 name, suffix,
494 uh_file_unix2date(s.st_mtime, buf, sizeof(buf)),
495 type, s.st_size / 1024.0);
496
497 *file = 0;
498 free(files[i]);
499 }
500 }
501
502 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
503 {
504 struct dirent **files = NULL;
505 int count = 0;
506
507 uh_file_response_200(cl, NULL);
508 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
509
510 uh_chunk_printf(cl,
511 "<html><head><title>Index of %s</title></head>"
512 "<body><h1>Index of %s</h1><hr /><ol>",
513 pi->name, pi->name);
514
515 count = scandir(pi->phys, &files, NULL, dirent_cmp);
516 if (count > 0) {
517 strcpy(uh_buf, pi->phys);
518 list_entries(cl, files, count, pi->name, uh_buf);
519 }
520 free(files);
521
522 uh_chunk_printf(cl, "</ol><hr /></body></html>");
523 uh_request_done(cl);
524 }
525
526 static void file_write_cb(struct client *cl)
527 {
528 int fd = cl->dispatch.file.fd;
529 int r;
530
531 while (cl->us->w.data_bytes < 256) {
532 r = read(fd, uh_buf, sizeof(uh_buf));
533 if (r < 0) {
534 if (errno == EINTR)
535 continue;
536 }
537
538 if (!r) {
539 uh_request_done(cl);
540 return;
541 }
542
543 uh_chunk_write(cl, uh_buf, r);
544 }
545 }
546
547 static void uh_file_free(struct client *cl)
548 {
549 close(cl->dispatch.file.fd);
550 }
551
552 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
553 {
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");
562 uh_request_done(cl);
563 close(fd);
564 return;
565 }
566
567 /* write status */
568 uh_file_response_200(cl, &pi->stat);
569
570 ustream_printf(cl->us, "Content-Type: %s\r\n",
571 uh_file_mime_lookup(pi->name));
572
573 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
574 pi->stat.st_size);
575
576
577 /* send body */
578 if (cl->request.method == UH_HTTP_MSG_HEAD) {
579 uh_request_done(cl);
580 close(fd);
581 return;
582 }
583
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;
588 file_write_cb(cl);
589 }
590
591 static void uh_file_request(struct client *cl, const char *url,
592 struct path_info *pi, struct blob_attr **tb)
593 {
594 int fd;
595
596 if (!(pi->stat.st_mode & S_IROTH))
597 goto error;
598
599 if (pi->stat.st_mode & S_IFREG) {
600 fd = open(pi->phys, O_RDONLY);
601 if (fd < 0)
602 goto error;
603
604 cl->dispatch.file.hdr = tb;
605 uh_file_data(cl, pi, fd);
606 cl->dispatch.file.hdr = NULL;
607 return;
608 }
609
610 if ((pi->stat.st_mode & S_IFDIR)) {
611 if (conf.no_dirlists)
612 goto error;
613
614 uh_file_dirlist(cl, pi);
615 return;
616 }
617
618 error:
619 uh_client_error(cl, 403, "Forbidden",
620 "You don't have permission to access %s on this server.",
621 url);
622 }
623
624 void uh_dispatch_add(struct dispatch_handler *d)
625 {
626 list_add_tail(&d->list, &dispatch_handlers);
627 }
628
629 static struct dispatch_handler *
630 dispatch_find(const char *url, struct path_info *pi)
631 {
632 struct dispatch_handler *d;
633
634 list_for_each_entry(d, &dispatch_handlers, list) {
635 if (pi) {
636 if (d->check_url)
637 continue;
638
639 if (d->check_path(pi, url))
640 return d;
641 } else {
642 if (d->check_path)
643 continue;
644
645 if (d->check_url(url))
646 return d;
647 }
648 }
649
650 return NULL;
651 }
652
653 static bool __handle_file_request(struct client *cl, char *url)
654 {
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 },
662 };
663 struct dispatch_handler *d;
664 struct blob_attr *tb[__HDR_MAX];
665 struct path_info *pi;
666
667 pi = uh_path_lookup(cl, url);
668 if (!pi)
669 return false;
670
671 if (pi->redirected)
672 return true;
673
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]);
677
678 if (!uh_auth_check(cl, pi))
679 return true;
680
681 d = dispatch_find(url, pi);
682 if (d)
683 d->handle_request(cl, url, pi);
684 else
685 uh_file_request(cl, url, pi, tb);
686
687 return true;
688 }
689
690 void uh_handle_request(struct client *cl)
691 {
692 struct http_request *req = &cl->request;
693 struct dispatch_handler *d;
694 char *url = blobmsg_data(blob_data(cl->hdr.head));;
695 char *error_handler;
696
697 req->redirect_status = 200;
698 d = dispatch_find(url, NULL);
699 if (d) {
700 d->handle_request(cl, url, NULL);
701 return;
702 }
703
704 if (__handle_file_request(cl, url))
705 return;
706
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))
712 return;
713 }
714
715 uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", url);
716 }