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