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 char *strip_path(char*, int);
55 static void fmt_sbuf(const char*, struct client*, const char*);
56 static int apply_block_return(struct client*);
57 static void handle_open_conn(int, short, void*);
58 static void start_reply(struct client*, int, const char*);
59 static void handle_start_reply(int, short, void*);
60 static void start_cgi(const char*, const char*, struct client*);
61 static void send_file(int, short, void*);
62 static void open_dir(struct client*);
63 static void redirect_canonical_dir(struct client*);
64 static void enter_handle_dirlist(int, short, void*);
65 static void handle_dirlist(int, short, void*);
66 static int read_next_dir_entry(struct client*);
67 static void send_directory_listing(int, short, void*);
68 static void handle_cgi_reply(int, short, void*);
69 static void handle_cgi(int, short, void*);
70 static void close_conn(int, short, void*);
71 static void do_accept(int, short, void*);
72 static void handle_sighup(int, short, void*);
74 static inline void
75 reschedule_read(int fd, struct client *c, statefn fn)
76 {
77 event_once(fd, EV_READ, fn, c, NULL);
78 }
80 void
81 reschedule_write(int fd, struct client *c, statefn fn)
82 {
83 event_once(fd, EV_WRITE, fn, c, NULL);
84 }
86 const char *
87 vhost_lang(struct vhost *v, const char *path)
88 {
89 struct location *loc;
91 if (v == NULL || path == NULL)
92 return NULL;
94 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
95 if (loc->lang != NULL) {
96 if (!fnmatch(loc->match, path, 0))
97 return loc->lang;
98 }
99 }
101 return v->locations[0].lang;
104 const char *
105 vhost_default_mime(struct vhost *v, const char *path)
107 struct location *loc;
108 const char *default_mime = "application/octet-stream";
110 if (v == NULL || path == NULL)
111 return default_mime;
113 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
114 if (loc->default_mime != NULL) {
115 if (!fnmatch(loc->match, path, 0))
116 return loc->default_mime;
120 if (v->locations[0].default_mime != NULL)
121 return v->locations[0].default_mime;
122 return default_mime;
125 const char *
126 vhost_index(struct vhost *v, const char *path)
128 struct location *loc;
129 const char *index = "index.gmi";
131 if (v == NULL || path == NULL)
132 return index;
134 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
135 if (loc->index != NULL) {
136 if (!fnmatch(loc->match, path, 0))
137 return loc->index;
141 if (v->locations[0].index != NULL)
142 return v->locations[0].index;
143 return index;
146 int
147 vhost_auto_index(struct vhost *v, const char *path)
149 struct location *loc;
151 if (v == NULL || path == NULL)
152 return 0;
154 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
155 if (loc->auto_index != 0) {
156 if (!fnmatch(loc->match, path, 0))
157 return loc->auto_index == 1;
161 return v->locations[0].auto_index == 1;
164 int
165 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
167 struct location *loc;
169 if (v == NULL || path == NULL)
170 return 0;
172 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
173 if (loc->block_code != 0) {
174 if (!fnmatch(loc->match, path, 0)) {
175 *code = loc->block_code;
176 *fmt = loc->block_fmt;
177 return 1;
182 *code = v->locations[0].block_code;
183 *fmt = v->locations[0].block_fmt;
184 return v->locations[0].block_code != 0;
187 int
188 vhost_strip(struct vhost *v, const char *path)
190 struct location *loc;
192 if (v == NULL || path == NULL)
193 return 0;
195 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
196 if (loc->strip != 0) {
197 if (!fnmatch(loc->match, path, 0))
198 return loc->strip;
202 return v->locations[0].strip;
205 static int
206 check_path(struct client *c, const char *path, int *fd)
208 struct stat sb;
209 const char *p;
210 int flags;
212 assert(path != NULL);
214 if (*path == '\0')
215 p = ".";
216 else if (*path == '/')
217 /* in send_dir we add an initial / (to be
218 * redirect-friendly), but here we want to skip it */
219 p = path+1;
220 else
221 p = path;
223 flags = O_RDONLY | O_NOFOLLOW;
225 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
226 return FILE_MISSING;
228 if (fstat(*fd, &sb) == -1) {
229 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
230 return FILE_MISSING;
233 if (S_ISDIR(sb.st_mode))
234 return FILE_DIRECTORY;
236 if (sb.st_mode & S_IXUSR)
237 return FILE_EXECUTABLE;
239 return FILE_EXISTS;
242 static void
243 open_file(struct client *c)
245 switch (check_path(c, c->iri.path, &c->pfd)) {
246 case FILE_EXECUTABLE:
247 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
248 start_cgi(c->iri.path, "", c);
249 return;
252 /* fallthrough */
254 case FILE_EXISTS:
255 load_file(c);
256 return;
258 case FILE_DIRECTORY:
259 open_dir(c);
260 return;
262 case FILE_MISSING:
263 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
264 check_for_cgi(c);
265 return;
267 start_reply(c, NOT_FOUND, "not found");
268 return;
270 default:
271 /* unreachable */
272 abort();
276 static void
277 load_file(struct client *c)
279 if ((c->len = filesize(c->pfd)) == -1) {
280 log_err(c, "failed to get file size for %s: %s",
281 c->iri.path, strerror(errno));
282 start_reply(c, TEMP_FAILURE, "internal server error");
283 return;
286 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
287 c->pfd, 0)) == MAP_FAILED) {
288 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
289 start_reply(c, TEMP_FAILURE, "internal server error");
290 return;
292 c->i = c->buf;
293 c->next = send_file;
294 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
297 /*
298 * the inverse of this algorithm, i.e. starting from the start of the
299 * path + strlen(cgi), and checking if each component, should be
300 * faster. But it's tedious to write. This does the opposite: starts
301 * from the end and strip one component at a time, until either an
302 * executable is found or we emptied the path.
303 */
304 static void
305 check_for_cgi(struct client *c)
307 char path[PATH_MAX];
308 char *end;
310 strlcpy(path, c->iri.path, sizeof(path));
311 end = strchr(path, '\0');
313 while (end > path) {
314 /* go up one level. UNIX paths are simple and POSIX
315 * dirname, with its ambiguities on if the given path
316 * is changed or not, gives me headaches. */
317 while (*end != '/')
318 end--;
319 *end = '\0';
321 switch (check_path(c, path, &c->pfd)) {
322 case FILE_EXECUTABLE:
323 start_cgi(path, end+1, c);
324 return;
325 case FILE_MISSING:
326 break;
327 default:
328 goto err;
331 *end = '/';
332 end--;
335 err:
336 start_reply(c, NOT_FOUND, "not found");
337 return;
340 void
341 mark_nonblock(int fd)
343 int flags;
345 if ((flags = fcntl(fd, F_GETFL)) == -1)
346 fatal("fcntl(F_GETFL): %s", strerror(errno));
347 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
348 fatal("fcntl(F_SETFL): %s", strerror(errno));
351 static void
352 handle_handshake(int fd, short ev, void *d)
354 struct client *c = d;
355 struct vhost *h;
356 const char *servname;
357 const char *parse_err = "unknown error";
359 switch (tls_handshake(c->ctx)) {
360 case 0: /* success */
361 case -1: /* already handshaked */
362 break;
363 case TLS_WANT_POLLIN:
364 reschedule_read(fd, c, &handle_handshake);
365 return;
366 case TLS_WANT_POLLOUT:
367 reschedule_write(fd, c, &handle_handshake);
368 return;
369 default:
370 /* unreachable */
371 abort();
374 servname = tls_conn_servername(c->ctx);
375 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
376 log_info(c, "puny_decode: %s", parse_err);
377 goto err;
380 for (h = hosts; h->domain != NULL; ++h) {
381 if (!fnmatch(h->domain, c->domain, 0))
382 break;
385 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
386 servname != NULL ? servname : "(null)",
387 c->domain,
388 h->domain != NULL ? h->domain : "(null)");
390 if (h->domain != NULL) {
391 c->host = h;
392 handle_open_conn(fd, ev, c);
393 return;
396 err:
397 if (servname != NULL)
398 strncpy(c->req, servname, sizeof(c->req));
399 else
400 strncpy(c->req, "null", sizeof(c->req));
402 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
405 static char *
406 strip_path(char *path, int strip)
408 char *t;
410 while (strip > 0) {
411 if ((t = strchr(path, '/')) == NULL) {
412 path = strchr(path, '\0');
413 break;
415 path = t;
416 strip--;
419 return path;
422 static void
423 fmt_sbuf(const char *fmt, struct client *c, const char *path)
425 size_t i;
426 char buf[32];
428 memset(buf, 0, sizeof(buf));
429 for (i = 0; *fmt; ++fmt) {
430 if (i == sizeof(buf)-1 || *fmt == '%') {
431 strlcat(c->sbuf, buf, sizeof(c->sbuf));
432 memset(buf, 0, sizeof(buf));
433 i = 0;
436 if (*fmt != '%') {
437 buf[i++] = *fmt;
438 continue;
441 switch (*++fmt) {
442 case '%':
443 strlcat(c->sbuf, "%", sizeof(c->sbuf));
444 break;
445 case 'p':
446 strlcat(c->sbuf, path, sizeof(c->sbuf));
447 break;
448 case 'q':
449 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
450 break;
451 case 'P':
452 snprintf(buf, sizeof(buf), "%d", conf.port);
453 strlcat(c->sbuf, buf, sizeof(c->sbuf));
454 memset(buf, 0, sizeof(buf));
455 break;
456 case 'N':
457 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
458 break;
459 default:
460 fatal("%s: unknown fmt specifier %c",
461 __func__, *fmt);
465 if (i != 0)
466 strlcat(c->sbuf, buf, sizeof(c->sbuf));
469 /* 1 if a matching `block return' (and apply it), 0 otherwise */
470 static int
471 apply_block_return(struct client *c)
473 const char *fmt, *path;
474 int code;
476 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
477 return 0;
479 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
480 fmt_sbuf(fmt, c, path);
482 start_reply(c, code, c->sbuf);
483 return 1;
486 static void
487 handle_open_conn(int fd, short ev, void *d)
489 struct client *c = d;
490 const char *parse_err = "invalid request";
491 char decoded[DOMAIN_NAME_LEN];
493 bzero(c->req, sizeof(c->req));
494 bzero(&c->iri, sizeof(c->iri));
496 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
497 case -1:
498 log_err(c, "tls_read: %s", tls_error(c->ctx));
499 close_conn(fd, ev, c);
500 return;
502 case TLS_WANT_POLLIN:
503 reschedule_read(fd, c, &handle_open_conn);
504 return;
506 case TLS_WANT_POLLOUT:
507 reschedule_write(fd, c, &handle_open_conn);
508 return;
511 if (!trim_req_iri(c->req, &parse_err)
512 || !parse_iri(c->req, &c->iri, &parse_err)
513 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
514 log_info(c, "iri parse error: %s", parse_err);
515 start_reply(c, BAD_REQUEST, "invalid request");
516 return;
519 if (c->iri.port_no != conf.port
520 || strcmp(c->iri.schema, "gemini")
521 || strcmp(decoded, c->domain)) {
522 start_reply(c, PROXY_REFUSED, "won't proxy request");
523 return;
526 if (apply_block_return(c))
527 return;
529 if (c->host->entrypoint != NULL) {
530 start_cgi(c->host->entrypoint, c->iri.path, c);
531 return;
534 open_file(c);
537 static void
538 start_reply(struct client *c, int code, const char *meta)
540 c->code = code;
541 c->meta = meta;
542 handle_start_reply(c->fd, 0, c);
545 static void
546 handle_start_reply(int fd, short ev, void *d)
548 struct client *c = d;
549 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
550 const char *lang;
551 size_t len;
553 lang = vhost_lang(c->host, c->iri.path);
555 snprintf(buf, sizeof(buf), "%d ", c->code);
556 strlcat(buf, c->meta, sizeof(buf));
557 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
558 strlcat(buf, "; lang=", sizeof(buf));
559 strlcat(buf, lang, sizeof(buf));
562 len = strlcat(buf, "\r\n", sizeof(buf));
563 assert(len < sizeof(buf));
565 switch (tls_write(c->ctx, buf, len)) {
566 case -1:
567 close_conn(fd, ev, c);
568 return;
569 case TLS_WANT_POLLIN:
570 reschedule_read(fd, c, &handle_start_reply);
571 return;
572 case TLS_WANT_POLLOUT:
573 reschedule_write(fd, c, &handle_start_reply);
574 return;
577 log_request(c, buf, sizeof(buf));
579 if (c->code != SUCCESS)
580 close_conn(fd, ev, c);
581 else
582 c->next(fd, ev, c);
585 static void
586 start_cgi(const char *spath, const char *relpath, struct client *c)
588 char addr[NI_MAXHOST];
589 int e;
591 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
592 addr, sizeof(addr),
593 NULL, 0,
594 NI_NUMERICHOST);
595 if (e != 0)
596 goto err;
598 if (!send_iri(exfd, &c->iri)
599 || !send_string(exfd, spath)
600 || !send_string(exfd, relpath)
601 || !send_string(exfd, addr)
602 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
603 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
604 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
605 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
606 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
607 || !send_vhost(exfd, c->host))
608 goto err;
610 close(c->pfd);
611 if ((c->pfd = recv_fd(exfd)) == -1) {
612 start_reply(c, TEMP_FAILURE, "internal server error");
613 return;
616 reschedule_read(c->pfd, c, &handle_cgi_reply);
617 return;
619 err:
620 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
621 fatal("cannot talk to the executor process");
624 static void
625 send_file(int fd, short ev, void *d)
627 struct client *c = d;
628 ssize_t ret, len;
630 len = (c->buf + c->len) - c->i;
632 while (len > 0) {
633 switch (ret = tls_write(c->ctx, c->i, len)) {
634 case -1:
635 log_err(c, "tls_write: %s", tls_error(c->ctx));
636 close_conn(fd, ev, c);
637 return;
639 case TLS_WANT_POLLIN:
640 reschedule_read(fd, c, &send_file);
641 return;
643 case TLS_WANT_POLLOUT:
644 reschedule_write(fd, c, &send_file);
645 return;
647 default:
648 c->i += ret;
649 len -= ret;
650 break;
654 close_conn(fd, ev, c);
657 static void
658 open_dir(struct client *c)
660 size_t len;
661 int dirfd;
662 char *before_file;
664 len = strlen(c->iri.path);
665 if (len > 0 && !ends_with(c->iri.path, "/")) {
666 redirect_canonical_dir(c);
667 return;
670 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
671 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
672 if (!ends_with(c->sbuf, "/"))
673 strlcat(c->sbuf, "/", sizeof(c->sbuf));
674 before_file = strchr(c->sbuf, '\0');
675 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
676 sizeof(c->sbuf));
677 if (len >= sizeof(c->sbuf)) {
678 start_reply(c, TEMP_FAILURE, "internal server error");
679 return;
682 c->iri.path = c->sbuf;
684 /* close later unless we have to generate the dir listing */
685 dirfd = c->pfd;
686 c->pfd = -1;
688 switch (check_path(c, c->iri.path, &c->pfd)) {
689 case FILE_EXECUTABLE:
690 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
691 start_cgi(c->iri.path, "", c);
692 break;
695 /* fallthrough */
697 case FILE_EXISTS:
698 load_file(c);
699 break;
701 case FILE_DIRECTORY:
702 start_reply(c, TEMP_REDIRECT, c->sbuf);
703 break;
705 case FILE_MISSING:
706 *before_file = '\0';
708 if (!vhost_auto_index(c->host, c->iri.path)) {
709 start_reply(c, NOT_FOUND, "not found");
710 break;
713 c->pfd = dirfd;
714 c->next = enter_handle_dirlist;
716 if ((c->dir = fdopendir(c->pfd)) == NULL) {
717 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
718 c->pfd, c->host->domain, c->iri.path, strerror(errno));
719 start_reply(c, TEMP_FAILURE, "internal server error");
720 return;
722 c->off = 0;
724 start_reply(c, SUCCESS, "text/gemini");
725 return;
727 default:
728 /* unreachable */
729 abort();
732 close(dirfd);
735 static void
736 redirect_canonical_dir(struct client *c)
738 size_t len;
740 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
741 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
742 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
744 if (len >= sizeof(c->sbuf)) {
745 start_reply(c, TEMP_FAILURE, "internal server error");
746 return;
749 start_reply(c, TEMP_REDIRECT, c->sbuf);
752 static void
753 enter_handle_dirlist(int fd, short ev, void *d)
755 struct client *c = d;
756 char b[PATH_MAX];
757 size_t l;
759 strlcpy(b, c->iri.path, sizeof(b));
760 l = snprintf(c->sbuf, sizeof(c->sbuf),
761 "# Index of %s\n\n", b);
762 if (l >= sizeof(c->sbuf)) {
763 /* this is impossible, given that we have enough space
764 * in c->sbuf to hold the ancilliary string plus the
765 * full path; but it wouldn't read nice without some
766 * error checking, and I'd like to avoid a strlen. */
767 close_conn(fd, ev, c);
768 return;
771 c->len = l;
772 handle_dirlist(fd, ev, c);
775 static void
776 handle_dirlist(int fd, short ev, void *d)
778 struct client *c = d;
779 ssize_t r;
781 while (c->len > 0) {
782 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
783 case -1:
784 close_conn(fd, ev, c);
785 return;
786 case TLS_WANT_POLLOUT:
787 reschedule_read(fd, c, &handle_dirlist);
788 return;
789 case TLS_WANT_POLLIN:
790 reschedule_write(fd, c, &handle_dirlist);
791 return;
792 default:
793 c->off += r;
794 c->len -= r;
798 send_directory_listing(fd, ev, c);
801 static int
802 read_next_dir_entry(struct client *c)
804 struct dirent *d;
806 do {
807 errno = 0;
808 if ((d = readdir(c->dir)) == NULL) {
809 if (errno != 0)
810 log_err(c, "readdir: %s", strerror(errno));
811 return 0;
813 } while (!strcmp(d->d_name, "."));
815 /* XXX: url escape */
816 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
817 d->d_name, d->d_name);
818 c->len = strlen(c->sbuf);
819 c->off = 0;
821 return 1;
824 static void
825 send_directory_listing(int fd, short ev, void *d)
827 struct client *c = d;
828 ssize_t r;
830 while (1) {
831 if (c->len == 0) {
832 if (!read_next_dir_entry(c))
833 goto end;
836 while (c->len > 0) {
837 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
838 case -1:
839 goto end;
841 case TLS_WANT_POLLOUT:
842 reschedule_read(fd, c, &send_directory_listing);
843 return;
845 case TLS_WANT_POLLIN:
846 reschedule_write(fd, c, &send_directory_listing);
847 return;
849 default:
850 c->off += r;
851 c->len -= r;
852 break;
857 end:
858 close_conn(fd, ev, d);
861 /* accumulate the meta line from the cgi script. */
862 static void
863 handle_cgi_reply(int fd, short ev, void *d)
865 struct client *c = d;
866 void *buf, *e;
867 size_t len;
868 ssize_t r;
871 buf = c->sbuf + c->len;
872 len = sizeof(c->sbuf) - c->len;
874 r = read(c->pfd, buf, len);
875 if (r == 0 || r == -1) {
876 start_reply(c, CGI_ERROR, "CGI error");
877 return;
880 c->len += r;
882 /* TODO: error if the CGI script don't reply correctly */
883 e = strchr(c->sbuf, '\n');
884 if (e != NULL || c->len == sizeof(c->sbuf)) {
885 log_request(c, c->sbuf, c->len);
887 c->off = 0;
888 handle_cgi(fd, ev, c);
889 return;
892 reschedule_read(fd, c, &handle_cgi_reply);
895 static void
896 handle_cgi(int fd, short ev, void *d)
898 struct client *c = d;
899 ssize_t r;
901 while (1) {
902 if (c->len == 0) {
903 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
904 case 0:
905 goto end;
906 case -1:
907 if (errno == EAGAIN || errno == EWOULDBLOCK) {
908 reschedule_read(c->pfd, c, &handle_cgi);
909 return;
911 goto end;
912 default:
913 c->len = r;
914 c->off = 0;
918 while (c->len > 0) {
919 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
920 case -1:
921 goto end;
923 case TLS_WANT_POLLOUT:
924 reschedule_read(c->fd, c, &handle_cgi);
925 return;
927 case TLS_WANT_POLLIN:
928 reschedule_write(c->fd, c, &handle_cgi);
929 return;
931 default:
932 c->off += r;
933 c->len -= r;
934 break;
939 end:
940 close_conn(c->fd, ev, d);
943 static void
944 close_conn(int fd, short ev, void *d)
946 struct client *c = d;
948 switch (tls_close(c->ctx)) {
949 case TLS_WANT_POLLIN:
950 reschedule_read(fd, c, &close_conn);
951 return;
952 case TLS_WANT_POLLOUT:
953 reschedule_read(fd, c, &close_conn);
954 return;
957 connected_clients--;
959 tls_free(c->ctx);
960 c->ctx = NULL;
962 if (c->buf != MAP_FAILED)
963 munmap(c->buf, c->len);
965 if (c->pfd != -1)
966 close(c->pfd);
968 if (c->dir != NULL)
969 closedir(c->dir);
971 close(c->fd);
972 c->fd = -1;
975 static void
976 do_accept(int sock, short et, void *d)
978 struct client *c;
979 struct server *s = d;
980 struct sockaddr_storage addr;
981 struct sockaddr *saddr;
982 socklen_t len;
983 int i, fd;
985 (void)et;
988 saddr = (struct sockaddr*)&addr;
989 len = sizeof(addr);
990 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
991 if (errno == EWOULDBLOCK || errno == EAGAIN)
992 return;
993 fatal("accept: %s", strerror(errno));
996 for (i = 0; i < MAX_USERS; ++i) {
997 c = &s->clients[i];
998 if (c->fd == -1) {
999 memset(c, 0, sizeof(*c));
1000 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1001 break; /* goodbye fd! */
1003 c->fd = fd;
1004 c->pfd = -1;
1005 c->buf = MAP_FAILED;
1006 c->dir = NULL;
1007 c->addr = addr;
1009 reschedule_read(fd, c, &handle_handshake);
1010 connected_clients++;
1011 return;
1015 close(fd);
1018 static void
1019 handle_sighup(int fd, short ev, void *d)
1021 struct server_events *events = d;
1023 (void)fd;
1024 (void)ev;
1026 event_del(&events->e4);
1027 if (events->has_ipv6)
1028 event_del(&events->e6);
1029 signal_del(&events->sighup);
1032 static void
1033 handle_siginfo(int fd, short ev, void *d)
1035 (void)fd;
1036 (void)ev;
1037 (void)d;
1039 log_info(NULL, "%d connected clients", connected_clients);
1042 void
1043 loop(struct tls *ctx, int sock4, int sock6)
1045 struct server_events events;
1046 struct server server;
1047 struct event info;
1048 size_t i;
1050 event_init();
1052 memset(&events, 0, sizeof(events));
1053 memset(&server, 0, sizeof(server));
1054 for (i = 0; i < MAX_USERS; ++i)
1055 server.clients[i].fd = -1;
1057 event_set(&events.e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1058 event_add(&events.e4, NULL);
1060 if (sock6 != -1) {
1061 events.has_ipv6 = 1;
1062 event_set(&events.e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1063 event_add(&events.e6, NULL);
1066 signal_set(&events.sighup, SIGHUP, &handle_sighup, &events);
1067 signal_add(&events.sighup, NULL);
1069 #ifdef SIGINFO
1070 signal_set(&info, SIGINFO, &handle_siginfo, NULL);
1071 signal_add(&info, NULL);
1072 #endif
1073 signal_set(&info, SIGUSR2, &handle_siginfo, NULL);
1074 signal_add(&info, NULL);
1076 server.ctx = ctx;
1078 sandbox();
1079 event_dispatch();
1080 _exit(0);