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 if (!vhost_disable_log(c->host, c->iri.path))
624 log_request(c, buf, sizeof(buf));
626 if (c->code != SUCCESS)
627 close_conn(fd, ev, c);
628 else
629 c->next(fd, ev, c);
632 static void
633 start_cgi(const char *spath, const char *relpath, struct client *c)
635 char addr[NI_MAXHOST];
636 int e;
638 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
639 addr, sizeof(addr),
640 NULL, 0,
641 NI_NUMERICHOST);
642 if (e != 0)
643 goto err;
645 if (!send_iri(exfd, &c->iri)
646 || !send_string(exfd, spath)
647 || !send_string(exfd, relpath)
648 || !send_string(exfd, addr)
649 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
650 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
651 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
652 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
653 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
654 || !send_vhost(exfd, c->host))
655 goto err;
657 close(c->pfd);
658 if ((c->pfd = recv_fd(exfd)) == -1) {
659 start_reply(c, TEMP_FAILURE, "internal server error");
660 return;
663 reschedule_read(c->pfd, c, &handle_cgi_reply);
664 return;
666 err:
667 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
668 fatal("cannot talk to the executor process");
671 static void
672 open_dir(struct client *c)
674 size_t len;
675 int dirfd;
676 char *before_file;
678 len = strlen(c->iri.path);
679 if (len > 0 && !ends_with(c->iri.path, "/")) {
680 redirect_canonical_dir(c);
681 return;
684 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
685 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
686 if (!ends_with(c->sbuf, "/"))
687 strlcat(c->sbuf, "/", sizeof(c->sbuf));
688 before_file = strchr(c->sbuf, '\0');
689 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
690 sizeof(c->sbuf));
691 if (len >= sizeof(c->sbuf)) {
692 start_reply(c, TEMP_FAILURE, "internal server error");
693 return;
696 c->iri.path = c->sbuf;
698 /* close later unless we have to generate the dir listing */
699 dirfd = c->pfd;
700 c->pfd = -1;
702 switch (check_path(c, c->iri.path, &c->pfd)) {
703 case FILE_EXECUTABLE:
704 if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
705 start_cgi(c->iri.path, "", c);
706 break;
709 /* fallthrough */
711 case FILE_EXISTS:
712 c->next = handle_copy;
713 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
714 break;
716 case FILE_DIRECTORY:
717 start_reply(c, TEMP_REDIRECT, c->sbuf);
718 break;
720 case FILE_MISSING:
721 *before_file = '\0';
723 if (!vhost_auto_index(c->host, c->iri.path)) {
724 start_reply(c, NOT_FOUND, "not found");
725 break;
728 c->pfd = dirfd;
729 c->next = enter_handle_dirlist;
731 if ((c->dir = fdopendir(c->pfd)) == NULL) {
732 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
733 c->pfd, c->host->domain, c->iri.path, strerror(errno));
734 start_reply(c, TEMP_FAILURE, "internal server error");
735 return;
737 c->off = 0;
739 start_reply(c, SUCCESS, "text/gemini");
740 return;
742 default:
743 /* unreachable */
744 abort();
747 close(dirfd);
750 static void
751 redirect_canonical_dir(struct client *c)
753 size_t len;
755 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
756 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
757 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
759 if (len >= sizeof(c->sbuf)) {
760 start_reply(c, TEMP_FAILURE, "internal server error");
761 return;
764 start_reply(c, TEMP_REDIRECT, c->sbuf);
767 static void
768 enter_handle_dirlist(int fd, short ev, void *d)
770 struct client *c = d;
771 char b[PATH_MAX];
772 size_t l;
774 strlcpy(b, c->iri.path, sizeof(b));
775 l = snprintf(c->sbuf, sizeof(c->sbuf),
776 "# Index of %s\n\n", b);
777 if (l >= sizeof(c->sbuf)) {
778 /* this is impossible, given that we have enough space
779 * in c->sbuf to hold the ancilliary string plus the
780 * full path; but it wouldn't read nice without some
781 * error checking, and I'd like to avoid a strlen. */
782 close_conn(fd, ev, c);
783 return;
786 c->len = l;
787 handle_dirlist(fd, ev, c);
790 static void
791 handle_dirlist(int fd, short ev, void *d)
793 struct client *c = d;
794 ssize_t r;
796 while (c->len > 0) {
797 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
798 case -1:
799 close_conn(fd, ev, c);
800 return;
801 case TLS_WANT_POLLOUT:
802 reschedule_read(fd, c, &handle_dirlist);
803 return;
804 case TLS_WANT_POLLIN:
805 reschedule_write(fd, c, &handle_dirlist);
806 return;
807 default:
808 c->off += r;
809 c->len -= r;
813 send_directory_listing(fd, ev, c);
816 static int
817 read_next_dir_entry(struct client *c)
819 struct dirent *d;
821 do {
822 errno = 0;
823 if ((d = readdir(c->dir)) == NULL) {
824 if (errno != 0)
825 log_err(c, "readdir: %s", strerror(errno));
826 return 0;
828 } while (!strcmp(d->d_name, "."));
830 /* XXX: url escape */
831 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
832 d->d_name, d->d_name);
833 c->len = strlen(c->sbuf);
834 c->off = 0;
836 return 1;
839 static void
840 send_directory_listing(int fd, short ev, void *d)
842 struct client *c = d;
843 ssize_t r;
845 while (1) {
846 if (c->len == 0) {
847 if (!read_next_dir_entry(c))
848 goto end;
851 while (c->len > 0) {
852 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
853 case -1:
854 goto end;
856 case TLS_WANT_POLLOUT:
857 reschedule_read(fd, c, &send_directory_listing);
858 return;
860 case TLS_WANT_POLLIN:
861 reschedule_write(fd, c, &send_directory_listing);
862 return;
864 default:
865 c->off += r;
866 c->len -= r;
867 break;
872 end:
873 close_conn(fd, ev, d);
876 /* accumulate the meta line from the cgi script. */
877 static void
878 handle_cgi_reply(int fd, short ev, void *d)
880 struct client *c = d;
881 void *buf, *e;
882 size_t len;
883 ssize_t r;
886 buf = c->sbuf + c->len;
887 len = sizeof(c->sbuf) - c->len;
889 r = read(c->pfd, buf, len);
890 if (r == 0 || r == -1) {
891 start_reply(c, CGI_ERROR, "CGI error");
892 return;
895 c->len += r;
897 /* TODO: error if the CGI script don't reply correctly */
898 e = strchr(c->sbuf, '\n');
899 if (e != NULL || c->len == sizeof(c->sbuf)) {
900 log_request(c, c->sbuf, c->len);
902 c->off = 0;
903 handle_copy(fd, ev, c);
904 return;
907 reschedule_read(fd, c, &handle_cgi_reply);
910 static void
911 handle_copy(int fd, short ev, void *d)
913 struct client *c = d;
914 ssize_t r;
916 while (1) {
917 while (c->len > 0) {
918 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
919 case -1:
920 goto end;
922 case TLS_WANT_POLLOUT:
923 reschedule_write(c->fd, c, &handle_copy);
924 return;
926 case TLS_WANT_POLLIN:
927 reschedule_read(c->fd, c, &handle_copy);
928 return;
930 default:
931 c->off += r;
932 c->len -= r;
933 break;
937 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
938 case 0:
939 goto end;
940 case -1:
941 if (errno == EAGAIN || errno == EWOULDBLOCK) {
942 reschedule_read(c->pfd, c, &handle_copy);
943 return;
945 goto end;
946 default:
947 c->len = r;
948 c->off = 0;
952 end:
953 close_conn(c->fd, ev, d);
956 static void
957 close_conn(int fd, short ev, void *d)
959 struct client *c = d;
961 switch (tls_close(c->ctx)) {
962 case TLS_WANT_POLLIN:
963 reschedule_read(fd, c, &close_conn);
964 return;
965 case TLS_WANT_POLLOUT:
966 reschedule_read(fd, c, &close_conn);
967 return;
970 connected_clients--;
972 tls_free(c->ctx);
973 c->ctx = NULL;
975 if (c->pfd != -1)
976 close(c->pfd);
978 if (c->dir != NULL)
979 closedir(c->dir);
981 close(c->fd);
982 c->fd = -1;
985 static void
986 do_accept(int sock, short et, void *d)
988 struct client *c;
989 struct server *s = d;
990 struct sockaddr_storage addr;
991 struct sockaddr *saddr;
992 socklen_t len;
993 int i, fd;
995 (void)et;
998 saddr = (struct sockaddr*)&addr;
999 len = sizeof(addr);
1000 if ((fd = accept(sock, saddr, &len)) == -1) {
1001 if (errno == EWOULDBLOCK || errno == EAGAIN)
1002 return;
1003 fatal("accept: %s", strerror(errno));
1006 mark_nonblock(fd);
1008 for (i = 0; i < MAX_USERS; ++i) {
1009 c = &s->clients[i];
1010 if (c->fd == -1) {
1011 memset(c, 0, sizeof(*c));
1012 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1013 break; /* goodbye fd! */
1015 c->fd = fd;
1016 c->pfd = -1;
1017 c->dir = NULL;
1018 c->addr = addr;
1020 reschedule_read(fd, c, &handle_handshake);
1021 connected_clients++;
1022 return;
1026 close(fd);
1029 static void
1030 handle_sighup(int fd, short ev, void *d)
1032 (void)fd;
1033 (void)ev;
1035 event_del(&e4);
1036 if (has_ipv6)
1037 event_del(&e6);
1038 if (has_siginfo)
1039 signal_del(&siginfo);
1040 signal_del(&sigusr2);
1041 signal_del(&sighup);
1044 static void
1045 handle_siginfo(int fd, short ev, void *d)
1047 (void)fd;
1048 (void)ev;
1049 (void)d;
1051 log_info(NULL, "%d connected clients", connected_clients);
1054 void
1055 loop(struct tls *ctx, int sock4, int sock6)
1057 struct server server;
1058 size_t i;
1060 event_init();
1062 memset(&server, 0, sizeof(server));
1063 for (i = 0; i < MAX_USERS; ++i)
1064 server.clients[i].fd = -1;
1066 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1067 event_add(&e4, NULL);
1069 if (sock6 != -1) {
1070 has_ipv6 = 1;
1071 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1072 event_add(&e6, NULL);
1075 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1076 signal_add(&sighup, NULL);
1078 #ifdef SIGINFO
1079 has_siginfo = 1;
1080 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1081 signal_add(&siginfo, NULL);
1082 #endif
1083 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1084 signal_add(&sigusr2, NULL);
1086 server.ctx = ctx;
1088 sandbox();
1089 event_dispatch();
1090 _exit(0);