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