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