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 reschedule_read(int, struct client*, statefn);
40 static inline void reschedule_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 void start_cgi(const char*, const char*, struct client*);
54 static void open_dir(struct client*);
55 static void redirect_canonical_dir(struct client*);
56 static void enter_handle_dirlist(int, short, void*);
57 static void handle_dirlist(int, short, void*);
58 static int read_next_dir_entry(struct client*);
59 static void send_directory_listing(int, short, void*);
60 static void handle_cgi_reply(int, short, void*);
61 static void handle_copy(int, short, void*);
62 static void close_conn(int, short, void*);
63 static void do_accept(int, short, void*);
64 struct client *client_by_id(int);
65 static void handle_imsg_cgi_res(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 };
74 static inline int
75 matches(const char *pattern, const char *path)
76 {
77 if (*path == '/')
78 path++;
79 return !fnmatch(pattern, path, 0);
80 }
82 static inline void
83 reschedule_read(int fd, struct client *c, statefn fn)
84 {
85 event_once(fd, EV_READ, fn, c, NULL);
86 }
88 static inline void
89 reschedule_write(int fd, struct client *c, statefn fn)
90 {
91 event_once(fd, EV_WRITE, fn, c, NULL);
92 }
94 const char *
95 vhost_lang(struct vhost *v, const char *path)
96 {
97 struct location *loc;
99 if (v == NULL || path == NULL)
100 return NULL;
102 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
103 if (loc->lang != NULL) {
104 if (matches(loc->match, path))
105 return loc->lang;
109 return v->locations[0].lang;
112 const char *
113 vhost_default_mime(struct vhost *v, const char *path)
115 struct location *loc;
116 const char *default_mime = "application/octet-stream";
118 if (v == NULL || path == NULL)
119 return default_mime;
121 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
122 if (loc->default_mime != NULL) {
123 if (matches(loc->match, path))
124 return loc->default_mime;
128 if (v->locations[0].default_mime != NULL)
129 return v->locations[0].default_mime;
130 return default_mime;
133 const char *
134 vhost_index(struct vhost *v, const char *path)
136 struct location *loc;
137 const char *index = "index.gmi";
139 if (v == NULL || path == NULL)
140 return index;
142 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
143 if (loc->index != NULL) {
144 if (matches(loc->match, path))
145 return loc->index;
149 if (v->locations[0].index != NULL)
150 return v->locations[0].index;
151 return index;
154 int
155 vhost_auto_index(struct vhost *v, const char *path)
157 struct location *loc;
159 if (v == NULL || path == NULL)
160 return 0;
162 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
163 if (loc->auto_index != 0) {
164 if (matches(loc->match, path))
165 return loc->auto_index == 1;
169 return v->locations[0].auto_index == 1;
172 int
173 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
175 struct location *loc;
177 if (v == NULL || path == NULL)
178 return 0;
180 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
181 if (loc->block_code != 0) {
182 if (matches(loc->match, path)) {
183 *code = loc->block_code;
184 *fmt = loc->block_fmt;
185 return 1;
190 *code = v->locations[0].block_code;
191 *fmt = v->locations[0].block_fmt;
192 return v->locations[0].block_code != 0;
195 int
196 vhost_strip(struct vhost *v, const char *path)
198 struct location *loc;
200 if (v == NULL || path == NULL)
201 return 0;
203 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
204 if (loc->strip != 0) {
205 if (matches(loc->match, path))
206 return loc->strip;
210 return v->locations[0].strip;
213 X509_STORE *
214 vhost_require_ca(struct vhost *v, const char *path)
216 struct location *loc;
218 if (v == NULL || path == NULL)
219 return NULL;
221 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
222 if (loc->reqca != NULL) {
223 if (matches(loc->match, path))
224 return loc->reqca;
228 return v->locations[0].reqca;
231 int
232 vhost_disable_log(struct vhost *v, const char *path)
234 struct location *loc;
236 if (v == NULL || path == NULL)
237 return 0;
239 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
240 if (loc->disable_log && matches(loc->match, path))
241 return 1;
244 return v->locations[0].disable_log;
247 static int
248 check_path(struct client *c, const char *path, int *fd)
250 struct stat sb;
251 const char *p;
252 int flags;
254 assert(path != NULL);
256 if (*path == '\0')
257 p = ".";
258 else if (*path == '/')
259 /* in send_dir we add an initial / (to be
260 * redirect-friendly), but here we want to skip it */
261 p = path+1;
262 else
263 p = path;
265 flags = O_RDONLY | O_NOFOLLOW;
267 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
268 return FILE_MISSING;
270 if (fstat(*fd, &sb) == -1) {
271 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
272 return FILE_MISSING;
275 if (S_ISDIR(sb.st_mode))
276 return FILE_DIRECTORY;
278 if (sb.st_mode & S_IXUSR)
279 return FILE_EXECUTABLE;
281 return FILE_EXISTS;
284 static void
285 open_file(struct client *c)
287 switch (check_path(c, c->iri.path, &c->pfd)) {
288 case FILE_EXECUTABLE:
289 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
290 start_cgi(c->iri.path, "", c);
291 return;
294 /* fallthrough */
296 case FILE_EXISTS:
297 c->next = handle_copy;
298 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
299 return;
301 case FILE_DIRECTORY:
302 open_dir(c);
303 return;
305 case FILE_MISSING:
306 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
307 check_for_cgi(c);
308 return;
310 start_reply(c, NOT_FOUND, "not found");
311 return;
313 default:
314 /* unreachable */
315 abort();
319 /*
320 * the inverse of this algorithm, i.e. starting from the start of the
321 * path + strlen(cgi), and checking if each component, should be
322 * faster. But it's tedious to write. This does the opposite: starts
323 * from the end and strip one component at a time, until either an
324 * executable is found or we emptied the path.
325 */
326 static void
327 check_for_cgi(struct client *c)
329 char path[PATH_MAX];
330 char *end;
332 strlcpy(path, c->iri.path, sizeof(path));
333 end = strchr(path, '\0');
335 while (end > path) {
336 /* go up one level. UNIX paths are simple and POSIX
337 * dirname, with its ambiguities on if the given path
338 * is changed or not, gives me headaches. */
339 while (*end != '/')
340 end--;
341 *end = '\0';
343 switch (check_path(c, path, &c->pfd)) {
344 case FILE_EXECUTABLE:
345 start_cgi(path, end+1, c);
346 return;
347 case FILE_MISSING:
348 break;
349 default:
350 goto err;
353 *end = '/';
354 end--;
357 err:
358 start_reply(c, NOT_FOUND, "not found");
359 return;
362 void
363 mark_nonblock(int fd)
365 int flags;
367 if ((flags = fcntl(fd, F_GETFL)) == -1)
368 fatal("fcntl(F_GETFL): %s", strerror(errno));
369 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
370 fatal("fcntl(F_SETFL): %s", strerror(errno));
373 static void
374 handle_handshake(int fd, short ev, void *d)
376 struct client *c = d;
377 struct vhost *h;
378 const char *servname;
379 const char *parse_err = "unknown error";
381 switch (tls_handshake(c->ctx)) {
382 case 0: /* success */
383 case -1: /* already handshaked */
384 break;
385 case TLS_WANT_POLLIN:
386 reschedule_read(fd, c, &handle_handshake);
387 return;
388 case TLS_WANT_POLLOUT:
389 reschedule_write(fd, c, &handle_handshake);
390 return;
391 default:
392 /* unreachable */
393 abort();
396 servname = tls_conn_servername(c->ctx);
397 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
398 log_info(c, "puny_decode: %s", parse_err);
399 goto err;
402 for (h = hosts; h->domain != NULL; ++h) {
403 if (matches(h->domain, c->domain))
404 break;
407 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
408 servname != NULL ? servname : "(null)",
409 c->domain,
410 h->domain != NULL ? h->domain : "(null)");
412 if (h->domain != NULL) {
413 c->host = h;
414 handle_open_conn(fd, ev, c);
415 return;
418 err:
419 if (servname != NULL)
420 strncpy(c->req, servname, sizeof(c->req));
421 else
422 strncpy(c->req, "null", sizeof(c->req));
424 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
427 static char *
428 strip_path(char *path, int strip)
430 char *t;
432 while (strip > 0) {
433 if ((t = strchr(path, '/')) == NULL) {
434 path = strchr(path, '\0');
435 break;
437 path = t;
438 strip--;
441 return path;
444 static void
445 fmt_sbuf(const char *fmt, struct client *c, const char *path)
447 size_t i;
448 char buf[32];
450 memset(buf, 0, sizeof(buf));
451 for (i = 0; *fmt; ++fmt) {
452 if (i == sizeof(buf)-1 || *fmt == '%') {
453 strlcat(c->sbuf, buf, sizeof(c->sbuf));
454 memset(buf, 0, sizeof(buf));
455 i = 0;
458 if (*fmt != '%') {
459 buf[i++] = *fmt;
460 continue;
463 switch (*++fmt) {
464 case '%':
465 strlcat(c->sbuf, "%", sizeof(c->sbuf));
466 break;
467 case 'p':
468 strlcat(c->sbuf, path, sizeof(c->sbuf));
469 break;
470 case 'q':
471 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
472 break;
473 case 'P':
474 snprintf(buf, sizeof(buf), "%d", conf.port);
475 strlcat(c->sbuf, buf, sizeof(c->sbuf));
476 memset(buf, 0, sizeof(buf));
477 break;
478 case 'N':
479 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
480 break;
481 default:
482 fatal("%s: unknown fmt specifier %c",
483 __func__, *fmt);
487 if (i != 0)
488 strlcat(c->sbuf, buf, sizeof(c->sbuf));
491 /* 1 if a matching `block return' (and apply it), 0 otherwise */
492 static int
493 apply_block_return(struct client *c)
495 const char *fmt, *path;
496 int code;
498 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
499 return 0;
501 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
502 fmt_sbuf(fmt, c, path);
504 start_reply(c, code, c->sbuf);
505 return 1;
508 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
509 static int
510 apply_require_ca(struct client *c)
512 X509_STORE *store;
513 const uint8_t *cert;
514 size_t len;
516 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
517 return 0;
519 if (!tls_peer_cert_provided(c->ctx)) {
520 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
521 return 1;
524 cert = tls_peer_cert_chain_pem(c->ctx, &len);
525 if (!validate_against_ca(store, cert, len)) {
526 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
527 return 1;
530 return 0;
533 static void
534 handle_open_conn(int fd, short ev, void *d)
536 struct client *c = d;
537 const char *parse_err = "invalid request";
538 char decoded[DOMAIN_NAME_LEN];
540 bzero(c->req, sizeof(c->req));
541 bzero(&c->iri, sizeof(c->iri));
543 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
544 case -1:
545 log_err(c, "tls_read: %s", tls_error(c->ctx));
546 close_conn(fd, ev, c);
547 return;
549 case TLS_WANT_POLLIN:
550 reschedule_read(fd, c, &handle_open_conn);
551 return;
553 case TLS_WANT_POLLOUT:
554 reschedule_write(fd, c, &handle_open_conn);
555 return;
558 if (!trim_req_iri(c->req, &parse_err)
559 || !parse_iri(c->req, &c->iri, &parse_err)
560 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
561 log_info(c, "iri parse error: %s", parse_err);
562 start_reply(c, BAD_REQUEST, "invalid request");
563 return;
566 if (c->iri.port_no != conf.port
567 || strcmp(c->iri.schema, "gemini")
568 || strcmp(decoded, c->domain)) {
569 start_reply(c, PROXY_REFUSED, "won't proxy request");
570 return;
573 if (apply_require_ca(c))
574 return;
576 if (apply_block_return(c))
577 return;
579 if (c->host->entrypoint != NULL) {
580 start_cgi(c->host->entrypoint, c->iri.path, c);
581 return;
584 open_file(c);
587 static void
588 start_reply(struct client *c, int code, const char *meta)
590 c->code = code;
591 c->meta = meta;
592 handle_start_reply(c->fd, 0, c);
595 static void
596 handle_start_reply(int fd, short ev, void *d)
598 struct client *c = d;
599 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
600 const char *lang;
601 size_t len;
603 lang = vhost_lang(c->host, c->iri.path);
605 snprintf(buf, sizeof(buf), "%d ", c->code);
606 strlcat(buf, c->meta, sizeof(buf));
607 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
608 strlcat(buf, "; lang=", sizeof(buf));
609 strlcat(buf, lang, sizeof(buf));
612 len = strlcat(buf, "\r\n", sizeof(buf));
613 assert(len < sizeof(buf));
615 switch (tls_write(c->ctx, buf, len)) {
616 case -1:
617 close_conn(fd, ev, c);
618 return;
619 case TLS_WANT_POLLIN:
620 reschedule_read(fd, c, &handle_start_reply);
621 return;
622 case TLS_WANT_POLLOUT:
623 reschedule_write(fd, c, &handle_start_reply);
624 return;
627 if (!vhost_disable_log(c->host, c->iri.path))
628 log_request(c, buf, sizeof(buf));
630 if (c->code != SUCCESS)
631 close_conn(fd, ev, c);
632 else
633 c->next(fd, ev, c);
636 static void
637 start_cgi(const char *spath, const char *relpath, struct client *c)
639 char addr[NI_MAXHOST];
640 const char *t;
641 struct cgireq req;
642 int e;
644 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
645 addr, sizeof(addr),
646 NULL, 0,
647 NI_NUMERICHOST);
648 if (e != 0)
649 fatal("getnameinfo failed");
651 memset(&req, 0, sizeof(req));
653 memcpy(req.buf, c->req, sizeof(req.buf));
655 req.iri_schema_off = c->iri.schema - c->req;
656 req.iri_host_off = c->iri.host - c->req;
657 req.iri_port_off = c->iri.port - c->req;
658 req.iri_path_off = c->iri.path - c->req;
659 req.iri_query_off = c->iri.query - c->req;
660 req.iri_fragment_off = c->iri.fragment - c->req;
662 req.iri_portno = c->iri.port_no;
664 strlcpy(req.spath, spath, sizeof(req.spath));
665 strlcpy(req.relpath, relpath, sizeof(req.relpath));
666 strlcpy(req.addr, addr, sizeof(req.addr));
668 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
669 strlcpy(req.subject, t, sizeof(req.subject));
670 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
671 strlcpy(req.issuer, t, sizeof(req.issuer));
672 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
673 strlcpy(req.hash, t, sizeof(req.hash));
675 req.notbefore = tls_peer_cert_notbefore(c->ctx);
676 req.notafter = tls_peer_cert_notafter(c->ctx);
678 req.host_off = c->host - hosts;
680 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
681 imsg_flush(&exibuf);
683 close(c->pfd);
686 static void
687 open_dir(struct client *c)
689 size_t len;
690 int dirfd;
691 char *before_file;
693 len = strlen(c->iri.path);
694 if (len > 0 && !ends_with(c->iri.path, "/")) {
695 redirect_canonical_dir(c);
696 return;
699 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
700 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
701 if (!ends_with(c->sbuf, "/"))
702 strlcat(c->sbuf, "/", sizeof(c->sbuf));
703 before_file = strchr(c->sbuf, '\0');
704 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
705 sizeof(c->sbuf));
706 if (len >= sizeof(c->sbuf)) {
707 start_reply(c, TEMP_FAILURE, "internal server error");
708 return;
711 c->iri.path = c->sbuf;
713 /* close later unless we have to generate the dir listing */
714 dirfd = c->pfd;
715 c->pfd = -1;
717 switch (check_path(c, c->iri.path, &c->pfd)) {
718 case FILE_EXECUTABLE:
719 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
720 start_cgi(c->iri.path, "", c);
721 break;
724 /* fallthrough */
726 case FILE_EXISTS:
727 c->next = handle_copy;
728 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
729 break;
731 case FILE_DIRECTORY:
732 start_reply(c, TEMP_REDIRECT, c->sbuf);
733 break;
735 case FILE_MISSING:
736 *before_file = '\0';
738 if (!vhost_auto_index(c->host, c->iri.path)) {
739 start_reply(c, NOT_FOUND, "not found");
740 break;
743 c->pfd = dirfd;
744 c->next = enter_handle_dirlist;
746 if ((c->dir = fdopendir(c->pfd)) == NULL) {
747 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
748 c->pfd, c->host->domain, c->iri.path, strerror(errno));
749 start_reply(c, TEMP_FAILURE, "internal server error");
750 return;
752 c->off = 0;
754 start_reply(c, SUCCESS, "text/gemini");
755 return;
757 default:
758 /* unreachable */
759 abort();
762 close(dirfd);
765 static void
766 redirect_canonical_dir(struct client *c)
768 size_t len;
770 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
771 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
772 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
774 if (len >= sizeof(c->sbuf)) {
775 start_reply(c, TEMP_FAILURE, "internal server error");
776 return;
779 start_reply(c, TEMP_REDIRECT, c->sbuf);
782 static void
783 enter_handle_dirlist(int fd, short ev, void *d)
785 struct client *c = d;
786 char b[PATH_MAX];
787 size_t l;
789 strlcpy(b, c->iri.path, sizeof(b));
790 l = snprintf(c->sbuf, sizeof(c->sbuf),
791 "# Index of %s\n\n", b);
792 if (l >= sizeof(c->sbuf)) {
793 /* this is impossible, given that we have enough space
794 * in c->sbuf to hold the ancilliary string plus the
795 * full path; but it wouldn't read nice without some
796 * error checking, and I'd like to avoid a strlen. */
797 close_conn(fd, ev, c);
798 return;
801 c->len = l;
802 handle_dirlist(fd, ev, c);
805 static void
806 handle_dirlist(int fd, short ev, void *d)
808 struct client *c = d;
809 ssize_t r;
811 while (c->len > 0) {
812 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
813 case -1:
814 close_conn(fd, ev, c);
815 return;
816 case TLS_WANT_POLLOUT:
817 reschedule_read(fd, c, &handle_dirlist);
818 return;
819 case TLS_WANT_POLLIN:
820 reschedule_write(fd, c, &handle_dirlist);
821 return;
822 default:
823 c->off += r;
824 c->len -= r;
828 send_directory_listing(fd, ev, c);
831 static int
832 read_next_dir_entry(struct client *c)
834 struct dirent *d;
836 do {
837 errno = 0;
838 if ((d = readdir(c->dir)) == NULL) {
839 if (errno != 0)
840 log_err(c, "readdir: %s", strerror(errno));
841 return 0;
843 } while (!strcmp(d->d_name, "."));
845 /* XXX: url escape */
846 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
847 d->d_name, d->d_name);
848 c->len = strlen(c->sbuf);
849 c->off = 0;
851 return 1;
854 static void
855 send_directory_listing(int fd, short ev, void *d)
857 struct client *c = d;
858 ssize_t r;
860 while (1) {
861 if (c->len == 0) {
862 if (!read_next_dir_entry(c))
863 goto end;
866 while (c->len > 0) {
867 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
868 case -1:
869 goto end;
871 case TLS_WANT_POLLOUT:
872 reschedule_read(fd, c, &send_directory_listing);
873 return;
875 case TLS_WANT_POLLIN:
876 reschedule_write(fd, c, &send_directory_listing);
877 return;
879 default:
880 c->off += r;
881 c->len -= r;
882 break;
887 end:
888 close_conn(fd, ev, d);
891 /* accumulate the meta line from the cgi script. */
892 static void
893 handle_cgi_reply(int fd, short ev, void *d)
895 struct client *c = d;
896 void *buf, *e;
897 size_t len;
898 ssize_t r;
901 buf = c->sbuf + c->len;
902 len = sizeof(c->sbuf) - c->len;
904 r = read(c->pfd, buf, len);
905 if (r == 0 || r == -1) {
906 start_reply(c, CGI_ERROR, "CGI error");
907 return;
910 c->len += r;
912 /* TODO: error if the CGI script don't reply correctly */
913 e = strchr(c->sbuf, '\n');
914 if (e != NULL || c->len == sizeof(c->sbuf)) {
915 log_request(c, c->sbuf, c->len);
917 c->off = 0;
918 handle_copy(fd, ev, c);
919 return;
922 reschedule_read(fd, c, &handle_cgi_reply);
925 static void
926 handle_copy(int fd, short ev, void *d)
928 struct client *c = d;
929 ssize_t r;
931 while (1) {
932 while (c->len > 0) {
933 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
934 case -1:
935 goto end;
937 case TLS_WANT_POLLOUT:
938 reschedule_write(c->fd, c, &handle_copy);
939 return;
941 case TLS_WANT_POLLIN:
942 reschedule_read(c->fd, c, &handle_copy);
943 return;
945 default:
946 c->off += r;
947 c->len -= r;
948 break;
952 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
953 case 0:
954 goto end;
955 case -1:
956 if (errno == EAGAIN || errno == EWOULDBLOCK) {
957 reschedule_read(c->pfd, c, &handle_copy);
958 return;
960 goto end;
961 default:
962 c->len = r;
963 c->off = 0;
967 end:
968 close_conn(c->fd, ev, d);
971 static void
972 close_conn(int fd, short ev, void *d)
974 struct client *c = d;
976 switch (tls_close(c->ctx)) {
977 case TLS_WANT_POLLIN:
978 reschedule_read(fd, c, &close_conn);
979 return;
980 case TLS_WANT_POLLOUT:
981 reschedule_read(fd, c, &close_conn);
982 return;
985 connected_clients--;
987 tls_free(c->ctx);
988 c->ctx = NULL;
990 if (c->pfd != -1)
991 close(c->pfd);
993 if (c->dir != NULL)
994 closedir(c->dir);
996 close(c->fd);
997 c->fd = -1;
1000 static void
1001 do_accept(int sock, short et, void *d)
1003 struct client *c;
1004 struct sockaddr_storage addr;
1005 struct sockaddr *saddr;
1006 socklen_t len;
1007 int i, fd;
1009 (void)et;
1011 saddr = (struct sockaddr*)&addr;
1012 len = sizeof(addr);
1013 if ((fd = accept(sock, saddr, &len)) == -1) {
1014 if (errno == EWOULDBLOCK || errno == EAGAIN)
1015 return;
1016 fatal("accept: %s", strerror(errno));
1019 mark_nonblock(fd);
1021 for (i = 0; i < MAX_USERS; ++i) {
1022 c = &clients[i];
1023 if (c->fd == -1) {
1024 memset(c, 0, sizeof(*c));
1025 c->id = i;
1026 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1027 break; /* goodbye fd! */
1029 c->fd = fd;
1030 c->pfd = -1;
1031 c->dir = NULL;
1032 c->addr = addr;
1034 reschedule_read(fd, c, &handle_handshake);
1035 connected_clients++;
1036 return;
1040 close(fd);
1043 struct client *
1044 client_by_id(int id)
1046 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1047 fatal("in client_by_id: invalid id %d", id);
1048 return &clients[id];
1051 static void
1052 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1054 struct client *c;
1056 c = client_by_id(imsg->hdr.peerid);
1058 if ((c->pfd = imsg->fd) == -1)
1059 start_reply(c, TEMP_FAILURE, "internal server error");
1060 else
1061 reschedule_read(c->pfd, c, &handle_cgi_reply);
1064 static void
1065 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1067 (void)imsg;
1068 (void)len;
1070 /* don't call event_loopbreak since we want to finish to
1071 * handle the ongoing connections. */
1073 event_del(&e4);
1074 if (has_ipv6)
1075 event_del(&e6);
1076 if (has_siginfo)
1077 signal_del(&siginfo);
1078 event_del(&imsgev);
1079 signal_del(&sigusr2);
1082 static void
1083 handle_dispatch_imsg(int fd, short ev, void *d)
1085 struct imsgbuf *ibuf = d;
1086 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1089 static void
1090 handle_siginfo(int fd, short ev, void *d)
1092 (void)fd;
1093 (void)ev;
1094 (void)d;
1096 log_info(NULL, "%d connected clients", connected_clients);
1099 void
1100 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1102 size_t i;
1104 ctx = ctx_;
1106 event_init();
1108 memset(&clients, 0, sizeof(clients));
1109 for (i = 0; i < MAX_USERS; ++i)
1110 clients[i].fd = -1;
1112 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1113 event_add(&e4, NULL);
1115 if (sock6 != -1) {
1116 has_ipv6 = 1;
1117 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1118 event_add(&e6, NULL);
1121 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1122 event_add(&imsgev, NULL);
1124 #ifdef SIGINFO
1125 has_siginfo = 1;
1126 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1127 signal_add(&siginfo, NULL);
1128 #endif
1129 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1130 signal_add(&sigusr2, NULL);
1132 sandbox();
1133 event_dispatch();
1134 _exit(0);