Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "gmid.h"
19 #include <sys/stat.h>
21 #include <assert.h>
22 #include <errno.h>
23 #include <event.h>
24 #include <fcntl.h>
25 #include <fnmatch.h>
26 #include <limits.h>
27 #include <string.h>
29 int shutting_down;
31 struct client clients[MAX_USERS];
33 static struct tls *ctx;
35 static struct event e4, e6, imsgev, siginfo, sigusr2;
36 static int has_ipv6, has_siginfo;
38 int connected_clients;
40 static inline int matches(const char*, const char*);
42 static inline void yield_read(int, struct client*, statefn);
43 static inline void yield_write(int, struct client*, statefn);
45 static int check_path(struct client*, const char*, int*);
46 static void open_file(struct client*);
47 static void check_for_cgi(struct client*);
48 static void handle_handshake(int, short, void*);
49 static const char *strip_path(const char*, int);
50 static void fmt_sbuf(const char*, struct client*, const char*);
51 static int apply_block_return(struct client*);
52 static int apply_require_ca(struct client*);
53 static void handle_open_conn(int, short, void*);
54 static void handle_start_reply(int, short, void*);
55 static size_t host_nth(struct vhost*);
56 static void start_cgi(const char*, const char*, struct client*);
57 static void open_dir(struct client*);
58 static void redirect_canonical_dir(struct client*);
59 static void enter_handle_dirlist(int, short, void*);
60 static void handle_dirlist(int, short, void*);
61 static int read_next_dir_entry(struct client*);
62 static void send_directory_listing(int, short, void*);
63 static void handle_cgi_reply(int, short, void*);
64 static void handle_copy(int, short, void*);
65 static void do_accept(int, short, void*);
66 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
67 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
68 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
69 static void handle_siginfo(int, short, void*);
71 static imsg_handlerfn *handlers[] = {
72 [IMSG_QUIT] = handle_imsg_quit,
73 [IMSG_CGI_RES] = handle_imsg_cgi_res,
74 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
75 };
77 static inline int
78 matches(const char *pattern, const char *path)
79 {
80 if (*path == '/')
81 path++;
82 return !fnmatch(pattern, path, 0);
83 }
85 static inline void
86 yield_read(int fd, struct client *c, statefn fn)
87 {
88 event_once(fd, EV_READ, fn, c, NULL);
89 }
91 static inline void
92 yield_write(int fd, struct client *c, statefn fn)
93 {
94 event_once(fd, EV_WRITE, fn, c, NULL);
95 }
97 const char *
98 vhost_lang(struct vhost *v, const char *path)
99 {
100 struct location *loc;
102 if (v == NULL || path == NULL)
103 return NULL;
105 loc = TAILQ_FIRST(&v->locations);
106 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
107 if (loc->lang != NULL) {
108 if (matches(loc->match, path))
109 return loc->lang;
113 return TAILQ_FIRST(&v->locations)->lang;
116 const char *
117 vhost_default_mime(struct vhost *v, const char *path)
119 struct location *loc;
120 const char *default_mime = "application/octet-stream";
122 if (v == NULL || path == NULL)
123 return default_mime;
125 loc = TAILQ_FIRST(&v->locations);
126 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
127 if (loc->default_mime != NULL) {
128 if (matches(loc->match, path))
129 return loc->default_mime;
133 loc = TAILQ_FIRST(&v->locations);
134 if (loc->default_mime != NULL)
135 return loc->default_mime;
136 return default_mime;
139 const char *
140 vhost_index(struct vhost *v, const char *path)
142 struct location *loc;
143 const char *index = "index.gmi";
145 if (v == NULL || path == NULL)
146 return index;
148 loc = TAILQ_FIRST(&v->locations);
149 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
150 if (loc->index != NULL) {
151 if (matches(loc->match, path))
152 return loc->index;
156 loc = TAILQ_FIRST(&v->locations);
157 if (loc->index != NULL)
158 return loc->index;
159 return index;
162 int
163 vhost_auto_index(struct vhost *v, const char *path)
165 struct location *loc;
167 if (v == NULL || path == NULL)
168 return 0;
170 loc = TAILQ_FIRST(&v->locations);
171 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
172 if (loc->auto_index != 0) {
173 if (matches(loc->match, path))
174 return loc->auto_index == 1;
178 loc = TAILQ_FIRST(&v->locations);
179 return loc->auto_index == 1;
182 int
183 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
185 struct location *loc;
187 if (v == NULL || path == NULL)
188 return 0;
190 loc = TAILQ_FIRST(&v->locations);
191 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
192 if (loc->block_code != 0) {
193 if (matches(loc->match, path)) {
194 *code = loc->block_code;
195 *fmt = loc->block_fmt;
196 return 1;
201 loc = TAILQ_FIRST(&v->locations);
202 *code = loc->block_code;
203 *fmt = loc->block_fmt;
204 return loc->block_code != 0;
207 int
208 vhost_fastcgi(struct vhost *v, const char *path)
210 struct location *loc;
212 if (v == NULL || path == NULL)
213 return -1;
215 loc = TAILQ_FIRST(&v->locations);
216 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
217 if (loc->fcgi != -1)
218 if (matches(loc->match, path))
219 return loc->fcgi;
222 loc = TAILQ_FIRST(&v->locations);
223 return loc->fcgi;
226 int
227 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
229 struct location *loc;
230 size_t l = 0;
232 if (v == NULL || path == NULL)
233 return -1;
235 loc = TAILQ_FIRST(&v->locations);
236 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
237 l++;
238 if (loc->dirfd != -1)
239 if (matches(loc->match, path)) {
240 *retloc = l;
241 return loc->dirfd;
245 *retloc = 0;
246 loc = TAILQ_FIRST(&v->locations);
247 return loc->dirfd;
250 int
251 vhost_strip(struct vhost *v, const char *path)
253 struct location *loc;
255 if (v == NULL || path == NULL)
256 return 0;
258 loc = TAILQ_FIRST(&v->locations);
259 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
260 if (loc->strip != 0) {
261 if (matches(loc->match, path))
262 return loc->strip;
266 loc = TAILQ_FIRST(&v->locations);
267 return loc->strip;
270 X509_STORE *
271 vhost_require_ca(struct vhost *v, const char *path)
273 struct location *loc;
275 if (v == NULL || path == NULL)
276 return NULL;
278 loc = TAILQ_FIRST(&v->locations);
279 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
280 if (loc->reqca != NULL) {
281 if (matches(loc->match, path))
282 return loc->reqca;
286 loc = TAILQ_FIRST(&v->locations);
287 return loc->reqca;
290 int
291 vhost_disable_log(struct vhost *v, const char *path)
293 struct location *loc;
295 if (v == NULL || path == NULL)
296 return 0;
298 loc = TAILQ_FIRST(&v->locations);
299 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
300 if (loc->disable_log && matches(loc->match, path))
301 return 1;
304 loc = TAILQ_FIRST(&v->locations);
305 return loc->disable_log;
308 static int
309 check_path(struct client *c, const char *path, int *fd)
311 struct stat sb;
312 const char *p;
313 int dirfd, strip;
315 assert(path != NULL);
317 /*
318 * in send_dir we add an initial / (to be redirect-friendly),
319 * but here we want to skip it
320 */
321 if (*path == '/')
322 path++;
324 strip = vhost_strip(c->host, path);
325 p = strip_path(path, strip);
327 if (*p == '/')
328 p = p+1;
329 if (*p == '\0')
330 p = ".";
332 dirfd = vhost_dirfd(c->host, path, &c->loc);
333 log_debug(c, "check_path: strip=%d path=%s original=%s",
334 strip, p, path);
335 if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
336 return FILE_MISSING;
338 if (fstat(*fd, &sb) == -1) {
339 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
340 return FILE_MISSING;
343 if (S_ISDIR(sb.st_mode))
344 return FILE_DIRECTORY;
346 if (sb.st_mode & S_IXUSR)
347 return FILE_EXECUTABLE;
349 return FILE_EXISTS;
352 static void
353 open_file(struct client *c)
355 switch (check_path(c, c->iri.path, &c->pfd)) {
356 case FILE_EXECUTABLE:
357 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
358 start_cgi(c->iri.path, "", c);
359 return;
362 /* fallthrough */
364 case FILE_EXISTS:
365 c->next = handle_copy;
366 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
367 return;
369 case FILE_DIRECTORY:
370 open_dir(c);
371 return;
373 case FILE_MISSING:
374 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
375 check_for_cgi(c);
376 return;
378 start_reply(c, NOT_FOUND, "not found");
379 return;
381 default:
382 /* unreachable */
383 abort();
387 /*
388 * the inverse of this algorithm, i.e. starting from the start of the
389 * path + strlen(cgi), and checking if each component, should be
390 * faster. But it's tedious to write. This does the opposite: starts
391 * from the end and strip one component at a time, until either an
392 * executable is found or we emptied the path.
393 */
394 static void
395 check_for_cgi(struct client *c)
397 char path[PATH_MAX];
398 char *end;
400 strlcpy(path, c->iri.path, sizeof(path));
401 end = strchr(path, '\0');
403 while (end > path) {
404 /*
405 * go up one level. UNIX paths are simple and POSIX
406 * dirname, with its ambiguities on if the given
407 * pointer is changed or not, gives me headaches.
408 */
409 while (*end != '/' && end > path)
410 end--;
412 if (end == path)
413 break;
415 *end = '\0';
417 switch (check_path(c, path, &c->pfd)) {
418 case FILE_EXECUTABLE:
419 start_cgi(path, end+1, c);
420 return;
421 case FILE_MISSING:
422 break;
423 default:
424 goto err;
427 *end = '/';
428 end--;
431 err:
432 start_reply(c, NOT_FOUND, "not found");
433 return;
436 void
437 mark_nonblock(int fd)
439 int flags;
441 if ((flags = fcntl(fd, F_GETFL)) == -1)
442 fatal("fcntl(F_GETFL): %s", strerror(errno));
443 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
444 fatal("fcntl(F_SETFL): %s", strerror(errno));
447 static void
448 handle_handshake(int fd, short ev, void *d)
450 struct client *c = d;
451 struct vhost *h;
452 struct alist *a;
453 const char *servname;
454 const char *parse_err = "unknown error";
456 switch (tls_handshake(c->ctx)) {
457 case 0: /* success */
458 case -1: /* already handshaked */
459 break;
460 case TLS_WANT_POLLIN:
461 yield_read(fd, c, &handle_handshake);
462 return;
463 case TLS_WANT_POLLOUT:
464 yield_write(fd, c, &handle_handshake);
465 return;
466 default:
467 /* unreachable */
468 abort();
471 if ((servname = tls_conn_servername(c->ctx)) == NULL) {
472 log_debug(c, "handshake: missing SNI");
473 goto err;
476 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
477 log_info(c, "puny_decode: %s", parse_err);
478 goto err;
481 TAILQ_FOREACH(h, &hosts, vhosts) {
482 if (matches(h->domain, c->domain))
483 goto found;
484 TAILQ_FOREACH(a, &h->aliases, aliases) {
485 if (matches(a->alias, c->domain))
486 goto found;
490 found:
491 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
492 servname != NULL ? servname : "(null)",
493 c->domain,
494 h != NULL ? h->domain : "(null)");
496 if (h != NULL) {
497 c->host = h;
498 handle_open_conn(fd, ev, c);
499 return;
502 err:
503 if (servname != NULL)
504 strlcpy(c->req, servname, sizeof(c->req));
505 else
506 strlcpy(c->req, "null", sizeof(c->req));
508 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
511 static const char *
512 strip_path(const char *path, int strip)
514 char *t;
516 while (strip > 0) {
517 if ((t = strchr(path, '/')) == NULL) {
518 path = strchr(path, '\0');
519 break;
521 path = t;
522 strip--;
525 return path;
528 static void
529 fmt_sbuf(const char *fmt, struct client *c, const char *path)
531 size_t i;
532 char buf[32];
534 memset(buf, 0, sizeof(buf));
535 for (i = 0; *fmt; ++fmt) {
536 if (i == sizeof(buf)-1 || *fmt == '%') {
537 strlcat(c->sbuf, buf, sizeof(c->sbuf));
538 memset(buf, 0, sizeof(buf));
539 i = 0;
542 if (*fmt != '%') {
543 buf[i++] = *fmt;
544 continue;
547 switch (*++fmt) {
548 case '%':
549 strlcat(c->sbuf, "%", sizeof(c->sbuf));
550 break;
551 case 'p':
552 if (*path != '/')
553 strlcat(c->sbuf, "/", sizeof(c->sbuf));
554 strlcat(c->sbuf, path, sizeof(c->sbuf));
555 break;
556 case 'q':
557 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
558 break;
559 case 'P':
560 snprintf(buf, sizeof(buf), "%d", conf.port);
561 strlcat(c->sbuf, buf, sizeof(c->sbuf));
562 memset(buf, 0, sizeof(buf));
563 break;
564 case 'N':
565 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
566 break;
567 default:
568 fatal("%s: unknown fmt specifier %c",
569 __func__, *fmt);
573 if (i != 0)
574 strlcat(c->sbuf, buf, sizeof(c->sbuf));
577 /* 1 if a matching `block return' (and apply it), 0 otherwise */
578 static int
579 apply_block_return(struct client *c)
581 const char *fmt, *path;
582 int code;
584 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
585 return 0;
587 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
588 fmt_sbuf(fmt, c, path);
590 start_reply(c, code, c->sbuf);
591 return 1;
594 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
595 static int
596 apply_fastcgi(struct client *c)
598 int id;
599 struct fcgi *f;
601 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
602 return 0;
604 switch ((f = &fcgi[id])->s) {
605 case FCGI_OFF:
606 f->s = FCGI_INFLIGHT;
607 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
608 f->path, f->port, f->prog);
609 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
610 &id, sizeof(id));
611 imsg_flush(&exibuf);
612 /* fallthrough */
613 case FCGI_INFLIGHT:
614 c->fcgi = id;
615 break;
616 case FCGI_READY:
617 c->fcgi = id;
618 fcgi_req(f, c);
619 break;
622 return 1;
625 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
626 static int
627 apply_require_ca(struct client *c)
629 X509_STORE *store;
630 const uint8_t *cert;
631 size_t len;
633 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
634 return 0;
636 if (!tls_peer_cert_provided(c->ctx)) {
637 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
638 return 1;
641 cert = tls_peer_cert_chain_pem(c->ctx, &len);
642 if (!validate_against_ca(store, cert, len)) {
643 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
644 return 1;
647 return 0;
650 static void
651 handle_open_conn(int fd, short ev, void *d)
653 struct client *c = d;
654 const char *parse_err = "invalid request";
655 char decoded[DOMAIN_NAME_LEN];
657 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
658 case -1:
659 log_err(c, "tls_read: %s", tls_error(c->ctx));
660 close_conn(fd, ev, c);
661 return;
663 case TLS_WANT_POLLIN:
664 yield_read(fd, c, &handle_open_conn);
665 return;
667 case TLS_WANT_POLLOUT:
668 yield_write(fd, c, &handle_open_conn);
669 return;
672 if (!trim_req_iri(c->req, &parse_err) ||
673 !parse_iri(c->req, &c->iri, &parse_err) ||
674 !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
675 log_info(c, "iri parse error: %s", parse_err);
676 start_reply(c, BAD_REQUEST, "invalid request");
677 return;
680 if (c->iri.port_no != conf.port ||
681 strcmp(c->iri.schema, "gemini") ||
682 strcmp(decoded, c->domain)) {
683 start_reply(c, PROXY_REFUSED, "won't proxy request");
684 return;
687 if (apply_require_ca(c))
688 return;
690 if (apply_block_return(c))
691 return;
693 if (apply_fastcgi(c))
694 return;
696 if (c->host->entrypoint != NULL) {
697 c->loc = 0;
698 start_cgi(c->host->entrypoint, c->iri.path, c);
699 return;
702 open_file(c);
705 void
706 start_reply(struct client *c, int code, const char *meta)
708 c->code = code;
709 c->meta = meta;
710 handle_start_reply(c->fd, 0, c);
713 static void
714 handle_start_reply(int fd, short ev, void *d)
716 struct client *c = d;
717 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
718 const char *lang;
719 size_t len;
721 lang = vhost_lang(c->host, c->iri.path);
723 snprintf(buf, sizeof(buf), "%d ", c->code);
724 strlcat(buf, c->meta, sizeof(buf));
725 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
726 strlcat(buf, "; lang=", sizeof(buf));
727 strlcat(buf, lang, sizeof(buf));
730 len = strlcat(buf, "\r\n", sizeof(buf));
731 assert(len < sizeof(buf));
733 switch (tls_write(c->ctx, buf, len)) {
734 case -1:
735 close_conn(fd, ev, c);
736 return;
737 case TLS_WANT_POLLIN:
738 yield_read(fd, c, &handle_start_reply);
739 return;
740 case TLS_WANT_POLLOUT:
741 yield_write(fd, c, &handle_start_reply);
742 return;
745 if (!vhost_disable_log(c->host, c->iri.path))
746 log_request(c, buf, sizeof(buf));
748 if (c->code != SUCCESS)
749 close_conn(fd, ev, c);
750 else
751 c->next(fd, ev, c);
754 static size_t
755 host_nth(struct vhost *h)
757 struct vhost *v;
758 size_t i = 0;
760 TAILQ_FOREACH(v, &hosts, vhosts) {
761 if (v == h)
762 return i;
763 i++;
766 abort();
769 static void
770 start_cgi(const char *spath, const char *relpath, struct client *c)
772 char addr[NI_MAXHOST];
773 const char *t;
774 struct cgireq req;
775 int e;
777 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
778 addr, sizeof(addr),
779 NULL, 0,
780 NI_NUMERICHOST);
781 if (e != 0)
782 fatal("getnameinfo failed");
784 memset(&req, 0, sizeof(req));
786 memcpy(req.buf, c->req, sizeof(req.buf));
788 req.iri_schema_off = c->iri.schema - c->req;
789 req.iri_host_off = c->iri.host - c->req;
790 req.iri_port_off = c->iri.port - c->req;
791 req.iri_path_off = c->iri.path - c->req;
792 req.iri_query_off = c->iri.query - c->req;
793 req.iri_fragment_off = c->iri.fragment - c->req;
795 req.iri_portno = c->iri.port_no;
797 strlcpy(req.spath, spath, sizeof(req.spath));
798 strlcpy(req.relpath, relpath, sizeof(req.relpath));
799 strlcpy(req.addr, addr, sizeof(req.addr));
801 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
802 strlcpy(req.subject, t, sizeof(req.subject));
803 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
804 strlcpy(req.issuer, t, sizeof(req.issuer));
805 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
806 strlcpy(req.hash, t, sizeof(req.hash));
807 if ((t = tls_conn_version(c->ctx)) != NULL)
808 strlcpy(req.version, t, sizeof(req.version));
809 if ((t = tls_conn_cipher(c->ctx)) != NULL)
810 strlcpy(req.cipher, t, sizeof(req.cipher));
812 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
813 req.notbefore = tls_peer_cert_notbefore(c->ctx);
814 req.notafter = tls_peer_cert_notafter(c->ctx);
816 req.host_off = host_nth(c->host);
817 req.loc_off = c->loc;
819 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
820 imsg_flush(&exibuf);
822 close(c->pfd);
825 static void
826 open_dir(struct client *c)
828 size_t len;
829 int dirfd, root;
830 char *before_file;
832 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
834 len = strlen(c->iri.path);
835 if (len > 0 && !ends_with(c->iri.path, "/")) {
836 redirect_canonical_dir(c);
837 return;
840 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
841 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
842 if (!ends_with(c->sbuf, "/"))
843 strlcat(c->sbuf, "/", sizeof(c->sbuf));
844 before_file = strchr(c->sbuf, '\0');
845 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
846 sizeof(c->sbuf));
847 if (len >= sizeof(c->sbuf)) {
848 start_reply(c, TEMP_FAILURE, "internal server error");
849 return;
852 c->iri.path = c->sbuf;
854 /* close later unless we have to generate the dir listing */
855 dirfd = c->pfd;
856 c->pfd = -1;
858 switch (check_path(c, c->iri.path, &c->pfd)) {
859 case FILE_EXECUTABLE:
860 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
861 start_cgi(c->iri.path, "", c);
862 break;
865 /* fallthrough */
867 case FILE_EXISTS:
868 c->next = handle_copy;
869 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
870 break;
872 case FILE_DIRECTORY:
873 start_reply(c, TEMP_REDIRECT, c->sbuf);
874 break;
876 case FILE_MISSING:
877 *before_file = '\0';
879 if (!vhost_auto_index(c->host, c->iri.path)) {
880 start_reply(c, NOT_FOUND, "not found");
881 break;
884 c->next = enter_handle_dirlist;
886 c->dirlen = scandir_fd(dirfd, &c->dir,
887 root ? select_non_dotdot : select_non_dot,
888 alphasort);
889 if (c->dirlen == -1) {
890 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
891 c->pfd, c->host->domain, c->iri.path, strerror(errno));
892 start_reply(c, TEMP_FAILURE, "internal server error");
893 return;
895 c->diroff = 0;
896 c->off = 0;
898 start_reply(c, SUCCESS, "text/gemini");
899 return;
901 default:
902 /* unreachable */
903 abort();
906 close(dirfd);
909 static void
910 redirect_canonical_dir(struct client *c)
912 size_t len;
914 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
915 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
916 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
918 if (len >= sizeof(c->sbuf)) {
919 start_reply(c, TEMP_FAILURE, "internal server error");
920 return;
923 start_reply(c, TEMP_REDIRECT, c->sbuf);
926 static void
927 enter_handle_dirlist(int fd, short ev, void *d)
929 struct client *c = d;
930 char b[PATH_MAX];
931 size_t l;
933 strlcpy(b, c->iri.path, sizeof(b));
934 l = snprintf(c->sbuf, sizeof(c->sbuf),
935 "# Index of %s\n\n", b);
936 if (l >= sizeof(c->sbuf)) {
937 /*
938 * This is impossible, given that we have enough space
939 * in c->sbuf to hold the ancilliary string plus the
940 * full path; but it wouldn't read nice without some
941 * error checking, and I'd like to avoid a strlen.
942 */
943 close_conn(fd, ev, c);
944 return;
947 c->len = l;
948 handle_dirlist(fd, ev, c);
951 static void
952 handle_dirlist(int fd, short ev, void *d)
954 struct client *c = d;
955 ssize_t r;
957 while (c->len > 0) {
958 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
959 case -1:
960 close_conn(fd, ev, c);
961 return;
962 case TLS_WANT_POLLOUT:
963 yield_read(fd, c, &handle_dirlist);
964 return;
965 case TLS_WANT_POLLIN:
966 yield_write(fd, c, &handle_dirlist);
967 return;
968 default:
969 c->off += r;
970 c->len -= r;
974 send_directory_listing(fd, ev, c);
977 static int
978 read_next_dir_entry(struct client *c)
980 if (c->diroff == c->dirlen)
981 return 0;
983 /* XXX: url escape */
984 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
985 c->dir[c->diroff]->d_name);
987 free(c->dir[c->diroff]);
988 c->diroff++;
990 c->len = strlen(c->sbuf);
991 c->off = 0;
992 return 1;
995 static void
996 send_directory_listing(int fd, short ev, void *d)
998 struct client *c = d;
999 ssize_t r;
1001 while (1) {
1002 if (c->len == 0) {
1003 if (!read_next_dir_entry(c))
1004 goto end;
1007 while (c->len > 0) {
1008 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1009 case -1:
1010 goto end;
1012 case TLS_WANT_POLLOUT:
1013 yield_read(fd, c, &send_directory_listing);
1014 return;
1016 case TLS_WANT_POLLIN:
1017 yield_write(fd, c, &send_directory_listing);
1018 return;
1020 default:
1021 c->off += r;
1022 c->len -= r;
1023 break;
1028 end:
1029 close_conn(fd, ev, d);
1032 /* accumulate the meta line from the cgi script. */
1033 static void
1034 handle_cgi_reply(int fd, short ev, void *d)
1036 struct client *c = d;
1037 void *buf, *e;
1038 size_t len;
1039 ssize_t r;
1042 buf = c->sbuf + c->len;
1043 len = sizeof(c->sbuf) - c->len;
1045 r = read(c->pfd, buf, len);
1046 if (r == 0 || r == -1) {
1047 start_reply(c, CGI_ERROR, "CGI error");
1048 return;
1051 c->len += r;
1053 /* TODO: error if the CGI script don't reply correctly */
1054 e = strchr(c->sbuf, '\n');
1055 if (e != NULL || c->len == sizeof(c->sbuf)) {
1056 log_request(c, c->sbuf, c->len);
1058 c->off = 0;
1059 handle_copy(fd, ev, c);
1060 return;
1063 yield_read(fd, c, &handle_cgi_reply);
1066 static void
1067 handle_copy(int fd, short ev, void *d)
1069 struct client *c = d;
1070 ssize_t r;
1072 while (1) {
1073 while (c->len > 0) {
1074 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1075 case -1:
1076 goto end;
1078 case TLS_WANT_POLLOUT:
1079 yield_write(c->fd, c, &handle_copy);
1080 return;
1082 case TLS_WANT_POLLIN:
1083 yield_read(c->fd, c, &handle_copy);
1084 return;
1086 default:
1087 c->off += r;
1088 c->len -= r;
1089 break;
1093 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1094 case 0:
1095 goto end;
1096 case -1:
1097 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1098 yield_read(c->pfd, c, &handle_copy);
1099 return;
1101 goto end;
1102 default:
1103 c->len = r;
1104 c->off = 0;
1108 end:
1109 close_conn(c->fd, ev, d);
1112 void
1113 close_conn(int fd, short ev, void *d)
1115 struct client *c = d;
1116 struct mbuf *mbuf;
1118 switch (tls_close(c->ctx)) {
1119 case TLS_WANT_POLLIN:
1120 yield_read(c->fd, c, &close_conn);
1121 return;
1122 case TLS_WANT_POLLOUT:
1123 yield_read(c->fd, c, &close_conn);
1124 return;
1127 connected_clients--;
1129 while ((mbuf = TAILQ_FIRST(&c->mbufhead)) != NULL) {
1130 TAILQ_REMOVE(&c->mbufhead, mbuf, mbufs);
1131 free(mbuf);
1134 tls_free(c->ctx);
1135 c->ctx = NULL;
1137 if (c->pfd != -1)
1138 close(c->pfd);
1140 if (c->dir != NULL)
1141 free(c->dir);
1143 close(c->fd);
1144 c->fd = -1;
1147 static void
1148 do_accept(int sock, short et, void *d)
1150 struct client *c;
1151 struct sockaddr_storage addr;
1152 struct sockaddr *saddr;
1153 socklen_t len;
1154 int i, fd;
1156 (void)et;
1158 saddr = (struct sockaddr*)&addr;
1159 len = sizeof(addr);
1160 if ((fd = accept(sock, saddr, &len)) == -1) {
1161 if (errno == EWOULDBLOCK || errno == EAGAIN)
1162 return;
1163 fatal("accept: %s", strerror(errno));
1166 mark_nonblock(fd);
1168 for (i = 0; i < MAX_USERS; ++i) {
1169 c = &clients[i];
1170 if (c->fd == -1) {
1171 memset(c, 0, sizeof(*c));
1172 c->id = i;
1173 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1174 break; /* goodbye fd! */
1176 c->fd = fd;
1177 c->pfd = -1;
1178 c->dir = NULL;
1179 c->addr = addr;
1180 c->fcgi = -1;
1182 TAILQ_INIT(&c->mbufhead);
1184 yield_read(fd, c, &handle_handshake);
1185 connected_clients++;
1186 return;
1190 close(fd);
1193 static struct client *
1194 client_by_id(int id)
1196 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1197 fatal("in client_by_id: invalid id %d", id);
1198 return &clients[id];
1201 struct client *
1202 try_client_by_id(int id)
1204 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1205 return NULL;
1206 return &clients[id];
1209 static void
1210 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1212 struct client *c;
1214 c = client_by_id(imsg->hdr.peerid);
1216 if ((c->pfd = imsg->fd) == -1)
1217 start_reply(c, TEMP_FAILURE, "internal server error");
1218 else
1219 yield_read(c->pfd, c, &handle_cgi_reply);
1222 static void
1223 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1225 struct client *c;
1226 struct fcgi *f;
1227 int i, id;
1229 id = imsg->hdr.peerid;
1230 f = &fcgi[id];
1232 if ((f->fd = imsg->fd) == -1)
1233 f->s = FCGI_OFF;
1234 else {
1235 mark_nonblock(f->fd);
1237 f->s = FCGI_READY;
1239 f->bev = bufferevent_new(f->fd, fcgi_read, fcgi_write,
1240 fcgi_error, f);
1241 if (f->bev == NULL) {
1242 close(f->fd);
1243 log_err(NULL, "%s: failed to allocate client buffer",
1244 __func__);
1245 f->s = FCGI_OFF;
1248 bufferevent_enable(f->bev, EV_READ|EV_WRITE);
1251 for (i = 0; i < MAX_USERS; ++i) {
1252 c = &clients[i];
1253 if (c->fd == -1)
1254 continue;
1255 if (c->fcgi != id)
1256 continue;
1258 if (f->s == FCGI_OFF) {
1259 c->fcgi = -1;
1260 start_reply(c, TEMP_FAILURE, "internal server error");
1261 } else
1262 fcgi_req(f, c);
1266 static void
1267 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1269 size_t i;
1271 (void)imsg;
1272 (void)len;
1275 * don't call event_loopbreak since we want to finish to
1276 * handle the ongoing connections.
1279 shutting_down = 1;
1281 event_del(&e4);
1282 if (has_ipv6)
1283 event_del(&e6);
1284 if (has_siginfo)
1285 signal_del(&siginfo);
1286 event_del(&imsgev);
1287 signal_del(&sigusr2);
1289 for (i = 0; i < FCGI_MAX; ++i) {
1290 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
1291 break;
1293 if (fcgi[i].bev == NULL || fcgi[i].pending != 0)
1294 continue;
1296 fcgi_close_backend(&fcgi[i]);
1300 static void
1301 handle_dispatch_imsg(int fd, short ev, void *d)
1303 struct imsgbuf *ibuf = d;
1304 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1307 static void
1308 handle_siginfo(int fd, short ev, void *d)
1310 (void)fd;
1311 (void)ev;
1312 (void)d;
1314 log_info(NULL, "%d connected clients", connected_clients);
1317 void
1318 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1320 size_t i;
1322 ctx = ctx_;
1324 event_init();
1326 memset(&clients, 0, sizeof(clients));
1327 for (i = 0; i < MAX_USERS; ++i)
1328 clients[i].fd = -1;
1330 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1331 event_add(&e4, NULL);
1333 if (sock6 != -1) {
1334 has_ipv6 = 1;
1335 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1336 event_add(&e6, NULL);
1339 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1340 event_add(&imsgev, NULL);
1342 #ifdef SIGINFO
1343 has_siginfo = 1;
1344 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1345 signal_add(&siginfo, NULL);
1346 #endif
1347 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1348 signal_add(&sigusr2, NULL);
1350 sandbox_server_process();
1351 event_dispatch();
1352 _exit(0);