• source navigation  • diff markup  • identifier search  • freetext search  • 

Sources/uhttpd/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; charset=%s\r\n\r\n",
550                 conf.dirlist_charset ? conf.dirlist_charset : "UTF-8");
551 
552         uh_chunk_printf(cl,
553                 "<html><head><title>Index of %s</title></head>"
554                 "<body><h1>Index of %s</h1><hr /><ol>",
555                 escaped_path, escaped_path);
556 
557         count = scandir(pi->phys, &files, NULL, dirent_cmp);
558         if (count > 0) {
559                 strcpy(uh_buf, pi->phys);
560                 list_entries(cl, files, count, escaped_path, uh_buf);
561         }
562         free(escaped_path);
563         free(files);
564 
565         uh_chunk_printf(cl, "</ol><hr /></body></html>");
566         uh_request_done(cl);
567 }
568 
569 static void file_write_cb(struct client *cl)
570 {
571         int fd = cl->dispatch.file.fd;
572         int r;
573 
574         while (cl->us->w.data_bytes < 256) {
575                 r = read(fd, uh_buf, sizeof(uh_buf));
576                 if (r < 0) {
577                         if (errno == EINTR)
578                                 continue;
579                 }
580 
581                 if (!r) {
582                         uh_request_done(cl);
583                         return;
584                 }
585 
586                 uh_chunk_write(cl, uh_buf, r);
587         }
588 }
589 
590 static void uh_file_free(struct client *cl)
591 {
592         close(cl->dispatch.file.fd);
593 }
594 
595 static void uh_file_data(struct client *cl, struct path_info *pi, int fd)
596 {
597         /* test preconditions */
598         if (!cl->dispatch.no_cache &&
599             (!uh_file_if_modified_since(cl, &pi->stat) ||
600              !uh_file_if_match(cl, &pi->stat) ||
601              !uh_file_if_range(cl, &pi->stat) ||
602              !uh_file_if_unmodified_since(cl, &pi->stat) ||
603              !uh_file_if_none_match(cl, &pi->stat))) {
604                 ustream_printf(cl->us, "\r\n");
605                 uh_request_done(cl);
606                 close(fd);
607                 return;
608         }
609 
610         /* write status */
611         uh_file_response_200(cl, &pi->stat);
612 
613         ustream_printf(cl->us, "Content-Type: %s\r\n",
614                            uh_file_mime_lookup(pi->name));
615 
616         ustream_printf(cl->us, "Content-Length: %" PRIu64 "\r\n\r\n",
617                            pi->stat.st_size);
618 
619 
620         /* send body */
621         if (cl->request.method == UH_HTTP_MSG_HEAD) {
622                 uh_request_done(cl);
623                 close(fd);
624                 return;
625         }
626 
627         cl->dispatch.file.fd = fd;
628         cl->dispatch.write_cb = file_write_cb;
629         cl->dispatch.free = uh_file_free;
630         cl->dispatch.close_fds = uh_file_free;
631         file_write_cb(cl);
632 }
633 
634 static bool __handle_file_request(struct client *cl, char *url);
635 
636 static void uh_file_request(struct client *cl, const char *url,
637                             struct path_info *pi, struct blob_attr **tb)
638 {
639         int fd;
640         struct http_request *req = &cl->request;
641         char *error_handler, *escaped_url;
642 
643         switch (cl->request.method) {
644         case UH_HTTP_MSG_GET:
645         case UH_HTTP_MSG_POST:
646         case UH_HTTP_MSG_HEAD:
647         case UH_HTTP_MSG_OPTIONS:
648                 break;
649 
650         default:
651                 uh_file_response_405(cl);
652                 ustream_printf(cl->us, "\r\n");
653                 uh_request_done(cl);
654                 return;
655         }
656 
657         if (!(pi->stat.st_mode & S_IROTH))
658                 goto error;
659 
660         if (pi->stat.st_mode & S_IFREG) {
661                 fd = open(pi->phys, O_RDONLY);
662                 if (fd < 0)
663                         goto error;
664 
665                 req->disable_chunked = true;
666                 cl->dispatch.file.hdr = tb;
667                 uh_file_data(cl, pi, fd);
668                 cl->dispatch.file.hdr = NULL;
669                 return;
670         }
671 
672         if ((pi->stat.st_mode & S_IFDIR)) {
673                 if (conf.no_dirlists)
674                         goto error;
675 
676                 uh_file_dirlist(cl, pi);
677                 return;
678         }
679 
680 error:
681         /* check for a previously set 403 redirect status to prevent infinite
682            recursion when the error page itself lacks sufficient permissions */
683         if (conf.error_handler && req->redirect_status != 403) {
684                 req->redirect_status = 403;
685                 error_handler = alloca(strlen(conf.error_handler) + 1);
686                 strcpy(error_handler, conf.error_handler);
687                 if (__handle_file_request(cl, error_handler))
688                         return;
689         }
690 
691         escaped_url = uh_htmlescape(url);
692 
693         uh_client_error(cl, 403, "Forbidden",
694                         "You don't have permission to access %s on this server.",
695                         escaped_url ? escaped_url : "the url");
696 
697         if (escaped_url)
698                 free(escaped_url);
699 }
700 
701 void uh_dispatch_add(struct dispatch_handler *d)
702 {
703         list_add_tail(&d->list, &dispatch_handlers);
704 }
705 
706 static struct dispatch_handler *
707 dispatch_find(const char *url, struct path_info *pi)
708 {
709         struct dispatch_handler *d;
710 
711         list_for_each_entry(d, &dispatch_handlers, list) {
712                 if (pi) {
713                         if (d->check_url)
714                                 continue;
715 
716                         if (d->check_path(pi, url))
717                                 return d;
718                 } else {
719                         if (d->check_path)
720                                 continue;
721 
722                         if (d->check_url(url))
723                                 return d;
724                 }
725         }
726 
727         return NULL;
728 }
729 
730 static void
731 uh_invoke_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
732 {
733         char *url = blobmsg_data(blob_data(cl->hdr.head));
734 
735         n_requests++;
736         d->handle_request(cl, url, pi);
737 }
738 
739 static void uh_complete_request(struct client *cl)
740 {
741         struct deferred_request *dr;
742 
743         n_requests--;
744 
745         while (!list_empty(&pending_requests)) {
746                 if (n_requests >= conf.max_script_requests)
747                         return;
748 
749                 dr = list_first_entry(&pending_requests, struct deferred_request, list);
750                 list_del(&dr->list);
751 
752                 cl = dr->cl;
753                 dr->called = true;
754                 cl->dispatch.data_blocked = false;
755                 uh_invoke_script(cl, dr->d, dr->path ? &dr->pi : NULL);
756                 client_poll_post_data(cl);
757                 ustream_poll(cl->us);
758         }
759 }
760 
761 
762 static void
763 uh_free_pending_request(struct client *cl)
764 {
765         struct deferred_request *dr = cl->dispatch.req_data;
766 
767         if (dr->called)
768                 uh_complete_request(cl);
769         else
770                 list_del(&dr->list);
771         free(dr);
772 }
773 
774 static int field_len(const char *ptr)
775 {
776         if (!ptr)
777                 return 0;
778 
779         return strlen(ptr) + 1;
780 }
781 
782 #define path_info_fields \
783         _field(root) \
784         _field(phys) \
785         _field(name) \
786         _field(info) \
787         _field(query)
788 
789 static void
790 uh_defer_script(struct client *cl, struct dispatch_handler *d, struct path_info *pi)
791 {
792         struct deferred_request *dr;
793         char *_root, *_phys, *_name, *_info, *_query;
794 
795         cl->dispatch.req_free = uh_free_pending_request;
796 
797         if (pi) {
798                 /* allocate enough memory to duplicate all path_info strings in one block */
799 #undef _field
800 #define _field(_name) &_##_name, field_len(pi->_name),
801                 dr = calloc_a(sizeof(*dr), path_info_fields NULL);
802 
803                 memcpy(&dr->pi, pi, sizeof(*pi));
804                 dr->path = true;
805 
806                 /* copy all path_info strings */
807 #undef _field
808 #define _field(_name) if (pi->_name) dr->pi._name = strcpy(_##_name, pi->_name);
809                 path_info_fields
810         } else {
811                 dr = calloc(1, sizeof(*dr));
812         }
813 
814         cl->dispatch.req_data = dr;
815         cl->dispatch.data_blocked = true;
816         dr->cl = cl;
817         dr->d = d;
818         list_add(&dr->list, &pending_requests);
819 }
820 
821 static void
822 uh_invoke_handler(struct client *cl, struct dispatch_handler *d, char *url, struct path_info *pi)
823 {
824         if (!d->script)
825                 return d->handle_request(cl, url, pi);
826 
827         if (n_requests >= conf.max_script_requests)
828                 return uh_defer_script(cl, d, pi);
829 
830         cl->dispatch.req_free = uh_complete_request;
831         uh_invoke_script(cl, d, pi);
832 }
833 
834 static bool __handle_file_request(struct client *cl, char *url)
835 {
836         static const struct blobmsg_policy hdr_policy[__HDR_MAX] = {
837                 [HDR_AUTHORIZATION] = { "authorization", BLOBMSG_TYPE_STRING },
838                 [HDR_IF_MODIFIED_SINCE] = { "if-modified-since", BLOBMSG_TYPE_STRING },
839                 [HDR_IF_UNMODIFIED_SINCE] = { "if-unmodified-since", BLOBMSG_TYPE_STRING },
840                 [HDR_IF_MATCH] = { "if-match", BLOBMSG_TYPE_STRING },
841                 [HDR_IF_NONE_MATCH] = { "if-none-match", BLOBMSG_TYPE_STRING },
842                 [HDR_IF_RANGE] = { "if-range", BLOBMSG_TYPE_STRING },
843         };
844         struct dispatch_handler *d;
845         struct blob_attr *tb[__HDR_MAX];
846         struct path_info *pi;
847         char *user, *pass, *auth;
848 
849         pi = uh_path_lookup(cl, url);
850         if (!pi)
851                 return false;
852 
853         if (pi->redirected)
854                 return true;
855 
856         blobmsg_parse(hdr_policy, __HDR_MAX, tb, blob_data(cl->hdr.head), blob_len(cl->hdr.head));
857 
858         auth = tb[HDR_AUTHORIZATION] ? blobmsg_data(tb[HDR_AUTHORIZATION]) : NULL;
859 
860         if (!uh_auth_check(cl, pi->name, auth, &user, &pass))
861                 return true;
862 
863         if (user && pass) {
864                 blobmsg_add_string(&cl->hdr, "http-auth-user", user);
865                 blobmsg_add_string(&cl->hdr, "http-auth-pass", pass);
866         }
867 
868         d = dispatch_find(url, pi);
869         if (d)
870                 uh_invoke_handler(cl, d, url, pi);
871         else
872                 uh_file_request(cl, url, pi, tb);
873 
874         return true;
875 }
876 
877 static char *uh_handle_alias(char *old_url)
878 {
879         struct alias *alias;
880         static char *new_url;
881         static int url_len;
882 
883         if (!list_empty(&conf.cgi_alias)) list_for_each_entry(alias, &conf.cgi_alias, list) {
884                 int old_len;
885                 int new_len;
886                 int path_len = 0;
887 
888                 if (!uh_path_match(alias->alias, old_url))
889                         continue;
890 
891                 if (alias->path)
892                         path_len = strlen(alias->path);
893 
894                 old_len = strlen(old_url) + 1;
895                 new_len = old_len + MAX(conf.cgi_prefix_len, path_len);
896 
897                 if (new_len > url_len) {
898                         new_url = realloc(new_url, new_len);
899                         url_len = new_len;
900                 }
901 
902                 *new_url = '\0';
903 
904                 if (alias->path)
905                         strcpy(new_url, alias->path);
906                 else if (conf.cgi_prefix)
907                         strcpy(new_url, conf.cgi_prefix);
908                 strcat(new_url, old_url);
909 
910                 return new_url;
911         }
912         return old_url;
913 }
914 
915 void uh_handle_request(struct client *cl)
916 {
917         struct http_request *req = &cl->request;
918         struct dispatch_handler *d;
919         char *url = blobmsg_data(blob_data(cl->hdr.head));
920         char *error_handler, *escaped_url;
921 
922         blob_buf_init(&cl->hdr_response, 0);
923         url = uh_handle_alias(url);
924 
925         uh_handler_run(cl, &url, false);
926         if (!url)
927                 return;
928 
929         req->redirect_status = 200;
930         d = dispatch_find(url, NULL);
931         if (d)
932                 return uh_invoke_handler(cl, d, url, NULL);
933 
934         if (__handle_file_request(cl, url))
935                 return;
936 
937         if (uh_handler_run(cl, &url, true)) {
938                 if (!url)
939                         return;
940 
941                 uh_handler_run(cl, &url, false);
942                 if (__handle_file_request(cl, url))
943                         return;
944         }
945 
946         req->redirect_status = 404;
947         if (conf.error_handler) {
948                 error_handler = alloca(strlen(conf.error_handler) + 1);
949                 strcpy(error_handler, conf.error_handler);
950                 if (__handle_file_request(cl, error_handler))
951                         return;
952         }
953 
954         escaped_url = uh_htmlescape(url);
955 
956         uh_client_error(cl, 404, "Not Found", "The requested URL %s was not found on this server.",
957                         escaped_url ? escaped_url : "");
958 
959         if (escaped_url)
960                 free(escaped_url);
961 }
962 

This page was automatically generated by LXR 0.3.1.  •  OpenWrt