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 != '/')
410 end--;
411 *end = '\0';
413 switch (check_path(c, path, &c->pfd)) {
414 case FILE_EXECUTABLE:
415 start_cgi(path, end+1, c);
416 return;
417 case FILE_MISSING:
418 break;
419 default:
420 goto err;
423 *end = '/';
424 end--;
427 err:
428 start_reply(c, NOT_FOUND, "not found");
429 return;
432 void
433 mark_nonblock(int fd)
435 int flags;
437 if ((flags = fcntl(fd, F_GETFL)) == -1)
438 fatal("fcntl(F_GETFL): %s", strerror(errno));
439 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
440 fatal("fcntl(F_SETFL): %s", strerror(errno));
443 static void
444 handle_handshake(int fd, short ev, void *d)
446 struct client *c = d;
447 struct vhost *h;
448 struct alist *a;
449 const char *servname;
450 const char *parse_err = "unknown error";
452 switch (tls_handshake(c->ctx)) {
453 case 0: /* success */
454 case -1: /* already handshaked */
455 break;
456 case TLS_WANT_POLLIN:
457 yield_read(fd, c, &handle_handshake);
458 return;
459 case TLS_WANT_POLLOUT:
460 yield_write(fd, c, &handle_handshake);
461 return;
462 default:
463 /* unreachable */
464 abort();
467 servname = tls_conn_servername(c->ctx);
468 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
469 log_info(c, "puny_decode: %s", parse_err);
470 goto err;
473 TAILQ_FOREACH(h, &hosts, vhosts) {
474 if (matches(h->domain, c->domain))
475 goto found;
476 TAILQ_FOREACH(a, &h->aliases, aliases) {
477 if (matches(a->alias, c->domain))
478 goto found;
482 found:
483 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
484 servname != NULL ? servname : "(null)",
485 c->domain,
486 h != NULL ? h->domain : "(null)");
488 if (h != NULL) {
489 c->host = h;
490 handle_open_conn(fd, ev, c);
491 return;
494 err:
495 if (servname != NULL)
496 strlcpy(c->req, servname, sizeof(c->req));
497 else
498 strlcpy(c->req, "null", sizeof(c->req));
500 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
503 static const char *
504 strip_path(const char *path, int strip)
506 char *t;
508 while (strip > 0) {
509 if ((t = strchr(path, '/')) == NULL) {
510 path = strchr(path, '\0');
511 break;
513 path = t;
514 strip--;
517 return path;
520 static void
521 fmt_sbuf(const char *fmt, struct client *c, const char *path)
523 size_t i;
524 char buf[32];
526 memset(buf, 0, sizeof(buf));
527 for (i = 0; *fmt; ++fmt) {
528 if (i == sizeof(buf)-1 || *fmt == '%') {
529 strlcat(c->sbuf, buf, sizeof(c->sbuf));
530 memset(buf, 0, sizeof(buf));
531 i = 0;
534 if (*fmt != '%') {
535 buf[i++] = *fmt;
536 continue;
539 switch (*++fmt) {
540 case '%':
541 strlcat(c->sbuf, "%", sizeof(c->sbuf));
542 break;
543 case 'p':
544 if (*path != '/')
545 strlcat(c->sbuf, "/", sizeof(c->sbuf));
546 strlcat(c->sbuf, path, sizeof(c->sbuf));
547 break;
548 case 'q':
549 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
550 break;
551 case 'P':
552 snprintf(buf, sizeof(buf), "%d", conf.port);
553 strlcat(c->sbuf, buf, sizeof(c->sbuf));
554 memset(buf, 0, sizeof(buf));
555 break;
556 case 'N':
557 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
558 break;
559 default:
560 fatal("%s: unknown fmt specifier %c",
561 __func__, *fmt);
565 if (i != 0)
566 strlcat(c->sbuf, buf, sizeof(c->sbuf));
569 /* 1 if a matching `block return' (and apply it), 0 otherwise */
570 static int
571 apply_block_return(struct client *c)
573 const char *fmt, *path;
574 int code;
576 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
577 return 0;
579 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
580 fmt_sbuf(fmt, c, path);
582 start_reply(c, code, c->sbuf);
583 return 1;
586 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
587 static int
588 apply_fastcgi(struct client *c)
590 int id;
591 struct fcgi *f;
593 if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
594 return 0;
596 switch ((f = &fcgi[id])->s) {
597 case FCGI_OFF:
598 f->s = FCGI_INFLIGHT;
599 log_info(c, "opening fastcgi connection for (%s,%s,%s)",
600 f->path, f->port, f->prog);
601 imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
602 &id, sizeof(id));
603 imsg_flush(&exibuf);
604 /* fallthrough */
605 case FCGI_INFLIGHT:
606 c->fcgi = id;
607 break;
608 case FCGI_READY:
609 c->fcgi = id;
610 send_fcgi_req(f, c);
611 break;
614 return 1;
617 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
618 static int
619 apply_require_ca(struct client *c)
621 X509_STORE *store;
622 const uint8_t *cert;
623 size_t len;
625 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
626 return 0;
628 if (!tls_peer_cert_provided(c->ctx)) {
629 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
630 return 1;
633 cert = tls_peer_cert_chain_pem(c->ctx, &len);
634 if (!validate_against_ca(store, cert, len)) {
635 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
636 return 1;
639 return 0;
642 static void
643 handle_open_conn(int fd, short ev, void *d)
645 struct client *c = d;
646 const char *parse_err = "invalid request";
647 char decoded[DOMAIN_NAME_LEN];
649 bzero(c->req, sizeof(c->req));
650 bzero(&c->iri, sizeof(c->iri));
652 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
653 case -1:
654 log_err(c, "tls_read: %s", tls_error(c->ctx));
655 close_conn(fd, ev, c);
656 return;
658 case TLS_WANT_POLLIN:
659 yield_read(fd, c, &handle_open_conn);
660 return;
662 case TLS_WANT_POLLOUT:
663 yield_write(fd, c, &handle_open_conn);
664 return;
667 if (!trim_req_iri(c->req, &parse_err)
668 || !parse_iri(c->req, &c->iri, &parse_err)
669 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
670 log_info(c, "iri parse error: %s", parse_err);
671 start_reply(c, BAD_REQUEST, "invalid request");
672 return;
675 if (c->iri.port_no != conf.port
676 || strcmp(c->iri.schema, "gemini")
677 || strcmp(decoded, c->domain)) {
678 start_reply(c, PROXY_REFUSED, "won't proxy request");
679 return;
682 if (apply_require_ca(c))
683 return;
685 if (apply_block_return(c))
686 return;
688 if (apply_fastcgi(c))
689 return;
691 if (c->host->entrypoint != NULL) {
692 c->loc = 0;
693 start_cgi(c->host->entrypoint, c->iri.path, c);
694 return;
697 open_file(c);
700 void
701 start_reply(struct client *c, int code, const char *meta)
703 c->code = code;
704 c->meta = meta;
705 handle_start_reply(c->fd, 0, c);
708 static void
709 handle_start_reply(int fd, short ev, void *d)
711 struct client *c = d;
712 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
713 const char *lang;
714 size_t len;
716 lang = vhost_lang(c->host, c->iri.path);
718 snprintf(buf, sizeof(buf), "%d ", c->code);
719 strlcat(buf, c->meta, sizeof(buf));
720 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
721 strlcat(buf, "; lang=", sizeof(buf));
722 strlcat(buf, lang, sizeof(buf));
725 len = strlcat(buf, "\r\n", sizeof(buf));
726 assert(len < sizeof(buf));
728 switch (tls_write(c->ctx, buf, len)) {
729 case -1:
730 close_conn(fd, ev, c);
731 return;
732 case TLS_WANT_POLLIN:
733 yield_read(fd, c, &handle_start_reply);
734 return;
735 case TLS_WANT_POLLOUT:
736 yield_write(fd, c, &handle_start_reply);
737 return;
740 if (!vhost_disable_log(c->host, c->iri.path))
741 log_request(c, buf, sizeof(buf));
743 if (c->code != SUCCESS)
744 close_conn(fd, ev, c);
745 else
746 c->next(fd, ev, c);
749 static size_t
750 host_nth(struct vhost *h)
752 struct vhost *v;
753 size_t i = 0;
755 TAILQ_FOREACH(v, &hosts, vhosts) {
756 if (v == h)
757 return i;
758 i++;
761 abort();
764 static void
765 start_cgi(const char *spath, const char *relpath, struct client *c)
767 char addr[NI_MAXHOST];
768 const char *t;
769 struct cgireq req;
770 int e;
772 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
773 addr, sizeof(addr),
774 NULL, 0,
775 NI_NUMERICHOST);
776 if (e != 0)
777 fatal("getnameinfo failed");
779 memset(&req, 0, sizeof(req));
781 memcpy(req.buf, c->req, sizeof(req.buf));
783 req.iri_schema_off = c->iri.schema - c->req;
784 req.iri_host_off = c->iri.host - c->req;
785 req.iri_port_off = c->iri.port - c->req;
786 req.iri_path_off = c->iri.path - c->req;
787 req.iri_query_off = c->iri.query - c->req;
788 req.iri_fragment_off = c->iri.fragment - c->req;
790 req.iri_portno = c->iri.port_no;
792 strlcpy(req.spath, spath, sizeof(req.spath));
793 strlcpy(req.relpath, relpath, sizeof(req.relpath));
794 strlcpy(req.addr, addr, sizeof(req.addr));
796 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
797 strlcpy(req.subject, t, sizeof(req.subject));
798 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
799 strlcpy(req.issuer, t, sizeof(req.issuer));
800 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
801 strlcpy(req.hash, t, sizeof(req.hash));
802 if ((t = tls_conn_version(c->ctx)) != NULL)
803 strlcpy(req.version, t, sizeof(req.version));
804 if ((t = tls_conn_cipher(c->ctx)) != NULL)
805 strlcpy(req.cipher, t, sizeof(req.cipher));
807 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
808 req.notbefore = tls_peer_cert_notbefore(c->ctx);
809 req.notafter = tls_peer_cert_notafter(c->ctx);
811 req.host_off = host_nth(c->host);
812 req.loc_off = c->loc;
814 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
815 imsg_flush(&exibuf);
817 close(c->pfd);
820 static void
821 open_dir(struct client *c)
823 size_t len;
824 int dirfd, root;
825 char *before_file;
827 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
829 len = strlen(c->iri.path);
830 if (len > 0 && !ends_with(c->iri.path, "/")) {
831 redirect_canonical_dir(c);
832 return;
835 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
836 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
837 if (!ends_with(c->sbuf, "/"))
838 strlcat(c->sbuf, "/", sizeof(c->sbuf));
839 before_file = strchr(c->sbuf, '\0');
840 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
841 sizeof(c->sbuf));
842 if (len >= sizeof(c->sbuf)) {
843 start_reply(c, TEMP_FAILURE, "internal server error");
844 return;
847 c->iri.path = c->sbuf;
849 /* close later unless we have to generate the dir listing */
850 dirfd = c->pfd;
851 c->pfd = -1;
853 switch (check_path(c, c->iri.path, &c->pfd)) {
854 case FILE_EXECUTABLE:
855 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
856 start_cgi(c->iri.path, "", c);
857 break;
860 /* fallthrough */
862 case FILE_EXISTS:
863 c->next = handle_copy;
864 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
865 break;
867 case FILE_DIRECTORY:
868 start_reply(c, TEMP_REDIRECT, c->sbuf);
869 break;
871 case FILE_MISSING:
872 *before_file = '\0';
874 if (!vhost_auto_index(c->host, c->iri.path)) {
875 start_reply(c, NOT_FOUND, "not found");
876 break;
879 c->next = enter_handle_dirlist;
881 c->dirlen = scandir_fd(dirfd, &c->dir,
882 root ? select_non_dotdot : select_non_dot,
883 alphasort);
884 if (c->dirlen == -1) {
885 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
886 c->pfd, c->host->domain, c->iri.path, strerror(errno));
887 start_reply(c, TEMP_FAILURE, "internal server error");
888 return;
890 c->diroff = 0;
891 c->off = 0;
893 start_reply(c, SUCCESS, "text/gemini");
894 return;
896 default:
897 /* unreachable */
898 abort();
901 close(dirfd);
904 static void
905 redirect_canonical_dir(struct client *c)
907 size_t len;
909 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
910 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
911 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
913 if (len >= sizeof(c->sbuf)) {
914 start_reply(c, TEMP_FAILURE, "internal server error");
915 return;
918 start_reply(c, TEMP_REDIRECT, c->sbuf);
921 static void
922 enter_handle_dirlist(int fd, short ev, void *d)
924 struct client *c = d;
925 char b[PATH_MAX];
926 size_t l;
928 strlcpy(b, c->iri.path, sizeof(b));
929 l = snprintf(c->sbuf, sizeof(c->sbuf),
930 "# Index of %s\n\n", b);
931 if (l >= sizeof(c->sbuf)) {
932 /*
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 */
938 close_conn(fd, ev, c);
939 return;
942 c->len = l;
943 handle_dirlist(fd, ev, c);
946 static void
947 handle_dirlist(int fd, short ev, void *d)
949 struct client *c = d;
950 ssize_t r;
952 while (c->len > 0) {
953 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
954 case -1:
955 close_conn(fd, ev, c);
956 return;
957 case TLS_WANT_POLLOUT:
958 yield_read(fd, c, &handle_dirlist);
959 return;
960 case TLS_WANT_POLLIN:
961 yield_write(fd, c, &handle_dirlist);
962 return;
963 default:
964 c->off += r;
965 c->len -= r;
969 send_directory_listing(fd, ev, c);
972 static int
973 read_next_dir_entry(struct client *c)
975 if (c->diroff == c->dirlen)
976 return 0;
978 /* XXX: url escape */
979 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
980 c->dir[c->diroff]->d_name);
982 free(c->dir[c->diroff]);
983 c->diroff++;
985 c->len = strlen(c->sbuf);
986 c->off = 0;
987 return 1;
990 static void
991 send_directory_listing(int fd, short ev, void *d)
993 struct client *c = d;
994 ssize_t r;
996 while (1) {
997 if (c->len == 0) {
998 if (!read_next_dir_entry(c))
999 goto end;
1002 while (c->len > 0) {
1003 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1004 case -1:
1005 goto end;
1007 case TLS_WANT_POLLOUT:
1008 yield_read(fd, c, &send_directory_listing);
1009 return;
1011 case TLS_WANT_POLLIN:
1012 yield_write(fd, c, &send_directory_listing);
1013 return;
1015 default:
1016 c->off += r;
1017 c->len -= r;
1018 break;
1023 end:
1024 close_conn(fd, ev, d);
1027 /* accumulate the meta line from the cgi script. */
1028 static void
1029 handle_cgi_reply(int fd, short ev, void *d)
1031 struct client *c = d;
1032 void *buf, *e;
1033 size_t len;
1034 ssize_t r;
1037 buf = c->sbuf + c->len;
1038 len = sizeof(c->sbuf) - c->len;
1040 r = read(c->pfd, buf, len);
1041 if (r == 0 || r == -1) {
1042 start_reply(c, CGI_ERROR, "CGI error");
1043 return;
1046 c->len += r;
1048 /* TODO: error if the CGI script don't reply correctly */
1049 e = strchr(c->sbuf, '\n');
1050 if (e != NULL || c->len == sizeof(c->sbuf)) {
1051 log_request(c, c->sbuf, c->len);
1053 c->off = 0;
1054 handle_copy(fd, ev, c);
1055 return;
1058 yield_read(fd, c, &handle_cgi_reply);
1061 static void
1062 handle_copy(int fd, short ev, void *d)
1064 struct client *c = d;
1065 ssize_t r;
1067 while (1) {
1068 while (c->len > 0) {
1069 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1070 case -1:
1071 goto end;
1073 case TLS_WANT_POLLOUT:
1074 yield_write(c->fd, c, &handle_copy);
1075 return;
1077 case TLS_WANT_POLLIN:
1078 yield_read(c->fd, c, &handle_copy);
1079 return;
1081 default:
1082 c->off += r;
1083 c->len -= r;
1084 break;
1088 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1089 case 0:
1090 goto end;
1091 case -1:
1092 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1093 yield_read(c->pfd, c, &handle_copy);
1094 return;
1096 goto end;
1097 default:
1098 c->len = r;
1099 c->off = 0;
1103 end:
1104 close_conn(c->fd, ev, d);
1107 void
1108 close_conn(int fd, short ev, void *d)
1110 struct client *c = d;
1111 struct mbuf *mbuf;
1113 switch (tls_close(c->ctx)) {
1114 case TLS_WANT_POLLIN:
1115 yield_read(c->fd, c, &close_conn);
1116 return;
1117 case TLS_WANT_POLLOUT:
1118 yield_read(c->fd, c, &close_conn);
1119 return;
1122 connected_clients--;
1124 while ((mbuf = TAILQ_FIRST(&c->mbufhead)) != NULL) {
1125 TAILQ_REMOVE(&c->mbufhead, mbuf, mbufs);
1126 free(mbuf);
1129 tls_free(c->ctx);
1130 c->ctx = NULL;
1132 if (c->pfd != -1)
1133 close(c->pfd);
1135 if (c->dir != NULL)
1136 free(c->dir);
1138 close(c->fd);
1139 c->fd = -1;
1142 static void
1143 do_accept(int sock, short et, void *d)
1145 struct client *c;
1146 struct sockaddr_storage addr;
1147 struct sockaddr *saddr;
1148 socklen_t len;
1149 int i, fd;
1151 (void)et;
1153 saddr = (struct sockaddr*)&addr;
1154 len = sizeof(addr);
1155 if ((fd = accept(sock, saddr, &len)) == -1) {
1156 if (errno == EWOULDBLOCK || errno == EAGAIN)
1157 return;
1158 fatal("accept: %s", strerror(errno));
1161 mark_nonblock(fd);
1163 for (i = 0; i < MAX_USERS; ++i) {
1164 c = &clients[i];
1165 if (c->fd == -1) {
1166 memset(c, 0, sizeof(*c));
1167 c->id = i;
1168 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1169 break; /* goodbye fd! */
1171 c->fd = fd;
1172 c->pfd = -1;
1173 c->dir = NULL;
1174 c->addr = addr;
1175 c->fcgi = -1;
1177 yield_read(fd, c, &handle_handshake);
1178 connected_clients++;
1179 return;
1183 close(fd);
1186 static struct client *
1187 client_by_id(int id)
1189 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1190 fatal("in client_by_id: invalid id %d", id);
1191 return &clients[id];
1194 struct client *
1195 try_client_by_id(int id)
1197 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1198 return NULL;
1199 return &clients[id];
1202 static void
1203 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1205 struct client *c;
1207 c = client_by_id(imsg->hdr.peerid);
1209 if ((c->pfd = imsg->fd) == -1)
1210 start_reply(c, TEMP_FAILURE, "internal server error");
1211 else
1212 yield_read(c->pfd, c, &handle_cgi_reply);
1215 static void
1216 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1218 struct client *c;
1219 struct fcgi *f;
1220 int i, id;
1222 id = imsg->hdr.peerid;
1223 f = &fcgi[id];
1225 if ((f->fd = imsg->fd) != -1) {
1226 f->s = FCGI_READY;
1227 event_set(&f->e, imsg->fd, EV_READ | EV_PERSIST, &handle_fcgi,
1228 &fcgi[id]);
1229 event_add(&f->e, NULL);
1230 } else {
1231 f->s = FCGI_OFF;
1234 for (i = 0; i < MAX_USERS; ++i) {
1235 c = &clients[i];
1236 if (c->fd == -1)
1237 continue;
1238 if (c->fcgi != id)
1239 continue;
1241 if (f->fd == -1) {
1242 c->fcgi = -1;
1243 start_reply(c, TEMP_FAILURE, "internal server error");
1244 } else
1245 send_fcgi_req(f, c);
1249 static void
1250 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1252 size_t i;
1254 (void)imsg;
1255 (void)len;
1258 * don't call event_loopbreak since we want to finish to
1259 * handle the ongoing connections.
1262 shutting_down = 1;
1264 event_del(&e4);
1265 if (has_ipv6)
1266 event_del(&e6);
1267 if (has_siginfo)
1268 signal_del(&siginfo);
1269 event_del(&imsgev);
1270 signal_del(&sigusr2);
1272 for (i = 0; i < FCGI_MAX; ++i) {
1273 if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
1274 break;
1276 if (!event_pending(&fcgi[i].e, EV_READ, NULL) ||
1277 fcgi[i].pending != 0)
1278 continue;
1280 fcgi_close_backend(&fcgi[i]);
1284 static void
1285 handle_dispatch_imsg(int fd, short ev, void *d)
1287 struct imsgbuf *ibuf = d;
1288 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1291 static void
1292 handle_siginfo(int fd, short ev, void *d)
1294 (void)fd;
1295 (void)ev;
1296 (void)d;
1298 log_info(NULL, "%d connected clients", connected_clients);
1301 void
1302 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1304 size_t i;
1306 ctx = ctx_;
1308 event_init();
1310 memset(&clients, 0, sizeof(clients));
1311 for (i = 0; i < MAX_USERS; ++i)
1312 clients[i].fd = -1;
1314 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1315 event_add(&e4, NULL);
1317 if (sock6 != -1) {
1318 has_ipv6 = 1;
1319 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1320 event_add(&e6, NULL);
1323 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1324 event_add(&imsgev, NULL);
1326 #ifdef SIGINFO
1327 has_siginfo = 1;
1328 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1329 signal_add(&siginfo, NULL);
1330 #endif
1331 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1332 signal_add(&sigusr2, NULL);
1334 sandbox_server_process();
1335 event_dispatch();
1336 _exit(0);