Initial implementation
[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 #include <sys/types.h>
21 #include <sys/dir.h>
22
23 #include <libubox/blobmsg.h>
24
25 #include "uhttpd.h"
26 #include "uhttpd-mimetypes.h"
27
28 static LIST_HEAD(index_files);
29
30 struct index_file {
31 struct list_head list;
32 const char *name;
33 };
34
35 struct path_info {
36 char *root;
37 char *phys;
38 char *name;
39 char *info;
40 char *query;
41 int redirected;
42 struct stat stat;
43 };
44
45 enum file_hdr {
46 HDR_IF_MODIFIED_SINCE,
47 HDR_IF_UNMODIFIED_SINCE,
48 HDR_IF_MATCH,
49 HDR_IF_NONE_MATCH,
50 HDR_IF_RANGE,
51 __HDR_MAX
52 };
53
54 void uh_index_add(const char *filename)
55 {
56 struct index_file *idx;
57
58 idx = calloc(1, sizeof(*idx));
59 idx->name = filename;
60 list_add_tail(&idx->list, &index_files);
61 }
62
63 static char * canonpath(const char *path, char *path_resolved)
64 {
65 char path_copy[PATH_MAX];
66 char *path_cpy = path_copy;
67 char *path_res = path_resolved;
68 struct stat s;
69
70 /* relative -> absolute */
71 if (*path != '/') {
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));
75 } else {
76 strncpy(path_copy, path, PATH_MAX);
77 }
78
79 /* normalize */
80 while ((*path_cpy != '\0') && (path_cpy < (path_copy + PATH_MAX - 2))) {
81 if (*path_cpy != '/')
82 goto next;
83
84 /* skip repeating / */
85 if (path_cpy[1] == '/') {
86 path_cpy++;
87 continue;
88 }
89
90 /* /./ or /../ */
91 if (path_cpy[1] == '.') {
92 /* skip /./ */
93 if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
94 path_cpy += 2;
95 continue;
96 }
97
98 /* collapse /x/../ */
99 if ((path_cpy[2] == '.') &&
100 ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
101 while ((path_res > path_resolved) && (*--path_res != '/'));
102
103 path_cpy += 3;
104 continue;
105 }
106 }
107
108 next:
109 *path_res++ = *path_cpy++;
110 }
111
112 /* remove trailing slash if not root / */
113 if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
114 path_res--;
115 else if (path_res == path_resolved)
116 *path_res++ = '/';
117
118 *path_res = '\0';
119
120 /* test access */
121 if (!stat(path_resolved, &s) && (s.st_mode & S_IROTH))
122 return path_resolved;
123
124 return NULL;
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 struct path_info * uh_path_lookup(struct client *cl, const char *url)
131 {
132 static char path_phys[PATH_MAX];
133 static char path_info[PATH_MAX];
134 static struct path_info p;
135
136 char buffer[UH_LIMIT_MSGHEAD];
137 char *docroot = conf.docroot;
138 char *pathptr = NULL;
139
140 int slash = 0;
141 int no_sym = conf.no_symlinks;
142 int i = 0;
143 struct stat s;
144 struct index_file *idx;
145
146 /* back out early if url is undefined */
147 if (url == NULL)
148 return NULL;
149
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));
154
155 /* copy docroot */
156 memcpy(buffer, docroot,
157 min(strlen(docroot), sizeof(buffer) - 1));
158
159 /* separate query string from url */
160 if ((pathptr = strchr(url, '?')) != NULL) {
161 p.query = pathptr[1] ? pathptr + 1 : NULL;
162
163 /* urldecode component w/o query */
164 if (pathptr > url) {
165 if (uh_urldecode(&buffer[strlen(docroot)],
166 sizeof(buffer) - strlen(docroot) - 1,
167 url, pathptr - url ) < 0)
168 return NULL; /* bad URL */
169 }
170 }
171
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 */
177
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));
183
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));
189
190 break;
191 }
192 }
193 }
194
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)] != '/')))
199 return NULL;
200
201 /* test current path */
202 if (!stat(path_phys, &p.stat)) {
203 /* is a regular file */
204 if (p.stat.st_mode & S_IFREG) {
205 p.root = docroot;
206 p.phys = path_phys;
207 p.name = &path_phys[strlen(docroot)];
208 p.info = path_info[0] ? path_info : NULL;
209 }
210
211 /* is a directory */
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)] = '/';
216
217 /* try to locate index file */
218 memset(buffer, 0, sizeof(buffer));
219 memcpy(buffer, path_phys, sizeof(buffer));
220 pathptr = &buffer[strlen(buffer)];
221
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 */
225 if (!slash) {
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)],
229 p.query ? "?" : "",
230 p.query ? p.query : "");
231 uh_request_done(cl);
232 p.redirected = 1;
233 } else {
234 list_for_each_entry(idx, &index_files, list) {
235 strncat(buffer, idx->name, sizeof(buffer));
236
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));
240 break;
241 }
242
243 *pathptr = 0;
244 }
245 }
246
247 p.root = docroot;
248 p.phys = path_phys;
249 p.name = &path_phys[strlen(docroot)];
250 }
251 }
252
253 return p.phys ? &p : NULL;
254 }
255
256 #ifdef __APPLE__
257 time_t timegm (struct tm *tm);
258 #endif
259
260 static const char * uh_file_mime_lookup(const char *path)
261 {
262 struct mimetype *m = &uh_mime_types[0];
263 const char *e;
264
265 while (m->extn) {
266 e = &path[strlen(path)-1];
267
268 while (e >= path) {
269 if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
270 return m->mime;
271
272 e--;
273 }
274
275 m++;
276 }
277
278 return "application/octet-stream";
279 }
280
281 static const char * uh_file_mktag(struct stat *s)
282 {
283 static char tag[128];
284
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);
289
290 return tag;
291 }
292
293 static time_t uh_file_date2unix(const char *date)
294 {
295 struct tm t;
296
297 memset(&t, 0, sizeof(t));
298
299 if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
300 return timegm(&t);
301
302 return 0;
303 }
304
305 static char * uh_file_unix2date(time_t ts)
306 {
307 static char str[128];
308 struct tm *t = gmtime(&ts);
309
310 strftime(str, sizeof(str), "%a, %d %b %Y %H:%M:%S GMT", t);
311
312 return str;
313 }
314
315 static char *uh_file_header(struct client *cl, int idx)
316 {
317 if (!cl->data.file.hdr[idx])
318 return NULL;
319
320 return (char *) blobmsg_data(cl->data.file.hdr[idx]);
321 }
322
323 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
324 {
325 if (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));
329 }
330 ustream_printf(cl->us, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
331 }
332
333 static void uh_file_response_200(struct client *cl, struct stat *s)
334 {
335 uh_http_header(cl, 200, "OK");
336 return uh_file_response_ok_hdrs(cl, s);
337 }
338
339 static void uh_file_response_304(struct client *cl, struct stat *s)
340 {
341 uh_http_header(cl, 304, "Not Modified");
342
343 return uh_file_response_ok_hdrs(cl, s);
344 }
345
346 static void uh_file_response_412(struct client *cl)
347 {
348 uh_http_header(cl, 412, "Precondition Failed");
349 }
350
351 static bool uh_file_if_match(struct client *cl, struct stat *s)
352 {
353 const char *tag = uh_file_mktag(s);
354 char *hdr = uh_file_header(cl, HDR_IF_MATCH);
355 char *p;
356 int i;
357
358 if (!hdr)
359 return true;
360
361 p = &hdr[0];
362 for (i = 0; i < strlen(hdr); i++)
363 {
364 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
365 hdr[i++] = 0;
366 p = &hdr[i];
367 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
368 return true;
369 }
370 }
371
372 uh_file_response_412(cl);
373 return false;
374 }
375
376 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
377 {
378 char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
379
380 if (!hdr)
381 return true;
382
383 if (uh_file_date2unix(hdr) >= s->st_mtime) {
384 uh_file_response_304(cl, s);
385 return false;
386 }
387
388 return true;
389 }
390
391 static int uh_file_if_none_match(struct client *cl, struct stat *s)
392 {
393 const char *tag = uh_file_mktag(s);
394 char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
395 char *p;
396 int i;
397
398 if (!hdr)
399 return true;
400
401 p = &hdr[0];
402 for (i = 0; i < strlen(hdr); i++) {
403 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
404 hdr[i++] = 0;
405 p = &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);
410 else
411 uh_file_response_412(cl);
412
413 return false;
414 }
415 }
416
417 return true;
418 }
419
420 static int uh_file_if_range(struct client *cl, struct stat *s)
421 {
422 char *hdr = uh_file_header(cl, HDR_IF_RANGE);
423
424 if (hdr) {
425 uh_file_response_412(cl);
426 return false;
427 }
428
429 return true;
430 }
431
432 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
433 {
434 char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
435
436 if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
437 uh_file_response_412(cl);
438 return false;
439 }
440
441 return true;
442 }
443
444
445 static int uh_file_scandir_filter_dir(const struct dirent *e)
446 {
447 return strcmp(e->d_name, ".") ? 1 : 0;
448 }
449
450 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
451 {
452 int i;
453 int count = 0;
454 char filename[PATH_MAX];
455 char *pathptr;
456 struct dirent **files = NULL;
457 struct stat s;
458
459 uh_file_response_200(cl, NULL);
460 ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
461
462 uh_chunk_printf(cl,
463 "<html><head><title>Index of %s</title></head>"
464 "<body><h1>Index of %s</h1><hr /><ol>",
465 pi->name, pi->name);
466
467 if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
468 alphasort)) > 0)
469 {
470 memset(filename, 0, sizeof(filename));
471 memcpy(filename, pi->phys, sizeof(filename));
472 pathptr = &filename[strlen(filename)];
473
474 /* list subdirs */
475 for (i = 0; i < count; i++) {
476 strncat(filename, files[i]->d_name,
477 sizeof(filename) - strlen(files[i]->d_name));
478
479 if (!stat(filename, &s) &&
480 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
481 uh_chunk_printf(cl,
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,
487 files[i]->d_name,
488 uh_file_unix2date(s.st_mtime),
489 s.st_size / 1024.0);
490
491 *pathptr = 0;
492 }
493
494 /* list files */
495 for (i = 0; i < count; i++) {
496 strncat(filename, files[i]->d_name,
497 sizeof(filename) - strlen(files[i]->d_name));
498
499 if (!stat(filename, &s) &&
500 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
501 uh_chunk_printf(cl,
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,
507 files[i]->d_name,
508 uh_file_unix2date(s.st_mtime),
509 uh_file_mime_lookup(filename),
510 s.st_size / 1024.0);
511
512 *pathptr = 0;
513 }
514 }
515
516 uh_chunk_printf(cl, "</ol><hr /></body></html>");
517 uh_request_done(cl);
518
519 if (files)
520 {
521 for (i = 0; i < count; i++)
522 free(files[i]);
523
524 free(files);
525 }
526 }
527
528 static void file_write_cb(struct client *cl)
529 {
530 char buf[512];
531 int fd = cl->data.file.fd;
532 int r;
533
534 while (cl->us->w.data_bytes < 256) {
535 r = read(fd, buf, sizeof(buf));
536 if (r < 0) {
537 if (errno == EINTR)
538 continue;
539 }
540
541 if (!r) {
542 uh_request_done(cl);
543 return;
544 }
545
546 uh_chunk_write(cl, buf, r);
547 }
548 }
549
550 static void uh_file_free(struct client *cl)
551 {
552 close(cl->data.file.fd);
553 }
554
555 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
556 {
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)) {
563 uh_request_done(cl);
564 close(fd);
565 return;
566 }
567
568 /* write status */
569 uh_file_response_200(cl, &pi->stat);
570
571 ustream_printf(cl->us, "Content-Type: %s\r\n",
572 uh_file_mime_lookup(pi->name));
573
574 ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
575 pi->stat.st_size);
576
577
578 /* send body */
579 if (cl->request.method == UH_HTTP_MSG_HEAD) {
580 uh_request_done(cl);
581 close(fd);
582 return;
583 }
584
585 cl->data.file.fd = fd;
586 cl->dispatch_write_cb = file_write_cb;
587 cl->dispatch_free = uh_file_free;
588 file_write_cb(cl);
589 }
590
591 static void uh_file_request(struct client *cl, struct path_info *pi)
592 {
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 },
599 };
600 struct blob_attr *tb[__HDR_MAX];
601 int fd;
602
603 blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
604
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);
610 else
611 uh_client_error(cl, 403, "Forbidden",
612 "Access to this resource is forbidden");
613 cl->data.file.hdr = NULL;
614 }
615
616 void uh_handle_file_request(struct client *cl)
617 {
618 struct path_info *pi;
619
620 pi = uh_path_lookup(cl, cl->request.url);
621 if (!pi) {
622 uh_request_done(cl);
623 return;
624 }
625
626 if (pi->redirected)
627 return;
628
629 uh_file_request(cl, pi);
630 }