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 <sys/mman.h>
18 #include <sys/stat.h>
20 #include <netdb.h>
22 #include <assert.h>
23 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <fnmatch.h>
27 #include <limits.h>
28 #include <string.h>
30 #include "gmid.h"
32 struct server {
33 struct client clients[MAX_USERS];
34 struct tls *ctx;
35 };
37 struct server_events {
38 struct event e4;
39 int has_ipv6;
40 struct event e6;
41 struct event sighup;
42 };
44 int connected_clients;
46 static inline void reschedule_read(int, struct client*, statefn);
47 static inline void reschedule_write(int, struct client*, statefn);
49 static int check_path(struct client*, const char*, int*);
50 static void open_file(struct client*);
51 static void load_file(struct client*);
52 static void check_for_cgi(struct client*);
53 static void handle_handshake(int, short, void*);
54 static int apply_block_return(struct client*);
55 static void handle_open_conn(int, short, void*);
56 static void start_reply(struct client*, int, const char*);
57 static void handle_start_reply(int, short, void*);
58 static void start_cgi(const char*, const char*, struct client*);
59 static void send_file(int, short, void*);
60 static void open_dir(struct client*);
61 static void redirect_canonical_dir(struct client*);
62 static void enter_handle_dirlist(int, short, void*);
63 static void handle_dirlist(int, short, void*);
64 static int read_next_dir_entry(struct client*);
65 static void send_directory_listing(int, short, void*);
66 static void handle_cgi_reply(int, short, void*);
67 static void handle_cgi(int, short, void*);
68 static void close_conn(int, short, void*);
69 static void do_accept(int, short, void*);
70 static void handle_sighup(int, short, void*);
72 static inline void
73 reschedule_read(int fd, struct client *c, statefn fn)
74 {
75 event_once(fd, EV_READ, fn, c, NULL);
76 }
78 void
79 reschedule_write(int fd, struct client *c, statefn fn)
80 {
81 event_once(fd, EV_WRITE, fn, c, NULL);
82 }
84 const char *
85 vhost_lang(struct vhost *v, const char *path)
86 {
87 struct location *loc;
89 if (v == NULL || path == NULL)
90 return NULL;
92 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
93 if (loc->lang != NULL) {
94 if (!fnmatch(loc->match, path, 0))
95 return loc->lang;
96 }
97 }
99 return v->locations[0].lang;
102 const char *
103 vhost_default_mime(struct vhost *v, const char *path)
105 struct location *loc;
106 const char *default_mime = "application/octet-stream";
108 if (v == NULL || path == NULL)
109 return default_mime;
111 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
112 if (loc->default_mime != NULL) {
113 if (!fnmatch(loc->match, path, 0))
114 return loc->default_mime;
118 if (v->locations[0].default_mime != NULL)
119 return v->locations[0].default_mime;
120 return default_mime;
123 const char *
124 vhost_index(struct vhost *v, const char *path)
126 struct location *loc;
127 const char *index = "index.gmi";
129 if (v == NULL || path == NULL)
130 return index;
132 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
133 if (loc->index != NULL) {
134 if (!fnmatch(loc->match, path, 0))
135 return loc->index;
139 if (v->locations[0].index != NULL)
140 return v->locations[0].index;
141 return index;
144 int
145 vhost_auto_index(struct vhost *v, const char *path)
147 struct location *loc;
149 if (v == NULL || path == NULL)
150 return 0;
152 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
153 if (loc->auto_index != 0) {
154 if (!fnmatch(loc->match, path, 0))
155 return loc->auto_index == 1;
159 return v->locations[0].auto_index == 1;
162 int
163 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
165 struct location *loc;
167 if (v == NULL || path == NULL)
168 return 0;
170 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
171 if (loc->block_code != 0) {
172 if (!fnmatch(loc->match, path, 0)) {
173 *code = loc->block_code;
174 *fmt = loc->block_fmt;
175 return 1;
180 *code = v->locations[0].block_code;
181 *fmt = v->locations[0].block_fmt;
182 return v->locations[0].block_code != 0;
185 int
186 vhost_strip(struct vhost *v, const char *path)
188 struct location *loc;
190 if (v == NULL || path == NULL)
191 return 0;
193 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
194 if (loc->strip != 0) {
195 if (!fnmatch(loc->match, path, 0))
196 return loc->strip;
200 return v->locations[0].strip;
203 static int
204 check_path(struct client *c, const char *path, int *fd)
206 struct stat sb;
207 const char *p;
208 int flags;
210 assert(path != NULL);
212 if (*path == '\0')
213 p = ".";
214 else if (*path == '/')
215 /* in send_dir we add an initial / (to be
216 * redirect-friendly), but here we want to skip it */
217 p = path+1;
218 else
219 p = path;
221 flags = O_RDONLY | O_NOFOLLOW;
223 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
224 return FILE_MISSING;
226 if (fstat(*fd, &sb) == -1) {
227 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
228 return FILE_MISSING;
231 if (S_ISDIR(sb.st_mode))
232 return FILE_DIRECTORY;
234 if (sb.st_mode & S_IXUSR)
235 return FILE_EXECUTABLE;
237 return FILE_EXISTS;
240 static void
241 open_file(struct client *c)
243 switch (check_path(c, c->iri.path, &c->pfd)) {
244 case FILE_EXECUTABLE:
245 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
246 start_cgi(c->iri.path, "", c);
247 return;
250 /* fallthrough */
252 case FILE_EXISTS:
253 load_file(c);
254 return;
256 case FILE_DIRECTORY:
257 open_dir(c);
258 return;
260 case FILE_MISSING:
261 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
262 check_for_cgi(c);
263 return;
265 start_reply(c, NOT_FOUND, "not found");
266 return;
268 default:
269 /* unreachable */
270 abort();
274 static void
275 load_file(struct client *c)
277 if ((c->len = filesize(c->pfd)) == -1) {
278 log_err(c, "failed to get file size for %s: %s",
279 c->iri.path, strerror(errno));
280 start_reply(c, TEMP_FAILURE, "internal server error");
281 return;
284 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
285 c->pfd, 0)) == MAP_FAILED) {
286 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
287 start_reply(c, TEMP_FAILURE, "internal server error");
288 return;
290 c->i = c->buf;
291 c->next = send_file;
292 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
295 /*
296 * the inverse of this algorithm, i.e. starting from the start of the
297 * path + strlen(cgi), and checking if each component, should be
298 * faster. But it's tedious to write. This does the opposite: starts
299 * from the end and strip one component at a time, until either an
300 * executable is found or we emptied the path.
301 */
302 static void
303 check_for_cgi(struct client *c)
305 char path[PATH_MAX];
306 char *end;
308 strlcpy(path, c->iri.path, sizeof(path));
309 end = strchr(path, '\0');
311 while (end > path) {
312 /* go up one level. UNIX paths are simple and POSIX
313 * dirname, with its ambiguities on if the given path
314 * is changed or not, gives me headaches. */
315 while (*end != '/')
316 end--;
317 *end = '\0';
319 switch (check_path(c, path, &c->pfd)) {
320 case FILE_EXECUTABLE:
321 start_cgi(path, end+1, c);
322 return;
323 case FILE_MISSING:
324 break;
325 default:
326 goto err;
329 *end = '/';
330 end--;
333 err:
334 start_reply(c, NOT_FOUND, "not found");
335 return;
338 void
339 mark_nonblock(int fd)
341 int flags;
343 if ((flags = fcntl(fd, F_GETFL)) == -1)
344 fatal("fcntl(F_GETFL): %s", strerror(errno));
345 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
346 fatal("fcntl(F_SETFL): %s", strerror(errno));
349 static void
350 handle_handshake(int fd, short ev, void *d)
352 struct client *c = d;
353 struct vhost *h;
354 const char *servname;
355 const char *parse_err = "unknown error";
357 switch (tls_handshake(c->ctx)) {
358 case 0: /* success */
359 case -1: /* already handshaked */
360 break;
361 case TLS_WANT_POLLIN:
362 reschedule_read(fd, c, &handle_handshake);
363 return;
364 case TLS_WANT_POLLOUT:
365 reschedule_write(fd, c, &handle_handshake);
366 return;
367 default:
368 /* unreachable */
369 abort();
372 servname = tls_conn_servername(c->ctx);
373 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
374 log_info(c, "puny_decode: %s", parse_err);
375 goto err;
378 for (h = hosts; h->domain != NULL; ++h) {
379 if (!fnmatch(h->domain, c->domain, 0))
380 break;
383 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
384 servname != NULL ? servname : "(null)",
385 c->domain,
386 h->domain != NULL ? h->domain : "(null)");
388 if (h->domain != NULL) {
389 c->host = h;
390 handle_open_conn(fd, ev, c);
391 return;
394 err:
395 if (servname != NULL)
396 strncpy(c->req, servname, sizeof(c->req));
397 else
398 strncpy(c->req, "null", sizeof(c->req));
400 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
403 /* 1 if a matching `block return' (and apply it), 0 otherwise */
404 static int
405 apply_block_return(struct client *c)
407 char *t, *path, buf[32];
408 const char *fmt;
409 int strip, code;
410 size_t i;
412 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
413 return 0;
415 strip = vhost_strip(c->host, c->iri.path);
416 path = c->iri.path;
417 while (strip > 0) {
418 if ((t = strchr(path, '/')) == NULL) {
419 path = strchr(path, '\0');
420 break;
422 path = t;
423 strip--;
426 memset(buf, 0, sizeof(buf));
427 for (i = 0; *fmt; ++fmt) {
428 if (i == sizeof(buf)-1 || *fmt == '%') {
429 strlcat(c->sbuf, buf, sizeof(c->sbuf));
430 memset(buf, 0, sizeof(buf));
431 i = 0;
434 if (*fmt != '%') {
435 buf[i++] = *fmt;
436 continue;
439 switch (*++fmt) {
440 case '%':
441 strlcat(c->sbuf, "%", sizeof(c->sbuf));
442 break;
443 case 'p':
444 strlcat(c->sbuf, path, sizeof(c->sbuf));
445 break;
446 case 'q':
447 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
448 break;
449 case 'P':
450 snprintf(buf, sizeof(buf), "%d", conf.port);
451 strlcat(c->sbuf, buf, sizeof(c->sbuf));
452 memset(buf, 0, sizeof(buf));
453 break;
454 case 'N':
455 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
456 break;
457 default:
458 fatal("%s: unknown fmt specifier %c",
459 __func__, *fmt);
463 if (i != 0)
464 strlcat(c->sbuf, buf, sizeof(c->sbuf));
466 start_reply(c, code, c->sbuf);
467 return 1;
470 static void
471 handle_open_conn(int fd, short ev, void *d)
473 struct client *c = d;
474 const char *parse_err = "invalid request";
475 char decoded[DOMAIN_NAME_LEN];
477 bzero(c->req, sizeof(c->req));
478 bzero(&c->iri, sizeof(c->iri));
480 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
481 case -1:
482 log_err(c, "tls_read: %s", tls_error(c->ctx));
483 close_conn(fd, ev, c);
484 return;
486 case TLS_WANT_POLLIN:
487 reschedule_read(fd, c, &handle_open_conn);
488 return;
490 case TLS_WANT_POLLOUT:
491 reschedule_write(fd, c, &handle_open_conn);
492 return;
495 if (!trim_req_iri(c->req, &parse_err)
496 || !parse_iri(c->req, &c->iri, &parse_err)
497 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
498 log_info(c, "iri parse error: %s", parse_err);
499 start_reply(c, BAD_REQUEST, "invalid request");
500 return;
503 if (c->iri.port_no != conf.port
504 || strcmp(c->iri.schema, "gemini")
505 || strcmp(decoded, c->domain)) {
506 start_reply(c, PROXY_REFUSED, "won't proxy request");
507 return;
510 if (apply_block_return(c))
511 return;
513 if (c->host->entrypoint != NULL) {
514 start_cgi(c->host->entrypoint, c->iri.path, c);
515 return;
518 open_file(c);
521 static void
522 start_reply(struct client *c, int code, const char *meta)
524 c->code = code;
525 c->meta = meta;
526 handle_start_reply(c->fd, 0, c);
529 static void
530 handle_start_reply(int fd, short ev, void *d)
532 struct client *c = d;
533 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
534 const char *lang;
535 size_t len;
537 lang = vhost_lang(c->host, c->iri.path);
539 snprintf(buf, sizeof(buf), "%d ", c->code);
540 strlcat(buf, c->meta, sizeof(buf));
541 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
542 strlcat(buf, "; lang=", sizeof(buf));
543 strlcat(buf, lang, sizeof(buf));
546 len = strlcat(buf, "\r\n", sizeof(buf));
547 assert(len < sizeof(buf));
549 switch (tls_write(c->ctx, buf, len)) {
550 case -1:
551 close_conn(fd, ev, c);
552 return;
553 case TLS_WANT_POLLIN:
554 reschedule_read(fd, c, &handle_start_reply);
555 return;
556 case TLS_WANT_POLLOUT:
557 reschedule_write(fd, c, &handle_start_reply);
558 return;
561 log_request(c, buf, sizeof(buf));
563 if (c->code != SUCCESS)
564 close_conn(fd, ev, c);
565 else
566 c->next(fd, ev, c);
569 static void
570 start_cgi(const char *spath, const char *relpath, struct client *c)
572 char addr[NI_MAXHOST];
573 int e;
575 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
576 addr, sizeof(addr),
577 NULL, 0,
578 NI_NUMERICHOST);
579 if (e != 0)
580 goto err;
582 if (!send_iri(exfd, &c->iri)
583 || !send_string(exfd, spath)
584 || !send_string(exfd, relpath)
585 || !send_string(exfd, addr)
586 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
587 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
588 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
589 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
590 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
591 || !send_vhost(exfd, c->host))
592 goto err;
594 close(c->pfd);
595 if ((c->pfd = recv_fd(exfd)) == -1) {
596 start_reply(c, TEMP_FAILURE, "internal server error");
597 return;
600 reschedule_read(c->pfd, c, &handle_cgi_reply);
601 return;
603 err:
604 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
605 fatal("cannot talk to the executor process");
608 static void
609 send_file(int fd, short ev, void *d)
611 struct client *c = d;
612 ssize_t ret, len;
614 len = (c->buf + c->len) - c->i;
616 while (len > 0) {
617 switch (ret = tls_write(c->ctx, c->i, len)) {
618 case -1:
619 log_err(c, "tls_write: %s", tls_error(c->ctx));
620 close_conn(fd, ev, c);
621 return;
623 case TLS_WANT_POLLIN:
624 reschedule_read(fd, c, &send_file);
625 return;
627 case TLS_WANT_POLLOUT:
628 reschedule_write(fd, c, &send_file);
629 return;
631 default:
632 c->i += ret;
633 len -= ret;
634 break;
638 close_conn(fd, ev, c);
641 static void
642 open_dir(struct client *c)
644 size_t len;
645 int dirfd;
646 char *before_file;
648 len = strlen(c->iri.path);
649 if (len > 0 && !ends_with(c->iri.path, "/")) {
650 redirect_canonical_dir(c);
651 return;
654 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
655 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
656 if (!ends_with(c->sbuf, "/"))
657 strlcat(c->sbuf, "/", sizeof(c->sbuf));
658 before_file = strchr(c->sbuf, '\0');
659 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
660 sizeof(c->sbuf));
661 if (len >= sizeof(c->sbuf)) {
662 start_reply(c, TEMP_FAILURE, "internal server error");
663 return;
666 c->iri.path = c->sbuf;
668 /* close later unless we have to generate the dir listing */
669 dirfd = c->pfd;
670 c->pfd = -1;
672 switch (check_path(c, c->iri.path, &c->pfd)) {
673 case FILE_EXECUTABLE:
674 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
675 start_cgi(c->iri.path, "", c);
676 break;
679 /* fallthrough */
681 case FILE_EXISTS:
682 load_file(c);
683 break;
685 case FILE_DIRECTORY:
686 start_reply(c, TEMP_REDIRECT, c->sbuf);
687 break;
689 case FILE_MISSING:
690 *before_file = '\0';
692 if (!vhost_auto_index(c->host, c->iri.path)) {
693 start_reply(c, NOT_FOUND, "not found");
694 break;
697 c->pfd = dirfd;
698 c->next = enter_handle_dirlist;
700 if ((c->dir = fdopendir(c->pfd)) == NULL) {
701 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
702 c->pfd, c->host->domain, c->iri.path, strerror(errno));
703 start_reply(c, TEMP_FAILURE, "internal server error");
704 return;
706 c->off = 0;
708 start_reply(c, SUCCESS, "text/gemini");
709 return;
711 default:
712 /* unreachable */
713 abort();
716 close(dirfd);
719 static void
720 redirect_canonical_dir(struct client *c)
722 size_t len;
724 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
725 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
726 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
728 if (len >= sizeof(c->sbuf)) {
729 start_reply(c, TEMP_FAILURE, "internal server error");
730 return;
733 start_reply(c, TEMP_REDIRECT, c->sbuf);
736 static void
737 enter_handle_dirlist(int fd, short ev, void *d)
739 struct client *c = d;
740 char b[PATH_MAX];
741 size_t l;
743 strlcpy(b, c->iri.path, sizeof(b));
744 l = snprintf(c->sbuf, sizeof(c->sbuf),
745 "# Index of %s\n\n", b);
746 if (l >= sizeof(c->sbuf)) {
747 /* this is impossible, given that we have enough space
748 * in c->sbuf to hold the ancilliary string plus the
749 * full path; but it wouldn't read nice without some
750 * error checking, and I'd like to avoid a strlen. */
751 close_conn(fd, ev, c);
752 return;
755 c->len = l;
756 handle_dirlist(fd, ev, c);
759 static void
760 handle_dirlist(int fd, short ev, void *d)
762 struct client *c = d;
763 ssize_t r;
765 while (c->len > 0) {
766 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
767 case -1:
768 close_conn(fd, ev, c);
769 return;
770 case TLS_WANT_POLLOUT:
771 reschedule_read(fd, c, &handle_dirlist);
772 return;
773 case TLS_WANT_POLLIN:
774 reschedule_write(fd, c, &handle_dirlist);
775 return;
776 default:
777 c->off += r;
778 c->len -= r;
782 send_directory_listing(fd, ev, c);
785 static int
786 read_next_dir_entry(struct client *c)
788 struct dirent *d;
790 do {
791 errno = 0;
792 if ((d = readdir(c->dir)) == NULL) {
793 if (errno != 0)
794 log_err(c, "readdir: %s", strerror(errno));
795 return 0;
797 } while (!strcmp(d->d_name, "."));
799 /* XXX: url escape */
800 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
801 d->d_name, d->d_name);
802 c->len = strlen(c->sbuf);
803 c->off = 0;
805 return 1;
808 static void
809 send_directory_listing(int fd, short ev, void *d)
811 struct client *c = d;
812 ssize_t r;
814 while (1) {
815 if (c->len == 0) {
816 if (!read_next_dir_entry(c))
817 goto end;
820 while (c->len > 0) {
821 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
822 case -1:
823 goto end;
825 case TLS_WANT_POLLOUT:
826 reschedule_read(fd, c, &send_directory_listing);
827 return;
829 case TLS_WANT_POLLIN:
830 reschedule_write(fd, c, &send_directory_listing);
831 return;
833 default:
834 c->off += r;
835 c->len -= r;
836 break;
841 end:
842 close_conn(fd, ev, d);
845 /* accumulate the meta line from the cgi script. */
846 static void
847 handle_cgi_reply(int fd, short ev, void *d)
849 struct client *c = d;
850 void *buf, *e;
851 size_t len;
852 ssize_t r;
855 buf = c->sbuf + c->len;
856 len = sizeof(c->sbuf) - c->len;
858 r = read(c->pfd, buf, len);
859 if (r == 0 || r == -1) {
860 start_reply(c, CGI_ERROR, "CGI error");
861 return;
864 c->len += r;
866 /* TODO: error if the CGI script don't reply correctly */
867 e = strchr(c->sbuf, '\n');
868 if (e != NULL || c->len == sizeof(c->sbuf)) {
869 log_request(c, c->sbuf, c->len);
871 c->off = 0;
872 handle_cgi(fd, ev, c);
873 return;
876 reschedule_read(fd, c, &handle_cgi_reply);
879 static void
880 handle_cgi(int fd, short ev, void *d)
882 struct client *c = d;
883 ssize_t r;
885 while (1) {
886 if (c->len == 0) {
887 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
888 case 0:
889 goto end;
890 case -1:
891 if (errno == EAGAIN || errno == EWOULDBLOCK) {
892 reschedule_read(c->pfd, c, &handle_cgi);
893 return;
895 goto end;
896 default:
897 c->len = r;
898 c->off = 0;
902 while (c->len > 0) {
903 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
904 case -1:
905 goto end;
907 case TLS_WANT_POLLOUT:
908 reschedule_read(c->fd, c, &handle_cgi);
909 return;
911 case TLS_WANT_POLLIN:
912 reschedule_write(c->fd, c, &handle_cgi);
913 return;
915 default:
916 c->off += r;
917 c->len -= r;
918 break;
923 end:
924 close_conn(c->fd, ev, d);
927 static void
928 close_conn(int fd, short ev, void *d)
930 struct client *c = d;
932 switch (tls_close(c->ctx)) {
933 case TLS_WANT_POLLIN:
934 reschedule_read(fd, c, &close_conn);
935 return;
936 case TLS_WANT_POLLOUT:
937 reschedule_read(fd, c, &close_conn);
938 return;
941 connected_clients--;
943 tls_free(c->ctx);
944 c->ctx = NULL;
946 if (c->buf != MAP_FAILED)
947 munmap(c->buf, c->len);
949 if (c->pfd != -1)
950 close(c->pfd);
952 if (c->dir != NULL)
953 closedir(c->dir);
955 close(c->fd);
956 c->fd = -1;
959 static void
960 do_accept(int sock, short et, void *d)
962 struct client *c;
963 struct server *s = d;
964 struct sockaddr_storage addr;
965 struct sockaddr *saddr;
966 socklen_t len;
967 int i, fd;
969 (void)et;
972 saddr = (struct sockaddr*)&addr;
973 len = sizeof(addr);
974 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
975 if (errno == EWOULDBLOCK || errno == EAGAIN)
976 return;
977 fatal("accept: %s", strerror(errno));
980 for (i = 0; i < MAX_USERS; ++i) {
981 c = &s->clients[i];
982 if (c->fd == -1) {
983 memset(c, 0, sizeof(*c));
984 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
985 break; /* goodbye fd! */
987 c->fd = fd;
988 c->pfd = -1;
989 c->buf = MAP_FAILED;
990 c->dir = NULL;
991 c->addr = addr;
993 reschedule_read(fd, c, &handle_handshake);
994 connected_clients++;
995 return;
999 close(fd);
1002 static void
1003 handle_sighup(int fd, short ev, void *d)
1005 struct server_events *events = d;
1007 (void)fd;
1008 (void)ev;
1010 event_del(&events->e4);
1011 if (events->has_ipv6)
1012 event_del(&events->e6);
1013 signal_del(&events->sighup);
1016 static void
1017 handle_siginfo(int fd, short ev, void *d)
1019 (void)fd;
1020 (void)ev;
1021 (void)d;
1023 log_info(NULL, "%d connected clients", connected_clients);
1026 void
1027 loop(struct tls *ctx, int sock4, int sock6)
1029 struct server_events events;
1030 struct server server;
1031 struct event info;
1032 size_t i;
1034 event_init();
1036 memset(&events, 0, sizeof(events));
1037 memset(&server, 0, sizeof(server));
1038 for (i = 0; i < MAX_USERS; ++i)
1039 server.clients[i].fd = -1;
1041 event_set(&events.e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1042 event_add(&events.e4, NULL);
1044 if (sock6 != -1) {
1045 events.has_ipv6 = 1;
1046 event_set(&events.e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1047 event_add(&events.e6, NULL);
1050 signal_set(&events.sighup, SIGHUP, &handle_sighup, &events);
1051 signal_add(&events.sighup, NULL);
1053 #ifdef SIGINFO
1054 signal_set(&info, SIGINFO, &handle_siginfo, NULL);
1055 signal_add(&info, NULL);
1056 #endif
1057 signal_set(&info, SIGUSR2, &handle_siginfo, NULL);
1058 signal_add(&info, NULL);
1060 server.ctx = ctx;
1062 event_dispatch();