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 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 reschedule_read(int fd, struct client *c, statefn fn)
85 {
86 event_once(fd, EV_READ, fn, c, NULL);
87 }
89 static inline void
90 reschedule_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 const char *servname;
395 const char *parse_err = "unknown error";
397 switch (tls_handshake(c->ctx)) {
398 case 0: /* success */
399 case -1: /* already handshaked */
400 break;
401 case TLS_WANT_POLLIN:
402 reschedule_read(fd, c, &handle_handshake);
403 return;
404 case TLS_WANT_POLLOUT:
405 reschedule_write(fd, c, &handle_handshake);
406 return;
407 default:
408 /* unreachable */
409 abort();
412 servname = tls_conn_servername(c->ctx);
413 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
414 log_info(c, "puny_decode: %s", parse_err);
415 goto err;
418 TAILQ_FOREACH(h, &hosts, vhosts) {
419 if (matches(h->domain, c->domain))
420 break;
423 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
424 servname != NULL ? servname : "(null)",
425 c->domain,
426 h != NULL ? h->domain : "(null)");
428 if (h != NULL) {
429 c->host = h;
430 handle_open_conn(fd, ev, c);
431 return;
434 err:
435 if (servname != NULL)
436 strncpy(c->req, servname, sizeof(c->req));
437 else
438 strncpy(c->req, "null", sizeof(c->req));
440 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
443 static char *
444 strip_path(char *path, int strip)
446 char *t;
448 while (strip > 0) {
449 if ((t = strchr(path, '/')) == NULL) {
450 path = strchr(path, '\0');
451 break;
453 path = t;
454 strip--;
457 return path;
460 static void
461 fmt_sbuf(const char *fmt, struct client *c, const char *path)
463 size_t i;
464 char buf[32];
466 memset(buf, 0, sizeof(buf));
467 for (i = 0; *fmt; ++fmt) {
468 if (i == sizeof(buf)-1 || *fmt == '%') {
469 strlcat(c->sbuf, buf, sizeof(c->sbuf));
470 memset(buf, 0, sizeof(buf));
471 i = 0;
474 if (*fmt != '%') {
475 buf[i++] = *fmt;
476 continue;
479 switch (*++fmt) {
480 case '%':
481 strlcat(c->sbuf, "%", sizeof(c->sbuf));
482 break;
483 case 'p':
484 strlcat(c->sbuf, path, sizeof(c->sbuf));
485 break;
486 case 'q':
487 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
488 break;
489 case 'P':
490 snprintf(buf, sizeof(buf), "%d", conf.port);
491 strlcat(c->sbuf, buf, sizeof(c->sbuf));
492 memset(buf, 0, sizeof(buf));
493 break;
494 case 'N':
495 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
496 break;
497 default:
498 fatal("%s: unknown fmt specifier %c",
499 __func__, *fmt);
503 if (i != 0)
504 strlcat(c->sbuf, buf, sizeof(c->sbuf));
507 /* 1 if a matching `block return' (and apply it), 0 otherwise */
508 static int
509 apply_block_return(struct client *c)
511 const char *fmt, *path;
512 int code;
514 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
515 return 0;
517 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
518 fmt_sbuf(fmt, c, path);
520 start_reply(c, code, c->sbuf);
521 return 1;
524 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
525 static int
526 apply_require_ca(struct client *c)
528 X509_STORE *store;
529 const uint8_t *cert;
530 size_t len;
532 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
533 return 0;
535 if (!tls_peer_cert_provided(c->ctx)) {
536 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
537 return 1;
540 cert = tls_peer_cert_chain_pem(c->ctx, &len);
541 if (!validate_against_ca(store, cert, len)) {
542 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
543 return 1;
546 return 0;
549 static void
550 handle_open_conn(int fd, short ev, void *d)
552 struct client *c = d;
553 const char *parse_err = "invalid request";
554 char decoded[DOMAIN_NAME_LEN];
556 bzero(c->req, sizeof(c->req));
557 bzero(&c->iri, sizeof(c->iri));
559 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
560 case -1:
561 log_err(c, "tls_read: %s", tls_error(c->ctx));
562 close_conn(fd, ev, c);
563 return;
565 case TLS_WANT_POLLIN:
566 reschedule_read(fd, c, &handle_open_conn);
567 return;
569 case TLS_WANT_POLLOUT:
570 reschedule_write(fd, c, &handle_open_conn);
571 return;
574 if (!trim_req_iri(c->req, &parse_err)
575 || !parse_iri(c->req, &c->iri, &parse_err)
576 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
577 log_info(c, "iri parse error: %s", parse_err);
578 start_reply(c, BAD_REQUEST, "invalid request");
579 return;
582 if (c->iri.port_no != conf.port
583 || strcmp(c->iri.schema, "gemini")
584 || strcmp(decoded, c->domain)) {
585 start_reply(c, PROXY_REFUSED, "won't proxy request");
586 return;
589 if (apply_require_ca(c))
590 return;
592 if (apply_block_return(c))
593 return;
595 if (c->host->entrypoint != NULL) {
596 start_cgi(c->host->entrypoint, c->iri.path, c);
597 return;
600 open_file(c);
603 static void
604 start_reply(struct client *c, int code, const char *meta)
606 c->code = code;
607 c->meta = meta;
608 handle_start_reply(c->fd, 0, c);
611 static void
612 handle_start_reply(int fd, short ev, void *d)
614 struct client *c = d;
615 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
616 const char *lang;
617 size_t len;
619 lang = vhost_lang(c->host, c->iri.path);
621 snprintf(buf, sizeof(buf), "%d ", c->code);
622 strlcat(buf, c->meta, sizeof(buf));
623 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
624 strlcat(buf, "; lang=", sizeof(buf));
625 strlcat(buf, lang, sizeof(buf));
628 len = strlcat(buf, "\r\n", sizeof(buf));
629 assert(len < sizeof(buf));
631 switch (tls_write(c->ctx, buf, len)) {
632 case -1:
633 close_conn(fd, ev, c);
634 return;
635 case TLS_WANT_POLLIN:
636 reschedule_read(fd, c, &handle_start_reply);
637 return;
638 case TLS_WANT_POLLOUT:
639 reschedule_write(fd, c, &handle_start_reply);
640 return;
643 if (!vhost_disable_log(c->host, c->iri.path))
644 log_request(c, buf, sizeof(buf));
646 if (c->code != SUCCESS)
647 close_conn(fd, ev, c);
648 else
649 c->next(fd, ev, c);
652 static size_t
653 host_nth(struct vhost *h)
655 struct vhost *v;
656 size_t i = 0;
658 TAILQ_FOREACH(v, &hosts, vhosts) {
659 if (v == h)
660 return i;
661 i++;
664 abort();
667 static void
668 start_cgi(const char *spath, const char *relpath, struct client *c)
670 char addr[NI_MAXHOST];
671 const char *t;
672 struct cgireq req;
673 int e;
675 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
676 addr, sizeof(addr),
677 NULL, 0,
678 NI_NUMERICHOST);
679 if (e != 0)
680 fatal("getnameinfo failed");
682 memset(&req, 0, sizeof(req));
684 memcpy(req.buf, c->req, sizeof(req.buf));
686 req.iri_schema_off = c->iri.schema - c->req;
687 req.iri_host_off = c->iri.host - c->req;
688 req.iri_port_off = c->iri.port - c->req;
689 req.iri_path_off = c->iri.path - c->req;
690 req.iri_query_off = c->iri.query - c->req;
691 req.iri_fragment_off = c->iri.fragment - c->req;
693 req.iri_portno = c->iri.port_no;
695 strlcpy(req.spath, spath, sizeof(req.spath));
696 strlcpy(req.relpath, relpath, sizeof(req.relpath));
697 strlcpy(req.addr, addr, sizeof(req.addr));
699 if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
700 strlcpy(req.subject, t, sizeof(req.subject));
701 if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
702 strlcpy(req.issuer, t, sizeof(req.issuer));
703 if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
704 strlcpy(req.hash, t, sizeof(req.hash));
706 req.notbefore = tls_peer_cert_notbefore(c->ctx);
707 req.notafter = tls_peer_cert_notafter(c->ctx);
709 req.host_off = host_nth(c->host);
711 imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
712 imsg_flush(&exibuf);
714 close(c->pfd);
717 static void
718 open_dir(struct client *c)
720 size_t len;
721 int dirfd;
722 char *before_file;
724 len = strlen(c->iri.path);
725 if (len > 0 && !ends_with(c->iri.path, "/")) {
726 redirect_canonical_dir(c);
727 return;
730 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
731 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
732 if (!ends_with(c->sbuf, "/"))
733 strlcat(c->sbuf, "/", sizeof(c->sbuf));
734 before_file = strchr(c->sbuf, '\0');
735 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
736 sizeof(c->sbuf));
737 if (len >= sizeof(c->sbuf)) {
738 start_reply(c, TEMP_FAILURE, "internal server error");
739 return;
742 c->iri.path = c->sbuf;
744 /* close later unless we have to generate the dir listing */
745 dirfd = c->pfd;
746 c->pfd = -1;
748 switch (check_path(c, c->iri.path, &c->pfd)) {
749 case FILE_EXECUTABLE:
750 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
751 start_cgi(c->iri.path, "", c);
752 break;
755 /* fallthrough */
757 case FILE_EXISTS:
758 c->next = handle_copy;
759 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
760 break;
762 case FILE_DIRECTORY:
763 start_reply(c, TEMP_REDIRECT, c->sbuf);
764 break;
766 case FILE_MISSING:
767 *before_file = '\0';
769 if (!vhost_auto_index(c->host, c->iri.path)) {
770 start_reply(c, NOT_FOUND, "not found");
771 break;
774 c->pfd = dirfd;
775 c->next = enter_handle_dirlist;
777 if ((c->dir = fdopendir(c->pfd)) == NULL) {
778 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
779 c->pfd, c->host->domain, c->iri.path, strerror(errno));
780 start_reply(c, TEMP_FAILURE, "internal server error");
781 return;
783 c->off = 0;
785 start_reply(c, SUCCESS, "text/gemini");
786 return;
788 default:
789 /* unreachable */
790 abort();
793 close(dirfd);
796 static void
797 redirect_canonical_dir(struct client *c)
799 size_t len;
801 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
802 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
803 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
805 if (len >= sizeof(c->sbuf)) {
806 start_reply(c, TEMP_FAILURE, "internal server error");
807 return;
810 start_reply(c, TEMP_REDIRECT, c->sbuf);
813 static void
814 enter_handle_dirlist(int fd, short ev, void *d)
816 struct client *c = d;
817 char b[PATH_MAX];
818 size_t l;
820 strlcpy(b, c->iri.path, sizeof(b));
821 l = snprintf(c->sbuf, sizeof(c->sbuf),
822 "# Index of %s\n\n", b);
823 if (l >= sizeof(c->sbuf)) {
824 /* this is impossible, given that we have enough space
825 * in c->sbuf to hold the ancilliary string plus the
826 * full path; but it wouldn't read nice without some
827 * error checking, and I'd like to avoid a strlen. */
828 close_conn(fd, ev, c);
829 return;
832 c->len = l;
833 handle_dirlist(fd, ev, c);
836 static void
837 handle_dirlist(int fd, short ev, void *d)
839 struct client *c = d;
840 ssize_t r;
842 while (c->len > 0) {
843 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
844 case -1:
845 close_conn(fd, ev, c);
846 return;
847 case TLS_WANT_POLLOUT:
848 reschedule_read(fd, c, &handle_dirlist);
849 return;
850 case TLS_WANT_POLLIN:
851 reschedule_write(fd, c, &handle_dirlist);
852 return;
853 default:
854 c->off += r;
855 c->len -= r;
859 send_directory_listing(fd, ev, c);
862 static int
863 read_next_dir_entry(struct client *c)
865 struct dirent *d;
867 do {
868 errno = 0;
869 if ((d = readdir(c->dir)) == NULL) {
870 if (errno != 0)
871 log_err(c, "readdir: %s", strerror(errno));
872 return 0;
874 } while (!strcmp(d->d_name, "."));
876 /* XXX: url escape */
877 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
878 d->d_name, d->d_name);
879 c->len = strlen(c->sbuf);
880 c->off = 0;
882 return 1;
885 static void
886 send_directory_listing(int fd, short ev, void *d)
888 struct client *c = d;
889 ssize_t r;
891 while (1) {
892 if (c->len == 0) {
893 if (!read_next_dir_entry(c))
894 goto end;
897 while (c->len > 0) {
898 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
899 case -1:
900 goto end;
902 case TLS_WANT_POLLOUT:
903 reschedule_read(fd, c, &send_directory_listing);
904 return;
906 case TLS_WANT_POLLIN:
907 reschedule_write(fd, c, &send_directory_listing);
908 return;
910 default:
911 c->off += r;
912 c->len -= r;
913 break;
918 end:
919 close_conn(fd, ev, d);
922 /* accumulate the meta line from the cgi script. */
923 static void
924 handle_cgi_reply(int fd, short ev, void *d)
926 struct client *c = d;
927 void *buf, *e;
928 size_t len;
929 ssize_t r;
932 buf = c->sbuf + c->len;
933 len = sizeof(c->sbuf) - c->len;
935 r = read(c->pfd, buf, len);
936 if (r == 0 || r == -1) {
937 start_reply(c, CGI_ERROR, "CGI error");
938 return;
941 c->len += r;
943 /* TODO: error if the CGI script don't reply correctly */
944 e = strchr(c->sbuf, '\n');
945 if (e != NULL || c->len == sizeof(c->sbuf)) {
946 log_request(c, c->sbuf, c->len);
948 c->off = 0;
949 handle_copy(fd, ev, c);
950 return;
953 reschedule_read(fd, c, &handle_cgi_reply);
956 static void
957 handle_copy(int fd, short ev, void *d)
959 struct client *c = d;
960 ssize_t r;
962 while (1) {
963 while (c->len > 0) {
964 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
965 case -1:
966 goto end;
968 case TLS_WANT_POLLOUT:
969 reschedule_write(c->fd, c, &handle_copy);
970 return;
972 case TLS_WANT_POLLIN:
973 reschedule_read(c->fd, c, &handle_copy);
974 return;
976 default:
977 c->off += r;
978 c->len -= r;
979 break;
983 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
984 case 0:
985 goto end;
986 case -1:
987 if (errno == EAGAIN || errno == EWOULDBLOCK) {
988 reschedule_read(c->pfd, c, &handle_copy);
989 return;
991 goto end;
992 default:
993 c->len = r;
994 c->off = 0;
998 end:
999 close_conn(c->fd, ev, d);
1002 static void
1003 close_conn(int fd, short ev, void *d)
1005 struct client *c = d;
1007 switch (tls_close(c->ctx)) {
1008 case TLS_WANT_POLLIN:
1009 reschedule_read(fd, c, &close_conn);
1010 return;
1011 case TLS_WANT_POLLOUT:
1012 reschedule_read(fd, c, &close_conn);
1013 return;
1016 connected_clients--;
1018 tls_free(c->ctx);
1019 c->ctx = NULL;
1021 if (c->pfd != -1)
1022 close(c->pfd);
1024 if (c->dir != NULL)
1025 closedir(c->dir);
1027 close(c->fd);
1028 c->fd = -1;
1031 static void
1032 do_accept(int sock, short et, void *d)
1034 struct client *c;
1035 struct sockaddr_storage addr;
1036 struct sockaddr *saddr;
1037 socklen_t len;
1038 int i, fd;
1040 (void)et;
1042 saddr = (struct sockaddr*)&addr;
1043 len = sizeof(addr);
1044 if ((fd = accept(sock, saddr, &len)) == -1) {
1045 if (errno == EWOULDBLOCK || errno == EAGAIN)
1046 return;
1047 fatal("accept: %s", strerror(errno));
1050 mark_nonblock(fd);
1052 for (i = 0; i < MAX_USERS; ++i) {
1053 c = &clients[i];
1054 if (c->fd == -1) {
1055 memset(c, 0, sizeof(*c));
1056 c->id = i;
1057 if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1058 break; /* goodbye fd! */
1060 c->fd = fd;
1061 c->pfd = -1;
1062 c->dir = NULL;
1063 c->addr = addr;
1065 reschedule_read(fd, c, &handle_handshake);
1066 connected_clients++;
1067 return;
1071 close(fd);
1074 struct client *
1075 client_by_id(int id)
1077 if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1078 fatal("in client_by_id: invalid id %d", id);
1079 return &clients[id];
1082 static void
1083 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1085 struct client *c;
1087 c = client_by_id(imsg->hdr.peerid);
1089 if ((c->pfd = imsg->fd) == -1)
1090 start_reply(c, TEMP_FAILURE, "internal server error");
1091 else
1092 reschedule_read(c->pfd, c, &handle_cgi_reply);
1095 static void
1096 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1098 (void)imsg;
1099 (void)len;
1101 /* don't call event_loopbreak since we want to finish to
1102 * handle the ongoing connections. */
1104 event_del(&e4);
1105 if (has_ipv6)
1106 event_del(&e6);
1107 if (has_siginfo)
1108 signal_del(&siginfo);
1109 event_del(&imsgev);
1110 signal_del(&sigusr2);
1113 static void
1114 handle_dispatch_imsg(int fd, short ev, void *d)
1116 struct imsgbuf *ibuf = d;
1117 dispatch_imsg(ibuf, handlers, sizeof(handlers));
1120 static void
1121 handle_siginfo(int fd, short ev, void *d)
1123 (void)fd;
1124 (void)ev;
1125 (void)d;
1127 log_info(NULL, "%d connected clients", connected_clients);
1130 void
1131 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1133 size_t i;
1135 ctx = ctx_;
1137 event_init();
1139 memset(&clients, 0, sizeof(clients));
1140 for (i = 0; i < MAX_USERS; ++i)
1141 clients[i].fd = -1;
1143 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1144 event_add(&e4, NULL);
1146 if (sock6 != -1) {
1147 has_ipv6 = 1;
1148 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1149 event_add(&e6, NULL);
1152 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1153 event_add(&imsgev, NULL);
1155 #ifdef SIGINFO
1156 has_siginfo = 1;
1157 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1158 signal_add(&siginfo, NULL);
1159 #endif
1160 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1161 signal_add(&sigusr2, NULL);
1163 sandbox_server_process();
1164 event_dispatch();
1165 _exit(0);