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