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