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 <netdb.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <event.h>
26 #include <fcntl.h>
27 #include <fnmatch.h>
28 #include <limits.h>
29 #include <string.h>
31 struct server {
32 struct client clients[MAX_USERS];
33 struct tls *ctx;
34 };
36 static struct event e4, e6, sighup, siginfo, sigusr2;
37 static int has_ipv6, has_siginfo;
39 int connected_clients;
41 static inline int matches(const char*, const char*);
43 static inline void reschedule_read(int, struct client*, statefn);
44 static inline void reschedule_write(int, struct client*, statefn);
46 static int check_path(struct client*, const char*, int*);
47 static void open_file(struct client*);
48 static void check_for_cgi(struct client*);
49 static void handle_handshake(int, short, void*);
50 static char *strip_path(char*, int);
51 static void fmt_sbuf(const char*, struct client*, const char*);
52 static int apply_block_return(struct client*);
53 static int apply_require_ca(struct client*);
54 static void handle_open_conn(int, short, void*);
55 static void start_reply(struct client*, int, const char*);
56 static void handle_start_reply(int, short, void*);
57 static void start_cgi(const char*, const char*, struct client*);
58 static void open_dir(struct client*);
59 static void redirect_canonical_dir(struct client*);
60 static void enter_handle_dirlist(int, short, void*);
61 static void handle_dirlist(int, short, void*);
62 static int read_next_dir_entry(struct client*);
63 static void send_directory_listing(int, short, void*);
64 static void handle_cgi_reply(int, short, void*);
65 static void handle_copy(int, short, void*);
66 static void close_conn(int, short, void*);
67 static void do_accept(int, short, void*);
68 static void handle_sighup(int, short, void*);
70 static inline int
71 matches(const char *pattern, const char *path)
72 {
73 if (*path == '/')
74 path++;
75 return !fnmatch(pattern, path, 0);
76 }
78 static inline void
79 reschedule_read(int fd, struct client *c, statefn fn)
80 {
81 event_once(fd, EV_READ, fn, c, NULL);
82 }
84 static inline void
85 reschedule_write(int fd, struct client *c, statefn fn)
86 {
87 event_once(fd, EV_WRITE, fn, c, NULL);
88 }
90 const char *
91 vhost_lang(struct vhost *v, const char *path)
92 {
93 struct location *loc;
95 if (v == NULL || path == NULL)
96 return NULL;
98 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
99 if (loc->lang != NULL) {
100 if (matches(loc->match, path))
101 return loc->lang;
105 return v->locations[0].lang;
108 const char *
109 vhost_default_mime(struct vhost *v, const char *path)
111 struct location *loc;
112 const char *default_mime = "application/octet-stream";
114 if (v == NULL || path == NULL)
115 return default_mime;
117 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
118 if (loc->default_mime != NULL) {
119 if (matches(loc->match, path))
120 return loc->default_mime;
124 if (v->locations[0].default_mime != NULL)
125 return v->locations[0].default_mime;
126 return default_mime;
129 const char *
130 vhost_index(struct vhost *v, const char *path)
132 struct location *loc;
133 const char *index = "index.gmi";
135 if (v == NULL || path == NULL)
136 return index;
138 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
139 if (loc->index != NULL) {
140 if (matches(loc->match, path))
141 return loc->index;
145 if (v->locations[0].index != NULL)
146 return v->locations[0].index;
147 return index;
150 int
151 vhost_auto_index(struct vhost *v, const char *path)
153 struct location *loc;
155 if (v == NULL || path == NULL)
156 return 0;
158 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
159 if (loc->auto_index != 0) {
160 if (matches(loc->match, path))
161 return loc->auto_index == 1;
165 return v->locations[0].auto_index == 1;
168 int
169 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
171 struct location *loc;
173 if (v == NULL || path == NULL)
174 return 0;
176 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
177 if (loc->block_code != 0) {
178 if (matches(loc->match, path)) {
179 *code = loc->block_code;
180 *fmt = loc->block_fmt;
181 return 1;
186 *code = v->locations[0].block_code;
187 *fmt = v->locations[0].block_fmt;
188 return v->locations[0].block_code != 0;
191 int
192 vhost_strip(struct vhost *v, const char *path)
194 struct location *loc;
196 if (v == NULL || path == NULL)
197 return 0;
199 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
200 if (loc->strip != 0) {
201 if (matches(loc->match, path))
202 return loc->strip;
206 return v->locations[0].strip;
209 X509_STORE *
210 vhost_require_ca(struct vhost *v, const char *path)
212 struct location *loc;
214 if (v == NULL || path == NULL)
215 return NULL;
217 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
218 if (loc->reqca != NULL) {
219 if (matches(loc->match, path))
220 return loc->reqca;
224 return v->locations[0].reqca;
227 int
228 vhost_disable_log(struct vhost *v, const char *path)
230 struct location *loc;
232 if (v == NULL || path == NULL)
233 return 0;
235 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
236 if (loc->disable_log && matches(loc->match, path))
237 return 1;
240 return v->locations[0].disable_log;
243 static int
244 check_path(struct client *c, const char *path, int *fd)
246 struct stat sb;
247 const char *p;
248 int flags;
250 assert(path != NULL);
252 if (*path == '\0')
253 p = ".";
254 else if (*path == '/')
255 /* in send_dir we add an initial / (to be
256 * redirect-friendly), but here we want to skip it */
257 p = path+1;
258 else
259 p = path;
261 flags = O_RDONLY | O_NOFOLLOW;
263 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
264 return FILE_MISSING;
266 if (fstat(*fd, &sb) == -1) {
267 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
268 return FILE_MISSING;
271 if (S_ISDIR(sb.st_mode))
272 return FILE_DIRECTORY;
274 if (sb.st_mode & S_IXUSR)
275 return FILE_EXECUTABLE;
277 return FILE_EXISTS;
280 static void
281 open_file(struct client *c)
283 switch (check_path(c, c->iri.path, &c->pfd)) {
284 case FILE_EXECUTABLE:
285 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
286 start_cgi(c->iri.path, "", c);
287 return;
290 /* fallthrough */
292 case FILE_EXISTS:
293 c->next = handle_copy;
294 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
295 return;
297 case FILE_DIRECTORY:
298 open_dir(c);
299 return;
301 case FILE_MISSING:
302 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
303 check_for_cgi(c);
304 return;
306 start_reply(c, NOT_FOUND, "not found");
307 return;
309 default:
310 /* unreachable */
311 abort();
315 /*
316 * the inverse of this algorithm, i.e. starting from the start of the
317 * path + strlen(cgi), and checking if each component, should be
318 * faster. But it's tedious to write. This does the opposite: starts
319 * from the end and strip one component at a time, until either an
320 * executable is found or we emptied the path.
321 */
322 static void
323 check_for_cgi(struct client *c)
325 char path[PATH_MAX];
326 char *end;
328 strlcpy(path, c->iri.path, sizeof(path));
329 end = strchr(path, '\0');
331 while (end > path) {
332 /* go up one level. UNIX paths are simple and POSIX
333 * dirname, with its ambiguities on if the given path
334 * is changed or not, gives me headaches. */
335 while (*end != '/')
336 end--;
337 *end = '\0';
339 switch (check_path(c, path, &c->pfd)) {
340 case FILE_EXECUTABLE:
341 start_cgi(path, end+1, c);
342 return;
343 case FILE_MISSING:
344 break;
345 default:
346 goto err;
349 *end = '/';
350 end--;
353 err:
354 start_reply(c, NOT_FOUND, "not found");
355 return;
358 void
359 mark_nonblock(int fd)
361 int flags;
363 if ((flags = fcntl(fd, F_GETFL)) == -1)
364 fatal("fcntl(F_GETFL): %s", strerror(errno));
365 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
366 fatal("fcntl(F_SETFL): %s", strerror(errno));
369 static void
370 handle_handshake(int fd, short ev, void *d)
372 struct client *c = d;
373 struct vhost *h;
374 const char *servname;
375 const char *parse_err = "unknown error";
377 switch (tls_handshake(c->ctx)) {
378 case 0: /* success */
379 case -1: /* already handshaked */
380 break;
381 case TLS_WANT_POLLIN:
382 reschedule_read(fd, c, &handle_handshake);
383 return;
384 case TLS_WANT_POLLOUT:
385 reschedule_write(fd, c, &handle_handshake);
386 return;
387 default:
388 /* unreachable */
389 abort();
392 servname = tls_conn_servername(c->ctx);
393 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
394 log_info(c, "puny_decode: %s", parse_err);
395 goto err;
398 for (h = hosts; h->domain != NULL; ++h) {
399 if (matches(h->domain, c->domain))
400 break;
403 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
404 servname != NULL ? servname : "(null)",
405 c->domain,
406 h->domain != NULL ? h->domain : "(null)");
408 if (h->domain != NULL) {
409 c->host = h;
410 handle_open_conn(fd, ev, c);
411 return;
414 err:
415 if (servname != NULL)
416 strncpy(c->req, servname, sizeof(c->req));
417 else
418 strncpy(c->req, "null", sizeof(c->req));
420 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
423 static char *
424 strip_path(char *path, int strip)
426 char *t;
428 while (strip > 0) {
429 if ((t = strchr(path, '/')) == NULL) {
430 path = strchr(path, '\0');
431 break;
433 path = t;
434 strip--;
437 return path;
440 static void
441 fmt_sbuf(const char *fmt, struct client *c, const char *path)
443 size_t i;
444 char buf[32];
446 memset(buf, 0, sizeof(buf));
447 for (i = 0; *fmt; ++fmt) {
448 if (i == sizeof(buf)-1 || *fmt == '%') {
449 strlcat(c->sbuf, buf, sizeof(c->sbuf));
450 memset(buf, 0, sizeof(buf));
451 i = 0;
454 if (*fmt != '%') {
455 buf[i++] = *fmt;
456 continue;
459 switch (*++fmt) {
460 case '%':
461 strlcat(c->sbuf, "%", sizeof(c->sbuf));
462 break;
463 case 'p':
464 strlcat(c->sbuf, path, sizeof(c->sbuf));
465 break;
466 case 'q':
467 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
468 break;
469 case 'P':
470 snprintf(buf, sizeof(buf), "%d", conf.port);
471 strlcat(c->sbuf, buf, sizeof(c->sbuf));
472 memset(buf, 0, sizeof(buf));
473 break;
474 case 'N':
475 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
476 break;
477 default:
478 fatal("%s: unknown fmt specifier %c",
479 __func__, *fmt);
483 if (i != 0)
484 strlcat(c->sbuf, buf, sizeof(c->sbuf));
487 /* 1 if a matching `block return' (and apply it), 0 otherwise */
488 static int
489 apply_block_return(struct client *c)
491 const char *fmt, *path;
492 int code;
494 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
495 return 0;
497 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
498 fmt_sbuf(fmt, c, path);
500 start_reply(c, code, c->sbuf);
501 return 1;
504 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
505 static int
506 apply_require_ca(struct client *c)
508 X509_STORE *store;
509 const uint8_t *cert;
510 size_t len;
512 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
513 return 0;
515 if (!tls_peer_cert_provided(c->ctx)) {
516 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
517 return 1;
520 cert = tls_peer_cert_chain_pem(c->ctx, &len);
521 if (!validate_against_ca(store, cert, len)) {
522 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
523 return 1;
526 return 0;
529 static void
530 handle_open_conn(int fd, short ev, void *d)
532 struct client *c = d;
533 const char *parse_err = "invalid request";
534 char decoded[DOMAIN_NAME_LEN];
536 bzero(c->req, sizeof(c->req));
537 bzero(&c->iri, sizeof(c->iri));
539 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
540 case -1:
541 log_err(c, "tls_read: %s", tls_error(c->ctx));
542 close_conn(fd, ev, c);
543 return;
545 case TLS_WANT_POLLIN:
546 reschedule_read(fd, c, &handle_open_conn);
547 return;
549 case TLS_WANT_POLLOUT:
550 reschedule_write(fd, c, &handle_open_conn);
551 return;
554 if (!trim_req_iri(c->req, &parse_err)
555 || !parse_iri(c->req, &c->iri, &parse_err)
556 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
557 log_info(c, "iri parse error: %s", parse_err);
558 start_reply(c, BAD_REQUEST, "invalid request");
559 return;
562 if (c->iri.port_no != conf.port
563 || strcmp(c->iri.schema, "gemini")
564 || strcmp(decoded, c->domain)) {
565 start_reply(c, PROXY_REFUSED, "won't proxy request");
566 return;
569 if (apply_require_ca(c))
570 return;
572 if (apply_block_return(c))
573 return;
575 if (c->host->entrypoint != NULL) {
576 start_cgi(c->host->entrypoint, c->iri.path, c);
577 return;
580 open_file(c);
583 static void
584 start_reply(struct client *c, int code, const char *meta)
586 c->code = code;
587 c->meta = meta;
588 handle_start_reply(c->fd, 0, c);
591 static void
592 handle_start_reply(int fd, short ev, void *d)
594 struct client *c = d;
595 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
596 const char *lang;
597 size_t len;
599 lang = vhost_lang(c->host, c->iri.path);
601 snprintf(buf, sizeof(buf), "%d ", c->code);
602 strlcat(buf, c->meta, sizeof(buf));
603 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
604 strlcat(buf, "; lang=", sizeof(buf));
605 strlcat(buf, lang, sizeof(buf));
608 len = strlcat(buf, "\r\n", sizeof(buf));
609 assert(len < sizeof(buf));
611 switch (tls_write(c->ctx, buf, len)) {
612 case -1:
613 close_conn(fd, ev, c);
614 return;
615 case TLS_WANT_POLLIN:
616 reschedule_read(fd, c, &handle_start_reply);
617 return;
618 case TLS_WANT_POLLOUT:
619 reschedule_write(fd, c, &handle_start_reply);
620 return;
623 log_request(c, buf, sizeof(buf));
625 if (c->code != SUCCESS)
626 close_conn(fd, ev, c);
627 else
628 c->next(fd, ev, c);
631 static void
632 start_cgi(const char *spath, const char *relpath, struct client *c)
634 char addr[NI_MAXHOST];
635 int e;
637 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
638 addr, sizeof(addr),
639 NULL, 0,
640 NI_NUMERICHOST);
641 if (e != 0)
642 goto err;
644 if (!send_iri(exfd, &c->iri)
645 || !send_string(exfd, spath)
646 || !send_string(exfd, relpath)
647 || !send_string(exfd, addr)
648 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
649 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
650 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
651 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
652 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
653 || !send_vhost(exfd, c->host))
654 goto err;
656 close(c->pfd);
657 if ((c->pfd = recv_fd(exfd)) == -1) {
658 start_reply(c, TEMP_FAILURE, "internal server error");
659 return;
662 reschedule_read(c->pfd, c, &handle_cgi_reply);
663 return;
665 err:
666 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
667 fatal("cannot talk to the executor process");
670 static void
671 open_dir(struct client *c)
673 size_t len;
674 int dirfd;
675 char *before_file;
677 len = strlen(c->iri.path);
678 if (len > 0 && !ends_with(c->iri.path, "/")) {
679 redirect_canonical_dir(c);
680 return;
683 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
684 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
685 if (!ends_with(c->sbuf, "/"))
686 strlcat(c->sbuf, "/", sizeof(c->sbuf));
687 before_file = strchr(c->sbuf, '\0');
688 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
689 sizeof(c->sbuf));
690 if (len >= sizeof(c->sbuf)) {
691 start_reply(c, TEMP_FAILURE, "internal server error");
692 return;
695 c->iri.path = c->sbuf;
697 /* close later unless we have to generate the dir listing */
698 dirfd = c->pfd;
699 c->pfd = -1;
701 switch (check_path(c, c->iri.path, &c->pfd)) {
702 case FILE_EXECUTABLE:
703 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
704 start_cgi(c->iri.path, "", c);
705 break;
708 /* fallthrough */
710 case FILE_EXISTS:
711 c->next = handle_copy;
712 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
713 break;
715 case FILE_DIRECTORY:
716 start_reply(c, TEMP_REDIRECT, c->sbuf);
717 break;
719 case FILE_MISSING:
720 *before_file = '\0';
722 if (!vhost_auto_index(c->host, c->iri.path)) {
723 start_reply(c, NOT_FOUND, "not found");
724 break;
727 c->pfd = dirfd;
728 c->next = enter_handle_dirlist;
730 if ((c->dir = fdopendir(c->pfd)) == NULL) {
731 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
732 c->pfd, c->host->domain, c->iri.path, strerror(errno));
733 start_reply(c, TEMP_FAILURE, "internal server error");
734 return;
736 c->off = 0;
738 start_reply(c, SUCCESS, "text/gemini");
739 return;
741 default:
742 /* unreachable */
743 abort();
746 close(dirfd);
749 static void
750 redirect_canonical_dir(struct client *c)
752 size_t len;
754 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
755 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
756 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
758 if (len >= sizeof(c->sbuf)) {
759 start_reply(c, TEMP_FAILURE, "internal server error");
760 return;
763 start_reply(c, TEMP_REDIRECT, c->sbuf);
766 static void
767 enter_handle_dirlist(int fd, short ev, void *d)
769 struct client *c = d;
770 char b[PATH_MAX];
771 size_t l;
773 strlcpy(b, c->iri.path, sizeof(b));
774 l = snprintf(c->sbuf, sizeof(c->sbuf),
775 "# Index of %s\n\n", b);
776 if (l >= sizeof(c->sbuf)) {
777 /* this is impossible, given that we have enough space
778 * in c->sbuf to hold the ancilliary string plus the
779 * full path; but it wouldn't read nice without some
780 * error checking, and I'd like to avoid a strlen. */
781 close_conn(fd, ev, c);
782 return;
785 c->len = l;
786 handle_dirlist(fd, ev, c);
789 static void
790 handle_dirlist(int fd, short ev, void *d)
792 struct client *c = d;
793 ssize_t r;
795 while (c->len > 0) {
796 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
797 case -1:
798 close_conn(fd, ev, c);
799 return;
800 case TLS_WANT_POLLOUT:
801 reschedule_read(fd, c, &handle_dirlist);
802 return;
803 case TLS_WANT_POLLIN:
804 reschedule_write(fd, c, &handle_dirlist);
805 return;
806 default:
807 c->off += r;
808 c->len -= r;
812 send_directory_listing(fd, ev, c);
815 static int
816 read_next_dir_entry(struct client *c)
818 struct dirent *d;
820 do {
821 errno = 0;
822 if ((d = readdir(c->dir)) == NULL) {
823 if (errno != 0)
824 log_err(c, "readdir: %s", strerror(errno));
825 return 0;
827 } while (!strcmp(d->d_name, "."));
829 /* XXX: url escape */
830 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
831 d->d_name, d->d_name);
832 c->len = strlen(c->sbuf);
833 c->off = 0;
835 return 1;
838 static void
839 send_directory_listing(int fd, short ev, void *d)
841 struct client *c = d;
842 ssize_t r;
844 while (1) {
845 if (c->len == 0) {
846 if (!read_next_dir_entry(c))
847 goto end;
850 while (c->len > 0) {
851 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
852 case -1:
853 goto end;
855 case TLS_WANT_POLLOUT:
856 reschedule_read(fd, c, &send_directory_listing);
857 return;
859 case TLS_WANT_POLLIN:
860 reschedule_write(fd, c, &send_directory_listing);
861 return;
863 default:
864 c->off += r;
865 c->len -= r;
866 break;
871 end:
872 close_conn(fd, ev, d);
875 /* accumulate the meta line from the cgi script. */
876 static void
877 handle_cgi_reply(int fd, short ev, void *d)
879 struct client *c = d;
880 void *buf, *e;
881 size_t len;
882 ssize_t r;
885 buf = c->sbuf + c->len;
886 len = sizeof(c->sbuf) - c->len;
888 r = read(c->pfd, buf, len);
889 if (r == 0 || r == -1) {
890 start_reply(c, CGI_ERROR, "CGI error");
891 return;
894 c->len += r;
896 /* TODO: error if the CGI script don't reply correctly */
897 e = strchr(c->sbuf, '\n');
898 if (e != NULL || c->len == sizeof(c->sbuf)) {
899 log_request(c, c->sbuf, c->len);
901 c->off = 0;
902 handle_copy(fd, ev, c);
903 return;
906 reschedule_read(fd, c, &handle_cgi_reply);
909 static void
910 handle_copy(int fd, short ev, void *d)
912 struct client *c = d;
913 ssize_t r;
915 while (1) {
916 while (c->len > 0) {
917 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
918 case -1:
919 goto end;
921 case TLS_WANT_POLLOUT:
922 reschedule_write(c->fd, c, &handle_copy);
923 return;
925 case TLS_WANT_POLLIN:
926 reschedule_read(c->fd, c, &handle_copy);
927 return;
929 default:
930 c->off += r;
931 c->len -= r;
932 break;
936 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
937 case 0:
938 goto end;
939 case -1:
940 if (errno == EAGAIN || errno == EWOULDBLOCK) {
941 reschedule_read(c->pfd, c, &handle_copy);
942 return;
944 goto end;
945 default:
946 c->len = r;
947 c->off = 0;
951 end:
952 close_conn(c->fd, ev, d);
955 static void
956 close_conn(int fd, short ev, void *d)
958 struct client *c = d;
960 switch (tls_close(c->ctx)) {
961 case TLS_WANT_POLLIN:
962 reschedule_read(fd, c, &close_conn);
963 return;
964 case TLS_WANT_POLLOUT:
965 reschedule_read(fd, c, &close_conn);
966 return;
969 connected_clients--;
971 tls_free(c->ctx);
972 c->ctx = NULL;
974 if (c->pfd != -1)
975 close(c->pfd);
977 if (c->dir != NULL)
978 closedir(c->dir);
980 close(c->fd);
981 c->fd = -1;
984 static void
985 do_accept(int sock, short et, void *d)
987 struct client *c;
988 struct server *s = d;
989 struct sockaddr_storage addr;
990 struct sockaddr *saddr;
991 socklen_t len;
992 int i, fd;
994 (void)et;
997 saddr = (struct sockaddr*)&addr;
998 len = sizeof(addr);
999 if ((fd = accept(sock, saddr, &len)) == -1) {
1000 if (errno == EWOULDBLOCK || errno == EAGAIN)
1001 return;
1002 fatal("accept: %s", strerror(errno));
1005 mark_nonblock(fd);
1007 for (i = 0; i < MAX_USERS; ++i) {
1008 c = &s->clients[i];
1009 if (c->fd == -1) {
1010 memset(c, 0, sizeof(*c));
1011 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1012 break; /* goodbye fd! */
1014 c->fd = fd;
1015 c->pfd = -1;
1016 c->dir = NULL;
1017 c->addr = addr;
1019 reschedule_read(fd, c, &handle_handshake);
1020 connected_clients++;
1021 return;
1025 close(fd);
1028 static void
1029 handle_sighup(int fd, short ev, void *d)
1031 (void)fd;
1032 (void)ev;
1034 event_del(&e4);
1035 if (has_ipv6)
1036 event_del(&e6);
1037 if (has_siginfo)
1038 signal_del(&siginfo);
1039 signal_del(&sigusr2);
1040 signal_del(&sighup);
1043 static void
1044 handle_siginfo(int fd, short ev, void *d)
1046 (void)fd;
1047 (void)ev;
1048 (void)d;
1050 log_info(NULL, "%d connected clients", connected_clients);
1053 void
1054 loop(struct tls *ctx, int sock4, int sock6)
1056 struct server server;
1057 size_t i;
1059 event_init();
1061 memset(&server, 0, sizeof(server));
1062 for (i = 0; i < MAX_USERS; ++i)
1063 server.clients[i].fd = -1;
1065 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1066 event_add(&e4, NULL);
1068 if (sock6 != -1) {
1069 has_ipv6 = 1;
1070 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1071 event_add(&e6, NULL);
1074 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1075 signal_add(&sighup, NULL);
1077 #ifdef SIGINFO
1078 has_siginfo = 1;
1079 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1080 signal_add(&siginfo, NULL);
1081 #endif
1082 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1083 signal_add(&sigusr2, NULL);
1085 server.ctx = ctx;
1087 sandbox();
1088 event_dispatch();
1089 _exit(0);