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_strip(struct vhost *v, const char *path)
208 struct location *loc;
210 if (v == NULL || path == NULL)
211 return 0;
213 loc = TAILQ_FIRST(&v->locations);
214 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
215 if (loc->strip != 0) {
216 if (matches(loc->match, path))
217 return loc->strip;
221 loc = TAILQ_FIRST(&v->locations);
222 return loc->strip;
225 X509_STORE *
226 vhost_require_ca(struct vhost *v, const char *path)
228 struct location *loc;
230 if (v == NULL || path == NULL)
231 return NULL;
233 loc = TAILQ_FIRST(&v->locations);
234 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
235 if (loc->reqca != NULL) {
236 if (matches(loc->match, path))
237 return loc->reqca;
241 loc = TAILQ_FIRST(&v->locations);
242 return loc->reqca;
245 int
246 vhost_disable_log(struct vhost *v, const char *path)
248 struct location *loc;
250 if (v == NULL || path == NULL)
251 return 0;
253 loc = TAILQ_FIRST(&v->locations);
254 while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
255 if (loc->disable_log && matches(loc->match, path))
256 return 1;
259 loc = TAILQ_FIRST(&v->locations);
260 return loc->disable_log;
263 static int
264 check_path(struct client *c, const char *path, int *fd)
266 struct stat sb;
267 const char *p;
268 int flags;
270 assert(path != NULL);
272 if (*path == '\0')
273 p = ".";
274 else if (*path == '/')
275 /* in send_dir we add an initial / (to be
276 * redirect-friendly), but here we want to skip it */
277 p = path+1;
278 else
279 p = path;
281 flags = O_RDONLY | O_NOFOLLOW;
283 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
284 return FILE_MISSING;
286 if (fstat(*fd, &sb) == -1) {
287 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
288 return FILE_MISSING;
291 if (S_ISDIR(sb.st_mode))
292 return FILE_DIRECTORY;
294 if (sb.st_mode & S_IXUSR)
295 return FILE_EXECUTABLE;
297 return FILE_EXISTS;
300 static void
301 open_file(struct client *c)
303 switch (check_path(c, c->iri.path, &c->pfd)) {
304 case FILE_EXECUTABLE:
305 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
306 start_cgi(c->iri.path, "", c);
307 return;
310 /* fallthrough */
312 case FILE_EXISTS:
313 c->next = handle_copy;
314 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
315 return;
317 case FILE_DIRECTORY:
318 open_dir(c);
319 return;
321 case FILE_MISSING:
322 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
323 check_for_cgi(c);
324 return;
326 start_reply(c, NOT_FOUND, "not found");
327 return;
329 default:
330 /* unreachable */
331 abort();
335 /*
336 * the inverse of this algorithm, i.e. starting from the start of the
337 * path + strlen(cgi), and checking if each component, should be
338 * faster. But it's tedious to write. This does the opposite: starts
339 * from the end and strip one component at a time, until either an
340 * executable is found or we emptied the path.
341 */
342 static void
343 check_for_cgi(struct client *c)
345 char path[PATH_MAX];
346 char *end;
348 strlcpy(path, c->iri.path, sizeof(path));
349 end = strchr(path, '\0');
351 while (end > path) {
352 /* go up one level. UNIX paths are simple and POSIX
353 * dirname, with its ambiguities on if the given path
354 * is changed or not, gives me headaches. */
355 while (*end != '/')
356 end--;
357 *end = '\0';
359 switch (check_path(c, path, &c->pfd)) {
360 case FILE_EXECUTABLE:
361 start_cgi(path, end+1, c);
362 return;
363 case FILE_MISSING:
364 break;
365 default:
366 goto err;
369 *end = '/';
370 end--;
373 err:
374 start_reply(c, NOT_FOUND, "not found");
375 return;
378 void
379 mark_nonblock(int fd)
381 int flags;
383 if ((flags = fcntl(fd, F_GETFL)) == -1)
384 fatal("fcntl(F_GETFL): %s", strerror(errno));
385 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
386 fatal("fcntl(F_SETFL): %s", strerror(errno));
389 static void
390 handle_handshake(int fd, short ev, void *d)
392 struct client *c = d;
393 struct vhost *h;
394 struct alist *a;
395 const char *servname;
396 const char *parse_err = "unknown error";
398 switch (tls_handshake(c->ctx)) {
399 case 0: /* success */
400 case -1: /* already handshaked */
401 break;
402 case TLS_WANT_POLLIN:
403 yield_read(fd, c, &handle_handshake);
404 return;
405 case TLS_WANT_POLLOUT:
406 yield_write(fd, c, &handle_handshake);
407 return;
408 default:
409 /* unreachable */
410 abort();
413 servname = tls_conn_servername(c->ctx);
414 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
415 log_info(c, "puny_decode: %s", parse_err);
416 goto err;
419 TAILQ_FOREACH(h, &hosts, vhosts) {
420 if (matches(h->domain, c->domain))
421 goto found;
422 TAILQ_FOREACH(a, &h->aliases, aliases) {
423 if (matches(a->alias, c->domain))
424 goto found;
428 found:
429 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
430 servname != NULL ? servname : "(null)",
431 c->domain,
432 h != NULL ? h->domain : "(null)");
434 if (h != NULL) {
435 c->host = h;
436 handle_open_conn(fd, ev, c);
437 return;
440 err:
441 if (servname != NULL)
442 strncpy(c->req, servname, sizeof(c->req));
443 else
444 strncpy(c->req, "null", sizeof(c->req));
446 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
449 static char *
450 strip_path(char *path, int strip)
452 char *t;
454 while (strip > 0) {
455 if ((t = strchr(path, '/')) == NULL) {
456 path = strchr(path, '\0');
457 break;
459 path = t;
460 strip--;
463 return path;
466 static void
467 fmt_sbuf(const char *fmt, struct client *c, const char *path)
469 size_t i;
470 char buf[32];
472 memset(buf, 0, sizeof(buf));
473 for (i = 0; *fmt; ++fmt) {
474 if (i == sizeof(buf)-1 || *fmt == '%') {
475 strlcat(c->sbuf, buf, sizeof(c->sbuf));
476 memset(buf, 0, sizeof(buf));
477 i = 0;
480 if (*fmt != '%') {
481 buf[i++] = *fmt;
482 continue;
485 switch (*++fmt) {
486 case '%':
487 strlcat(c->sbuf, "%", sizeof(c->sbuf));
488 break;
489 case 'p':
490 strlcat(c->sbuf, path, sizeof(c->sbuf));
491 break;
492 case 'q':
493 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
494 break;
495 case 'P':
496 snprintf(buf, sizeof(buf), "%d", conf.port);
497 strlcat(c->sbuf, buf, sizeof(c->sbuf));
498 memset(buf, 0, sizeof(buf));
499 break;
500 case 'N':
501 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
502 break;
503 default:
504 fatal("%s: unknown fmt specifier %c",
505 __func__, *fmt);
509 if (i != 0)
510 strlcat(c->sbuf, buf, sizeof(c->sbuf));
513 /* 1 if a matching `block return' (and apply it), 0 otherwise */
514 static int
515 apply_block_return(struct client *c)
517 const char *fmt, *path;
518 int code;
520 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
521 return 0;
523 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
524 fmt_sbuf(fmt, c, path);
526 start_reply(c, code, c->sbuf);
527 return 1;
530 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
531 static int
532 apply_require_ca(struct client *c)
534 X509_STORE *store;
535 const uint8_t *cert;
536 size_t len;
538 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
539 return 0;
541 if (!tls_peer_cert_provided(c->ctx)) {
542 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
543 return 1;
546 cert = tls_peer_cert_chain_pem(c->ctx, &len);
547 if (!validate_against_ca(store, cert, len)) {
548 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
549 return 1;
552 return 0;
555 static void
556 handle_open_conn(int fd, short ev, void *d)
558 struct client *c = d;
559 const char *parse_err = "invalid request";
560 char decoded[DOMAIN_NAME_LEN];
562 bzero(c->req, sizeof(c->req));
563 bzero(&c->iri, sizeof(c->iri));
565 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
566 case -1:
567 log_err(c, "tls_read: %s", tls_error(c->ctx));
568 close_conn(fd, ev, c);
569 return;
571 case TLS_WANT_POLLIN:
572 yield_read(fd, c, &handle_open_conn);
573 return;
575 case TLS_WANT_POLLOUT:
576 yield_write(fd, c, &handle_open_conn);
577 return;
580 if (!trim_req_iri(c->req, &parse_err)
581 || !parse_iri(c->req, &c->iri, &parse_err)
582 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
583 log_info(c, "iri parse error: %s", parse_err);
584 start_reply(c, BAD_REQUEST, "invalid request");
585 return;
588 if (c->iri.port_no != conf.port
589 || strcmp(c->iri.schema, "gemini")
590 || strcmp(decoded, c->domain)) {
591 start_reply(c, PROXY_REFUSED, "won't proxy request");
592 return;
595 if (apply_require_ca(c))
596 return;
598 if (apply_block_return(c))
599 return;
601 if (c->host->entrypoint != NULL) {
602 start_cgi(c->host->entrypoint, c->iri.path, c);
603 return;
606 open_file(c);
609 static void
610 start_reply(struct client *c, int code, const char *meta)
612 c->code = code;
613 c->meta = meta;
614 handle_start_reply(c->fd, 0, c);
617 static void
618 handle_start_reply(int fd, short ev, void *d)
620 struct client *c = d;
621 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
622 const char *lang;
623 size_t len;
625 lang = vhost_lang(c->host, c->iri.path);
627 snprintf(buf, sizeof(buf), "%d ", c->code);
628 strlcat(buf, c->meta, sizeof(buf));
629 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
630 strlcat(buf, "; lang=", sizeof(buf));
631 strlcat(buf, lang, sizeof(buf));
634 len = strlcat(buf, "\r\n", sizeof(buf));
635 assert(len < sizeof(buf));
637 switch (tls_write(c->ctx, buf, len)) {
638 case -1:
639 close_conn(fd, ev, c);
640 return;
641 case TLS_WANT_POLLIN:
642 yield_read(fd, c, &handle_start_reply);
643 return;
644 case TLS_WANT_POLLOUT:
645 yield_write(fd, c, &handle_start_reply);
646 return;
649 if (!vhost_disable_log(c->host, c->iri.path))
650 log_request(c, buf, sizeof(buf));
652 if (c->code != SUCCESS)
653 close_conn(fd, ev, c);
654 else
655 c->next(fd, ev, c);
658 static size_t
659 host_nth(struct vhost *h)
661 struct vhost *v;
662 size_t i = 0;
664 TAILQ_FOREACH(v, &hosts, vhosts) {
665 if (v == h)
666 return i;
667 i++;
670 abort();
673 static void
674 start_cgi(const char *spath, const char *relpath, struct client *c)
676 char addr[NI_MAXHOST];
677 const char *t;
678 struct cgireq req;
679 int e;
681 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
682 addr, sizeof(addr),
683 NULL, 0,
684 NI_NUMERICHOST);
685 if (e != 0)
686 fatal("getnameinfo failed");
688 memset(&req, 0, sizeof(req));
690 memcpy(req.buf, c->req, sizeof(req.buf));
692 req.iri_schema_off = c->iri.schema - c->req;
693 req.iri_host_off = c->iri.host - c->req;
694 req.iri_port_off = c->iri.port - c->req;
695 req.iri_path_off = c->iri.path - c->req;
696 req.iri_query_off = c->iri.query - c->req;
697 req.iri_fragment_off = c->iri.fragment - c->req;
699 req.iri_portno = c->iri.port_no;
701 strlcpy(req.spath, spath, sizeof(req.spath));
702 strlcpy(req.relpath, relpath, sizeof(req.relpath));
703 strlcpy(req.addr, addr, sizeof(req.addr));
705 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
706 strlcpy(req.subject, t, sizeof(req.subject));
707 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
708 strlcpy(req.issuer, t, sizeof(req.issuer));
709 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
710 strlcpy(req.hash, t, sizeof(req.hash));
711 if ((t = tls_conn_version(c->ctx)) != NULL)
712 strlcpy(req.version, t, sizeof(req.version));
713 if ((t = tls_conn_cipher(c->ctx)) != NULL)
714 strlcpy(req.cipher, t, sizeof(req.cipher));
716 req.cipher_strength = tls_conn_cipher_strength(c->ctx);
717 req.notbefore = tls_peer_cert_notbefore(c->ctx);
718 req.notafter = tls_peer_cert_notafter(c->ctx);
720 req.host_off = host_nth(c->host);
722 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
723 imsg_flush(&exibuf);
725 close(c->pfd);
728 static void
729 open_dir(struct client *c)
731 size_t len;
732 int dirfd, root;
733 char *before_file;
735 root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
737 len = strlen(c->iri.path);
738 if (len > 0 && !ends_with(c->iri.path, "/")) {
739 redirect_canonical_dir(c);
740 return;
743 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
744 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
745 if (!ends_with(c->sbuf, "/"))
746 strlcat(c->sbuf, "/", sizeof(c->sbuf));
747 before_file = strchr(c->sbuf, '\0');
748 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
749 sizeof(c->sbuf));
750 if (len >= sizeof(c->sbuf)) {
751 start_reply(c, TEMP_FAILURE, "internal server error");
752 return;
755 c->iri.path = c->sbuf;
757 /* close later unless we have to generate the dir listing */
758 dirfd = c->pfd;
759 c->pfd = -1;
761 switch (check_path(c, c->iri.path, &c->pfd)) {
762 case FILE_EXECUTABLE:
763 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
764 start_cgi(c->iri.path, "", c);
765 break;
768 /* fallthrough */
770 case FILE_EXISTS:
771 c->next = handle_copy;
772 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
773 break;
775 case FILE_DIRECTORY:
776 start_reply(c, TEMP_REDIRECT, c->sbuf);
777 break;
779 case FILE_MISSING:
780 *before_file = '\0';
782 if (!vhost_auto_index(c->host, c->iri.path)) {
783 start_reply(c, NOT_FOUND, "not found");
784 break;
787 c->next = enter_handle_dirlist;
789 c->dirlen = scandir_fd(dirfd, &c->dir,
790 root ? select_non_dotdot : select_non_dot,
791 alphasort);
792 if (c->dirlen == -1) {
793 log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
794 c->pfd, c->host->domain, c->iri.path, strerror(errno));
795 start_reply(c, TEMP_FAILURE, "internal server error");
796 return;
798 c->diroff = 0;
799 c->off = 0;
801 start_reply(c, SUCCESS, "text/gemini");
802 return;
804 default:
805 /* unreachable */
806 abort();
809 close(dirfd);
812 static void
813 redirect_canonical_dir(struct client *c)
815 size_t len;
817 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
818 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
819 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
821 if (len >= sizeof(c->sbuf)) {
822 start_reply(c, TEMP_FAILURE, "internal server error");
823 return;
826 start_reply(c, TEMP_REDIRECT, c->sbuf);
829 static void
830 enter_handle_dirlist(int fd, short ev, void *d)
832 struct client *c = d;
833 char b[PATH_MAX];
834 size_t l;
836 strlcpy(b, c->iri.path, sizeof(b));
837 l = snprintf(c->sbuf, sizeof(c->sbuf),
838 "# Index of %s\n\n", b);
839 if (l >= sizeof(c->sbuf)) {
840 /* this is impossible, given that we have enough space
841 * in c->sbuf to hold the ancilliary string plus the
842 * full path; but it wouldn't read nice without some
843 * error checking, and I'd like to avoid a strlen. */
844 close_conn(fd, ev, c);
845 return;
848 c->len = l;
849 handle_dirlist(fd, ev, c);
852 static void
853 handle_dirlist(int fd, short ev, void *d)
855 struct client *c = d;
856 ssize_t r;
858 while (c->len > 0) {
859 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
860 case -1:
861 close_conn(fd, ev, c);
862 return;
863 case TLS_WANT_POLLOUT:
864 yield_read(fd, c, &handle_dirlist);
865 return;
866 case TLS_WANT_POLLIN:
867 yield_write(fd, c, &handle_dirlist);
868 return;
869 default:
870 c->off += r;
871 c->len -= r;
875 send_directory_listing(fd, ev, c);
878 static int
879 read_next_dir_entry(struct client *c)
881 if (c->diroff == c->dirlen)
882 return 0;
884 /* XXX: url escape */
885 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
886 c->dir[c->diroff]->d_name);
888 free(c->dir[c->diroff]);
889 c->diroff++;
891 c->len = strlen(c->sbuf);
892 c->off = 0;
893 return 1;
896 static void
897 send_directory_listing(int fd, short ev, void *d)
899 struct client *c = d;
900 ssize_t r;
902 while (1) {
903 if (c->len == 0) {
904 if (!read_next_dir_entry(c))
905 goto end;
908 while (c->len > 0) {
909 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
910 case -1:
911 goto end;
913 case TLS_WANT_POLLOUT:
914 yield_read(fd, c, &send_directory_listing);
915 return;
917 case TLS_WANT_POLLIN:
918 yield_write(fd, c, &send_directory_listing);
919 return;
921 default:
922 c->off += r;
923 c->len -= r;
924 break;
929 end:
930 close_conn(fd, ev, d);
933 /* accumulate the meta line from the cgi script. */
934 static void
935 handle_cgi_reply(int fd, short ev, void *d)
937 struct client *c = d;
938 void *buf, *e;
939 size_t len;
940 ssize_t r;
943 buf = c->sbuf + c->len;
944 len = sizeof(c->sbuf) - c->len;
946 r = read(c->pfd, buf, len);
947 if (r == 0 || r == -1) {
948 start_reply(c, CGI_ERROR, "CGI error");
949 return;
952 c->len += r;
954 /* TODO: error if the CGI script don't reply correctly */
955 e = strchr(c->sbuf, '\n');
956 if (e != NULL || c->len == sizeof(c->sbuf)) {
957 log_request(c, c->sbuf, c->len);
959 c->off = 0;
960 handle_copy(fd, ev, c);
961 return;
964 yield_read(fd, c, &handle_cgi_reply);
967 static void
968 handle_copy(int fd, short ev, void *d)
970 struct client *c = d;
971 ssize_t r;
973 while (1) {
974 while (c->len > 0) {
975 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
976 case -1:
977 goto end;
979 case TLS_WANT_POLLOUT:
980 yield_write(c->fd, c, &handle_copy);
981 return;
983 case TLS_WANT_POLLIN:
984 yield_read(c->fd, c, &handle_copy);
985 return;
987 default:
988 c->off += r;
989 c->len -= r;
990 break;
994 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
995 case 0:
996 goto end;
997 case -1:
998 if (errno == EAGAIN || errno == EWOULDBLOCK) {
999 yield_read(c->pfd, c, &handle_copy);
1000 return;
1002 goto end;
1003 default:
1004 c->len = r;
1005 c->off = 0;
1009 end:
1010 close_conn(c->fd, ev, d);
1013 static void
1014 close_conn(int fd, short ev, void *d)
1016 struct client *c = d;
1018 switch (tls_close(c->ctx)) {
1019 case TLS_WANT_POLLIN:
1020 yield_read(fd, c, &close_conn);
1021 return;
1022 case TLS_WANT_POLLOUT:
1023 yield_read(fd, c, &close_conn);
1024 return;
1027 connected_clients--;
1029 tls_free(c->ctx);
1030 c->ctx = NULL;
1032 if (c->pfd != -1)
1033 close(c->pfd);
1035 if (c->dir != NULL)
1036 free(c->dir);
1038 close(c->fd);
1039 c->fd = -1;
1042 static void
1043 do_accept(int sock, short et, void *d)
1045 struct client *c;
1046 struct sockaddr_storage addr;
1047 struct sockaddr *saddr;
1048 socklen_t len;
1049 int i, fd;
1051 (void)et;
1053 saddr = (struct sockaddr*)&addr;
1054 len = sizeof(addr);
1055 if ((fd = accept(sock, saddr, &len)) == -1) {
1056 if (errno == EWOULDBLOCK || errno == EAGAIN)
1057 return;
1058 fatal("accept: %s", strerror(errno));
1061 mark_nonblock(fd);
1063 for (i = 0; i < MAX_USERS; ++i) {
1064 c = &clients[i];
1065 if (c->fd == -1) {
1066 memset(c, 0, sizeof(*c));
1067 c->id = i;
1068 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1069 break; /* goodbye fd! */
1071 c->fd = fd;
1072 c->pfd = -1;
1073 c->dir = NULL;
1074 c->addr = addr;
1076 yield_read(fd, c, &handle_handshake);
1077 connected_clients++;
1078 return;
1082 close(fd);
1085 struct client *
1086 client_by_id(int id)
1088 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1089 fatal("in client_by_id: invalid id %d", id);
1090 return &clients[id];
1093 static void
1094 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1096 struct client *c;
1098 c = client_by_id(imsg->hdr.peerid);
1100 if ((c->pfd = imsg->fd) == -1)
1101 start_reply(c, TEMP_FAILURE, "internal server error");
1102 else
1103 yield_read(c->pfd, c, &handle_cgi_reply);
1106 static void
1107 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1109 (void)imsg;
1110 (void)len;
1112 /* don't call event_loopbreak since we want to finish to
1113 * handle the ongoing connections. */
1115 event_del(&e4);
1116 if (has_ipv6)
1117 event_del(&e6);
1118 if (has_siginfo)
1119 signal_del(&siginfo);
1120 event_del(&imsgev);
1121 signal_del(&sigusr2);
1124 static void
1125 handle_dispatch_imsg(int fd, short ev, void *d)
1127 struct imsgbuf *ibuf = d;
1128 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1131 static void
1132 handle_siginfo(int fd, short ev, void *d)
1134 (void)fd;
1135 (void)ev;
1136 (void)d;
1138 log_info(NULL, "%d connected clients", connected_clients);
1141 void
1142 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1144 size_t i;
1146 ctx = ctx_;
1148 event_init();
1150 memset(&clients, 0, sizeof(clients));
1151 for (i = 0; i < MAX_USERS; ++i)
1152 clients[i].fd = -1;
1154 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1155 event_add(&e4, NULL);
1157 if (sock6 != -1) {
1158 has_ipv6 = 1;
1159 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1160 event_add(&e6, NULL);
1163 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1164 event_add(&imsgev, NULL);
1166 #ifdef SIGINFO
1167 has_siginfo = 1;
1168 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1169 signal_add(&siginfo, NULL);
1170 #endif
1171 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1172 signal_add(&sigusr2, NULL);
1174 sandbox_server_process();
1175 event_dispatch();
1176 _exit(0);