add local/remote address env vars for cgi
[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_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 #ifdef __APPLE__
250 time_t timegm (struct tm *tm);
251 #endif
252
253 static const char * uh_file_mime_lookup(const char *path)
254 {
255         struct mimetype *m = &uh_mime_types[0];
256         const char *e;
257
258         while (m->extn) {
259                 e = &path[strlen(path)-1];
260
261                 while (e >= path) {
262                         if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
263                                 return m->mime;
264
265                         e--;
266                 }
267
268                 m++;
269         }
270
271         return "application/octet-stream";
272 }
273
274 static const char * uh_file_mktag(struct stat *s)
275 {
276         snprintf(_tag, sizeof(_tag), "\"%x-%x-%x\"",
277                          (unsigned int) s->st_ino,
278                          (unsigned int) s->st_size,
279                          (unsigned int) s->st_mtime);
280
281         return _tag;
282 }
283
284 static time_t uh_file_date2unix(const char *date)
285 {
286         struct tm t;
287
288         memset(&t, 0, sizeof(t));
289
290         if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
291                 return timegm(&t);
292
293         return 0;
294 }
295
296 static char * uh_file_unix2date(time_t ts)
297 {
298         struct tm *t = gmtime(&ts);
299
300         strftime(_tag, sizeof(_tag), "%a, %d %b %Y %H:%M:%S GMT", t);
301
302         return _tag;
303 }
304
305 static char *uh_file_header(struct client *cl, int idx)
306 {
307         if (!cl->dispatch.file.hdr[idx])
308                 return NULL;
309
310         return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
311 }
312
313 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
314 {
315         if (s) {
316                 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s));
317                 ustream_printf(cl->us, "Last-Modified: %s\r\n",
318                                uh_file_unix2date(s->st_mtime));
319         }
320         ustream_printf(cl->us, "Date: %s\r\n", uh_file_unix2date(time(NULL)));
321 }
322
323 static void uh_file_response_200(struct client *cl, struct stat *s)
324 {
325         uh_http_header(cl, 200, "OK");
326         return uh_file_response_ok_hdrs(cl, s);
327 }
328
329 static void uh_file_response_304(struct client *cl, struct stat *s)
330 {
331         uh_http_header(cl, 304, "Not Modified");
332
333         return uh_file_response_ok_hdrs(cl, s);
334 }
335
336 static void uh_file_response_412(struct client *cl)
337 {
338         uh_http_header(cl, 412, "Precondition Failed");
339 }
340
341 static bool uh_file_if_match(struct client *cl, struct stat *s)
342 {
343         const char *tag = uh_file_mktag(s);
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         const char *tag = uh_file_mktag(s);
384         char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
385         char *p;
386         int i;
387
388         if (!hdr)
389                 return true;
390
391         p = &hdr[0];
392         for (i = 0; i < strlen(hdr); i++) {
393                 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
394                         hdr[i++] = 0;
395                         p = &hdr[i];
396                 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
397                         if ((cl->request.method == UH_HTTP_MSG_GET) ||
398                                 (cl->request.method == UH_HTTP_MSG_HEAD))
399                                 uh_file_response_304(cl, s);
400                         else
401                                 uh_file_response_412(cl);
402
403                         return false;
404                 }
405         }
406
407         return true;
408 }
409
410 static int uh_file_if_range(struct client *cl, struct stat *s)
411 {
412         char *hdr = uh_file_header(cl, HDR_IF_RANGE);
413
414         if (hdr) {
415                 uh_file_response_412(cl);
416                 return false;
417         }
418
419         return true;
420 }
421
422 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
423 {
424         char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
425
426         if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
427                 uh_file_response_412(cl);
428                 return false;
429         }
430
431         return true;
432 }
433
434
435 static int uh_file_scandir_filter_dir(const struct dirent *e)
436 {
437         return strcmp(e->d_name, ".") ? 1 : 0;
438 }
439
440 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
441 {
442         int i;
443         int count = 0;
444         char filename[PATH_MAX];
445         char *pathptr;
446         struct dirent **files = NULL;
447         struct stat s;
448
449         uh_file_response_200(cl, NULL);
450         ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
451
452         uh_chunk_printf(cl,
453                 "<html><head><title>Index of %s</title></head>"
454                 "<body><h1>Index of %s</h1><hr /><ol>",
455                 pi->name, pi->name);
456
457         if ((count = scandir(pi->phys, &files, uh_file_scandir_filter_dir,
458                                                  alphasort)) > 0)
459         {
460                 memset(filename, 0, sizeof(filename));
461                 memcpy(filename, pi->phys, sizeof(filename));
462                 pathptr = &filename[strlen(filename)];
463
464                 /* list subdirs */
465                 for (i = 0; i < count; i++) {
466                         strncat(filename, files[i]->d_name,
467                                         sizeof(filename) - strlen(files[i]->d_name));
468
469                         if (!stat(filename, &s) &&
470                                 (s.st_mode & S_IFDIR) && (s.st_mode & S_IXOTH))
471                                 uh_chunk_printf(cl,
472                                         "<li><strong><a href='%s%s/'>%s</a>/"
473                                         "</strong><br /><small>modified: %s"
474                                         "<br />directory - %.02f kbyte<br />"
475                                         "<br /></small></li>",
476                                         pi->name, files[i]->d_name,
477                                         files[i]->d_name,
478                                         uh_file_unix2date(s.st_mtime),
479                                         s.st_size / 1024.0);
480
481                         *pathptr = 0;
482                 }
483
484                 /* list files */
485                 for (i = 0; i < count; i++) {
486                         strncat(filename, files[i]->d_name,
487                                         sizeof(filename) - strlen(files[i]->d_name));
488
489                         if (!stat(filename, &s) &&
490                                 !(s.st_mode & S_IFDIR) && (s.st_mode & S_IROTH))
491                                 uh_chunk_printf(cl,
492                                         "<li><strong><a href='%s%s'>%s</a>"
493                                         "</strong><br /><small>modified: %s"
494                                         "<br />%s - %.02f kbyte<br />"
495                                         "<br /></small></li>",
496                                         pi->name, files[i]->d_name,
497                                         files[i]->d_name,
498                                         uh_file_unix2date(s.st_mtime),
499                                         uh_file_mime_lookup(filename),
500                                         s.st_size / 1024.0);
501
502                         *pathptr = 0;
503                 }
504         }
505
506         uh_chunk_printf(cl, "</ol><hr /></body></html>");
507         uh_request_done(cl);
508
509         if (files)
510         {
511                 for (i = 0; i < count; i++)
512                         free(files[i]);
513
514                 free(files);
515         }
516 }
517
518 static void file_write_cb(struct client *cl)
519 {
520         int fd = cl->dispatch.file.fd;
521         int r;
522
523         while (cl->us->w.data_bytes < 256) {
524                 r = read(fd, uh_buf, sizeof(uh_buf));
525                 if (r < 0) {
526                         if (errno == EINTR)
527                                 continue;
528                 }
529
530                 if (!r) {
531                         uh_request_done(cl);
532                         return;
533                 }
534
535                 uh_chunk_write(cl, uh_buf, r);
536         }
537 }
538
539 static void uh_file_free(struct client *cl)
540 {
541         close(cl->dispatch.file.fd);
542 }
543
544 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
545 {
546         /* test preconditions */
547         if (!uh_file_if_modified_since(cl, &pi->stat) ||
548                 !uh_file_if_match(cl, &pi->stat) ||
549                 !uh_file_if_range(cl, &pi->stat) ||
550                 !uh_file_if_unmodified_since(cl, &pi->stat) ||
551                 !uh_file_if_none_match(cl, &pi->stat)) {
552                 uh_request_done(cl);
553                 close(fd);
554                 return;
555         }
556
557         /* write status */
558         uh_file_response_200(cl, &pi->stat);
559
560         ustream_printf(cl->us, "Content-Type: %s\r\n",
561                            uh_file_mime_lookup(pi->name));
562
563         ustream_printf(cl->us, "Content-Length: %i\r\n\r\n",
564                            pi->stat.st_size);
565
566
567         /* send body */
568         if (cl->request.method == UH_HTTP_MSG_HEAD) {
569                 uh_request_done(cl);
570                 close(fd);
571                 return;
572         }
573
574         cl->dispatch.file.fd = fd;
575         cl->dispatch.write_cb = file_write_cb;
576         cl->dispatch.free = uh_file_free;
577         cl->dispatch.close_fds = uh_file_free;
578         file_write_cb(cl);
579 }
580
581 static void uh_file_request(struct client *cl, const char *url, struct path_info *pi)
582 {
583         static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
584                 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
585                 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
586                 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
587                 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
588                 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
589         };
590         struct blob_attr *tb[__HDR_MAX];
591         int fd;
592
593         blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
594
595         cl->dispatch.file.hdr = tb;
596
597         if (!(pi->stat.st_mode & S_IROTH))
598                 goto error;
599
600         if (pi->stat.st_mode & S_IFREG) {
601                 fd = open(pi->phys, O_RDONLY);
602                 if (fd < 0)
603                         goto error;
604
605                 uh_file_data(cl, pi, fd);
606         } else if ((pi->stat.st_mode & S_IFDIR)) {
607                 if (conf.no_dirlists)
608                         goto error;
609
610                 uh_file_dirlist(cl, pi);
611         } else {
612                 goto error;
613         }
614
615         cl->dispatch.file.hdr = NULL;
616         return;
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         cl->dispatch.file.hdr = NULL;
623 }
624
625 void uh_dispatch_add(struct dispatch_handler *d)
626 {
627         list_add_tail(&d->list, &dispatch_handlers);
628 }
629
630 static struct dispatch_handler *
631 dispatch_find(const char *url, struct path_info *pi)
632 {
633         struct dispatch_handler *d;
634
635         list_for_each_entry(d, &dispatch_handlers, list) {
636                 if (pi) {
637                         if (d->check_url)
638                                 continue;
639
640                         if (d->check_path(pi, url))
641                                 return d;
642                 } else {
643                         if (d->check_path)
644                                 continue;
645
646                         if (d->check_url(url))
647                                 return d;
648                 }
649         }
650
651         return NULL;
652 }
653
654 static bool __handle_file_request(struct client *cl, const char *url)
655 {
656         struct dispatch_handler *d;
657         struct path_info *pi;
658
659         pi = uh_path_lookup(cl, url);
660         if (!pi)
661                 return false;
662
663         if (pi->redirected)
664                 return true;
665
666         d = dispatch_find(url, pi);
667         if (d)
668                 d->handle_request(cl, url, pi);
669         else
670                 uh_file_request(cl, url, pi);
671
672         return true;
673 }
674
675 void uh_handle_request(struct client *cl)
676 {
677         struct dispatch_handler *d;
678         const char *url = cl->request.url;
679
680         d = dispatch_find(url, NULL);
681         if (d) {
682                 d->handle_request(cl, url, NULL);
683                 return;
684         }
685
686         if (__handle_file_request(cl, url) ||
687             __handle_file_request(cl, conf.error_handler))
688                 return;
689
690         uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", cl->request.url);
691 }