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 if (*path != '/')
518 strlcat(c->sbuf, "/", sizeof(c->sbuf));
519 strlcat(c->sbuf, path, sizeof(c->sbuf));
520 break;
521 case 'q':
522 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
523 break;
524 case 'P':
525 snprintf(buf, sizeof(buf), "%d", conf.port);
526 strlcat(c->sbuf, buf, sizeof(c->sbuf));
527 memset(buf, 0, sizeof(buf));
528 break;
529 case 'N':
530 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
531 break;
532 default:
533 fatal("%s: unknown fmt specifier %c",
534 __func__, *fmt);
538 if (i != 0)
539 strlcat(c->sbuf, buf, sizeof(c->sbuf));
542 /* 1 if a matching `block return' (and apply it), 0 otherwise */
543 static int
544 apply_block_return(struct client *c)
546 const char *fmt, *path;
547 int code;
549 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
550 return 0;
552 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
553 fmt_sbuf(fmt, c, path);
555 start_reply(c, code, c->sbuf);
556 return 1;
559 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
560 static int
561 apply_require_ca(struct client *c)
563 X509_STORE *store;
564 const uint8_t *cert;
565 size_t len;
567 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
568 return 0;
570 if (!tls_peer_cert_provided(c->ctx)) {
571 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
572 return 1;
575 cert = tls_peer_cert_chain_pem(c->ctx, &len);
576 if (!validate_against_ca(store, cert, len)) {
577 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
578 return 1;
581 return 0;
584 static void
585 handle_open_conn(int fd, short ev, void *d)
587 struct client *c = d;
588 const char *parse_err = "invalid request";
589 char decoded[DOMAIN_NAME_LEN];
591 bzero(c->req, sizeof(c->req));
592 bzero(&c->iri, sizeof(c->iri));
594 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
595 case -1:
596 log_err(c, "tls_read: %s", tls_error(c->ctx));
597 close_conn(fd, ev, c);
598 return;
600 case TLS_WANT_POLLIN:
601 yield_read(fd, c, &handle_open_conn);
602 return;
604 case TLS_WANT_POLLOUT:
605 yield_write(fd, c, &handle_open_conn);
606 return;
609 if (!trim_req_iri(c->req, &parse_err)
610 || !parse_iri(c->req, &c->iri, &parse_err)
611 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
612 log_info(c, "iri parse error: %s", parse_err);
613 start_reply(c, BAD_REQUEST, "invalid request");
614 return;
617 if (c->iri.port_no != conf.port
618 || strcmp(c->iri.schema, "gemini")
619 || strcmp(decoded, c->domain)) {
620 start_reply(c, PROXY_REFUSED, "won't proxy request");
621 return;
624 if (apply_require_ca(c))
625 return;
627 if (apply_block_return(c))
628 return;
630 if (c->host->entrypoint != NULL) {
631 start_cgi(c->host->entrypoint, c->iri.path, c);
632 return;
635 open_file(c);
638 static void
639 start_reply(struct client *c, int code, const char *meta)
641 c->code = code;
642 c->meta = meta;
643 handle_start_reply(c->fd, 0, c);
646 static void
647 handle_start_reply(int fd, short ev, void *d)
649 struct client *c = d;
650 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
651 const char *lang;
652 size_t len;
654 lang = vhost_lang(c->host, c->iri.path);
656 snprintf(buf, sizeof(buf), "%d ", c->code);
657 strlcat(buf, c->meta, sizeof(buf));
658 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
659 strlcat(buf, "; lang=", sizeof(buf));
660 strlcat(buf, lang, sizeof(buf));
663 len = strlcat(buf, "\r\n", sizeof(buf));
664 assert(len < sizeof(buf));
666 switch (tls_write(c->ctx, buf, len)) {
667 case -1:
668 close_conn(fd, ev, c);
669 return;
670 case TLS_WANT_POLLIN:
671 yield_read(fd, c, &handle_start_reply);
672 return;
673 case TLS_WANT_POLLOUT:
674 yield_write(fd, c, &handle_start_reply);
675 return;
678 if (!vhost_disable_log(c->host, c->iri.path))
679 log_request(c, buf, sizeof(buf));
681 if (c->code != SUCCESS)
682 close_conn(fd, ev, c);
683 else
684 c->next(fd, ev, c);
687 static size_t
688 host_nth(struct vhost *h)
690 struct vhost *v;
691 size_t i = 0;
693 TAILQ_FOREACH(v, &hosts, vhosts) {
694 if (v == h)
695 return i;
696 i++;
699 abort();
702 static void
703 start_cgi(const char *spath, const char *relpath, struct client *c)
705 char addr[NI_MAXHOST];
706 const char *t;
707 struct cgireq req;
708 int e;
710 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
711 addr, sizeof(addr),
712 NULL, 0,
713 NI_NUMERICHOST);
714 if (e != 0)
715 fatal("getnameinfo failed");
717 memset(&req, 0, sizeof(req));
719 memcpy(req.buf, c->req, sizeof(req.buf));
721 req.iri_schema_off = c->iri.schema - c->req;
722 req.iri_host_off = c->iri.host - c->req;
723 req.iri_port_off = c->iri.port - c->req;
724 req.iri_path_off = c->iri.path - c->req;
725 req.iri_query_off = c->iri.query - c->req;
726 req.iri_fragment_off = c->iri.fragment - c->req;
728 req.iri_portno = c->iri.port_no;
730 strlcpy(req.spath, spath, sizeof(req.spath));
731 strlcpy(req.relpath, relpath, sizeof(req.relpath));
732 strlcpy(req.addr, addr, sizeof(req.addr));
734 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
735 strlcpy(req.subject, t, sizeof(req.subject));
736 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
737 strlcpy(req.issuer, t, sizeof(req.issuer));
738 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
739 strlcpy(req.hash, t, sizeof(req.hash));
740 if ((t = tls_conn_version(c->ctx)) != NULL)
741 strlcpy(req.version, t, sizeof(req.version));
742 if ((t = tls_conn_cipher(c->ctx)) != NULL)
743 strlcpy(req.cipher, t, sizeof(req.cipher));
745 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
746 req.notbefore = tls_peer_cert_notbefore(c->ctx);
747 req.notafter = tls_peer_cert_notafter(c->ctx);
749 req.host_off = host_nth(c->host);
751 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
752 imsg_flush(&exibuf);
754 close(c->pfd);
757 static void
758 open_dir(struct client *c)
760 size_t len;
761 int dirfd, root;
762 char *before_file;
764 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
766 len = strlen(c->iri.path);
767 if (len > 0 && !ends_with(c->iri.path, "/")) {
768 redirect_canonical_dir(c);
769 return;
772 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
773 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
774 if (!ends_with(c->sbuf, "/"))
775 strlcat(c->sbuf, "/", sizeof(c->sbuf));
776 before_file = strchr(c->sbuf, '\0');
777 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
778 sizeof(c->sbuf));
779 if (len >= sizeof(c->sbuf)) {
780 start_reply(c, TEMP_FAILURE, "internal server error");
781 return;
784 c->iri.path = c->sbuf;
786 /* close later unless we have to generate the dir listing */
787 dirfd = c->pfd;
788 c->pfd = -1;
790 switch (check_path(c, c->iri.path, &c->pfd)) {
791 case FILE_EXECUTABLE:
792 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
793 start_cgi(c->iri.path, "", c);
794 break;
797 /* fallthrough */
799 case FILE_EXISTS:
800 c->next = handle_copy;
801 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
802 break;
804 case FILE_DIRECTORY:
805 start_reply(c, TEMP_REDIRECT, c->sbuf);
806 break;
808 case FILE_MISSING:
809 *before_file = '\0';
811 if (!vhost_auto_index(c->host, c->iri.path)) {
812 start_reply(c, NOT_FOUND, "not found");
813 break;
816 c->next = enter_handle_dirlist;
818 c->dirlen = scandir_fd(dirfd, &c->dir,
819 root ? select_non_dotdot : select_non_dot,
820 alphasort);
821 if (c->dirlen == -1) {
822 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
823 c->pfd, c->host->domain, c->iri.path, strerror(errno));
824 start_reply(c, TEMP_FAILURE, "internal server error");
825 return;
827 c->diroff = 0;
828 c->off = 0;
830 start_reply(c, SUCCESS, "text/gemini");
831 return;
833 default:
834 /* unreachable */
835 abort();
838 close(dirfd);
841 static void
842 redirect_canonical_dir(struct client *c)
844 size_t len;
846 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
847 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
848 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
850 if (len >= sizeof(c->sbuf)) {
851 start_reply(c, TEMP_FAILURE, "internal server error");
852 return;
855 start_reply(c, TEMP_REDIRECT, c->sbuf);
858 static void
859 enter_handle_dirlist(int fd, short ev, void *d)
861 struct client *c = d;
862 char b[PATH_MAX];
863 size_t l;
865 strlcpy(b, c->iri.path, sizeof(b));
866 l = snprintf(c->sbuf, sizeof(c->sbuf),
867 "# Index of %s\n\n", b);
868 if (l >= sizeof(c->sbuf)) {
869 /* this is impossible, given that we have enough space
870 * in c->sbuf to hold the ancilliary string plus the
871 * full path; but it wouldn't read nice without some
872 * error checking, and I'd like to avoid a strlen. */
873 close_conn(fd, ev, c);
874 return;
877 c->len = l;
878 handle_dirlist(fd, ev, c);
881 static void
882 handle_dirlist(int fd, short ev, void *d)
884 struct client *c = d;
885 ssize_t r;
887 while (c->len > 0) {
888 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
889 case -1:
890 close_conn(fd, ev, c);
891 return;
892 case TLS_WANT_POLLOUT:
893 yield_read(fd, c, &handle_dirlist);
894 return;
895 case TLS_WANT_POLLIN:
896 yield_write(fd, c, &handle_dirlist);
897 return;
898 default:
899 c->off += r;
900 c->len -= r;
904 send_directory_listing(fd, ev, c);
907 static int
908 read_next_dir_entry(struct client *c)
910 if (c->diroff == c->dirlen)
911 return 0;
913 /* XXX: url escape */
914 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
915 c->dir[c->diroff]->d_name);
917 free(c->dir[c->diroff]);
918 c->diroff++;
920 c->len = strlen(c->sbuf);
921 c->off = 0;
922 return 1;
925 static void
926 send_directory_listing(int fd, short ev, void *d)
928 struct client *c = d;
929 ssize_t r;
931 while (1) {
932 if (c->len == 0) {
933 if (!read_next_dir_entry(c))
934 goto end;
937 while (c->len > 0) {
938 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
939 case -1:
940 goto end;
942 case TLS_WANT_POLLOUT:
943 yield_read(fd, c, &send_directory_listing);
944 return;
946 case TLS_WANT_POLLIN:
947 yield_write(fd, c, &send_directory_listing);
948 return;
950 default:
951 c->off += r;
952 c->len -= r;
953 break;
958 end:
959 close_conn(fd, ev, d);
962 /* accumulate the meta line from the cgi script. */
963 static void
964 handle_cgi_reply(int fd, short ev, void *d)
966 struct client *c = d;
967 void *buf, *e;
968 size_t len;
969 ssize_t r;
972 buf = c->sbuf + c->len;
973 len = sizeof(c->sbuf) - c->len;
975 r = read(c->pfd, buf, len);
976 if (r == 0 || r == -1) {
977 start_reply(c, CGI_ERROR, "CGI error");
978 return;
981 c->len += r;
983 /* TODO: error if the CGI script don't reply correctly */
984 e = strchr(c->sbuf, '\n');
985 if (e != NULL || c->len == sizeof(c->sbuf)) {
986 log_request(c, c->sbuf, c->len);
988 c->off = 0;
989 handle_copy(fd, ev, c);
990 return;
993 yield_read(fd, c, &handle_cgi_reply);
996 static void
997 handle_copy(int fd, short ev, void *d)
999 struct client *c = d;
1000 ssize_t r;
1002 while (1) {
1003 while (c->len > 0) {
1004 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1005 case -1:
1006 goto end;
1008 case TLS_WANT_POLLOUT:
1009 yield_write(c->fd, c, &handle_copy);
1010 return;
1012 case TLS_WANT_POLLIN:
1013 yield_read(c->fd, c, &handle_copy);
1014 return;
1016 default:
1017 c->off += r;
1018 c->len -= r;
1019 break;
1023 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1024 case 0:
1025 goto end;
1026 case -1:
1027 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1028 yield_read(c->pfd, c, &handle_copy);
1029 return;
1031 goto end;
1032 default:
1033 c->len = r;
1034 c->off = 0;
1038 end:
1039 close_conn(c->fd, ev, d);
1042 static void
1043 close_conn(int fd, short ev, void *d)
1045 struct client *c = d;
1047 switch (tls_close(c->ctx)) {
1048 case TLS_WANT_POLLIN:
1049 yield_read(fd, c, &close_conn);
1050 return;
1051 case TLS_WANT_POLLOUT:
1052 yield_read(fd, c, &close_conn);
1053 return;
1056 connected_clients--;
1058 tls_free(c->ctx);
1059 c->ctx = NULL;
1061 if (c->pfd != -1)
1062 close(c->pfd);
1064 if (c->dir != NULL)
1065 free(c->dir);
1067 close(c->fd);
1068 c->fd = -1;
1071 static void
1072 do_accept(int sock, short et, void *d)
1074 struct client *c;
1075 struct sockaddr_storage addr;
1076 struct sockaddr *saddr;
1077 socklen_t len;
1078 int i, fd;
1080 (void)et;
1082 saddr = (struct sockaddr*)&addr;
1083 len = sizeof(addr);
1084 if ((fd = accept(sock, saddr, &len)) == -1) {
1085 if (errno == EWOULDBLOCK || errno == EAGAIN)
1086 return;
1087 fatal("accept: %s", strerror(errno));
1090 mark_nonblock(fd);
1092 for (i = 0; i < MAX_USERS; ++i) {
1093 c = &clients[i];
1094 if (c->fd == -1) {
1095 memset(c, 0, sizeof(*c));
1096 c->id = i;
1097 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1098 break; /* goodbye fd! */
1100 c->fd = fd;
1101 c->pfd = -1;
1102 c->dir = NULL;
1103 c->addr = addr;
1105 yield_read(fd, c, &handle_handshake);
1106 connected_clients++;
1107 return;
1111 close(fd);
1114 struct client *
1115 client_by_id(int id)
1117 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1118 fatal("in client_by_id: invalid id %d", id);
1119 return &clients[id];
1122 static void
1123 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1125 struct client *c;
1127 c = client_by_id(imsg->hdr.peerid);
1129 if ((c->pfd = imsg->fd) == -1)
1130 start_reply(c, TEMP_FAILURE, "internal server error");
1131 else
1132 yield_read(c->pfd, c, &handle_cgi_reply);
1135 static void
1136 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1138 (void)imsg;
1139 (void)len;
1141 /* don't call event_loopbreak since we want to finish to
1142 * handle the ongoing connections. */
1144 event_del(&e4);
1145 if (has_ipv6)
1146 event_del(&e6);
1147 if (has_siginfo)
1148 signal_del(&siginfo);
1149 event_del(&imsgev);
1150 signal_del(&sigusr2);
1153 static void
1154 handle_dispatch_imsg(int fd, short ev, void *d)
1156 struct imsgbuf *ibuf = d;
1157 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1160 static void
1161 handle_siginfo(int fd, short ev, void *d)
1163 (void)fd;
1164 (void)ev;
1165 (void)d;
1167 log_info(NULL, "%d connected clients", connected_clients);
1170 void
1171 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1173 size_t i;
1175 ctx = ctx_;
1177 event_init();
1179 memset(&clients, 0, sizeof(clients));
1180 for (i = 0; i < MAX_USERS; ++i)
1181 clients[i].fd = -1;
1183 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1184 event_add(&e4, NULL);
1186 if (sock6 != -1) {
1187 has_ipv6 = 1;
1188 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1189 event_add(&e6, NULL);
1192 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1193 event_add(&imsgev, NULL);
1195 #ifdef SIGINFO
1196 has_siginfo = 1;
1197 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1198 signal_add(&siginfo, NULL);
1199 #endif
1200 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1201 signal_add(&sigusr2, NULL);
1203 sandbox_server_process();
1204 event_dispatch();
1205 _exit(0);