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, size_t *retloc)
227 struct location *loc;
228 size_t l = 0;
230 if (v == NULL || path == NULL)
231 return -1;
233 loc = TAILQ_FIRST(&v->locations);
234 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
235 l++;
236 if (loc->dirfd != -1)
237 if (matches(loc->match, path)) {
238 *retloc = l;
239 return loc->dirfd;
243 *retloc = 0;
244 loc = TAILQ_FIRST(&v->locations);
245 return loc->dirfd;
248 int
249 vhost_strip(struct vhost *v, const char *path)
251 struct location *loc;
253 if (v == NULL || path == NULL)
254 return 0;
256 loc = TAILQ_FIRST(&v->locations);
257 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
258 if (loc->strip != 0) {
259 if (matches(loc->match, path))
260 return loc->strip;
264 loc = TAILQ_FIRST(&v->locations);
265 return loc->strip;
268 X509_STORE *
269 vhost_require_ca(struct vhost *v, const char *path)
271 struct location *loc;
273 if (v == NULL || path == NULL)
274 return NULL;
276 loc = TAILQ_FIRST(&v->locations);
277 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
278 if (loc->reqca != NULL) {
279 if (matches(loc->match, path))
280 return loc->reqca;
284 loc = TAILQ_FIRST(&v->locations);
285 return loc->reqca;
288 int
289 vhost_disable_log(struct vhost *v, const char *path)
291 struct location *loc;
293 if (v == NULL || path == NULL)
294 return 0;
296 loc = TAILQ_FIRST(&v->locations);
297 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
298 if (loc->disable_log && matches(loc->match, path))
299 return 1;
302 loc = TAILQ_FIRST(&v->locations);
303 return loc->disable_log;
306 static int
307 check_path(struct client *c, const char *path, int *fd)
309 struct stat sb;
310 const char *p;
311 int flags, dirfd, strip;
313 assert(path != NULL);
315 /*
316 * in send_dir we add an initial / (to be redirect-friendly),
317 * but here we want to skip it
318 */
319 if (*path == '/')
320 path++;
322 strip = vhost_strip(c->host, path);
323 p = strip_path(path, strip);
325 if (*p == '/')
326 p = p+1;
327 if (*p == '\0')
328 p = ".";
330 dirfd = vhost_dirfd(c->host, path, &c->loc);
331 log_debug(c, "check_path: strip=%d path=%s original=%s",
332 strip, p, path);
333 flags = O_RDONLY | O_NOFOLLOW;
334 if (*fd == -1 && (*fd = openat(dirfd, p, flags)) == -1)
335 return FILE_MISSING;
337 if (fstat(*fd, &sb) == -1) {
338 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
339 return FILE_MISSING;
342 if (S_ISDIR(sb.st_mode))
343 return FILE_DIRECTORY;
345 if (sb.st_mode & S_IXUSR)
346 return FILE_EXECUTABLE;
348 return FILE_EXISTS;
351 static void
352 open_file(struct client *c)
354 switch (check_path(c, c->iri.path, &c->pfd)) {
355 case FILE_EXECUTABLE:
356 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
357 start_cgi(c->iri.path, "", c);
358 return;
361 /* fallthrough */
363 case FILE_EXISTS:
364 c->next = handle_copy;
365 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
366 return;
368 case FILE_DIRECTORY:
369 open_dir(c);
370 return;
372 case FILE_MISSING:
373 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
374 check_for_cgi(c);
375 return;
377 start_reply(c, NOT_FOUND, "not found");
378 return;
380 default:
381 /* unreachable */
382 abort();
386 /*
387 * the inverse of this algorithm, i.e. starting from the start of the
388 * path + strlen(cgi), and checking if each component, should be
389 * faster. But it's tedious to write. This does the opposite: starts
390 * from the end and strip one component at a time, until either an
391 * executable is found or we emptied the path.
392 */
393 static void
394 check_for_cgi(struct client *c)
396 char path[PATH_MAX];
397 char *end;
399 strlcpy(path, c->iri.path, sizeof(path));
400 end = strchr(path, '\0');
402 while (end > path) {
403 /*
404 * go up one level. UNIX paths are simple and POSIX
405 * dirname, with its ambiguities on if the given
406 * pointer is changed or not, gives me headaches.
407 */
408 while (*end != '/')
409 end--;
410 *end = '\0';
412 switch (check_path(c, path, &c->pfd)) {
413 case FILE_EXECUTABLE:
414 start_cgi(path, end+1, c);
415 return;
416 case FILE_MISSING:
417 break;
418 default:
419 goto err;
422 *end = '/';
423 end--;
426 err:
427 start_reply(c, NOT_FOUND, "not found");
428 return;
431 void
432 mark_nonblock(int fd)
434 int flags;
436 if ((flags = fcntl(fd, F_GETFL)) == -1)
437 fatal("fcntl(F_GETFL): %s", strerror(errno));
438 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
439 fatal("fcntl(F_SETFL): %s", strerror(errno));
442 static void
443 handle_handshake(int fd, short ev, void *d)
445 struct client *c = d;
446 struct vhost *h;
447 struct alist *a;
448 const char *servname;
449 const char *parse_err = "unknown error";
451 switch (tls_handshake(c->ctx)) {
452 case 0: /* success */
453 case -1: /* already handshaked */
454 break;
455 case TLS_WANT_POLLIN:
456 yield_read(fd, c, &handle_handshake);
457 return;
458 case TLS_WANT_POLLOUT:
459 yield_write(fd, c, &handle_handshake);
460 return;
461 default:
462 /* unreachable */
463 abort();
466 servname = tls_conn_servername(c->ctx);
467 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
468 log_info(c, "puny_decode: %s", parse_err);
469 goto err;
472 TAILQ_FOREACH(h, &hosts, vhosts) {
473 if (matches(h->domain, c->domain))
474 goto found;
475 TAILQ_FOREACH(a, &h->aliases, aliases) {
476 if (matches(a->alias, c->domain))
477 goto found;
481 found:
482 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
483 servname != NULL ? servname : "(null)",
484 c->domain,
485 h != NULL ? h->domain : "(null)");
487 if (h != NULL) {
488 c->host = h;
489 handle_open_conn(fd, ev, c);
490 return;
493 err:
494 if (servname != NULL)
495 strncpy(c->req, servname, sizeof(c->req));
496 else
497 strncpy(c->req, "null", sizeof(c->req));
499 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
502 static const char *
503 strip_path(const char *path, int strip)
505 char *t;
507 while (strip > 0) {
508 if ((t = strchr(path, '/')) == NULL) {
509 path = strchr(path, '\0');
510 break;
512 path = t;
513 strip--;
516 return path;
519 static void
520 fmt_sbuf(const char *fmt, struct client *c, const char *path)
522 size_t i;
523 char buf[32];
525 memset(buf, 0, sizeof(buf));
526 for (i = 0; *fmt; ++fmt) {
527 if (i == sizeof(buf)-1 || *fmt == '%') {
528 strlcat(c->sbuf, buf, sizeof(c->sbuf));
529 memset(buf, 0, sizeof(buf));
530 i = 0;
533 if (*fmt != '%') {
534 buf[i++] = *fmt;
535 continue;
538 switch (*++fmt) {
539 case '%':
540 strlcat(c->sbuf, "%", sizeof(c->sbuf));
541 break;
542 case 'p':
543 if (*path != '/')
544 strlcat(c->sbuf, "/", sizeof(c->sbuf));
545 strlcat(c->sbuf, path, sizeof(c->sbuf));
546 break;
547 case 'q':
548 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
549 break;
550 case 'P':
551 snprintf(buf, sizeof(buf), "%d", conf.port);
552 strlcat(c->sbuf, buf, sizeof(c->sbuf));
553 memset(buf, 0, sizeof(buf));
554 break;
555 case 'N':
556 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
557 break;
558 default:
559 fatal("%s: unknown fmt specifier %c",
560 __func__, *fmt);
564 if (i != 0)
565 strlcat(c->sbuf, buf, sizeof(c->sbuf));
568 /* 1 if a matching `block return' (and apply it), 0 otherwise */
569 static int
570 apply_block_return(struct client *c)
572 const char *fmt, *path;
573 int code;
575 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
576 return 0;
578 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
579 fmt_sbuf(fmt, c, path);
581 start_reply(c, code, c->sbuf);
582 return 1;
585 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
586 static int
587 apply_fastcgi(struct client *c)
589 int id;
590 struct fcgi *f;
592 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
593 return 0;
595 switch ((f = &fcgi[id])->s) {
596 case FCGI_OFF:
597 f->s = FCGI_INFLIGHT;
598 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
599 f->path, f->port, f->prog);
600 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
601 &id, sizeof(id));
602 imsg_flush(&exibuf);
603 /* fallthrough */
604 case FCGI_INFLIGHT:
605 c->fcgi = id;
606 break;
607 case FCGI_READY:
608 c->fcgi = id;
609 send_fcgi_req(f, c);
610 break;
613 return 1;
616 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
617 static int
618 apply_require_ca(struct client *c)
620 X509_STORE *store;
621 const uint8_t *cert;
622 size_t len;
624 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
625 return 0;
627 if (!tls_peer_cert_provided(c->ctx)) {
628 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
629 return 1;
632 cert = tls_peer_cert_chain_pem(c->ctx, &len);
633 if (!validate_against_ca(store, cert, len)) {
634 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
635 return 1;
638 return 0;
641 static void
642 handle_open_conn(int fd, short ev, void *d)
644 struct client *c = d;
645 const char *parse_err = "invalid request";
646 char decoded[DOMAIN_NAME_LEN];
648 bzero(c->req, sizeof(c->req));
649 bzero(&c->iri, sizeof(c->iri));
651 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
652 case -1:
653 log_err(c, "tls_read: %s", tls_error(c->ctx));
654 close_conn(fd, ev, c);
655 return;
657 case TLS_WANT_POLLIN:
658 yield_read(fd, c, &handle_open_conn);
659 return;
661 case TLS_WANT_POLLOUT:
662 yield_write(fd, c, &handle_open_conn);
663 return;
666 if (!trim_req_iri(c->req, &parse_err)
667 || !parse_iri(c->req, &c->iri, &parse_err)
668 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
669 log_info(c, "iri parse error: %s", parse_err);
670 start_reply(c, BAD_REQUEST, "invalid request");
671 return;
674 if (c->iri.port_no != conf.port
675 || strcmp(c->iri.schema, "gemini")
676 || strcmp(decoded, c->domain)) {
677 start_reply(c, PROXY_REFUSED, "won't proxy request");
678 return;
681 if (apply_require_ca(c))
682 return;
684 if (apply_block_return(c))
685 return;
687 if (apply_fastcgi(c))
688 return;
690 if (c->host->entrypoint != NULL) {
691 c->loc = 0;
692 start_cgi(c->host->entrypoint, c->iri.path, c);
693 return;
696 open_file(c);
699 void
700 start_reply(struct client *c, int code, const char *meta)
702 c->code = code;
703 c->meta = meta;
704 handle_start_reply(c->fd, 0, c);
707 static void
708 handle_start_reply(int fd, short ev, void *d)
710 struct client *c = d;
711 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
712 const char *lang;
713 size_t len;
715 lang = vhost_lang(c->host, c->iri.path);
717 snprintf(buf, sizeof(buf), "%d ", c->code);
718 strlcat(buf, c->meta, sizeof(buf));
719 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
720 strlcat(buf, "; lang=", sizeof(buf));
721 strlcat(buf, lang, sizeof(buf));
724 len = strlcat(buf, "\r\n", sizeof(buf));
725 assert(len < sizeof(buf));
727 switch (tls_write(c->ctx, buf, len)) {
728 case -1:
729 close_conn(fd, ev, c);
730 return;
731 case TLS_WANT_POLLIN:
732 yield_read(fd, c, &handle_start_reply);
733 return;
734 case TLS_WANT_POLLOUT:
735 yield_write(fd, c, &handle_start_reply);
736 return;
739 if (!vhost_disable_log(c->host, c->iri.path))
740 log_request(c, buf, sizeof(buf));
742 if (c->code != SUCCESS)
743 close_conn(fd, ev, c);
744 else
745 c->next(fd, ev, c);
748 static size_t
749 host_nth(struct vhost *h)
751 struct vhost *v;
752 size_t i = 0;
754 TAILQ_FOREACH(v, &hosts, vhosts) {
755 if (v == h)
756 return i;
757 i++;
760 abort();
763 static void
764 start_cgi(const char *spath, const char *relpath, struct client *c)
766 char addr[NI_MAXHOST];
767 const char *t;
768 struct cgireq req;
769 int e;
771 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
772 addr, sizeof(addr),
773 NULL, 0,
774 NI_NUMERICHOST);
775 if (e != 0)
776 fatal("getnameinfo failed");
778 memset(&req, 0, sizeof(req));
780 memcpy(req.buf, c->req, sizeof(req.buf));
782 req.iri_schema_off = c->iri.schema - c->req;
783 req.iri_host_off = c->iri.host - c->req;
784 req.iri_port_off = c->iri.port - c->req;
785 req.iri_path_off = c->iri.path - c->req;
786 req.iri_query_off = c->iri.query - c->req;
787 req.iri_fragment_off = c->iri.fragment - c->req;
789 req.iri_portno = c->iri.port_no;
791 strlcpy(req.spath, spath, sizeof(req.spath));
792 strlcpy(req.relpath, relpath, sizeof(req.relpath));
793 strlcpy(req.addr, addr, sizeof(req.addr));
795 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
796 strlcpy(req.subject, t, sizeof(req.subject));
797 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
798 strlcpy(req.issuer, t, sizeof(req.issuer));
799 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
800 strlcpy(req.hash, t, sizeof(req.hash));
801 if ((t = tls_conn_version(c->ctx)) != NULL)
802 strlcpy(req.version, t, sizeof(req.version));
803 if ((t = tls_conn_cipher(c->ctx)) != NULL)
804 strlcpy(req.cipher, t, sizeof(req.cipher));
806 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
807 req.notbefore = tls_peer_cert_notbefore(c->ctx);
808 req.notafter = tls_peer_cert_notafter(c->ctx);
810 req.host_off = host_nth(c->host);
811 req.loc_off = c->loc;
813 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
814 imsg_flush(&exibuf);
816 close(c->pfd);
819 static void
820 open_dir(struct client *c)
822 size_t len;
823 int dirfd, root;
824 char *before_file;
826 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
828 len = strlen(c->iri.path);
829 if (len > 0 && !ends_with(c->iri.path, "/")) {
830 redirect_canonical_dir(c);
831 return;
834 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
835 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
836 if (!ends_with(c->sbuf, "/"))
837 strlcat(c->sbuf, "/", sizeof(c->sbuf));
838 before_file = strchr(c->sbuf, '\0');
839 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
840 sizeof(c->sbuf));
841 if (len >= sizeof(c->sbuf)) {
842 start_reply(c, TEMP_FAILURE, "internal server error");
843 return;
846 c->iri.path = c->sbuf;
848 /* close later unless we have to generate the dir listing */
849 dirfd = c->pfd;
850 c->pfd = -1;
852 switch (check_path(c, c->iri.path, &c->pfd)) {
853 case FILE_EXECUTABLE:
854 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
855 start_cgi(c->iri.path, "", c);
856 break;
859 /* fallthrough */
861 case FILE_EXISTS:
862 c->next = handle_copy;
863 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
864 break;
866 case FILE_DIRECTORY:
867 start_reply(c, TEMP_REDIRECT, c->sbuf);
868 break;
870 case FILE_MISSING:
871 *before_file = '\0';
873 if (!vhost_auto_index(c->host, c->iri.path)) {
874 start_reply(c, NOT_FOUND, "not found");
875 break;
878 c->next = enter_handle_dirlist;
880 c->dirlen = scandir_fd(dirfd, &c->dir,
881 root ? select_non_dotdot : select_non_dot,
882 alphasort);
883 if (c->dirlen == -1) {
884 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
885 c->pfd, c->host->domain, c->iri.path, strerror(errno));
886 start_reply(c, TEMP_FAILURE, "internal server error");
887 return;
889 c->diroff = 0;
890 c->off = 0;
892 start_reply(c, SUCCESS, "text/gemini");
893 return;
895 default:
896 /* unreachable */
897 abort();
900 close(dirfd);
903 static void
904 redirect_canonical_dir(struct client *c)
906 size_t len;
908 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
909 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
910 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
912 if (len >= sizeof(c->sbuf)) {
913 start_reply(c, TEMP_FAILURE, "internal server error");
914 return;
917 start_reply(c, TEMP_REDIRECT, c->sbuf);
920 static void
921 enter_handle_dirlist(int fd, short ev, void *d)
923 struct client *c = d;
924 char b[PATH_MAX];
925 size_t l;
927 strlcpy(b, c->iri.path, sizeof(b));
928 l = snprintf(c->sbuf, sizeof(c->sbuf),
929 "# Index of %s\n\n", b);
930 if (l >= sizeof(c->sbuf)) {
931 /* this is impossible, given that we have enough space
932 * in c->sbuf to hold the ancilliary string plus the
933 * full path; but it wouldn't read nice without some
934 * error checking, and I'd like to avoid a strlen. */
935 close_conn(fd, ev, c);
936 return;
939 c->len = l;
940 handle_dirlist(fd, ev, c);
943 static void
944 handle_dirlist(int fd, short ev, void *d)
946 struct client *c = d;
947 ssize_t r;
949 while (c->len > 0) {
950 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
951 case -1:
952 close_conn(fd, ev, c);
953 return;
954 case TLS_WANT_POLLOUT:
955 yield_read(fd, c, &handle_dirlist);
956 return;
957 case TLS_WANT_POLLIN:
958 yield_write(fd, c, &handle_dirlist);
959 return;
960 default:
961 c->off += r;
962 c->len -= r;
966 send_directory_listing(fd, ev, c);
969 static int
970 read_next_dir_entry(struct client *c)
972 if (c->diroff == c->dirlen)
973 return 0;
975 /* XXX: url escape */
976 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
977 c->dir[c->diroff]->d_name);
979 free(c->dir[c->diroff]);
980 c->diroff++;
982 c->len = strlen(c->sbuf);
983 c->off = 0;
984 return 1;
987 static void
988 send_directory_listing(int fd, short ev, void *d)
990 struct client *c = d;
991 ssize_t r;
993 while (1) {
994 if (c->len == 0) {
995 if (!read_next_dir_entry(c))
996 goto end;
999 while (c->len > 0) {
1000 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1001 case -1:
1002 goto end;
1004 case TLS_WANT_POLLOUT:
1005 yield_read(fd, c, &send_directory_listing);
1006 return;
1008 case TLS_WANT_POLLIN:
1009 yield_write(fd, c, &send_directory_listing);
1010 return;
1012 default:
1013 c->off += r;
1014 c->len -= r;
1015 break;
1020 end:
1021 close_conn(fd, ev, d);
1024 /* accumulate the meta line from the cgi script. */
1025 static void
1026 handle_cgi_reply(int fd, short ev, void *d)
1028 struct client *c = d;
1029 void *buf, *e;
1030 size_t len;
1031 ssize_t r;
1034 buf = c->sbuf + c->len;
1035 len = sizeof(c->sbuf) - c->len;
1037 r = read(c->pfd, buf, len);
1038 if (r == 0 || r == -1) {
1039 start_reply(c, CGI_ERROR, "CGI error");
1040 return;
1043 c->len += r;
1045 /* TODO: error if the CGI script don't reply correctly */
1046 e = strchr(c->sbuf, '\n');
1047 if (e != NULL || c->len == sizeof(c->sbuf)) {
1048 log_request(c, c->sbuf, c->len);
1050 c->off = 0;
1051 handle_copy(fd, ev, c);
1052 return;
1055 yield_read(fd, c, &handle_cgi_reply);
1058 static void
1059 handle_copy(int fd, short ev, void *d)
1061 struct client *c = d;
1062 ssize_t r;
1064 while (1) {
1065 while (c->len > 0) {
1066 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1067 case -1:
1068 goto end;
1070 case TLS_WANT_POLLOUT:
1071 yield_write(c->fd, c, &handle_copy);
1072 return;
1074 case TLS_WANT_POLLIN:
1075 yield_read(c->fd, c, &handle_copy);
1076 return;
1078 default:
1079 c->off += r;
1080 c->len -= r;
1081 break;
1085 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1086 case 0:
1087 goto end;
1088 case -1:
1089 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1090 yield_read(c->pfd, c, &handle_copy);
1091 return;
1093 goto end;
1094 default:
1095 c->len = r;
1096 c->off = 0;
1100 end:
1101 close_conn(c->fd, ev, d);
1104 void
1105 close_conn(int fd, short ev, void *d)
1107 struct client *c = d;
1108 struct mbuf *mbuf;
1110 switch (tls_close(c->ctx)) {
1111 case TLS_WANT_POLLIN:
1112 yield_read(fd, c, &close_conn);
1113 return;
1114 case TLS_WANT_POLLOUT:
1115 yield_read(fd, c, &close_conn);
1116 return;
1119 connected_clients--;
1121 while ((mbuf = TAILQ_FIRST(&c->mbufhead)) != NULL) {
1122 TAILQ_REMOVE(&c->mbufhead, mbuf, mbufs);
1123 free(mbuf);
1126 tls_free(c->ctx);
1127 c->ctx = NULL;
1129 if (c->pfd != -1)
1130 close(c->pfd);
1132 if (c->dir != NULL)
1133 free(c->dir);
1135 close(c->fd);
1136 c->fd = -1;
1139 static void
1140 do_accept(int sock, short et, void *d)
1142 struct client *c;
1143 struct sockaddr_storage addr;
1144 struct sockaddr *saddr;
1145 socklen_t len;
1146 int i, fd;
1148 (void)et;
1150 saddr = (struct sockaddr*)&addr;
1151 len = sizeof(addr);
1152 if ((fd = accept(sock, saddr, &len)) == -1) {
1153 if (errno == EWOULDBLOCK || errno == EAGAIN)
1154 return;
1155 fatal("accept: %s", strerror(errno));
1158 mark_nonblock(fd);
1160 for (i = 0; i < MAX_USERS; ++i) {
1161 c = &clients[i];
1162 if (c->fd == -1) {
1163 memset(c, 0, sizeof(*c));
1164 c->id = i;
1165 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1166 break; /* goodbye fd! */
1168 c->fd = fd;
1169 c->pfd = -1;
1170 c->dir = NULL;
1171 c->addr = addr;
1172 c->fcgi = -1;
1174 yield_read(fd, c, &handle_handshake);
1175 connected_clients++;
1176 return;
1180 close(fd);
1183 static struct client *
1184 client_by_id(int id)
1186 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1187 fatal("in client_by_id: invalid id %d", id);
1188 return &clients[id];
1191 struct client *
1192 try_client_by_id(int id)
1194 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1195 return NULL;
1196 return &clients[id];
1199 static void
1200 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1202 struct client *c;
1204 c = client_by_id(imsg->hdr.peerid);
1206 if ((c->pfd = imsg->fd) == -1)
1207 start_reply(c, TEMP_FAILURE, "internal server error");
1208 else
1209 yield_read(c->pfd, c, &handle_cgi_reply);
1212 static void
1213 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1215 struct client *c;
1216 struct fcgi *f;
1217 int i, id;
1219 id = imsg->hdr.peerid;
1220 f = &fcgi[id];
1222 if ((f->fd = imsg->fd) != -1) {
1223 event_set(&f->e, imsg->fd, EV_READ | EV_PERSIST, &handle_fcgi,
1224 &fcgi[id]);
1225 event_add(&f->e, NULL);
1226 } else {
1227 f->s = FCGI_OFF;
1230 for (i = 0; i < MAX_USERS; ++i) {
1231 c = &clients[i];
1232 if (c->fd == -1)
1233 continue;
1234 if (c->fcgi != id)
1235 continue;
1237 if (f->fd == -1) {
1238 c->fcgi = -1;
1239 start_reply(c, TEMP_FAILURE, "internal server error");
1240 } else
1241 send_fcgi_req(f, c);
1245 static void
1246 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1248 (void)imsg;
1249 (void)len;
1251 /* don't call event_loopbreak since we want to finish to
1252 * handle the ongoing connections. */
1254 event_del(&e4);
1255 if (has_ipv6)
1256 event_del(&e6);
1257 if (has_siginfo)
1258 signal_del(&siginfo);
1259 event_del(&imsgev);
1260 signal_del(&sigusr2);
1263 static void
1264 handle_dispatch_imsg(int fd, short ev, void *d)
1266 struct imsgbuf *ibuf = d;
1267 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1270 static void
1271 handle_siginfo(int fd, short ev, void *d)
1273 (void)fd;
1274 (void)ev;
1275 (void)d;
1277 log_info(NULL, "%d connected clients", connected_clients);
1280 void
1281 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1283 size_t i;
1285 ctx = ctx_;
1287 event_init();
1289 memset(&clients, 0, sizeof(clients));
1290 for (i = 0; i < MAX_USERS; ++i)
1291 clients[i].fd = -1;
1293 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1294 event_add(&e4, NULL);
1296 if (sock6 != -1) {
1297 has_ipv6 = 1;
1298 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1299 event_add(&e6, NULL);
1302 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1303 event_add(&imsgev, NULL);
1305 #ifdef SIGINFO
1306 has_siginfo = 1;
1307 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1308 signal_add(&siginfo, NULL);
1309 #endif
1310 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1311 signal_add(&sigusr2, NULL);
1313 sandbox_server_process();
1314 event_dispatch();
1315 _exit(0);