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