client: allow keep-alive for POST requests
[oweals/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 #ifndef _DEFAULT_SOURCE
21 # define _DEFAULT_SOURCE
22 #endif
23
24 #define _BSD_SOURCE
25 #define _DARWIN_C_SOURCE
26 #define _XOPEN_SOURCE 700
27
28 #include <sys/types.h>
29 #include <sys/dir.h>
30 #include <time.h>
31 #include <strings.h>
32 #include <dirent.h>
33 #include <inttypes.h>
34
35 #include <libubox/blobmsg.h>
36
37 #include "uhttpd.h"
38 #include "mimetypes.h"
39
40 #define MAX(a, b)       (((a) > (b)) ? (a) : (b))
41
42 static LIST_HEAD(index_files);
43 static LIST_HEAD(dispatch_handlers);
44 static LIST_HEAD(pending_requests);
45 static int n_requests;
46
47 struct deferred_request {
48         struct list_head list;
49         struct dispatch_handler *d;
50         struct client *cl;
51         struct path_info pi;
52         bool called, path;
53 };
54
55 struct index_file {
56         struct list_head list;
57         const char *name;
58 };
59
60 enum file_hdr {
61         HDR_AUTHORIZATION,
62         HDR_IF_MODIFIED_SINCE,
63         HDR_IF_UNMODIFIED_SINCE,
64         HDR_IF_MATCH,
65         HDR_IF_NONE_MATCH,
66         HDR_IF_RANGE,
67         __HDR_MAX
68 };
69
70 void uh_index_add(const char *filename)
71 {
72         struct index_file *idx;
73
74         idx = calloc(1, sizeof(*idx));
75         idx->name = filename;
76         list_add_tail(&idx->list, &index_files);
77 }
78
79 static char * canonpath(const char *path, char *path_resolved)
80 {
81         const char *path_cpy = path;
82         char *path_res = path_resolved;
83
84         if (conf.no_symlinks)
85                 return realpath(path, path_resolved);
86
87         /* normalize */
88         while ((*path_cpy != '\0') && (path_cpy < (path + PATH_MAX - 2))) {
89                 if (*path_cpy != '/')
90                         goto next;
91
92                 /* skip repeating / */
93                 if (path_cpy[1] == '/') {
94                         path_cpy++;
95                         continue;
96                 }
97
98                 /* /./ or /../ */
99                 if (path_cpy[1] == '.') {
100                         /* skip /./ */
101                         if ((path_cpy[2] == '/') || (path_cpy[2] == '\0')) {
102                                 path_cpy += 2;
103                                 continue;
104                         }
105
106                         /* collapse /x/../ */
107                         if ((path_cpy[2] == '.') &&
108                             ((path_cpy[3] == '/') || (path_cpy[3] == '\0'))) {
109                                 while ((path_res > path_resolved) && (*--path_res != '/'));
110
111                                 path_cpy += 3;
112                                 continue;
113                         }
114                 }
115
116 next:
117                 *path_res++ = *path_cpy++;
118         }
119
120         /* remove trailing slash if not root / */
121         if ((path_res > (path_resolved+1)) && (path_res[-1] == '/'))
122                 path_res--;
123         else if (path_res == path_resolved)
124                 *path_res++ = '/';
125
126         *path_res = '\0';
127
128         return path_resolved;
129 }
130
131 /* Returns NULL on error.
132 ** NB: improperly encoded URL should give client 400 [Bad Syntax]; returning
133 ** NULL here causes 404 [Not Found], but that's not too unreasonable. */
134 struct path_info *
135 uh_path_lookup(struct client *cl, const char *url)
136 {
137         static char path_phys[PATH_MAX];
138         static char path_info[PATH_MAX];
139         static char path_query[PATH_MAX];
140         static struct path_info p;
141
142         const char *docroot = conf.docroot;
143         int docroot_len = strlen(docroot);
144         char *pathptr = NULL;
145         bool slash;
146
147         int i = 0;
148         int len;
149         struct stat s;
150         struct index_file *idx;
151
152         /* back out early if url is undefined */
153         if (url == NULL)
154                 return NULL;
155
156         memset(&p, 0, sizeof(p));
157         path_phys[0] = 0;
158         path_info[0] = 0;
159
160         strcpy(uh_buf, docroot);
161
162         /* separate query string from url */
163         if ((pathptr = strchr(url, '?')) != NULL) {
164                 if (pathptr[1]) {
165                         p.query = path_query;
166                         snprintf(path_query, sizeof(path_query), "%s",
167                                  pathptr + 1);
168                 }
169
170                 /* urldecode component w/o query */
171                 if (pathptr > url) {
172                         if (uh_urldecode(&uh_buf[docroot_len],
173                                          sizeof(uh_buf) - docroot_len - 1,
174                                          url, pathptr - url ) < 0)
175                                 return NULL;
176                 }
177         }
178
179         /* no query string, decode all of url */
180         else if (uh_urldecode(&uh_buf[docroot_len],
181                               sizeof(uh_buf) - docroot_len - 1,
182                               url, strlen(url) ) < 0)
183                 return NULL;
184
185         /* create canon path */
186         len = strlen(uh_buf);
187         slash = len && uh_buf[len - 1] == '/';
188         len = min(len, sizeof(path_phys) - 1);
189
190         for (i = len; i >= 0; i--) {
191                 char ch = uh_buf[i];
192                 bool exists;
193
194                 if (ch != 0 && ch != '/')
195                         continue;
196
197                 uh_buf[i] = 0;
198                 exists = !!canonpath(uh_buf, path_phys);
199                 uh_buf[i] = ch;
200
201                 if (!exists)
202                         continue;
203
204                 /* test current path */
205                 if (stat(path_phys, &p.stat))
206                         continue;
207
208                 snprintf(path_info, sizeof(path_info), "%s", uh_buf + i);
209                 break;
210         }
211
212         /* check whether found path is within docroot */
213         if (strncmp(path_phys, docroot, docroot_len) != 0 ||
214             (path_phys[docroot_len] != 0 &&
215              path_phys[docroot_len] != '/'))
216                 return NULL;
217
218         /* is a regular file */
219         if (p.stat.st_mode & S_IFREG) {
220                 p.root = docroot;
221                 p.phys = path_phys;
222                 p.name = &path_phys[docroot_len];
223                 p.info = path_info[0] ? path_info : NULL;
224                 return &p;
225         }
226
227         if (!(p.stat.st_mode & S_IFDIR))
228                 return NULL;
229
230         if (path_info[0])
231             return NULL;
232
233         pathptr = path_phys + strlen(path_phys);
234
235         /* ensure trailing slash */
236         if (pathptr[-1] != '/') {
237                 pathptr[0] = '/';
238                 pathptr[1] = 0;
239                 pathptr++;
240         }
241
242         /* if requested url resolves to a directory and a trailing slash
243            is missing in the request url, redirect the client to the same
244            url with trailing slash appended */
245         if (!slash) {
246                 uh_http_header(cl, 302, "Found");
247                 if (!uh_use_chunked(cl))
248                         ustream_printf(cl->us, "Content-Length: 0\r\n");
249                 ustream_printf(cl->us, "Location: %s%s%s\r\n\r\n",
250                                 &path_phys[docroot_len],
251                                 p.query ? "?" : "",
252                                 p.query ? p.query : "");
253                 uh_request_done(cl);
254                 p.redirected = 1;
255                 return &p;
256         }
257
258         /* try to locate index file */
259         len = path_phys + sizeof(path_phys) - pathptr - 1;
260         list_for_each_entry(idx, &index_files, list) {
261                 if (strlen(idx->name) > len)
262                         continue;
263
264                 strcpy(pathptr, idx->name);
265                 if (!stat(path_phys, &s) && (s.st_mode & S_IFREG)) {
266                         memcpy(&p.stat, &s, sizeof(p.stat));
267                         break;
268                 }
269
270                 *pathptr = 0;
271         }
272
273         p.root = docroot;
274         p.phys = path_phys;
275         p.name = &path_phys[docroot_len];
276
277         return p.phys ? &p : NULL;
278 }
279
280 static const char * uh_file_mime_lookup(const char *path)
281 {
282         const struct mimetype *m = &uh_mime_types[0];
283         const char *e;
284
285         while (m->extn) {
286                 e = &path[strlen(path)-1];
287
288                 while (e >= path) {
289                         if ((*e == '.' || *e == '/') && !strcasecmp(&e[1], m->extn))
290                                 return m->mime;
291
292                         e--;
293                 }
294
295                 m++;
296         }
297
298         return "application/octet-stream";
299 }
300
301 static const char * uh_file_mktag(struct stat *s, char *buf, int len)
302 {
303         snprintf(buf, len, "\"%" PRIx64 "-%" PRIx64 "-%" PRIx64 "\"",
304                  s->st_ino, s->st_size, (uint64_t)s->st_mtime);
305
306         return buf;
307 }
308
309 static time_t uh_file_date2unix(const char *date)
310 {
311         struct tm t;
312
313         memset(&t, 0, sizeof(t));
314
315         if (strptime(date, "%a, %d %b %Y %H:%M:%S %Z", &t) != NULL)
316                 return timegm(&t);
317
318         return 0;
319 }
320
321 static char * uh_file_unix2date(time_t ts, char *buf, int len)
322 {
323         struct tm *t = gmtime(&ts);
324
325         strftime(buf, len, "%a, %d %b %Y %H:%M:%S GMT", t);
326
327         return buf;
328 }
329
330 static char *uh_file_header(struct client *cl, int idx)
331 {
332         if (!cl->dispatch.file.hdr[idx])
333                 return NULL;
334
335         return (char *) blobmsg_data(cl->dispatch.file.hdr[idx]);
336 }
337
338 static void uh_file_response_ok_hdrs(struct client *cl, struct stat *s)
339 {
340         char buf[128];
341
342         if (s) {
343                 ustream_printf(cl->us, "ETag: %s\r\n", uh_file_mktag(s, buf, sizeof(buf)));
344                 ustream_printf(cl->us, "Last-Modified: %s\r\n",
345                                uh_file_unix2date(s->st_mtime, buf, sizeof(buf)));
346         }
347         ustream_printf(cl->us, "Date: %s\r\n",
348                        uh_file_unix2date(time(NULL), buf, sizeof(buf)));
349 }
350
351 static void uh_file_response_200(struct client *cl, struct stat *s)
352 {
353         uh_http_header(cl, 200, "OK");
354         return uh_file_response_ok_hdrs(cl, s);
355 }
356
357 static void uh_file_response_304(struct client *cl, struct stat *s)
358 {
359         uh_http_header(cl, 304, "Not Modified");
360
361         return uh_file_response_ok_hdrs(cl, s);
362 }
363
364 static void uh_file_response_405(struct client *cl)
365 {
366         uh_http_header(cl, 405, "Method Not Allowed");
367 }
368
369 static void uh_file_response_412(struct client *cl)
370 {
371         uh_http_header(cl, 412, "Precondition Failed");
372 }
373
374 static bool uh_file_if_match(struct client *cl, struct stat *s)
375 {
376         char buf[128];
377         const char *tag = uh_file_mktag(s, buf, sizeof(buf));
378         char *hdr = uh_file_header(cl, HDR_IF_MATCH);
379         char *p;
380         int i;
381
382         if (!hdr)
383                 return true;
384
385         p = &hdr[0];
386         for (i = 0; i < strlen(hdr); i++)
387         {
388                 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
389                         hdr[i++] = 0;
390                         p = &hdr[i];
391                 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
392                         return true;
393                 }
394         }
395
396         uh_file_response_412(cl);
397         return false;
398 }
399
400 static int uh_file_if_modified_since(struct client *cl, struct stat *s)
401 {
402         char *hdr = uh_file_header(cl, HDR_IF_MODIFIED_SINCE);
403
404         if (!hdr)
405                 return true;
406
407         if (uh_file_date2unix(hdr) >= s->st_mtime) {
408                 uh_file_response_304(cl, s);
409                 return false;
410         }
411
412         return true;
413 }
414
415 static int uh_file_if_none_match(struct client *cl, struct stat *s)
416 {
417         char buf[128];
418         const char *tag = uh_file_mktag(s, buf, sizeof(buf));
419         char *hdr = uh_file_header(cl, HDR_IF_NONE_MATCH);
420         char *p;
421         int i;
422
423         if (!hdr)
424                 return true;
425
426         p = &hdr[0];
427         for (i = 0; i < strlen(hdr); i++) {
428                 if ((hdr[i] == ' ') || (hdr[i] == ',')) {
429                         hdr[i++] = 0;
430                         p = &hdr[i];
431                 } else if (!strcmp(p, "*") || !strcmp(p, tag)) {
432                         if ((cl->request.method == UH_HTTP_MSG_GET) ||
433                                 (cl->request.method == UH_HTTP_MSG_HEAD))
434                                 uh_file_response_304(cl, s);
435                         else
436                                 uh_file_response_412(cl);
437
438                         return false;
439                 }
440         }
441
442         return true;
443 }
444
445 static int uh_file_if_range(struct client *cl, struct stat *s)
446 {
447         char *hdr = uh_file_header(cl, HDR_IF_RANGE);
448
449         if (hdr) {
450                 uh_file_response_412(cl);
451                 return false;
452         }
453
454         return true;
455 }
456
457 static int uh_file_if_unmodified_since(struct client *cl, struct stat *s)
458 {
459         char *hdr = uh_file_header(cl, HDR_IF_UNMODIFIED_SINCE);
460
461         if (hdr && uh_file_date2unix(hdr) <= s->st_mtime) {
462                 uh_file_response_412(cl);
463                 return false;
464         }
465
466         return true;
467 }
468
469 static int dirent_cmp(const struct dirent **a, const struct dirent **b)
470 {
471         bool dir_a = !!((*a)->d_type & DT_DIR);
472         bool dir_b = !!((*b)->d_type & DT_DIR);
473
474         /* directories first */
475         if (dir_a != dir_b)
476                 return dir_b - dir_a;
477
478         return alphasort(a, b);
479 }
480
481 static void list_entries(struct client *cl, struct dirent **files, int count,
482                          const char *path, char *local_path)
483 {
484         const char *suffix = "/";
485         const char *type = "directory";
486         unsigned int mode = S_IXOTH;
487         struct stat s;
488         char *escaped;
489         char *file;
490         char buf[128];
491         int i;
492
493         file = local_path + strlen(local_path);
494         for (i = 0; i < count; i++) {
495                 const char *name = files[i]->d_name;
496                 bool dir = !!(files[i]->d_type & DT_DIR);
497
498                 if (name[0] == '.' && name[1] == 0)
499                         goto next;
500
501                 sprintf(file, "%s", name);
502                 if (stat(local_path, &s))
503                         goto next;
504
505                 if (!dir) {
506                         suffix = "";
507                         mode = S_IROTH;
508                         type = uh_file_mime_lookup(local_path);
509                 }
510
511                 if (!(s.st_mode & mode))
512                         goto next;
513
514                 escaped = uh_htmlescape(name);
515
516                 if (!escaped)
517                         goto next;
518
519                 uh_chunk_printf(cl,
520                                 "<li><strong><a href='%s%s%s'>%s</a>%s"
521                                 "</strong><br /><small>modified: %s"
522                                 "<br />%s - %.02f kbyte<br />"
523                                 "<br /></small></li>",
524                                 path, escaped, suffix,
525                                 escaped, suffix,
526                                 uh_file_unix2date(s.st_mtime, buf, sizeof(buf)),
527                                 type, s.st_size / 1024.0);
528
529                 free(escaped);
530                 *file = 0;
531 next:
532                 free(files[i]);
533         }
534 }
535
536 static void uh_file_dirlist(struct client *cl, struct path_info *pi)
537 {
538         struct dirent **files = NULL;
539         char *escaped_path = uh_htmlescape(pi->name);
540         int count = 0;
541
542         if (!escaped_path)
543         {
544                 uh_client_error(cl, 500, "Internal Server Error", "Out of memory");
545                 return;
546         }
547
548         uh_file_response_200(cl, NULL);
549         ustream_printf(cl->us, "Content-Type: text/html\r\n\r\n");
550
551         uh_chunk_printf(cl,
552                 "<html><head><title>Index of %s</title></head>"
553                 "<body><h1>Index of %s</h1><hr /><ol>",
554                 escaped_path, escaped_path);
555
556         count = scandir(pi->phys, &files, NULL, dirent_cmp);
557         if (count > 0) {
558                 strcpy(uh_buf, pi->phys);
559                 list_entries(cl, files, count, escaped_path, uh_buf);
560         }
561         free(escaped_path);
562         free(files);
563
564         uh_chunk_printf(cl, "</ol><hr /></body></html>");
565         uh_request_done(cl);
566 }
567
568 static void file_write_cb(struct client *cl)
569 {
570         int fd = cl->dispatch.file.fd;
571         int r;
572
573         while (cl->us->w.data_bytes < 256) {
574                 r = read(fd, uh_buf, sizeof(uh_buf));
575                 if (r < 0) {
576                         if (errno == EINTR)
577                                 continue;
578                 }
579
580                 if (!r) {
581                         uh_request_done(cl);
582                         return;
583                 }
584
585                 uh_chunk_write(cl, uh_buf, r);
586         }
587 }
588
589 static void uh_file_free(struct client *cl)
590 {
591         close(cl->dispatch.file.fd);
592 }
593
594 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
595 {
596         /* test preconditions */
597         if (!cl->dispatch.no_cache &&
598             (!uh_file_if_modified_since(cl, &pi->stat) ||
599              !uh_file_if_match(cl, &pi->stat) ||
600              !uh_file_if_range(cl, &pi->stat) ||
601              !uh_file_if_unmodified_since(cl, &pi->stat) ||
602              !uh_file_if_none_match(cl, &pi->stat))) {
603                 ustream_printf(cl->us, "\r\n");
604                 uh_request_done(cl);
605                 close(fd);
606                 return;
607         }
608
609         /* write status */
610         uh_file_response_200(cl, &pi->stat);
611
612         ustream_printf(cl->us, "Content-Type: %s\r\n",
613                            uh_file_mime_lookup(pi->name));
614
615         ustream_printf(cl->us, "Content-Length: %" PRIu64 "\r\n\r\n",
616                            pi->stat.st_size);
617
618
619         /* send body */
620         if (cl->request.method == UH_HTTP_MSG_HEAD) {
621                 uh_request_done(cl);
622                 close(fd);
623                 return;
624         }
625
626         cl->dispatch.file.fd = fd;
627         cl->dispatch.write_cb = file_write_cb;
628         cl->dispatch.free = uh_file_free;
629         cl->dispatch.close_fds = uh_file_free;
630         file_write_cb(cl);
631 }
632
633 static bool __handle_file_request(struct client *cl, char *url);
634
635 static void uh_file_request(struct client *cl, const char *url,
636                             struct path_info *pi, struct blob_attr **tb)
637 {
638         int fd;
639         struct http_request *req = &cl->request;
640         char *error_handler, *escaped_url;
641
642         switch (cl->request.method) {
643         case UH_HTTP_MSG_GET:
644         case UH_HTTP_MSG_POST:
645         case UH_HTTP_MSG_HEAD:
646         case UH_HTTP_MSG_OPTIONS:
647                 break;
648
649         default:
650                 uh_file_response_405(cl);
651                 ustream_printf(cl->us, "\r\n");
652                 uh_request_done(cl);
653                 return;
654         }
655
656         if (!(pi->stat.st_mode & S_IROTH))
657                 goto error;
658
659         if (pi->stat.st_mode & S_IFREG) {
660                 fd = open(pi->phys, O_RDONLY);
661                 if (fd < 0)
662                         goto error;
663
664                 req->disable_chunked = true;
665                 cl->dispatch.file.hdr = tb;
666                 uh_file_data(cl, pi, fd);
667                 cl->dispatch.file.hdr = NULL;
668                 return;
669         }
670
671         if ((pi->stat.st_mode & S_IFDIR)) {
672                 if (conf.no_dirlists)
673                         goto error;
674
675                 uh_file_dirlist(cl, pi);
676                 return;
677         }
678
679 error:
680         /* check for a previously set 403 redirect status to prevent infinite
681            recursion when the error page itself lacks sufficient permissions */
682         if (conf.error_handler && req->redirect_status != 403) {
683                 req->redirect_status = 403;
684                 error_handler = alloca(strlen(conf.error_handler) + 1);
685                 strcpy(error_handler, conf.error_handler);
686                 if (__handle_file_request(cl, error_handler))
687                         return;
688         }
689
690         escaped_url = uh_htmlescape(url);
691
692         uh_client_error(cl, 403, "Forbidden",
693                         "You don't have permission to access %s on this server.",
694                         escaped_url ? escaped_url : "the url");
695
696         if (escaped_url)
697                 free(escaped_url);
698 }
699
700 void uh_dispatch_add(struct dispatch_handler *d)
701 {
702         list_add_tail(&d->list, &dispatch_handlers);
703 }
704
705 static struct dispatch_handler *
706 dispatch_find(const char *url, struct path_info *pi)
707 {
708         struct dispatch_handler *d;
709
710         list_for_each_entry(d, &dispatch_handlers, list) {
711                 if (pi) {
712                         if (d->check_url)
713                                 continue;
714
715                         if (d->check_path(pi, url))
716                                 return d;
717                 } else {
718                         if (d->check_path)
719                                 continue;
720
721                         if (d->check_url(url))
722                                 return d;
723                 }
724         }
725
726         return NULL;
727 }
728
729 static void
730 uh_invoke_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
731 {
732         char *url = blobmsg_data(blob_data(cl->hdr.head));
733
734         n_requests++;
735         d->handle_request(cl, url, pi);
736 }
737
738 static void uh_complete_request(struct client *cl)
739 {
740         struct deferred_request *dr;
741
742         n_requests--;
743
744         while (!list_empty(&pending_requests)) {
745                 if (n_requests >= conf.max_script_requests)
746                         return;
747
748                 dr = list_first_entry(&pending_requests, struct deferred_request, list);
749                 list_del(&dr->list);
750
751                 cl = dr->cl;
752                 dr->called = true;
753                 cl->dispatch.data_blocked = false;
754                 uh_invoke_script(cl, dr->d, dr->path ? &dr->pi : NULL);
755                 client_poll_post_data(cl);
756                 ustream_poll(cl->us);
757         }
758 }
759
760
761 static void
762 uh_free_pending_request(struct client *cl)
763 {
764         struct deferred_request *dr = cl->dispatch.req_data;
765
766         if (dr->called)
767                 uh_complete_request(cl);
768         else
769                 list_del(&dr->list);
770         free(dr);
771 }
772
773 static int field_len(const char *ptr)
774 {
775         if (!ptr)
776                 return 0;
777
778         return strlen(ptr) + 1;
779 }
780
781 #define path_info_fields \
782         _field(root) \
783         _field(phys) \
784         _field(name) \
785         _field(info) \
786         _field(query)
787
788 static void
789 uh_defer_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
790 {
791         struct deferred_request *dr;
792         char *_root, *_phys, *_name, *_info, *_query;
793
794         cl->dispatch.req_free = uh_free_pending_request;
795
796         if (pi) {
797                 /* allocate enough memory to duplicate all path_info strings in one block */
798 #undef _field
799 #define _field(_name) &_##_name, field_len(pi->_name),
800                 dr = calloc_a(sizeof(*dr), path_info_fields NULL);
801
802                 memcpy(&dr->pi, pi, sizeof(*pi));
803                 dr->path = true;
804
805                 /* copy all path_info strings */
806 #undef _field
807 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
808                 path_info_fields
809         } else {
810                 dr = calloc(1, sizeof(*dr));
811         }
812
813         cl->dispatch.req_data = dr;
814         cl->dispatch.data_blocked = true;
815         dr->cl = cl;
816         dr->d = d;
817         list_add(&dr->list, &pending_requests);
818 }
819
820 static void
821 uh_invoke_handler(struct client *cl, struct dispatch_handler *d, char *url, struct path_info *pi)
822 {
823         if (!d->script)
824                 return d->handle_request(cl, url, pi);
825
826         if (n_requests >= conf.max_script_requests)
827                 return uh_defer_script(cl, d, pi);
828
829         cl->dispatch.req_free = uh_complete_request;
830         uh_invoke_script(cl, d, pi);
831 }
832
833 static bool __handle_file_request(struct client *cl, char *url)
834 {
835         static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
836                 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
837                 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
838                 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
839                 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
840                 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
841                 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
842         };
843         struct dispatch_handler *d;
844         struct blob_attr *tb[__HDR_MAX];
845         struct path_info *pi;
846         char *user, *pass, *auth;
847
848         pi = uh_path_lookup(cl, url);
849         if (!pi)
850                 return false;
851
852         if (pi->redirected)
853                 return true;
854
855         blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
856
857         auth = tb[HDR_AUTHORIZATION] ? blobmsg_data(tb[HDR_AUTHORIZATION]) : NULL;
858
859         if (!uh_auth_check(cl, pi->name, auth, &user, &pass))
860                 return true;
861
862         if (user && pass) {
863                 blobmsg_add_string(&cl->hdr, "http-auth-user", user);
864                 blobmsg_add_string(&cl->hdr, "http-auth-pass", pass);
865         }
866
867         d = dispatch_find(url, pi);
868         if (d)
869                 uh_invoke_handler(cl, d, url, pi);
870         else
871                 uh_file_request(cl, url, pi, tb);
872
873         return true;
874 }
875
876 static char *uh_handle_alias(char *old_url)
877 {
878         struct alias *alias;
879         static char *new_url;
880         static int url_len;
881
882         if (!list_empty(&conf.cgi_alias)) list_for_each_entry(alias, &conf.cgi_alias, list) {
883                 int old_len;
884                 int new_len;
885                 int path_len = 0;
886
887                 if (!uh_path_match(alias->alias, old_url))
888                         continue;
889
890                 if (alias->path)
891                         path_len = strlen(alias->path);
892
893                 old_len = strlen(old_url) + 1;
894                 new_len = old_len + MAX(conf.cgi_prefix_len, path_len);
895
896                 if (new_len > url_len) {
897                         new_url = realloc(new_url, new_len);
898                         url_len = new_len;
899                 }
900
901                 *new_url = '\0';
902
903                 if (alias->path)
904                         strcpy(new_url, alias->path);
905                 else if (conf.cgi_prefix)
906                         strcpy(new_url, conf.cgi_prefix);
907                 strcat(new_url, old_url);
908
909                 return new_url;
910         }
911         return old_url;
912 }
913
914 void uh_handle_request(struct client *cl)
915 {
916         struct http_request *req = &cl->request;
917         struct dispatch_handler *d;
918         char *url = blobmsg_data(blob_data(cl->hdr.head));
919         char *error_handler, *escaped_url;
920
921         blob_buf_init(&cl->hdr_response, 0);
922         url = uh_handle_alias(url);
923
924         uh_handler_run(cl, &url, false);
925         if (!url)
926                 return;
927
928         req->redirect_status = 200;
929         d = dispatch_find(url, NULL);
930         if (d)
931                 return uh_invoke_handler(cl, d, url, NULL);
932
933         if (__handle_file_request(cl, url))
934                 return;
935
936         if (uh_handler_run(cl, &url, true)) {
937                 if (!url)
938                         return;
939
940                 uh_handler_run(cl, &url, false);
941                 if (__handle_file_request(cl, url))
942                         return;
943         }
944
945         req->redirect_status = 404;
946         if (conf.error_handler) {
947                 error_handler = alloca(strlen(conf.error_handler) + 1);
948                 strcpy(error_handler, conf.error_handler);
949                 if (__handle_file_request(cl, error_handler))
950                         return;
951         }
952
953         escaped_url = uh_htmlescape(url);
954
955         uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.",
956                         escaped_url ? escaped_url : "");
957
958         if (escaped_url)
959                 free(escaped_url);
960 }