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