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 struct event e4, e6, sighup, siginfo, sigusr2;
37 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 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 static int
228 check_path(struct client *c, const char *path, int *fd)
230 struct stat sb;
231 const char *p;
232 int flags;
234 assert(path != NULL);
236 if (*path == '\0')
237 p = ".";
238 else if (*path == '/')
239 /* in send_dir we add an initial / (to be
240 * redirect-friendly), but here we want to skip it */
241 p = path+1;
242 else
243 p = path;
245 flags = O_RDONLY | O_NOFOLLOW;
247 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
248 return FILE_MISSING;
250 if (fstat(*fd, &sb) == -1) {
251 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
252 return FILE_MISSING;
255 if (S_ISDIR(sb.st_mode))
256 return FILE_DIRECTORY;
258 if (sb.st_mode & S_IXUSR)
259 return FILE_EXECUTABLE;
261 return FILE_EXISTS;
264 static void
265 open_file(struct client *c)
267 switch (check_path(c, c->iri.path, &c->pfd)) {
268 case FILE_EXECUTABLE:
269 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
270 start_cgi(c->iri.path, "", c);
271 return;
274 /* fallthrough */
276 case FILE_EXISTS:
277 c->next = handle_copy;
278 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
279 return;
281 case FILE_DIRECTORY:
282 open_dir(c);
283 return;
285 case FILE_MISSING:
286 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
287 check_for_cgi(c);
288 return;
290 start_reply(c, NOT_FOUND, "not found");
291 return;
293 default:
294 /* unreachable */
295 abort();
299 /*
300 * the inverse of this algorithm, i.e. starting from the start of the
301 * path + strlen(cgi), and checking if each component, should be
302 * faster. But it's tedious to write. This does the opposite: starts
303 * from the end and strip one component at a time, until either an
304 * executable is found or we emptied the path.
305 */
306 static void
307 check_for_cgi(struct client *c)
309 char path[PATH_MAX];
310 char *end;
312 strlcpy(path, c->iri.path, sizeof(path));
313 end = strchr(path, '\0');
315 while (end > path) {
316 /* go up one level. UNIX paths are simple and POSIX
317 * dirname, with its ambiguities on if the given path
318 * is changed or not, gives me headaches. */
319 while (*end != '/')
320 end--;
321 *end = '\0';
323 switch (check_path(c, path, &c->pfd)) {
324 case FILE_EXECUTABLE:
325 start_cgi(path, end+1, c);
326 return;
327 case FILE_MISSING:
328 break;
329 default:
330 goto err;
333 *end = '/';
334 end--;
337 err:
338 start_reply(c, NOT_FOUND, "not found");
339 return;
342 void
343 mark_nonblock(int fd)
345 int flags;
347 if ((flags = fcntl(fd, F_GETFL)) == -1)
348 fatal("fcntl(F_GETFL): %s", strerror(errno));
349 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
350 fatal("fcntl(F_SETFL): %s", strerror(errno));
353 static void
354 handle_handshake(int fd, short ev, void *d)
356 struct client *c = d;
357 struct vhost *h;
358 const char *servname;
359 const char *parse_err = "unknown error";
361 switch (tls_handshake(c->ctx)) {
362 case 0: /* success */
363 case -1: /* already handshaked */
364 break;
365 case TLS_WANT_POLLIN:
366 reschedule_read(fd, c, &handle_handshake);
367 return;
368 case TLS_WANT_POLLOUT:
369 reschedule_write(fd, c, &handle_handshake);
370 return;
371 default:
372 /* unreachable */
373 abort();
376 servname = tls_conn_servername(c->ctx);
377 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
378 log_info(c, "puny_decode: %s", parse_err);
379 goto err;
382 for (h = hosts; h->domain != NULL; ++h) {
383 if (!fnmatch(h->domain, c->domain, 0))
384 break;
387 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
388 servname != NULL ? servname : "(null)",
389 c->domain,
390 h->domain != NULL ? h->domain : "(null)");
392 if (h->domain != NULL) {
393 c->host = h;
394 handle_open_conn(fd, ev, c);
395 return;
398 err:
399 if (servname != NULL)
400 strncpy(c->req, servname, sizeof(c->req));
401 else
402 strncpy(c->req, "null", sizeof(c->req));
404 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
407 static char *
408 strip_path(char *path, int strip)
410 char *t;
412 while (strip > 0) {
413 if ((t = strchr(path, '/')) == NULL) {
414 path = strchr(path, '\0');
415 break;
417 path = t;
418 strip--;
421 return path;
424 static void
425 fmt_sbuf(const char *fmt, struct client *c, const char *path)
427 size_t i;
428 char buf[32];
430 memset(buf, 0, sizeof(buf));
431 for (i = 0; *fmt; ++fmt) {
432 if (i == sizeof(buf)-1 || *fmt == '%') {
433 strlcat(c->sbuf, buf, sizeof(c->sbuf));
434 memset(buf, 0, sizeof(buf));
435 i = 0;
438 if (*fmt != '%') {
439 buf[i++] = *fmt;
440 continue;
443 switch (*++fmt) {
444 case '%':
445 strlcat(c->sbuf, "%", sizeof(c->sbuf));
446 break;
447 case 'p':
448 strlcat(c->sbuf, path, sizeof(c->sbuf));
449 break;
450 case 'q':
451 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
452 break;
453 case 'P':
454 snprintf(buf, sizeof(buf), "%d", conf.port);
455 strlcat(c->sbuf, buf, sizeof(c->sbuf));
456 memset(buf, 0, sizeof(buf));
457 break;
458 case 'N':
459 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
460 break;
461 default:
462 fatal("%s: unknown fmt specifier %c",
463 __func__, *fmt);
467 if (i != 0)
468 strlcat(c->sbuf, buf, sizeof(c->sbuf));
471 /* 1 if a matching `block return' (and apply it), 0 otherwise */
472 static int
473 apply_block_return(struct client *c)
475 const char *fmt, *path;
476 int code;
478 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
479 return 0;
481 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
482 fmt_sbuf(fmt, c, path);
484 start_reply(c, code, c->sbuf);
485 return 1;
488 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
489 static int
490 apply_require_ca(struct client *c)
492 X509_STORE *store;
493 const uint8_t *cert;
494 size_t len;
496 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
497 return 0;
499 if (!tls_peer_cert_provided(c->ctx)) {
500 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
501 return 1;
504 cert = tls_peer_cert_chain_pem(c->ctx, &len);
505 if (!validate_against_ca(store, cert, len)) {
506 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
507 return 1;
510 return 0;
513 static void
514 handle_open_conn(int fd, short ev, void *d)
516 struct client *c = d;
517 const char *parse_err = "invalid request";
518 char decoded[DOMAIN_NAME_LEN];
520 bzero(c->req, sizeof(c->req));
521 bzero(&c->iri, sizeof(c->iri));
523 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
524 case -1:
525 log_err(c, "tls_read: %s", tls_error(c->ctx));
526 close_conn(fd, ev, c);
527 return;
529 case TLS_WANT_POLLIN:
530 reschedule_read(fd, c, &handle_open_conn);
531 return;
533 case TLS_WANT_POLLOUT:
534 reschedule_write(fd, c, &handle_open_conn);
535 return;
538 if (!trim_req_iri(c->req, &parse_err)
539 || !parse_iri(c->req, &c->iri, &parse_err)
540 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
541 log_info(c, "iri parse error: %s", parse_err);
542 start_reply(c, BAD_REQUEST, "invalid request");
543 return;
546 if (c->iri.port_no != conf.port
547 || strcmp(c->iri.schema, "gemini")
548 || strcmp(decoded, c->domain)) {
549 start_reply(c, PROXY_REFUSED, "won't proxy request");
550 return;
553 if (apply_require_ca(c))
554 return;
556 if (apply_block_return(c))
557 return;
559 if (c->host->entrypoint != NULL) {
560 start_cgi(c->host->entrypoint, c->iri.path, c);
561 return;
564 open_file(c);
567 static void
568 start_reply(struct client *c, int code, const char *meta)
570 c->code = code;
571 c->meta = meta;
572 handle_start_reply(c->fd, 0, c);
575 static void
576 handle_start_reply(int fd, short ev, void *d)
578 struct client *c = d;
579 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
580 const char *lang;
581 size_t len;
583 lang = vhost_lang(c->host, c->iri.path);
585 snprintf(buf, sizeof(buf), "%d ", c->code);
586 strlcat(buf, c->meta, sizeof(buf));
587 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
588 strlcat(buf, "; lang=", sizeof(buf));
589 strlcat(buf, lang, sizeof(buf));
592 len = strlcat(buf, "\r\n", sizeof(buf));
593 assert(len < sizeof(buf));
595 switch (tls_write(c->ctx, buf, len)) {
596 case -1:
597 close_conn(fd, ev, c);
598 return;
599 case TLS_WANT_POLLIN:
600 reschedule_read(fd, c, &handle_start_reply);
601 return;
602 case TLS_WANT_POLLOUT:
603 reschedule_write(fd, c, &handle_start_reply);
604 return;
607 log_request(c, buf, sizeof(buf));
609 if (c->code != SUCCESS)
610 close_conn(fd, ev, c);
611 else
612 c->next(fd, ev, c);
615 static void
616 start_cgi(const char *spath, const char *relpath, struct client *c)
618 char addr[NI_MAXHOST];
619 int e;
621 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
622 addr, sizeof(addr),
623 NULL, 0,
624 NI_NUMERICHOST);
625 if (e != 0)
626 goto err;
628 if (!send_iri(exfd, &c->iri)
629 || !send_string(exfd, spath)
630 || !send_string(exfd, relpath)
631 || !send_string(exfd, addr)
632 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
633 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
634 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
635 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
636 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
637 || !send_vhost(exfd, c->host))
638 goto err;
640 close(c->pfd);
641 if ((c->pfd = recv_fd(exfd)) == -1) {
642 start_reply(c, TEMP_FAILURE, "internal server error");
643 return;
646 reschedule_read(c->pfd, c, &handle_cgi_reply);
647 return;
649 err:
650 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
651 fatal("cannot talk to the executor process");
654 static void
655 open_dir(struct client *c)
657 size_t len;
658 int dirfd;
659 char *before_file;
661 len = strlen(c->iri.path);
662 if (len > 0 && !ends_with(c->iri.path, "/")) {
663 redirect_canonical_dir(c);
664 return;
667 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
668 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
669 if (!ends_with(c->sbuf, "/"))
670 strlcat(c->sbuf, "/", sizeof(c->sbuf));
671 before_file = strchr(c->sbuf, '\0');
672 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
673 sizeof(c->sbuf));
674 if (len >= sizeof(c->sbuf)) {
675 start_reply(c, TEMP_FAILURE, "internal server error");
676 return;
679 c->iri.path = c->sbuf;
681 /* close later unless we have to generate the dir listing */
682 dirfd = c->pfd;
683 c->pfd = -1;
685 switch (check_path(c, c->iri.path, &c->pfd)) {
686 case FILE_EXECUTABLE:
687 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
688 start_cgi(c->iri.path, "", c);
689 break;
692 /* fallthrough */
694 case FILE_EXISTS:
695 c->next = handle_copy;
696 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
697 break;
699 case FILE_DIRECTORY:
700 start_reply(c, TEMP_REDIRECT, c->sbuf);
701 break;
703 case FILE_MISSING:
704 *before_file = '\0';
706 if (!vhost_auto_index(c->host, c->iri.path)) {
707 start_reply(c, NOT_FOUND, "not found");
708 break;
711 c->pfd = dirfd;
712 c->next = enter_handle_dirlist;
714 if ((c->dir = fdopendir(c->pfd)) == NULL) {
715 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
716 c->pfd, c->host->domain, c->iri.path, strerror(errno));
717 start_reply(c, TEMP_FAILURE, "internal server error");
718 return;
720 c->off = 0;
722 start_reply(c, SUCCESS, "text/gemini");
723 return;
725 default:
726 /* unreachable */
727 abort();
730 close(dirfd);
733 static void
734 redirect_canonical_dir(struct client *c)
736 size_t len;
738 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
739 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
740 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
742 if (len >= sizeof(c->sbuf)) {
743 start_reply(c, TEMP_FAILURE, "internal server error");
744 return;
747 start_reply(c, TEMP_REDIRECT, c->sbuf);
750 static void
751 enter_handle_dirlist(int fd, short ev, void *d)
753 struct client *c = d;
754 char b[PATH_MAX];
755 size_t l;
757 strlcpy(b, c->iri.path, sizeof(b));
758 l = snprintf(c->sbuf, sizeof(c->sbuf),
759 "# Index of %s\n\n", b);
760 if (l >= sizeof(c->sbuf)) {
761 /* this is impossible, given that we have enough space
762 * in c->sbuf to hold the ancilliary string plus the
763 * full path; but it wouldn't read nice without some
764 * error checking, and I'd like to avoid a strlen. */
765 close_conn(fd, ev, c);
766 return;
769 c->len = l;
770 handle_dirlist(fd, ev, c);
773 static void
774 handle_dirlist(int fd, short ev, void *d)
776 struct client *c = d;
777 ssize_t r;
779 while (c->len > 0) {
780 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
781 case -1:
782 close_conn(fd, ev, c);
783 return;
784 case TLS_WANT_POLLOUT:
785 reschedule_read(fd, c, &handle_dirlist);
786 return;
787 case TLS_WANT_POLLIN:
788 reschedule_write(fd, c, &handle_dirlist);
789 return;
790 default:
791 c->off += r;
792 c->len -= r;
796 send_directory_listing(fd, ev, c);
799 static int
800 read_next_dir_entry(struct client *c)
802 struct dirent *d;
804 do {
805 errno = 0;
806 if ((d = readdir(c->dir)) == NULL) {
807 if (errno != 0)
808 log_err(c, "readdir: %s", strerror(errno));
809 return 0;
811 } while (!strcmp(d->d_name, "."));
813 /* XXX: url escape */
814 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
815 d->d_name, d->d_name);
816 c->len = strlen(c->sbuf);
817 c->off = 0;
819 return 1;
822 static void
823 send_directory_listing(int fd, short ev, void *d)
825 struct client *c = d;
826 ssize_t r;
828 while (1) {
829 if (c->len == 0) {
830 if (!read_next_dir_entry(c))
831 goto end;
834 while (c->len > 0) {
835 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
836 case -1:
837 goto end;
839 case TLS_WANT_POLLOUT:
840 reschedule_read(fd, c, &send_directory_listing);
841 return;
843 case TLS_WANT_POLLIN:
844 reschedule_write(fd, c, &send_directory_listing);
845 return;
847 default:
848 c->off += r;
849 c->len -= r;
850 break;
855 end:
856 close_conn(fd, ev, d);
859 /* accumulate the meta line from the cgi script. */
860 static void
861 handle_cgi_reply(int fd, short ev, void *d)
863 struct client *c = d;
864 void *buf, *e;
865 size_t len;
866 ssize_t r;
869 buf = c->sbuf + c->len;
870 len = sizeof(c->sbuf) - c->len;
872 r = read(c->pfd, buf, len);
873 if (r == 0 || r == -1) {
874 start_reply(c, CGI_ERROR, "CGI error");
875 return;
878 c->len += r;
880 /* TODO: error if the CGI script don't reply correctly */
881 e = strchr(c->sbuf, '\n');
882 if (e != NULL || c->len == sizeof(c->sbuf)) {
883 log_request(c, c->sbuf, c->len);
885 c->off = 0;
886 handle_copy(fd, ev, c);
887 return;
890 reschedule_read(fd, c, &handle_cgi_reply);
893 static void
894 handle_copy(int fd, short ev, void *d)
896 struct client *c = d;
897 ssize_t r;
899 while (1) {
900 while (c->len > 0) {
901 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
902 case -1:
903 goto end;
905 case TLS_WANT_POLLOUT:
906 reschedule_write(c->fd, c, &handle_copy);
907 return;
909 case TLS_WANT_POLLIN:
910 reschedule_read(c->fd, c, &handle_copy);
911 return;
913 default:
914 c->off += r;
915 c->len -= r;
916 break;
920 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
921 case 0:
922 goto end;
923 case -1:
924 if (errno == EAGAIN || errno == EWOULDBLOCK) {
925 reschedule_read(c->pfd, c, &handle_copy);
926 return;
928 goto end;
929 default:
930 c->len = r;
931 c->off = 0;
935 end:
936 close_conn(c->fd, ev, d);
939 static void
940 close_conn(int fd, short ev, void *d)
942 struct client *c = d;
944 switch (tls_close(c->ctx)) {
945 case TLS_WANT_POLLIN:
946 reschedule_read(fd, c, &close_conn);
947 return;
948 case TLS_WANT_POLLOUT:
949 reschedule_read(fd, c, &close_conn);
950 return;
953 connected_clients--;
955 tls_free(c->ctx);
956 c->ctx = NULL;
958 if (c->pfd != -1)
959 close(c->pfd);
961 if (c->dir != NULL)
962 closedir(c->dir);
964 close(c->fd);
965 c->fd = -1;
968 static void
969 do_accept(int sock, short et, void *d)
971 struct client *c;
972 struct server *s = d;
973 struct sockaddr_storage addr;
974 struct sockaddr *saddr;
975 socklen_t len;
976 int i, fd;
978 (void)et;
981 saddr = (struct sockaddr*)&addr;
982 len = sizeof(addr);
983 if ((fd = accept(sock, saddr, &len)) == -1) {
984 if (errno == EWOULDBLOCK || errno == EAGAIN)
985 return;
986 fatal("accept: %s", strerror(errno));
989 mark_nonblock(fd);
991 for (i = 0; i < MAX_USERS; ++i) {
992 c = &s->clients[i];
993 if (c->fd == -1) {
994 memset(c, 0, sizeof(*c));
995 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
996 break; /* goodbye fd! */
998 c->fd = fd;
999 c->pfd = -1;
1000 c->dir = NULL;
1001 c->addr = addr;
1003 reschedule_read(fd, c, &handle_handshake);
1004 connected_clients++;
1005 return;
1009 close(fd);
1012 static void
1013 handle_sighup(int fd, short ev, void *d)
1015 (void)fd;
1016 (void)ev;
1018 event_del(&e4);
1019 if (has_ipv6)
1020 event_del(&e6);
1021 if (has_siginfo)
1022 signal_del(&siginfo);
1023 signal_del(&sigusr2);
1024 signal_del(&sighup);
1027 static void
1028 handle_siginfo(int fd, short ev, void *d)
1030 (void)fd;
1031 (void)ev;
1032 (void)d;
1034 log_info(NULL, "%d connected clients", connected_clients);
1037 void
1038 loop(struct tls *ctx, int sock4, int sock6)
1040 struct server server;
1041 size_t i;
1043 event_init();
1045 memset(&server, 0, sizeof(server));
1046 for (i = 0; i < MAX_USERS; ++i)
1047 server.clients[i].fd = -1;
1049 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1050 event_add(&e4, NULL);
1052 if (sock6 != -1) {
1053 has_ipv6 = 1;
1054 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1055 event_add(&e6, NULL);
1058 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1059 signal_add(&sighup, NULL);
1061 #ifdef SIGINFO
1062 has_siginfo = 1;
1063 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1064 signal_add(&siginfo, NULL);
1065 #endif
1066 signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1067 signal_add(&sigusr2, NULL);
1069 server.ctx = ctx;
1071 sandbox();
1072 event_dispatch();
1073 _exit(0);