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 static struct client clients[MAX_USERS];
30 static struct tls *ctx;
32 static struct event e4, e6, imsgev, siginfo, sigusr2;
33 static int has_ipv6, has_siginfo;
35 int connected_clients;
37 static inline int matches(const char*, const char*);
39 static inline void yield_read(int, struct client*, statefn);
40 static inline void yield_write(int, struct client*, statefn);
42 static int check_path(struct client*, const char*, int*);
43 static void open_file(struct client*);
44 static void check_for_cgi(struct client*);
45 static void handle_handshake(int, short, void*);
46 static char *strip_path(char*, int);
47 static void fmt_sbuf(const char*, struct client*, const char*);
48 static int apply_block_return(struct client*);
49 static int apply_require_ca(struct client*);
50 static void handle_open_conn(int, short, void*);
51 static void start_reply(struct client*, int, const char*);
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 close_conn(int, short, void*);
64 static void do_accept(int, short, void*);
65 struct client *client_by_id(int);
66 static void handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
67 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
68 static void handle_siginfo(int, short, void*);
70 static imsg_handlerfn *handlers[] = {
71 [IMSG_QUIT] = handle_imsg_quit,
72 [IMSG_CGI_RES] = handle_imsg_cgi_res,
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_dirfd(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->dirfd != -1)
216 if (matches(loc->match, path))
217 return loc->dirfd;
220 loc = TAILQ_FIRST(&v->locations);
221 return loc->dirfd;
224 int
225 vhost_strip(struct vhost *v, const char *path)
227 struct location *loc;
229 if (v == NULL || path == NULL)
230 return 0;
232 loc = TAILQ_FIRST(&v->locations);
233 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
234 if (loc->strip != 0) {
235 if (matches(loc->match, path))
236 return loc->strip;
240 loc = TAILQ_FIRST(&v->locations);
241 return loc->strip;
244 X509_STORE *
245 vhost_require_ca(struct vhost *v, const char *path)
247 struct location *loc;
249 if (v == NULL || path == NULL)
250 return NULL;
252 loc = TAILQ_FIRST(&v->locations);
253 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
254 if (loc->reqca != NULL) {
255 if (matches(loc->match, path))
256 return loc->reqca;
260 loc = TAILQ_FIRST(&v->locations);
261 return loc->reqca;
264 int
265 vhost_disable_log(struct vhost *v, const char *path)
267 struct location *loc;
269 if (v == NULL || path == NULL)
270 return 0;
272 loc = TAILQ_FIRST(&v->locations);
273 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
274 if (loc->disable_log && matches(loc->match, path))
275 return 1;
278 loc = TAILQ_FIRST(&v->locations);
279 return loc->disable_log;
282 static int
283 check_path(struct client *c, const char *path, int *fd)
285 struct stat sb;
286 const char *p;
287 int flags, dirfd, strip;
289 assert(path != NULL);
291 /*
292 * in send_dir we add an initial / (to be redirect-friendly),
293 * but here we want to skip it
294 */
295 if (*path == '/')
296 path++;
298 strip = vhost_strip(c->host, path);
299 p = strip_path(path, strip);
301 if (*p == '/')
302 p = p+1;
303 if (*p == '\0')
304 p = ".";
306 dirfd = vhost_dirfd(c->host, path);
307 log_debug(c, "check_path: strip=%d path=%s original=%s",
308 strip, p, path);
309 flags = O_RDONLY | O_NOFOLLOW;
310 if (*fd == -1 && (*fd = openat(dirfd, p, flags)) == -1)
311 return FILE_MISSING;
313 if (fstat(*fd, &sb) == -1) {
314 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
315 return FILE_MISSING;
318 if (S_ISDIR(sb.st_mode))
319 return FILE_DIRECTORY;
321 if (sb.st_mode & S_IXUSR)
322 return FILE_EXECUTABLE;
324 return FILE_EXISTS;
327 static void
328 open_file(struct client *c)
330 switch (check_path(c, c->iri.path, &c->pfd)) {
331 case FILE_EXECUTABLE:
332 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
333 start_cgi(c->iri.path, "", c);
334 return;
337 /* fallthrough */
339 case FILE_EXISTS:
340 c->next = handle_copy;
341 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
342 return;
344 case FILE_DIRECTORY:
345 open_dir(c);
346 return;
348 case FILE_MISSING:
349 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
350 check_for_cgi(c);
351 return;
353 start_reply(c, NOT_FOUND, "not found");
354 return;
356 default:
357 /* unreachable */
358 abort();
362 /*
363 * the inverse of this algorithm, i.e. starting from the start of the
364 * path + strlen(cgi), and checking if each component, should be
365 * faster. But it's tedious to write. This does the opposite: starts
366 * from the end and strip one component at a time, until either an
367 * executable is found or we emptied the path.
368 */
369 static void
370 check_for_cgi(struct client *c)
372 char path[PATH_MAX];
373 char *end;
375 strlcpy(path, c->iri.path, sizeof(path));
376 end = strchr(path, '\0');
378 while (end > path) {
379 /* go up one level. UNIX paths are simple and POSIX
380 * dirname, with its ambiguities on if the given path
381 * is changed or not, gives me headaches. */
382 while (*end != '/')
383 end--;
384 *end = '\0';
386 switch (check_path(c, path, &c->pfd)) {
387 case FILE_EXECUTABLE:
388 start_cgi(path, end+1, c);
389 return;
390 case FILE_MISSING:
391 break;
392 default:
393 goto err;
396 *end = '/';
397 end--;
400 err:
401 start_reply(c, NOT_FOUND, "not found");
402 return;
405 void
406 mark_nonblock(int fd)
408 int flags;
410 if ((flags = fcntl(fd, F_GETFL)) == -1)
411 fatal("fcntl(F_GETFL): %s", strerror(errno));
412 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
413 fatal("fcntl(F_SETFL): %s", strerror(errno));
416 static void
417 handle_handshake(int fd, short ev, void *d)
419 struct client *c = d;
420 struct vhost *h;
421 struct alist *a;
422 const char *servname;
423 const char *parse_err = "unknown error";
425 switch (tls_handshake(c->ctx)) {
426 case 0: /* success */
427 case -1: /* already handshaked */
428 break;
429 case TLS_WANT_POLLIN:
430 yield_read(fd, c, &handle_handshake);
431 return;
432 case TLS_WANT_POLLOUT:
433 yield_write(fd, c, &handle_handshake);
434 return;
435 default:
436 /* unreachable */
437 abort();
440 servname = tls_conn_servername(c->ctx);
441 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
442 log_info(c, "puny_decode: %s", parse_err);
443 goto err;
446 TAILQ_FOREACH(h, &hosts, vhosts) {
447 if (matches(h->domain, c->domain))
448 goto found;
449 TAILQ_FOREACH(a, &h->aliases, aliases) {
450 if (matches(a->alias, c->domain))
451 goto found;
455 found:
456 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
457 servname != NULL ? servname : "(null)",
458 c->domain,
459 h != NULL ? h->domain : "(null)");
461 if (h != NULL) {
462 c->host = h;
463 handle_open_conn(fd, ev, c);
464 return;
467 err:
468 if (servname != NULL)
469 strncpy(c->req, servname, sizeof(c->req));
470 else
471 strncpy(c->req, "null", sizeof(c->req));
473 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
476 static char *
477 strip_path(char *path, int strip)
479 char *t;
481 while (strip > 0) {
482 if ((t = strchr(path, '/')) == NULL) {
483 path = strchr(path, '\0');
484 break;
486 path = t;
487 strip--;
490 return path;
493 static void
494 fmt_sbuf(const char *fmt, struct client *c, const char *path)
496 size_t i;
497 char buf[32];
499 memset(buf, 0, sizeof(buf));
500 for (i = 0; *fmt; ++fmt) {
501 if (i == sizeof(buf)-1 || *fmt == '%') {
502 strlcat(c->sbuf, buf, sizeof(c->sbuf));
503 memset(buf, 0, sizeof(buf));
504 i = 0;
507 if (*fmt != '%') {
508 buf[i++] = *fmt;
509 continue;
512 switch (*++fmt) {
513 case '%':
514 strlcat(c->sbuf, "%", sizeof(c->sbuf));
515 break;
516 case 'p':
517 strlcat(c->sbuf, path, sizeof(c->sbuf));
518 break;
519 case 'q':
520 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
521 break;
522 case 'P':
523 snprintf(buf, sizeof(buf), "%d", conf.port);
524 strlcat(c->sbuf, buf, sizeof(c->sbuf));
525 memset(buf, 0, sizeof(buf));
526 break;
527 case 'N':
528 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
529 break;
530 default:
531 fatal("%s: unknown fmt specifier %c",
532 __func__, *fmt);
536 if (i != 0)
537 strlcat(c->sbuf, buf, sizeof(c->sbuf));
540 /* 1 if a matching `block return' (and apply it), 0 otherwise */
541 static int
542 apply_block_return(struct client *c)
544 const char *fmt, *path;
545 int code;
547 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
548 return 0;
550 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
551 fmt_sbuf(fmt, c, path);
553 start_reply(c, code, c->sbuf);
554 return 1;
557 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
558 static int
559 apply_require_ca(struct client *c)
561 X509_STORE *store;
562 const uint8_t *cert;
563 size_t len;
565 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
566 return 0;
568 if (!tls_peer_cert_provided(c->ctx)) {
569 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
570 return 1;
573 cert = tls_peer_cert_chain_pem(c->ctx, &len);
574 if (!validate_against_ca(store, cert, len)) {
575 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
576 return 1;
579 return 0;
582 static void
583 handle_open_conn(int fd, short ev, void *d)
585 struct client *c = d;
586 const char *parse_err = "invalid request";
587 char decoded[DOMAIN_NAME_LEN];
589 bzero(c->req, sizeof(c->req));
590 bzero(&c->iri, sizeof(c->iri));
592 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
593 case -1:
594 log_err(c, "tls_read: %s", tls_error(c->ctx));
595 close_conn(fd, ev, c);
596 return;
598 case TLS_WANT_POLLIN:
599 yield_read(fd, c, &handle_open_conn);
600 return;
602 case TLS_WANT_POLLOUT:
603 yield_write(fd, c, &handle_open_conn);
604 return;
607 if (!trim_req_iri(c->req, &parse_err)
608 || !parse_iri(c->req, &c->iri, &parse_err)
609 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
610 log_info(c, "iri parse error: %s", parse_err);
611 start_reply(c, BAD_REQUEST, "invalid request");
612 return;
615 if (c->iri.port_no != conf.port
616 || strcmp(c->iri.schema, "gemini")
617 || strcmp(decoded, c->domain)) {
618 start_reply(c, PROXY_REFUSED, "won't proxy request");
619 return;
622 if (apply_require_ca(c))
623 return;
625 if (apply_block_return(c))
626 return;
628 if (c->host->entrypoint != NULL) {
629 start_cgi(c->host->entrypoint, c->iri.path, c);
630 return;
633 open_file(c);
636 static void
637 start_reply(struct client *c, int code, const char *meta)
639 c->code = code;
640 c->meta = meta;
641 handle_start_reply(c->fd, 0, c);
644 static void
645 handle_start_reply(int fd, short ev, void *d)
647 struct client *c = d;
648 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
649 const char *lang;
650 size_t len;
652 lang = vhost_lang(c->host, c->iri.path);
654 snprintf(buf, sizeof(buf), "%d ", c->code);
655 strlcat(buf, c->meta, sizeof(buf));
656 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
657 strlcat(buf, "; lang=", sizeof(buf));
658 strlcat(buf, lang, sizeof(buf));
661 len = strlcat(buf, "\r\n", sizeof(buf));
662 assert(len < sizeof(buf));
664 switch (tls_write(c->ctx, buf, len)) {
665 case -1:
666 close_conn(fd, ev, c);
667 return;
668 case TLS_WANT_POLLIN:
669 yield_read(fd, c, &handle_start_reply);
670 return;
671 case TLS_WANT_POLLOUT:
672 yield_write(fd, c, &handle_start_reply);
673 return;
676 if (!vhost_disable_log(c->host, c->iri.path))
677 log_request(c, buf, sizeof(buf));
679 if (c->code != SUCCESS)
680 close_conn(fd, ev, c);
681 else
682 c->next(fd, ev, c);
685 static size_t
686 host_nth(struct vhost *h)
688 struct vhost *v;
689 size_t i = 0;
691 TAILQ_FOREACH(v, &hosts, vhosts) {
692 if (v == h)
693 return i;
694 i++;
697 abort();
700 static void
701 start_cgi(const char *spath, const char *relpath, struct client *c)
703 char addr[NI_MAXHOST];
704 const char *t;
705 struct cgireq req;
706 int e;
708 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
709 addr, sizeof(addr),
710 NULL, 0,
711 NI_NUMERICHOST);
712 if (e != 0)
713 fatal("getnameinfo failed");
715 memset(&req, 0, sizeof(req));
717 memcpy(req.buf, c->req, sizeof(req.buf));
719 req.iri_schema_off = c->iri.schema - c->req;
720 req.iri_host_off = c->iri.host - c->req;
721 req.iri_port_off = c->iri.port - c->req;
722 req.iri_path_off = c->iri.path - c->req;
723 req.iri_query_off = c->iri.query - c->req;
724 req.iri_fragment_off = c->iri.fragment - c->req;
726 req.iri_portno = c->iri.port_no;
728 strlcpy(req.spath, spath, sizeof(req.spath));
729 strlcpy(req.relpath, relpath, sizeof(req.relpath));
730 strlcpy(req.addr, addr, sizeof(req.addr));
732 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
733 strlcpy(req.subject, t, sizeof(req.subject));
734 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
735 strlcpy(req.issuer, t, sizeof(req.issuer));
736 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
737 strlcpy(req.hash, t, sizeof(req.hash));
738 if ((t = tls_conn_version(c->ctx)) != NULL)
739 strlcpy(req.version, t, sizeof(req.version));
740 if ((t = tls_conn_cipher(c->ctx)) != NULL)
741 strlcpy(req.cipher, t, sizeof(req.cipher));
743 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
744 req.notbefore = tls_peer_cert_notbefore(c->ctx);
745 req.notafter = tls_peer_cert_notafter(c->ctx);
747 req.host_off = host_nth(c->host);
749 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
750 imsg_flush(&exibuf);
752 close(c->pfd);
755 static void
756 open_dir(struct client *c)
758 size_t len;
759 int dirfd, root;
760 char *before_file;
762 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
764 len = strlen(c->iri.path);
765 if (len > 0 && !ends_with(c->iri.path, "/")) {
766 redirect_canonical_dir(c);
767 return;
770 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
771 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
772 if (!ends_with(c->sbuf, "/"))
773 strlcat(c->sbuf, "/", sizeof(c->sbuf));
774 before_file = strchr(c->sbuf, '\0');
775 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
776 sizeof(c->sbuf));
777 if (len >= sizeof(c->sbuf)) {
778 start_reply(c, TEMP_FAILURE, "internal server error");
779 return;
782 c->iri.path = c->sbuf;
784 /* close later unless we have to generate the dir listing */
785 dirfd = c->pfd;
786 c->pfd = -1;
788 switch (check_path(c, c->iri.path, &c->pfd)) {
789 case FILE_EXECUTABLE:
790 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
791 start_cgi(c->iri.path, "", c);
792 break;
795 /* fallthrough */
797 case FILE_EXISTS:
798 c->next = handle_copy;
799 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
800 break;
802 case FILE_DIRECTORY:
803 start_reply(c, TEMP_REDIRECT, c->sbuf);
804 break;
806 case FILE_MISSING:
807 *before_file = '\0';
809 if (!vhost_auto_index(c->host, c->iri.path)) {
810 start_reply(c, NOT_FOUND, "not found");
811 break;
814 c->next = enter_handle_dirlist;
816 c->dirlen = scandir_fd(dirfd, &c->dir,
817 root ? select_non_dotdot : select_non_dot,
818 alphasort);
819 if (c->dirlen == -1) {
820 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
821 c->pfd, c->host->domain, c->iri.path, strerror(errno));
822 start_reply(c, TEMP_FAILURE, "internal server error");
823 return;
825 c->diroff = 0;
826 c->off = 0;
828 start_reply(c, SUCCESS, "text/gemini");
829 return;
831 default:
832 /* unreachable */
833 abort();
836 close(dirfd);
839 static void
840 redirect_canonical_dir(struct client *c)
842 size_t len;
844 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
845 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
846 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
848 if (len >= sizeof(c->sbuf)) {
849 start_reply(c, TEMP_FAILURE, "internal server error");
850 return;
853 start_reply(c, TEMP_REDIRECT, c->sbuf);
856 static void
857 enter_handle_dirlist(int fd, short ev, void *d)
859 struct client *c = d;
860 char b[PATH_MAX];
861 size_t l;
863 strlcpy(b, c->iri.path, sizeof(b));
864 l = snprintf(c->sbuf, sizeof(c->sbuf),
865 "# Index of %s\n\n", b);
866 if (l >= sizeof(c->sbuf)) {
867 /* this is impossible, given that we have enough space
868 * in c->sbuf to hold the ancilliary string plus the
869 * full path; but it wouldn't read nice without some
870 * error checking, and I'd like to avoid a strlen. */
871 close_conn(fd, ev, c);
872 return;
875 c->len = l;
876 handle_dirlist(fd, ev, c);
879 static void
880 handle_dirlist(int fd, short ev, void *d)
882 struct client *c = d;
883 ssize_t r;
885 while (c->len > 0) {
886 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
887 case -1:
888 close_conn(fd, ev, c);
889 return;
890 case TLS_WANT_POLLOUT:
891 yield_read(fd, c, &handle_dirlist);
892 return;
893 case TLS_WANT_POLLIN:
894 yield_write(fd, c, &handle_dirlist);
895 return;
896 default:
897 c->off += r;
898 c->len -= r;
902 send_directory_listing(fd, ev, c);
905 static int
906 read_next_dir_entry(struct client *c)
908 if (c->diroff == c->dirlen)
909 return 0;
911 /* XXX: url escape */
912 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
913 c->dir[c->diroff]->d_name);
915 free(c->dir[c->diroff]);
916 c->diroff++;
918 c->len = strlen(c->sbuf);
919 c->off = 0;
920 return 1;
923 static void
924 send_directory_listing(int fd, short ev, void *d)
926 struct client *c = d;
927 ssize_t r;
929 while (1) {
930 if (c->len == 0) {
931 if (!read_next_dir_entry(c))
932 goto end;
935 while (c->len > 0) {
936 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
937 case -1:
938 goto end;
940 case TLS_WANT_POLLOUT:
941 yield_read(fd, c, &send_directory_listing);
942 return;
944 case TLS_WANT_POLLIN:
945 yield_write(fd, c, &send_directory_listing);
946 return;
948 default:
949 c->off += r;
950 c->len -= r;
951 break;
956 end:
957 close_conn(fd, ev, d);
960 /* accumulate the meta line from the cgi script. */
961 static void
962 handle_cgi_reply(int fd, short ev, void *d)
964 struct client *c = d;
965 void *buf, *e;
966 size_t len;
967 ssize_t r;
970 buf = c->sbuf + c->len;
971 len = sizeof(c->sbuf) - c->len;
973 r = read(c->pfd, buf, len);
974 if (r == 0 || r == -1) {
975 start_reply(c, CGI_ERROR, "CGI error");
976 return;
979 c->len += r;
981 /* TODO: error if the CGI script don't reply correctly */
982 e = strchr(c->sbuf, '\n');
983 if (e != NULL || c->len == sizeof(c->sbuf)) {
984 log_request(c, c->sbuf, c->len);
986 c->off = 0;
987 handle_copy(fd, ev, c);
988 return;
991 yield_read(fd, c, &handle_cgi_reply);
994 static void
995 handle_copy(int fd, short ev, void *d)
997 struct client *c = d;
998 ssize_t r;
1000 while (1) {
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_write(c->fd, c, &handle_copy);
1008 return;
1010 case TLS_WANT_POLLIN:
1011 yield_read(c->fd, c, &handle_copy);
1012 return;
1014 default:
1015 c->off += r;
1016 c->len -= r;
1017 break;
1021 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1022 case 0:
1023 goto end;
1024 case -1:
1025 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1026 yield_read(c->pfd, c, &handle_copy);
1027 return;
1029 goto end;
1030 default:
1031 c->len = r;
1032 c->off = 0;
1036 end:
1037 close_conn(c->fd, ev, d);
1040 static void
1041 close_conn(int fd, short ev, void *d)
1043 struct client *c = d;
1045 switch (tls_close(c->ctx)) {
1046 case TLS_WANT_POLLIN:
1047 yield_read(fd, c, &close_conn);
1048 return;
1049 case TLS_WANT_POLLOUT:
1050 yield_read(fd, c, &close_conn);
1051 return;
1054 connected_clients--;
1056 tls_free(c->ctx);
1057 c->ctx = NULL;
1059 if (c->pfd != -1)
1060 close(c->pfd);
1062 if (c->dir != NULL)
1063 free(c->dir);
1065 close(c->fd);
1066 c->fd = -1;
1069 static void
1070 do_accept(int sock, short et, void *d)
1072 struct client *c;
1073 struct sockaddr_storage addr;
1074 struct sockaddr *saddr;
1075 socklen_t len;
1076 int i, fd;
1078 (void)et;
1080 saddr = (struct sockaddr*)&addr;
1081 len = sizeof(addr);
1082 if ((fd = accept(sock, saddr, &len)) == -1) {
1083 if (errno == EWOULDBLOCK || errno == EAGAIN)
1084 return;
1085 fatal("accept: %s", strerror(errno));
1088 mark_nonblock(fd);
1090 for (i = 0; i < MAX_USERS; ++i) {
1091 c = &clients[i];
1092 if (c->fd == -1) {
1093 memset(c, 0, sizeof(*c));
1094 c->id = i;
1095 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1096 break; /* goodbye fd! */
1098 c->fd = fd;
1099 c->pfd = -1;
1100 c->dir = NULL;
1101 c->addr = addr;
1103 yield_read(fd, c, &handle_handshake);
1104 connected_clients++;
1105 return;
1109 close(fd);
1112 struct client *
1113 client_by_id(int id)
1115 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1116 fatal("in client_by_id: invalid id %d", id);
1117 return &clients[id];
1120 static void
1121 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1123 struct client *c;
1125 c = client_by_id(imsg->hdr.peerid);
1127 if ((c->pfd = imsg->fd) == -1)
1128 start_reply(c, TEMP_FAILURE, "internal server error");
1129 else
1130 yield_read(c->pfd, c, &handle_cgi_reply);
1133 static void
1134 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1136 (void)imsg;
1137 (void)len;
1139 /* don't call event_loopbreak since we want to finish to
1140 * handle the ongoing connections. */
1142 event_del(&e4);
1143 if (has_ipv6)
1144 event_del(&e6);
1145 if (has_siginfo)
1146 signal_del(&siginfo);
1147 event_del(&imsgev);
1148 signal_del(&sigusr2);
1151 static void
1152 handle_dispatch_imsg(int fd, short ev, void *d)
1154 struct imsgbuf *ibuf = d;
1155 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1158 static void
1159 handle_siginfo(int fd, short ev, void *d)
1161 (void)fd;
1162 (void)ev;
1163 (void)d;
1165 log_info(NULL, "%d connected clients", connected_clients);
1168 void
1169 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1171 size_t i;
1173 ctx = ctx_;
1175 event_init();
1177 memset(&clients, 0, sizeof(clients));
1178 for (i = 0; i < MAX_USERS; ++i)
1179 clients[i].fd = -1;
1181 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1182 event_add(&e4, NULL);
1184 if (sock6 != -1) {
1185 has_ipv6 = 1;
1186 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1187 event_add(&e6, NULL);
1190 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1191 event_add(&imsgev, NULL);
1193 #ifdef SIGINFO
1194 has_siginfo = 1;
1195 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1196 signal_add(&siginfo, NULL);
1197 #endif
1198 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1199 signal_add(&sigusr2, NULL);
1201 sandbox_server_process();
1202 event_dispatch();
1203 _exit(0);