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