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 struct client clients[MAX_USERS];
31 static struct tls *ctx;
33 static struct event e4, e6, imsgev, siginfo, sigusr2;
34 static int has_ipv6, has_siginfo;
36 int connected_clients;
38 static inline int matches(const char*, const char*);
40 static inline void yield_read(int, struct client*, statefn);
41 static inline void yield_write(int, struct client*, statefn);
43 static int check_path(struct client*, const char*, int*);
44 static void open_file(struct client*);
45 static void check_for_cgi(struct client*);
46 static void handle_handshake(int, short, void*);
47 static const char *strip_path(const char*, int);
48 static void fmt_sbuf(const char*, struct client*, const char*);
49 static int apply_block_return(struct client*);
50 static int apply_require_ca(struct client*);
51 static void handle_open_conn(int, short, void*);
52 static void handle_start_reply(int, short, void*);
53 static size_t host_nth(struct vhost*);
54 static void start_cgi(const char*, const char*, struct client*);
55 static void open_dir(struct client*);
56 static void redirect_canonical_dir(struct client*);
57 static void enter_handle_dirlist(int, short, void*);
58 static void handle_dirlist(int, short, void*);
59 static int read_next_dir_entry(struct client*);
60 static void send_directory_listing(int, short, void*);
61 static void handle_cgi_reply(int, short, void*);
62 static void handle_copy(int, short, void*);
63 static void do_accept(int, short, void*);
64 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
65 static void handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
66 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
67 static void handle_siginfo(int, short, void*);
69 static imsg_handlerfn *handlers[] = {
70 [IMSG_QUIT] = handle_imsg_quit,
71 [IMSG_CGI_RES] = handle_imsg_cgi_res,
72 [IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
73 };
75 static inline int
76 matches(const char *pattern, const char *path)
77 {
78 if (*path == '/')
79 path++;
80 return !fnmatch(pattern, path, 0);
81 }
83 static inline void
84 yield_read(int fd, struct client *c, statefn fn)
85 {
86 event_once(fd, EV_READ, fn, c, NULL);
87 }
89 static inline void
90 yield_write(int fd, struct client *c, statefn fn)
91 {
92 event_once(fd, EV_WRITE, fn, c, NULL);
93 }
95 const char *
96 vhost_lang(struct vhost *v, const char *path)
97 {
98 struct location *loc;
100 if (v == NULL || path == NULL)
101 return NULL;
103 loc = TAILQ_FIRST(&v->locations);
104 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
105 if (loc->lang != NULL) {
106 if (matches(loc->match, path))
107 return loc->lang;
111 return TAILQ_FIRST(&v->locations)->lang;
114 const char *
115 vhost_default_mime(struct vhost *v, const char *path)
117 struct location *loc;
118 const char *default_mime = "application/octet-stream";
120 if (v == NULL || path == NULL)
121 return default_mime;
123 loc = TAILQ_FIRST(&v->locations);
124 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
125 if (loc->default_mime != NULL) {
126 if (matches(loc->match, path))
127 return loc->default_mime;
131 loc = TAILQ_FIRST(&v->locations);
132 if (loc->default_mime != NULL)
133 return loc->default_mime;
134 return default_mime;
137 const char *
138 vhost_index(struct vhost *v, const char *path)
140 struct location *loc;
141 const char *index = "index.gmi";
143 if (v == NULL || path == NULL)
144 return index;
146 loc = TAILQ_FIRST(&v->locations);
147 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
148 if (loc->index != NULL) {
149 if (matches(loc->match, path))
150 return loc->index;
154 loc = TAILQ_FIRST(&v->locations);
155 if (loc->index != NULL)
156 return loc->index;
157 return index;
160 int
161 vhost_auto_index(struct vhost *v, const char *path)
163 struct location *loc;
165 if (v == NULL || path == NULL)
166 return 0;
168 loc = TAILQ_FIRST(&v->locations);
169 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
170 if (loc->auto_index != 0) {
171 if (matches(loc->match, path))
172 return loc->auto_index == 1;
176 loc = TAILQ_FIRST(&v->locations);
177 return loc->auto_index == 1;
180 int
181 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
183 struct location *loc;
185 if (v == NULL || path == NULL)
186 return 0;
188 loc = TAILQ_FIRST(&v->locations);
189 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
190 if (loc->block_code != 0) {
191 if (matches(loc->match, path)) {
192 *code = loc->block_code;
193 *fmt = loc->block_fmt;
194 return 1;
199 loc = TAILQ_FIRST(&v->locations);
200 *code = loc->block_code;
201 *fmt = loc->block_fmt;
202 return loc->block_code != 0;
205 int
206 vhost_fastcgi(struct vhost *v, const char *path)
208 struct location *loc;
210 if (v == NULL || path == NULL)
211 return -1;
213 loc = TAILQ_FIRST(&v->locations);
214 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
215 if (loc->fcgi != -1)
216 if (matches(loc->match, path))
217 return loc->fcgi;
220 loc = TAILQ_FIRST(&v->locations);
221 return loc->fcgi;
224 int
225 vhost_dirfd(struct vhost *v, const char *path)
227 struct location *loc;
229 if (v == NULL || path == NULL)
230 return -1;
232 loc = TAILQ_FIRST(&v->locations);
233 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
234 if (loc->dirfd != -1)
235 if (matches(loc->match, path))
236 return loc->dirfd;
239 loc = TAILQ_FIRST(&v->locations);
240 return loc->dirfd;
243 int
244 vhost_strip(struct vhost *v, const char *path)
246 struct location *loc;
248 if (v == NULL || path == NULL)
249 return 0;
251 loc = TAILQ_FIRST(&v->locations);
252 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
253 if (loc->strip != 0) {
254 if (matches(loc->match, path))
255 return loc->strip;
259 loc = TAILQ_FIRST(&v->locations);
260 return loc->strip;
263 X509_STORE *
264 vhost_require_ca(struct vhost *v, const char *path)
266 struct location *loc;
268 if (v == NULL || path == NULL)
269 return NULL;
271 loc = TAILQ_FIRST(&v->locations);
272 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
273 if (loc->reqca != NULL) {
274 if (matches(loc->match, path))
275 return loc->reqca;
279 loc = TAILQ_FIRST(&v->locations);
280 return loc->reqca;
283 int
284 vhost_disable_log(struct vhost *v, const char *path)
286 struct location *loc;
288 if (v == NULL || path == NULL)
289 return 0;
291 loc = TAILQ_FIRST(&v->locations);
292 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
293 if (loc->disable_log && matches(loc->match, path))
294 return 1;
297 loc = TAILQ_FIRST(&v->locations);
298 return loc->disable_log;
301 static int
302 check_path(struct client *c, const char *path, int *fd)
304 struct stat sb;
305 const char *p;
306 int flags, dirfd, strip;
308 assert(path != NULL);
310 /*
311 * in send_dir we add an initial / (to be redirect-friendly),
312 * but here we want to skip it
313 */
314 if (*path == '/')
315 path++;
317 strip = vhost_strip(c->host, path);
318 p = strip_path(path, strip);
320 if (*p == '/')
321 p = p+1;
322 if (*p == '\0')
323 p = ".";
325 dirfd = vhost_dirfd(c->host, path);
326 log_debug(c, "check_path: strip=%d path=%s original=%s",
327 strip, p, path);
328 flags = O_RDONLY | O_NOFOLLOW;
329 if (*fd == -1 && (*fd = openat(dirfd, p, flags)) == -1)
330 return FILE_MISSING;
332 if (fstat(*fd, &sb) == -1) {
333 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
334 return FILE_MISSING;
337 if (S_ISDIR(sb.st_mode))
338 return FILE_DIRECTORY;
340 if (sb.st_mode & S_IXUSR)
341 return FILE_EXECUTABLE;
343 return FILE_EXISTS;
346 static void
347 open_file(struct client *c)
349 switch (check_path(c, c->iri.path, &c->pfd)) {
350 case FILE_EXECUTABLE:
351 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
352 start_cgi(c->iri.path, "", c);
353 return;
356 /* fallthrough */
358 case FILE_EXISTS:
359 c->next = handle_copy;
360 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
361 return;
363 case FILE_DIRECTORY:
364 open_dir(c);
365 return;
367 case FILE_MISSING:
368 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
369 check_for_cgi(c);
370 return;
372 start_reply(c, NOT_FOUND, "not found");
373 return;
375 default:
376 /* unreachable */
377 abort();
381 /*
382 * the inverse of this algorithm, i.e. starting from the start of the
383 * path + strlen(cgi), and checking if each component, should be
384 * faster. But it's tedious to write. This does the opposite: starts
385 * from the end and strip one component at a time, until either an
386 * executable is found or we emptied the path.
387 */
388 static void
389 check_for_cgi(struct client *c)
391 char path[PATH_MAX];
392 char *end;
394 strlcpy(path, c->iri.path, sizeof(path));
395 end = strchr(path, '\0');
397 while (end > path) {
398 /*
399 * go up one level. UNIX paths are simple and POSIX
400 * dirname, with its ambiguities on if the given
401 * pointer is changed or not, gives me headaches.
402 */
403 while (*end != '/')
404 end--;
405 *end = '\0';
407 switch (check_path(c, path, &c->pfd)) {
408 case FILE_EXECUTABLE:
409 start_cgi(path, end+1, c);
410 return;
411 case FILE_MISSING:
412 break;
413 default:
414 goto err;
417 *end = '/';
418 end--;
421 err:
422 start_reply(c, NOT_FOUND, "not found");
423 return;
426 void
427 mark_nonblock(int fd)
429 int flags;
431 if ((flags = fcntl(fd, F_GETFL)) == -1)
432 fatal("fcntl(F_GETFL): %s", strerror(errno));
433 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
434 fatal("fcntl(F_SETFL): %s", strerror(errno));
437 static void
438 handle_handshake(int fd, short ev, void *d)
440 struct client *c = d;
441 struct vhost *h;
442 struct alist *a;
443 const char *servname;
444 const char *parse_err = "unknown error";
446 switch (tls_handshake(c->ctx)) {
447 case 0: /* success */
448 case -1: /* already handshaked */
449 break;
450 case TLS_WANT_POLLIN:
451 yield_read(fd, c, &handle_handshake);
452 return;
453 case TLS_WANT_POLLOUT:
454 yield_write(fd, c, &handle_handshake);
455 return;
456 default:
457 /* unreachable */
458 abort();
461 servname = tls_conn_servername(c->ctx);
462 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
463 log_info(c, "puny_decode: %s", parse_err);
464 goto err;
467 TAILQ_FOREACH(h, &hosts, vhosts) {
468 if (matches(h->domain, c->domain))
469 goto found;
470 TAILQ_FOREACH(a, &h->aliases, aliases) {
471 if (matches(a->alias, c->domain))
472 goto found;
476 found:
477 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
478 servname != NULL ? servname : "(null)",
479 c->domain,
480 h != NULL ? h->domain : "(null)");
482 if (h != NULL) {
483 c->host = h;
484 handle_open_conn(fd, ev, c);
485 return;
488 err:
489 if (servname != NULL)
490 strncpy(c->req, servname, sizeof(c->req));
491 else
492 strncpy(c->req, "null", sizeof(c->req));
494 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
497 static const char *
498 strip_path(const char *path, int strip)
500 char *t;
502 while (strip > 0) {
503 if ((t = strchr(path, '/')) == NULL) {
504 path = strchr(path, '\0');
505 break;
507 path = t;
508 strip--;
511 return path;
514 static void
515 fmt_sbuf(const char *fmt, struct client *c, const char *path)
517 size_t i;
518 char buf[32];
520 memset(buf, 0, sizeof(buf));
521 for (i = 0; *fmt; ++fmt) {
522 if (i == sizeof(buf)-1 || *fmt == '%') {
523 strlcat(c->sbuf, buf, sizeof(c->sbuf));
524 memset(buf, 0, sizeof(buf));
525 i = 0;
528 if (*fmt != '%') {
529 buf[i++] = *fmt;
530 continue;
533 switch (*++fmt) {
534 case '%':
535 strlcat(c->sbuf, "%", sizeof(c->sbuf));
536 break;
537 case 'p':
538 if (*path != '/')
539 strlcat(c->sbuf, "/", sizeof(c->sbuf));
540 strlcat(c->sbuf, path, sizeof(c->sbuf));
541 break;
542 case 'q':
543 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
544 break;
545 case 'P':
546 snprintf(buf, sizeof(buf), "%d", conf.port);
547 strlcat(c->sbuf, buf, sizeof(c->sbuf));
548 memset(buf, 0, sizeof(buf));
549 break;
550 case 'N':
551 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
552 break;
553 default:
554 fatal("%s: unknown fmt specifier %c",
555 __func__, *fmt);
559 if (i != 0)
560 strlcat(c->sbuf, buf, sizeof(c->sbuf));
563 /* 1 if a matching `block return' (and apply it), 0 otherwise */
564 static int
565 apply_block_return(struct client *c)
567 const char *fmt, *path;
568 int code;
570 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
571 return 0;
573 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
574 fmt_sbuf(fmt, c, path);
576 start_reply(c, code, c->sbuf);
577 return 1;
580 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
581 static int
582 apply_fastcgi(struct client *c)
584 int id;
585 struct fcgi *f;
587 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
588 return 0;
590 switch ((f = &fcgi[id])->s) {
591 case FCGI_OFF:
592 f->s = FCGI_INFLIGHT;
593 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
594 f->path, f->port, f->prog);
595 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
596 &id, sizeof(id));
597 imsg_flush(&exibuf);
598 /* fallthrough */
599 case FCGI_INFLIGHT:
600 c->fcgi = id;
601 break;
602 case FCGI_READY:
603 c->fcgi = id;
604 send_fcgi_req(f, c);
605 break;
608 return 1;
611 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
612 static int
613 apply_require_ca(struct client *c)
615 X509_STORE *store;
616 const uint8_t *cert;
617 size_t len;
619 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
620 return 0;
622 if (!tls_peer_cert_provided(c->ctx)) {
623 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
624 return 1;
627 cert = tls_peer_cert_chain_pem(c->ctx, &len);
628 if (!validate_against_ca(store, cert, len)) {
629 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
630 return 1;
633 return 0;
636 static void
637 handle_open_conn(int fd, short ev, void *d)
639 struct client *c = d;
640 const char *parse_err = "invalid request";
641 char decoded[DOMAIN_NAME_LEN];
643 bzero(c->req, sizeof(c->req));
644 bzero(&c->iri, sizeof(c->iri));
646 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
647 case -1:
648 log_err(c, "tls_read: %s", tls_error(c->ctx));
649 close_conn(fd, ev, c);
650 return;
652 case TLS_WANT_POLLIN:
653 yield_read(fd, c, &handle_open_conn);
654 return;
656 case TLS_WANT_POLLOUT:
657 yield_write(fd, c, &handle_open_conn);
658 return;
661 if (!trim_req_iri(c->req, &parse_err)
662 || !parse_iri(c->req, &c->iri, &parse_err)
663 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
664 log_info(c, "iri parse error: %s", parse_err);
665 start_reply(c, BAD_REQUEST, "invalid request");
666 return;
669 if (c->iri.port_no != conf.port
670 || strcmp(c->iri.schema, "gemini")
671 || strcmp(decoded, c->domain)) {
672 start_reply(c, PROXY_REFUSED, "won't proxy request");
673 return;
676 if (apply_require_ca(c))
677 return;
679 if (apply_block_return(c))
680 return;
682 if (apply_fastcgi(c))
683 return;
685 if (c->host->entrypoint != NULL) {
686 start_cgi(c->host->entrypoint, c->iri.path, c);
687 return;
690 open_file(c);
693 void
694 start_reply(struct client *c, int code, const char *meta)
696 c->code = code;
697 c->meta = meta;
698 handle_start_reply(c->fd, 0, c);
701 static void
702 handle_start_reply(int fd, short ev, void *d)
704 struct client *c = d;
705 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
706 const char *lang;
707 size_t len;
709 lang = vhost_lang(c->host, c->iri.path);
711 snprintf(buf, sizeof(buf), "%d ", c->code);
712 strlcat(buf, c->meta, sizeof(buf));
713 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
714 strlcat(buf, "; lang=", sizeof(buf));
715 strlcat(buf, lang, sizeof(buf));
718 len = strlcat(buf, "\r\n", sizeof(buf));
719 assert(len < sizeof(buf));
721 switch (tls_write(c->ctx, buf, len)) {
722 case -1:
723 close_conn(fd, ev, c);
724 return;
725 case TLS_WANT_POLLIN:
726 yield_read(fd, c, &handle_start_reply);
727 return;
728 case TLS_WANT_POLLOUT:
729 yield_write(fd, c, &handle_start_reply);
730 return;
733 if (!vhost_disable_log(c->host, c->iri.path))
734 log_request(c, buf, sizeof(buf));
736 if (c->code != SUCCESS)
737 close_conn(fd, ev, c);
738 else
739 c->next(fd, ev, c);
742 static size_t
743 host_nth(struct vhost *h)
745 struct vhost *v;
746 size_t i = 0;
748 TAILQ_FOREACH(v, &hosts, vhosts) {
749 if (v == h)
750 return i;
751 i++;
754 abort();
757 static void
758 start_cgi(const char *spath, const char *relpath, struct client *c)
760 char addr[NI_MAXHOST];
761 const char *t;
762 struct cgireq req;
763 int e;
765 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
766 addr, sizeof(addr),
767 NULL, 0,
768 NI_NUMERICHOST);
769 if (e != 0)
770 fatal("getnameinfo failed");
772 memset(&req, 0, sizeof(req));
774 memcpy(req.buf, c->req, sizeof(req.buf));
776 req.iri_schema_off = c->iri.schema - c->req;
777 req.iri_host_off = c->iri.host - c->req;
778 req.iri_port_off = c->iri.port - c->req;
779 req.iri_path_off = c->iri.path - c->req;
780 req.iri_query_off = c->iri.query - c->req;
781 req.iri_fragment_off = c->iri.fragment - c->req;
783 req.iri_portno = c->iri.port_no;
785 strlcpy(req.spath, spath, sizeof(req.spath));
786 strlcpy(req.relpath, relpath, sizeof(req.relpath));
787 strlcpy(req.addr, addr, sizeof(req.addr));
789 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
790 strlcpy(req.subject, t, sizeof(req.subject));
791 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
792 strlcpy(req.issuer, t, sizeof(req.issuer));
793 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
794 strlcpy(req.hash, t, sizeof(req.hash));
795 if ((t = tls_conn_version(c->ctx)) != NULL)
796 strlcpy(req.version, t, sizeof(req.version));
797 if ((t = tls_conn_cipher(c->ctx)) != NULL)
798 strlcpy(req.cipher, t, sizeof(req.cipher));
800 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
801 req.notbefore = tls_peer_cert_notbefore(c->ctx);
802 req.notafter = tls_peer_cert_notafter(c->ctx);
804 req.host_off = host_nth(c->host);
806 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
807 imsg_flush(&exibuf);
809 close(c->pfd);
812 static void
813 open_dir(struct client *c)
815 size_t len;
816 int dirfd, root;
817 char *before_file;
819 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
821 len = strlen(c->iri.path);
822 if (len > 0 && !ends_with(c->iri.path, "/")) {
823 redirect_canonical_dir(c);
824 return;
827 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
828 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
829 if (!ends_with(c->sbuf, "/"))
830 strlcat(c->sbuf, "/", sizeof(c->sbuf));
831 before_file = strchr(c->sbuf, '\0');
832 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
833 sizeof(c->sbuf));
834 if (len >= sizeof(c->sbuf)) {
835 start_reply(c, TEMP_FAILURE, "internal server error");
836 return;
839 c->iri.path = c->sbuf;
841 /* close later unless we have to generate the dir listing */
842 dirfd = c->pfd;
843 c->pfd = -1;
845 switch (check_path(c, c->iri.path, &c->pfd)) {
846 case FILE_EXECUTABLE:
847 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
848 start_cgi(c->iri.path, "", c);
849 break;
852 /* fallthrough */
854 case FILE_EXISTS:
855 c->next = handle_copy;
856 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
857 break;
859 case FILE_DIRECTORY:
860 start_reply(c, TEMP_REDIRECT, c->sbuf);
861 break;
863 case FILE_MISSING:
864 *before_file = '\0';
866 if (!vhost_auto_index(c->host, c->iri.path)) {
867 start_reply(c, NOT_FOUND, "not found");
868 break;
871 c->next = enter_handle_dirlist;
873 c->dirlen = scandir_fd(dirfd, &c->dir,
874 root ? select_non_dotdot : select_non_dot,
875 alphasort);
876 if (c->dirlen == -1) {
877 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
878 c->pfd, c->host->domain, c->iri.path, strerror(errno));
879 start_reply(c, TEMP_FAILURE, "internal server error");
880 return;
882 c->diroff = 0;
883 c->off = 0;
885 start_reply(c, SUCCESS, "text/gemini");
886 return;
888 default:
889 /* unreachable */
890 abort();
893 close(dirfd);
896 static void
897 redirect_canonical_dir(struct client *c)
899 size_t len;
901 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
902 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
903 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
905 if (len >= sizeof(c->sbuf)) {
906 start_reply(c, TEMP_FAILURE, "internal server error");
907 return;
910 start_reply(c, TEMP_REDIRECT, c->sbuf);
913 static void
914 enter_handle_dirlist(int fd, short ev, void *d)
916 struct client *c = d;
917 char b[PATH_MAX];
918 size_t l;
920 strlcpy(b, c->iri.path, sizeof(b));
921 l = snprintf(c->sbuf, sizeof(c->sbuf),
922 "# Index of %s\n\n", b);
923 if (l >= sizeof(c->sbuf)) {
924 /* this is impossible, given that we have enough space
925 * in c->sbuf to hold the ancilliary string plus the
926 * full path; but it wouldn't read nice without some
927 * error checking, and I'd like to avoid a strlen. */
928 close_conn(fd, ev, c);
929 return;
932 c->len = l;
933 handle_dirlist(fd, ev, c);
936 static void
937 handle_dirlist(int fd, short ev, void *d)
939 struct client *c = d;
940 ssize_t r;
942 while (c->len > 0) {
943 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
944 case -1:
945 close_conn(fd, ev, c);
946 return;
947 case TLS_WANT_POLLOUT:
948 yield_read(fd, c, &handle_dirlist);
949 return;
950 case TLS_WANT_POLLIN:
951 yield_write(fd, c, &handle_dirlist);
952 return;
953 default:
954 c->off += r;
955 c->len -= r;
959 send_directory_listing(fd, ev, c);
962 static int
963 read_next_dir_entry(struct client *c)
965 if (c->diroff == c->dirlen)
966 return 0;
968 /* XXX: url escape */
969 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
970 c->dir[c->diroff]->d_name);
972 free(c->dir[c->diroff]);
973 c->diroff++;
975 c->len = strlen(c->sbuf);
976 c->off = 0;
977 return 1;
980 static void
981 send_directory_listing(int fd, short ev, void *d)
983 struct client *c = d;
984 ssize_t r;
986 while (1) {
987 if (c->len == 0) {
988 if (!read_next_dir_entry(c))
989 goto end;
992 while (c->len > 0) {
993 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
994 case -1:
995 goto end;
997 case TLS_WANT_POLLOUT:
998 yield_read(fd, c, &send_directory_listing);
999 return;
1001 case TLS_WANT_POLLIN:
1002 yield_write(fd, c, &send_directory_listing);
1003 return;
1005 default:
1006 c->off += r;
1007 c->len -= r;
1008 break;
1013 end:
1014 close_conn(fd, ev, d);
1017 /* accumulate the meta line from the cgi script. */
1018 static void
1019 handle_cgi_reply(int fd, short ev, void *d)
1021 struct client *c = d;
1022 void *buf, *e;
1023 size_t len;
1024 ssize_t r;
1027 buf = c->sbuf + c->len;
1028 len = sizeof(c->sbuf) - c->len;
1030 r = read(c->pfd, buf, len);
1031 if (r == 0 || r == -1) {
1032 start_reply(c, CGI_ERROR, "CGI error");
1033 return;
1036 c->len += r;
1038 /* TODO: error if the CGI script don't reply correctly */
1039 e = strchr(c->sbuf, '\n');
1040 if (e != NULL || c->len == sizeof(c->sbuf)) {
1041 log_request(c, c->sbuf, c->len);
1043 c->off = 0;
1044 handle_copy(fd, ev, c);
1045 return;
1048 yield_read(fd, c, &handle_cgi_reply);
1051 static void
1052 handle_copy(int fd, short ev, void *d)
1054 struct client *c = d;
1055 ssize_t r;
1057 while (1) {
1058 while (c->len > 0) {
1059 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1060 case -1:
1061 goto end;
1063 case TLS_WANT_POLLOUT:
1064 yield_write(c->fd, c, &handle_copy);
1065 return;
1067 case TLS_WANT_POLLIN:
1068 yield_read(c->fd, c, &handle_copy);
1069 return;
1071 default:
1072 c->off += r;
1073 c->len -= r;
1074 break;
1078 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1079 case 0:
1080 goto end;
1081 case -1:
1082 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1083 yield_read(c->pfd, c, &handle_copy);
1084 return;
1086 goto end;
1087 default:
1088 c->len = r;
1089 c->off = 0;
1093 end:
1094 close_conn(c->fd, ev, d);
1097 void
1098 close_conn(int fd, short ev, void *d)
1100 struct client *c = d;
1101 struct mbuf *mbuf;
1103 switch (tls_close(c->ctx)) {
1104 case TLS_WANT_POLLIN:
1105 yield_read(fd, c, &close_conn);
1106 return;
1107 case TLS_WANT_POLLOUT:
1108 yield_read(fd, c, &close_conn);
1109 return;
1112 connected_clients--;
1114 while ((mbuf = TAILQ_FIRST(&c->mbufhead)) != NULL) {
1115 TAILQ_REMOVE(&c->mbufhead, mbuf, mbufs);
1116 free(mbuf);
1119 tls_free(c->ctx);
1120 c->ctx = NULL;
1122 if (c->pfd != -1)
1123 close(c->pfd);
1125 if (c->dir != NULL)
1126 free(c->dir);
1128 close(c->fd);
1129 c->fd = -1;
1132 static void
1133 do_accept(int sock, short et, void *d)
1135 struct client *c;
1136 struct sockaddr_storage addr;
1137 struct sockaddr *saddr;
1138 socklen_t len;
1139 int i, fd;
1141 (void)et;
1143 saddr = (struct sockaddr*)&addr;
1144 len = sizeof(addr);
1145 if ((fd = accept(sock, saddr, &len)) == -1) {
1146 if (errno == EWOULDBLOCK || errno == EAGAIN)
1147 return;
1148 fatal("accept: %s", strerror(errno));
1151 mark_nonblock(fd);
1153 for (i = 0; i < MAX_USERS; ++i) {
1154 c = &clients[i];
1155 if (c->fd == -1) {
1156 memset(c, 0, sizeof(*c));
1157 c->id = i;
1158 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1159 break; /* goodbye fd! */
1161 c->fd = fd;
1162 c->pfd = -1;
1163 c->dir = NULL;
1164 c->addr = addr;
1165 c->fcgi = -1;
1167 yield_read(fd, c, &handle_handshake);
1168 connected_clients++;
1169 return;
1173 close(fd);
1176 static struct client *
1177 client_by_id(int id)
1179 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1180 fatal("in client_by_id: invalid id %d", id);
1181 return &clients[id];
1184 struct client *
1185 try_client_by_id(int id)
1187 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1188 return NULL;
1189 return &clients[id];
1192 static void
1193 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1195 struct client *c;
1197 c = client_by_id(imsg->hdr.peerid);
1199 if ((c->pfd = imsg->fd) == -1)
1200 start_reply(c, TEMP_FAILURE, "internal server error");
1201 else
1202 yield_read(c->pfd, c, &handle_cgi_reply);
1205 static void
1206 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1208 struct client *c;
1209 struct fcgi *f;
1210 int i, id;
1212 id = imsg->hdr.peerid;
1213 f = &fcgi[id];
1215 if ((f->fd = imsg->fd) != -1) {
1216 event_set(&f->e, imsg->fd, EV_READ | EV_PERSIST, &handle_fcgi,
1217 &fcgi[id]);
1218 event_add(&f->e, NULL);
1219 } else {
1220 f->s = FCGI_OFF;
1223 for (i = 0; i < MAX_USERS; ++i) {
1224 c = &clients[i];
1225 if (c->fd == -1)
1226 continue;
1227 if (c->fcgi != id)
1228 continue;
1230 if (f->fd == -1) {
1231 c->fcgi = -1;
1232 start_reply(c, TEMP_FAILURE, "internal server error");
1233 } else
1234 send_fcgi_req(f, c);
1238 static void
1239 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1241 (void)imsg;
1242 (void)len;
1244 /* don't call event_loopbreak since we want to finish to
1245 * handle the ongoing connections. */
1247 event_del(&e4);
1248 if (has_ipv6)
1249 event_del(&e6);
1250 if (has_siginfo)
1251 signal_del(&siginfo);
1252 event_del(&imsgev);
1253 signal_del(&sigusr2);
1256 static void
1257 handle_dispatch_imsg(int fd, short ev, void *d)
1259 struct imsgbuf *ibuf = d;
1260 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1263 static void
1264 handle_siginfo(int fd, short ev, void *d)
1266 (void)fd;
1267 (void)ev;
1268 (void)d;
1270 log_info(NULL, "%d connected clients", connected_clients);
1273 void
1274 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1276 size_t i;
1278 ctx = ctx_;
1280 event_init();
1282 memset(&clients, 0, sizeof(clients));
1283 for (i = 0; i < MAX_USERS; ++i)
1284 clients[i].fd = -1;
1286 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1287 event_add(&e4, NULL);
1289 if (sock6 != -1) {
1290 has_ipv6 = 1;
1291 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1292 event_add(&e6, NULL);
1295 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1296 event_add(&imsgev, NULL);
1298 #ifdef SIGINFO
1299 has_siginfo = 1;
1300 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1301 signal_add(&siginfo, NULL);
1302 #endif
1303 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1304 signal_add(&sigusr2, NULL);
1306 sandbox_server_process();
1307 event_dispatch();
1308 _exit(0);