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 flags, 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 flags = O_RDONLY | O_NOFOLLOW;
336 if (*fd == -1 && (*fd = openat(dirfd, p, flags)) == -1)
337 return FILE_MISSING;
339 if (fstat(*fd, &sb) == -1) {
340 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
341 return FILE_MISSING;
344 if (S_ISDIR(sb.st_mode))
345 return FILE_DIRECTORY;
347 if (sb.st_mode & S_IXUSR)
348 return FILE_EXECUTABLE;
350 return FILE_EXISTS;
353 static void
354 open_file(struct client *c)
356 switch (check_path(c, c->iri.path, &c->pfd)) {
357 case FILE_EXECUTABLE:
358 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
359 start_cgi(c->iri.path, "", c);
360 return;
363 /* fallthrough */
365 case FILE_EXISTS:
366 c->next = handle_copy;
367 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
368 return;
370 case FILE_DIRECTORY:
371 open_dir(c);
372 return;
374 case FILE_MISSING:
375 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
376 check_for_cgi(c);
377 return;
379 start_reply(c, NOT_FOUND, "not found");
380 return;
382 default:
383 /* unreachable */
384 abort();
388 /*
389 * the inverse of this algorithm, i.e. starting from the start of the
390 * path + strlen(cgi), and checking if each component, should be
391 * faster. But it's tedious to write. This does the opposite: starts
392 * from the end and strip one component at a time, until either an
393 * executable is found or we emptied the path.
394 */
395 static void
396 check_for_cgi(struct client *c)
398 char path[PATH_MAX];
399 char *end;
401 strlcpy(path, c->iri.path, sizeof(path));
402 end = strchr(path, '\0');
404 while (end > path) {
405 /*
406 * go up one level. UNIX paths are simple and POSIX
407 * dirname, with its ambiguities on if the given
408 * pointer is changed or not, gives me headaches.
409 */
410 while (*end != '/')
411 end--;
412 *end = '\0';
414 switch (check_path(c, path, &c->pfd)) {
415 case FILE_EXECUTABLE:
416 start_cgi(path, end+1, c);
417 return;
418 case FILE_MISSING:
419 break;
420 default:
421 goto err;
424 *end = '/';
425 end--;
428 err:
429 start_reply(c, NOT_FOUND, "not found");
430 return;
433 void
434 mark_nonblock(int fd)
436 int flags;
438 if ((flags = fcntl(fd, F_GETFL)) == -1)
439 fatal("fcntl(F_GETFL): %s", strerror(errno));
440 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
441 fatal("fcntl(F_SETFL): %s", strerror(errno));
444 static void
445 handle_handshake(int fd, short ev, void *d)
447 struct client *c = d;
448 struct vhost *h;
449 struct alist *a;
450 const char *servname;
451 const char *parse_err = "unknown error";
453 switch (tls_handshake(c->ctx)) {
454 case 0: /* success */
455 case -1: /* already handshaked */
456 break;
457 case TLS_WANT_POLLIN:
458 yield_read(fd, c, &handle_handshake);
459 return;
460 case TLS_WANT_POLLOUT:
461 yield_write(fd, c, &handle_handshake);
462 return;
463 default:
464 /* unreachable */
465 abort();
468 servname = tls_conn_servername(c->ctx);
469 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
470 log_info(c, "puny_decode: %s", parse_err);
471 goto err;
474 TAILQ_FOREACH(h, &hosts, vhosts) {
475 if (matches(h->domain, c->domain))
476 goto found;
477 TAILQ_FOREACH(a, &h->aliases, aliases) {
478 if (matches(a->alias, c->domain))
479 goto found;
483 found:
484 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
485 servname != NULL ? servname : "(null)",
486 c->domain,
487 h != NULL ? h->domain : "(null)");
489 if (h != NULL) {
490 c->host = h;
491 handle_open_conn(fd, ev, c);
492 return;
495 err:
496 if (servname != NULL)
497 strlcpy(c->req, servname, sizeof(c->req));
498 else
499 strlcpy(c->req, "null", sizeof(c->req));
501 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
504 static const char *
505 strip_path(const char *path, int strip)
507 char *t;
509 while (strip > 0) {
510 if ((t = strchr(path, '/')) == NULL) {
511 path = strchr(path, '\0');
512 break;
514 path = t;
515 strip--;
518 return path;
521 static void
522 fmt_sbuf(const char *fmt, struct client *c, const char *path)
524 size_t i;
525 char buf[32];
527 memset(buf, 0, sizeof(buf));
528 for (i = 0; *fmt; ++fmt) {
529 if (i == sizeof(buf)-1 || *fmt == '%') {
530 strlcat(c->sbuf, buf, sizeof(c->sbuf));
531 memset(buf, 0, sizeof(buf));
532 i = 0;
535 if (*fmt != '%') {
536 buf[i++] = *fmt;
537 continue;
540 switch (*++fmt) {
541 case '%':
542 strlcat(c->sbuf, "%", sizeof(c->sbuf));
543 break;
544 case 'p':
545 if (*path != '/')
546 strlcat(c->sbuf, "/", sizeof(c->sbuf));
547 strlcat(c->sbuf, path, sizeof(c->sbuf));
548 break;
549 case 'q':
550 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
551 break;
552 case 'P':
553 snprintf(buf, sizeof(buf), "%d", conf.port);
554 strlcat(c->sbuf, buf, sizeof(c->sbuf));
555 memset(buf, 0, sizeof(buf));
556 break;
557 case 'N':
558 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
559 break;
560 default:
561 fatal("%s: unknown fmt specifier %c",
562 __func__, *fmt);
566 if (i != 0)
567 strlcat(c->sbuf, buf, sizeof(c->sbuf));
570 /* 1 if a matching `block return' (and apply it), 0 otherwise */
571 static int
572 apply_block_return(struct client *c)
574 const char *fmt, *path;
575 int code;
577 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
578 return 0;
580 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
581 fmt_sbuf(fmt, c, path);
583 start_reply(c, code, c->sbuf);
584 return 1;
587 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
588 static int
589 apply_fastcgi(struct client *c)
591 int id;
592 struct fcgi *f;
594 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
595 return 0;
597 switch ((f = &fcgi[id])->s) {
598 case FCGI_OFF:
599 f->s = FCGI_INFLIGHT;
600 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
601 f->path, f->port, f->prog);
602 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
603 &id, sizeof(id));
604 imsg_flush(&exibuf);
605 /* fallthrough */
606 case FCGI_INFLIGHT:
607 c->fcgi = id;
608 break;
609 case FCGI_READY:
610 c->fcgi = id;
611 send_fcgi_req(f, c);
612 break;
615 return 1;
618 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
619 static int
620 apply_require_ca(struct client *c)
622 X509_STORE *store;
623 const uint8_t *cert;
624 size_t len;
626 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
627 return 0;
629 if (!tls_peer_cert_provided(c->ctx)) {
630 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
631 return 1;
634 cert = tls_peer_cert_chain_pem(c->ctx, &len);
635 if (!validate_against_ca(store, cert, len)) {
636 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
637 return 1;
640 return 0;
643 static void
644 handle_open_conn(int fd, short ev, void *d)
646 struct client *c = d;
647 const char *parse_err = "invalid request";
648 char decoded[DOMAIN_NAME_LEN];
650 bzero(c->req, sizeof(c->req));
651 bzero(&c->iri, sizeof(c->iri));
653 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
654 case -1:
655 log_err(c, "tls_read: %s", tls_error(c->ctx));
656 close_conn(fd, ev, c);
657 return;
659 case TLS_WANT_POLLIN:
660 yield_read(fd, c, &handle_open_conn);
661 return;
663 case TLS_WANT_POLLOUT:
664 yield_write(fd, c, &handle_open_conn);
665 return;
668 if (!trim_req_iri(c->req, &parse_err)
669 || !parse_iri(c->req, &c->iri, &parse_err)
670 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
671 log_info(c, "iri parse error: %s", parse_err);
672 start_reply(c, BAD_REQUEST, "invalid request");
673 return;
676 if (c->iri.port_no != conf.port
677 || strcmp(c->iri.schema, "gemini")
678 || strcmp(decoded, c->domain)) {
679 start_reply(c, PROXY_REFUSED, "won't proxy request");
680 return;
683 if (apply_require_ca(c))
684 return;
686 if (apply_block_return(c))
687 return;
689 if (apply_fastcgi(c))
690 return;
692 if (c->host->entrypoint != NULL) {
693 c->loc = 0;
694 start_cgi(c->host->entrypoint, c->iri.path, c);
695 return;
698 open_file(c);
701 void
702 start_reply(struct client *c, int code, const char *meta)
704 c->code = code;
705 c->meta = meta;
706 handle_start_reply(c->fd, 0, c);
709 static void
710 handle_start_reply(int fd, short ev, void *d)
712 struct client *c = d;
713 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
714 const char *lang;
715 size_t len;
717 lang = vhost_lang(c->host, c->iri.path);
719 snprintf(buf, sizeof(buf), "%d ", c->code);
720 strlcat(buf, c->meta, sizeof(buf));
721 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
722 strlcat(buf, "; lang=", sizeof(buf));
723 strlcat(buf, lang, sizeof(buf));
726 len = strlcat(buf, "\r\n", sizeof(buf));
727 assert(len < sizeof(buf));
729 switch (tls_write(c->ctx, buf, len)) {
730 case -1:
731 close_conn(fd, ev, c);
732 return;
733 case TLS_WANT_POLLIN:
734 yield_read(fd, c, &handle_start_reply);
735 return;
736 case TLS_WANT_POLLOUT:
737 yield_write(fd, c, &handle_start_reply);
738 return;
741 if (!vhost_disable_log(c->host, c->iri.path))
742 log_request(c, buf, sizeof(buf));
744 if (c->code != SUCCESS)
745 close_conn(fd, ev, c);
746 else
747 c->next(fd, ev, c);
750 static size_t
751 host_nth(struct vhost *h)
753 struct vhost *v;
754 size_t i = 0;
756 TAILQ_FOREACH(v, &hosts, vhosts) {
757 if (v == h)
758 return i;
759 i++;
762 abort();
765 static void
766 start_cgi(const char *spath, const char *relpath, struct client *c)
768 char addr[NI_MAXHOST];
769 const char *t;
770 struct cgireq req;
771 int e;
773 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
774 addr, sizeof(addr),
775 NULL, 0,
776 NI_NUMERICHOST);
777 if (e != 0)
778 fatal("getnameinfo failed");
780 memset(&req, 0, sizeof(req));
782 memcpy(req.buf, c->req, sizeof(req.buf));
784 req.iri_schema_off = c->iri.schema - c->req;
785 req.iri_host_off = c->iri.host - c->req;
786 req.iri_port_off = c->iri.port - c->req;
787 req.iri_path_off = c->iri.path - c->req;
788 req.iri_query_off = c->iri.query - c->req;
789 req.iri_fragment_off = c->iri.fragment - c->req;
791 req.iri_portno = c->iri.port_no;
793 strlcpy(req.spath, spath, sizeof(req.spath));
794 strlcpy(req.relpath, relpath, sizeof(req.relpath));
795 strlcpy(req.addr, addr, sizeof(req.addr));
797 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
798 strlcpy(req.subject, t, sizeof(req.subject));
799 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
800 strlcpy(req.issuer, t, sizeof(req.issuer));
801 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
802 strlcpy(req.hash, t, sizeof(req.hash));
803 if ((t = tls_conn_version(c->ctx)) != NULL)
804 strlcpy(req.version, t, sizeof(req.version));
805 if ((t = tls_conn_cipher(c->ctx)) != NULL)
806 strlcpy(req.cipher, t, sizeof(req.cipher));
808 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
809 req.notbefore = tls_peer_cert_notbefore(c->ctx);
810 req.notafter = tls_peer_cert_notafter(c->ctx);
812 req.host_off = host_nth(c->host);
813 req.loc_off = c->loc;
815 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
816 imsg_flush(&exibuf);
818 close(c->pfd);
821 static void
822 open_dir(struct client *c)
824 size_t len;
825 int dirfd, root;
826 char *before_file;
828 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
830 len = strlen(c->iri.path);
831 if (len > 0 && !ends_with(c->iri.path, "/")) {
832 redirect_canonical_dir(c);
833 return;
836 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
837 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
838 if (!ends_with(c->sbuf, "/"))
839 strlcat(c->sbuf, "/", sizeof(c->sbuf));
840 before_file = strchr(c->sbuf, '\0');
841 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
842 sizeof(c->sbuf));
843 if (len >= sizeof(c->sbuf)) {
844 start_reply(c, TEMP_FAILURE, "internal server error");
845 return;
848 c->iri.path = c->sbuf;
850 /* close later unless we have to generate the dir listing */
851 dirfd = c->pfd;
852 c->pfd = -1;
854 switch (check_path(c, c->iri.path, &c->pfd)) {
855 case FILE_EXECUTABLE:
856 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
857 start_cgi(c->iri.path, "", c);
858 break;
861 /* fallthrough */
863 case FILE_EXISTS:
864 c->next = handle_copy;
865 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
866 break;
868 case FILE_DIRECTORY:
869 start_reply(c, TEMP_REDIRECT, c->sbuf);
870 break;
872 case FILE_MISSING:
873 *before_file = '\0';
875 if (!vhost_auto_index(c->host, c->iri.path)) {
876 start_reply(c, NOT_FOUND, "not found");
877 break;
880 c->next = enter_handle_dirlist;
882 c->dirlen = scandir_fd(dirfd, &c->dir,
883 root ? select_non_dotdot : select_non_dot,
884 alphasort);
885 if (c->dirlen == -1) {
886 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
887 c->pfd, c->host->domain, c->iri.path, strerror(errno));
888 start_reply(c, TEMP_FAILURE, "internal server error");
889 return;
891 c->diroff = 0;
892 c->off = 0;
894 start_reply(c, SUCCESS, "text/gemini");
895 return;
897 default:
898 /* unreachable */
899 abort();
902 close(dirfd);
905 static void
906 redirect_canonical_dir(struct client *c)
908 size_t len;
910 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
911 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
912 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
914 if (len >= sizeof(c->sbuf)) {
915 start_reply(c, TEMP_FAILURE, "internal server error");
916 return;
919 start_reply(c, TEMP_REDIRECT, c->sbuf);
922 static void
923 enter_handle_dirlist(int fd, short ev, void *d)
925 struct client *c = d;
926 char b[PATH_MAX];
927 size_t l;
929 strlcpy(b, c->iri.path, sizeof(b));
930 l = snprintf(c->sbuf, sizeof(c->sbuf),
931 "# Index of %s\n\n", b);
932 if (l >= sizeof(c->sbuf)) {
933 /* this is impossible, given that we have enough space
934 * in c->sbuf to hold the ancilliary string plus the
935 * full path; but it wouldn't read nice without some
936 * error checking, and I'd like to avoid a strlen. */
937 close_conn(fd, ev, c);
938 return;
941 c->len = l;
942 handle_dirlist(fd, ev, c);
945 static void
946 handle_dirlist(int fd, short ev, void *d)
948 struct client *c = d;
949 ssize_t r;
951 while (c->len > 0) {
952 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
953 case -1:
954 close_conn(fd, ev, c);
955 return;
956 case TLS_WANT_POLLOUT:
957 yield_read(fd, c, &handle_dirlist);
958 return;
959 case TLS_WANT_POLLIN:
960 yield_write(fd, c, &handle_dirlist);
961 return;
962 default:
963 c->off += r;
964 c->len -= r;
968 send_directory_listing(fd, ev, c);
971 static int
972 read_next_dir_entry(struct client *c)
974 if (c->diroff == c->dirlen)
975 return 0;
977 /* XXX: url escape */
978 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
979 c->dir[c->diroff]->d_name);
981 free(c->dir[c->diroff]);
982 c->diroff++;
984 c->len = strlen(c->sbuf);
985 c->off = 0;
986 return 1;
989 static void
990 send_directory_listing(int fd, short ev, void *d)
992 struct client *c = d;
993 ssize_t r;
995 while (1) {
996 if (c->len == 0) {
997 if (!read_next_dir_entry(c))
998 goto end;
1001 while (c->len > 0) {
1002 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1003 case -1:
1004 goto end;
1006 case TLS_WANT_POLLOUT:
1007 yield_read(fd, c, &send_directory_listing);
1008 return;
1010 case TLS_WANT_POLLIN:
1011 yield_write(fd, c, &send_directory_listing);
1012 return;
1014 default:
1015 c->off += r;
1016 c->len -= r;
1017 break;
1022 end:
1023 close_conn(fd, ev, d);
1026 /* accumulate the meta line from the cgi script. */
1027 static void
1028 handle_cgi_reply(int fd, short ev, void *d)
1030 struct client *c = d;
1031 void *buf, *e;
1032 size_t len;
1033 ssize_t r;
1036 buf = c->sbuf + c->len;
1037 len = sizeof(c->sbuf) - c->len;
1039 r = read(c->pfd, buf, len);
1040 if (r == 0 || r == -1) {
1041 start_reply(c, CGI_ERROR, "CGI error");
1042 return;
1045 c->len += r;
1047 /* TODO: error if the CGI script don't reply correctly */
1048 e = strchr(c->sbuf, '\n');
1049 if (e != NULL || c->len == sizeof(c->sbuf)) {
1050 log_request(c, c->sbuf, c->len);
1052 c->off = 0;
1053 handle_copy(fd, ev, c);
1054 return;
1057 yield_read(fd, c, &handle_cgi_reply);
1060 static void
1061 handle_copy(int fd, short ev, void *d)
1063 struct client *c = d;
1064 ssize_t r;
1066 while (1) {
1067 while (c->len > 0) {
1068 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1069 case -1:
1070 goto end;
1072 case TLS_WANT_POLLOUT:
1073 yield_write(c->fd, c, &handle_copy);
1074 return;
1076 case TLS_WANT_POLLIN:
1077 yield_read(c->fd, c, &handle_copy);
1078 return;
1080 default:
1081 c->off += r;
1082 c->len -= r;
1083 break;
1087 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1088 case 0:
1089 goto end;
1090 case -1:
1091 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1092 yield_read(c->pfd, c, &handle_copy);
1093 return;
1095 goto end;
1096 default:
1097 c->len = r;
1098 c->off = 0;
1102 end:
1103 close_conn(c->fd, ev, d);
1106 void
1107 close_conn(int fd, short ev, void *d)
1109 struct client *c = d;
1110 struct mbuf *mbuf;
1112 switch (tls_close(c->ctx)) {
1113 case TLS_WANT_POLLIN:
1114 yield_read(c->fd, c, &close_conn);
1115 return;
1116 case TLS_WANT_POLLOUT:
1117 yield_read(c->fd, c, &close_conn);
1118 return;
1121 connected_clients--;
1123 while ((mbuf = TAILQ_FIRST(&c->mbufhead)) != NULL) {
1124 TAILQ_REMOVE(&c->mbufhead, mbuf, mbufs);
1125 free(mbuf);
1128 tls_free(c->ctx);
1129 c->ctx = NULL;
1131 if (c->pfd != -1)
1132 close(c->pfd);
1134 if (c->dir != NULL)
1135 free(c->dir);
1137 close(c->fd);
1138 c->fd = -1;
1141 static void
1142 do_accept(int sock, short et, void *d)
1144 struct client *c;
1145 struct sockaddr_storage addr;
1146 struct sockaddr *saddr;
1147 socklen_t len;
1148 int i, fd;
1150 (void)et;
1152 saddr = (struct sockaddr*)&addr;
1153 len = sizeof(addr);
1154 if ((fd = accept(sock, saddr, &len)) == -1) {
1155 if (errno == EWOULDBLOCK || errno == EAGAIN)
1156 return;
1157 fatal("accept: %s", strerror(errno));
1160 mark_nonblock(fd);
1162 for (i = 0; i < MAX_USERS; ++i) {
1163 c = &clients[i];
1164 if (c->fd == -1) {
1165 memset(c, 0, sizeof(*c));
1166 c->id = i;
1167 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1168 break; /* goodbye fd! */
1170 c->fd = fd;
1171 c->pfd = -1;
1172 c->dir = NULL;
1173 c->addr = addr;
1174 c->fcgi = -1;
1176 yield_read(fd, c, &handle_handshake);
1177 connected_clients++;
1178 return;
1182 close(fd);
1185 static struct client *
1186 client_by_id(int id)
1188 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1189 fatal("in client_by_id: invalid id %d", id);
1190 return &clients[id];
1193 struct client *
1194 try_client_by_id(int id)
1196 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1197 return NULL;
1198 return &clients[id];
1201 static void
1202 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1204 struct client *c;
1206 c = client_by_id(imsg->hdr.peerid);
1208 if ((c->pfd = imsg->fd) == -1)
1209 start_reply(c, TEMP_FAILURE, "internal server error");
1210 else
1211 yield_read(c->pfd, c, &handle_cgi_reply);
1214 static void
1215 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1217 struct client *c;
1218 struct fcgi *f;
1219 int i, id;
1221 id = imsg->hdr.peerid;
1222 f = &fcgi[id];
1224 if ((f->fd = imsg->fd) != -1) {
1225 f->s = FCGI_READY;
1226 event_set(&f->e, imsg->fd, EV_READ | EV_PERSIST, &handle_fcgi,
1227 &fcgi[id]);
1228 event_add(&f->e, NULL);
1229 } else {
1230 f->s = FCGI_OFF;
1233 for (i = 0; i < MAX_USERS; ++i) {
1234 c = &clients[i];
1235 if (c->fd == -1)
1236 continue;
1237 if (c->fcgi != id)
1238 continue;
1240 if (f->fd == -1) {
1241 c->fcgi = -1;
1242 start_reply(c, TEMP_FAILURE, "internal server error");
1243 } else
1244 send_fcgi_req(f, c);
1248 static void
1249 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1251 size_t i;
1253 (void)imsg;
1254 (void)len;
1256 /* don't call event_loopbreak since we want to finish to
1257 * handle the ongoing connections. */
1259 shutting_down = 1;
1261 event_del(&e4);
1262 if (has_ipv6)
1263 event_del(&e6);
1264 if (has_siginfo)
1265 signal_del(&siginfo);
1266 event_del(&imsgev);
1267 signal_del(&sigusr2);
1269 for (i = 0; i < FCGI_MAX; ++i) {
1270 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
1271 break;
1273 if (!event_pending(&fcgi[i].e, EV_READ, NULL) ||
1274 fcgi[i].pending != 0)
1275 continue;
1277 fcgi_close_backend(&fcgi[i]);
1281 static void
1282 handle_dispatch_imsg(int fd, short ev, void *d)
1284 struct imsgbuf *ibuf = d;
1285 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1288 static void
1289 handle_siginfo(int fd, short ev, void *d)
1291 (void)fd;
1292 (void)ev;
1293 (void)d;
1295 log_info(NULL, "%d connected clients", connected_clients);
1298 void
1299 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1301 size_t i;
1303 ctx = ctx_;
1305 event_init();
1307 memset(&clients, 0, sizeof(clients));
1308 for (i = 0; i < MAX_USERS; ++i)
1309 clients[i].fd = -1;
1311 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1312 event_add(&e4, NULL);
1314 if (sock6 != -1) {
1315 has_ipv6 = 1;
1316 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1317 event_add(&e6, NULL);
1320 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1321 event_add(&imsgev, NULL);
1323 #ifdef SIGINFO
1324 has_siginfo = 1;
1325 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1326 signal_add(&siginfo, NULL);
1327 #endif
1328 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1329 signal_add(&sigusr2, NULL);
1331 sandbox_server_process();
1332 event_dispatch();
1333 _exit(0);