fix 404 and 403 error handling, improve error message output
[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 "uhttpd-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 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, const char *url)
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
607         if (!(pi->stat.st_mode & S_IROTH))
608                 goto error;
609
610         if (pi->stat.st_mode & S_IFREG) {
611                 fd = open(pi->phys, O_RDONLY);
612                 if (fd < 0)
613                         goto error;
614
615                 uh_file_data(cl, pi, fd);
616         } else if ((pi->stat.st_mode & S_IFDIR)) {
617                 if (conf.no_dirlists)
618                         goto error;
619
620                 uh_file_dirlist(cl, pi);
621         } else {
622                 goto error;
623         }
624
625         return;
626
627 error:
628         uh_client_error(cl, 403, "Forbidden",
629                         "You don't have permission to access %s on this server.",
630                         url);
631 }
632
633 static bool __handle_file_request(struct client *cl, const char *url)
634 {
635         struct path_info *pi;
636
637         pi = uh_path_lookup(cl, url);
638         if (!pi)
639                 return false;
640
641         if (!pi->redirected) {
642                 uh_file_request(cl, pi, url);
643                 cl->data.file.hdr = NULL;
644         }
645
646         return true;
647 }
648
649 void uh_handle_file_request(struct client *cl)
650 {
651         if (__handle_file_request(cl, cl->request.url) ||
652             __handle_file_request(cl, conf.error_handler))
653                 return;
654
655         uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.", cl->request.url);
656 }