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 int matches(const char*, const char*);
48 static inline void reschedule_read(int, struct client*, statefn);
49 static inline void reschedule_write(int, struct client*, statefn);
51 static int check_path(struct client*, const char*, int*);
52 static void open_file(struct client*);
53 static void load_file(struct client*);
54 static void check_for_cgi(struct client*);
55 static void handle_handshake(int, short, void*);
56 static char *strip_path(char*, int);
57 static void fmt_sbuf(const char*, struct client*, const char*);
58 static int apply_block_return(struct client*);
59 static int apply_require_ca(struct client*);
60 static void handle_open_conn(int, short, void*);
61 static void start_reply(struct client*, int, const char*);
62 static void handle_start_reply(int, short, void*);
63 static void start_cgi(const char*, const char*, struct client*);
64 static void send_file(int, short, void*);
65 static void open_dir(struct client*);
66 static void redirect_canonical_dir(struct client*);
67 static void enter_handle_dirlist(int, short, void*);
68 static void handle_dirlist(int, short, void*);
69 static int read_next_dir_entry(struct client*);
70 static void send_directory_listing(int, short, void*);
71 static void handle_cgi_reply(int, short, void*);
72 static void handle_cgi(int, short, void*);
73 static void close_conn(int, short, void*);
74 static void do_accept(int, short, void*);
75 static void handle_sighup(int, short, void*);
77 static inline int
78 matches(const char *pattern, const char *path)
79 {
80 if (*path == '/')
81 path++;
82 return !fnmatch(pattern, path, 0);
83 }
85 static inline void
86 reschedule_read(int fd, struct client *c, statefn fn)
87 {
88 event_once(fd, EV_READ, fn, c, NULL);
89 }
91 void
92 reschedule_write(int fd, struct client *c, statefn fn)
93 {
94 event_once(fd, EV_WRITE, fn, c, NULL);
95 }
97 const char *
98 vhost_lang(struct vhost *v, const char *path)
99 {
100 struct location *loc;
102 if (v == NULL || path == NULL)
103 return NULL;
105 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
106 if (loc->lang != NULL) {
107 if (matches(loc->match, path))
108 return loc->lang;
112 return v->locations[0].lang;
115 const char *
116 vhost_default_mime(struct vhost *v, const char *path)
118 struct location *loc;
119 const char *default_mime = "application/octet-stream";
121 if (v == NULL || path == NULL)
122 return default_mime;
124 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
125 if (loc->default_mime != NULL) {
126 if (matches(loc->match, path))
127 return loc->default_mime;
131 if (v->locations[0].default_mime != NULL)
132 return v->locations[0].default_mime;
133 return default_mime;
136 const char *
137 vhost_index(struct vhost *v, const char *path)
139 struct location *loc;
140 const char *index = "index.gmi";
142 if (v == NULL || path == NULL)
143 return index;
145 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
146 if (loc->index != NULL) {
147 if (matches(loc->match, path))
148 return loc->index;
152 if (v->locations[0].index != NULL)
153 return v->locations[0].index;
154 return index;
157 int
158 vhost_auto_index(struct vhost *v, const char *path)
160 struct location *loc;
162 if (v == NULL || path == NULL)
163 return 0;
165 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
166 if (loc->auto_index != 0) {
167 if (matches(loc->match, path))
168 return loc->auto_index == 1;
172 return v->locations[0].auto_index == 1;
175 int
176 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
178 struct location *loc;
180 if (v == NULL || path == NULL)
181 return 0;
183 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
184 if (loc->block_code != 0) {
185 if (matches(loc->match, path)) {
186 *code = loc->block_code;
187 *fmt = loc->block_fmt;
188 return 1;
193 *code = v->locations[0].block_code;
194 *fmt = v->locations[0].block_fmt;
195 return v->locations[0].block_code != 0;
198 int
199 vhost_strip(struct vhost *v, const char *path)
201 struct location *loc;
203 if (v == NULL || path == NULL)
204 return 0;
206 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
207 if (loc->strip != 0) {
208 if (matches(loc->match, path))
209 return loc->strip;
213 return v->locations[0].strip;
216 X509_STORE *
217 vhost_require_ca(struct vhost *v, const char *path)
219 struct location *loc;
221 if (v == NULL || path == NULL)
222 return NULL;
224 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
225 if (loc->reqca != NULL) {
226 if (matches(loc->match, path))
227 return loc->reqca;
231 return v->locations[0].reqca;
234 static int
235 check_path(struct client *c, const char *path, int *fd)
237 struct stat sb;
238 const char *p;
239 int flags;
241 assert(path != NULL);
243 if (*path == '\0')
244 p = ".";
245 else if (*path == '/')
246 /* in send_dir we add an initial / (to be
247 * redirect-friendly), but here we want to skip it */
248 p = path+1;
249 else
250 p = path;
252 flags = O_RDONLY | O_NOFOLLOW;
254 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
255 return FILE_MISSING;
257 if (fstat(*fd, &sb) == -1) {
258 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
259 return FILE_MISSING;
262 if (S_ISDIR(sb.st_mode))
263 return FILE_DIRECTORY;
265 if (sb.st_mode & S_IXUSR)
266 return FILE_EXECUTABLE;
268 return FILE_EXISTS;
271 static void
272 open_file(struct client *c)
274 switch (check_path(c, c->iri.path, &c->pfd)) {
275 case FILE_EXECUTABLE:
276 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
277 start_cgi(c->iri.path, "", c);
278 return;
281 /* fallthrough */
283 case FILE_EXISTS:
284 load_file(c);
285 return;
287 case FILE_DIRECTORY:
288 open_dir(c);
289 return;
291 case FILE_MISSING:
292 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
293 check_for_cgi(c);
294 return;
296 start_reply(c, NOT_FOUND, "not found");
297 return;
299 default:
300 /* unreachable */
301 abort();
305 static void
306 load_file(struct client *c)
308 if ((c->len = filesize(c->pfd)) == -1) {
309 log_err(c, "failed to get file size for %s: %s",
310 c->iri.path, strerror(errno));
311 start_reply(c, TEMP_FAILURE, "internal server error");
312 return;
315 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
316 c->pfd, 0)) == MAP_FAILED) {
317 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
318 start_reply(c, TEMP_FAILURE, "internal server error");
319 return;
321 c->i = c->buf;
322 c->next = send_file;
323 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
326 /*
327 * the inverse of this algorithm, i.e. starting from the start of the
328 * path + strlen(cgi), and checking if each component, should be
329 * faster. But it's tedious to write. This does the opposite: starts
330 * from the end and strip one component at a time, until either an
331 * executable is found or we emptied the path.
332 */
333 static void
334 check_for_cgi(struct client *c)
336 char path[PATH_MAX];
337 char *end;
339 strlcpy(path, c->iri.path, sizeof(path));
340 end = strchr(path, '\0');
342 while (end > path) {
343 /* go up one level. UNIX paths are simple and POSIX
344 * dirname, with its ambiguities on if the given path
345 * is changed or not, gives me headaches. */
346 while (*end != '/')
347 end--;
348 *end = '\0';
350 switch (check_path(c, path, &c->pfd)) {
351 case FILE_EXECUTABLE:
352 start_cgi(path, end+1, c);
353 return;
354 case FILE_MISSING:
355 break;
356 default:
357 goto err;
360 *end = '/';
361 end--;
364 err:
365 start_reply(c, NOT_FOUND, "not found");
366 return;
369 void
370 mark_nonblock(int fd)
372 int flags;
374 if ((flags = fcntl(fd, F_GETFL)) == -1)
375 fatal("fcntl(F_GETFL): %s", strerror(errno));
376 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
377 fatal("fcntl(F_SETFL): %s", strerror(errno));
380 static void
381 handle_handshake(int fd, short ev, void *d)
383 struct client *c = d;
384 struct vhost *h;
385 const char *servname;
386 const char *parse_err = "unknown error";
388 switch (tls_handshake(c->ctx)) {
389 case 0: /* success */
390 case -1: /* already handshaked */
391 break;
392 case TLS_WANT_POLLIN:
393 reschedule_read(fd, c, &handle_handshake);
394 return;
395 case TLS_WANT_POLLOUT:
396 reschedule_write(fd, c, &handle_handshake);
397 return;
398 default:
399 /* unreachable */
400 abort();
403 servname = tls_conn_servername(c->ctx);
404 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
405 log_info(c, "puny_decode: %s", parse_err);
406 goto err;
409 for (h = hosts; h->domain != NULL; ++h) {
410 if (!fnmatch(h->domain, c->domain, 0))
411 break;
414 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
415 servname != NULL ? servname : "(null)",
416 c->domain,
417 h->domain != NULL ? h->domain : "(null)");
419 if (h->domain != NULL) {
420 c->host = h;
421 handle_open_conn(fd, ev, c);
422 return;
425 err:
426 if (servname != NULL)
427 strncpy(c->req, servname, sizeof(c->req));
428 else
429 strncpy(c->req, "null", sizeof(c->req));
431 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
434 static char *
435 strip_path(char *path, int strip)
437 char *t;
439 while (strip > 0) {
440 if ((t = strchr(path, '/')) == NULL) {
441 path = strchr(path, '\0');
442 break;
444 path = t;
445 strip--;
448 return path;
451 static void
452 fmt_sbuf(const char *fmt, struct client *c, const char *path)
454 size_t i;
455 char buf[32];
457 memset(buf, 0, sizeof(buf));
458 for (i = 0; *fmt; ++fmt) {
459 if (i == sizeof(buf)-1 || *fmt == '%') {
460 strlcat(c->sbuf, buf, sizeof(c->sbuf));
461 memset(buf, 0, sizeof(buf));
462 i = 0;
465 if (*fmt != '%') {
466 buf[i++] = *fmt;
467 continue;
470 switch (*++fmt) {
471 case '%':
472 strlcat(c->sbuf, "%", sizeof(c->sbuf));
473 break;
474 case 'p':
475 strlcat(c->sbuf, path, sizeof(c->sbuf));
476 break;
477 case 'q':
478 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
479 break;
480 case 'P':
481 snprintf(buf, sizeof(buf), "%d", conf.port);
482 strlcat(c->sbuf, buf, sizeof(c->sbuf));
483 memset(buf, 0, sizeof(buf));
484 break;
485 case 'N':
486 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
487 break;
488 default:
489 fatal("%s: unknown fmt specifier %c",
490 __func__, *fmt);
494 if (i != 0)
495 strlcat(c->sbuf, buf, sizeof(c->sbuf));
498 /* 1 if a matching `block return' (and apply it), 0 otherwise */
499 static int
500 apply_block_return(struct client *c)
502 const char *fmt, *path;
503 int code;
505 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
506 return 0;
508 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
509 fmt_sbuf(fmt, c, path);
511 start_reply(c, code, c->sbuf);
512 return 1;
515 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
516 static int
517 apply_require_ca(struct client *c)
519 X509_STORE *store;
520 const uint8_t *cert;
521 size_t len;
523 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
524 return 0;
526 if (!tls_peer_cert_provided(c->ctx)) {
527 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
528 return 1;
531 cert = tls_peer_cert_chain_pem(c->ctx, &len);
532 if (!validate_against_ca(store, cert, len)) {
533 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
534 return 1;
537 return 0;
540 static void
541 handle_open_conn(int fd, short ev, void *d)
543 struct client *c = d;
544 const char *parse_err = "invalid request";
545 char decoded[DOMAIN_NAME_LEN];
547 bzero(c->req, sizeof(c->req));
548 bzero(&c->iri, sizeof(c->iri));
550 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
551 case -1:
552 log_err(c, "tls_read: %s", tls_error(c->ctx));
553 close_conn(fd, ev, c);
554 return;
556 case TLS_WANT_POLLIN:
557 reschedule_read(fd, c, &handle_open_conn);
558 return;
560 case TLS_WANT_POLLOUT:
561 reschedule_write(fd, c, &handle_open_conn);
562 return;
565 if (!trim_req_iri(c->req, &parse_err)
566 || !parse_iri(c->req, &c->iri, &parse_err)
567 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
568 log_info(c, "iri parse error: %s", parse_err);
569 start_reply(c, BAD_REQUEST, "invalid request");
570 return;
573 if (c->iri.port_no != conf.port
574 || strcmp(c->iri.schema, "gemini")
575 || strcmp(decoded, c->domain)) {
576 start_reply(c, PROXY_REFUSED, "won't proxy request");
577 return;
580 if (apply_require_ca(c))
581 return;
583 if (apply_block_return(c))
584 return;
586 if (c->host->entrypoint != NULL) {
587 start_cgi(c->host->entrypoint, c->iri.path, c);
588 return;
591 open_file(c);
594 static void
595 start_reply(struct client *c, int code, const char *meta)
597 c->code = code;
598 c->meta = meta;
599 handle_start_reply(c->fd, 0, c);
602 static void
603 handle_start_reply(int fd, short ev, void *d)
605 struct client *c = d;
606 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
607 const char *lang;
608 size_t len;
610 lang = vhost_lang(c->host, c->iri.path);
612 snprintf(buf, sizeof(buf), "%d ", c->code);
613 strlcat(buf, c->meta, sizeof(buf));
614 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
615 strlcat(buf, "; lang=", sizeof(buf));
616 strlcat(buf, lang, sizeof(buf));
619 len = strlcat(buf, "\r\n", sizeof(buf));
620 assert(len < sizeof(buf));
622 switch (tls_write(c->ctx, buf, len)) {
623 case -1:
624 close_conn(fd, ev, c);
625 return;
626 case TLS_WANT_POLLIN:
627 reschedule_read(fd, c, &handle_start_reply);
628 return;
629 case TLS_WANT_POLLOUT:
630 reschedule_write(fd, c, &handle_start_reply);
631 return;
634 log_request(c, buf, sizeof(buf));
636 if (c->code != SUCCESS)
637 close_conn(fd, ev, c);
638 else
639 c->next(fd, ev, c);
642 static void
643 start_cgi(const char *spath, const char *relpath, struct client *c)
645 char addr[NI_MAXHOST];
646 int e;
648 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
649 addr, sizeof(addr),
650 NULL, 0,
651 NI_NUMERICHOST);
652 if (e != 0)
653 goto err;
655 if (!send_iri(exfd, &c->iri)
656 || !send_string(exfd, spath)
657 || !send_string(exfd, relpath)
658 || !send_string(exfd, addr)
659 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
660 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
661 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
662 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
663 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
664 || !send_vhost(exfd, c->host))
665 goto err;
667 close(c->pfd);
668 if ((c->pfd = recv_fd(exfd)) == -1) {
669 start_reply(c, TEMP_FAILURE, "internal server error");
670 return;
673 reschedule_read(c->pfd, c, &handle_cgi_reply);
674 return;
676 err:
677 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
678 fatal("cannot talk to the executor process");
681 static void
682 send_file(int fd, short ev, void *d)
684 struct client *c = d;
685 ssize_t ret, len;
687 len = (c->buf + c->len) - c->i;
689 while (len > 0) {
690 switch (ret = tls_write(c->ctx, c->i, len)) {
691 case -1:
692 log_err(c, "tls_write: %s", tls_error(c->ctx));
693 close_conn(fd, ev, c);
694 return;
696 case TLS_WANT_POLLIN:
697 reschedule_read(fd, c, &send_file);
698 return;
700 case TLS_WANT_POLLOUT:
701 reschedule_write(fd, c, &send_file);
702 return;
704 default:
705 c->i += ret;
706 len -= ret;
707 break;
711 close_conn(fd, ev, c);
714 static void
715 open_dir(struct client *c)
717 size_t len;
718 int dirfd;
719 char *before_file;
721 len = strlen(c->iri.path);
722 if (len > 0 && !ends_with(c->iri.path, "/")) {
723 redirect_canonical_dir(c);
724 return;
727 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
728 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
729 if (!ends_with(c->sbuf, "/"))
730 strlcat(c->sbuf, "/", sizeof(c->sbuf));
731 before_file = strchr(c->sbuf, '\0');
732 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
733 sizeof(c->sbuf));
734 if (len >= sizeof(c->sbuf)) {
735 start_reply(c, TEMP_FAILURE, "internal server error");
736 return;
739 c->iri.path = c->sbuf;
741 /* close later unless we have to generate the dir listing */
742 dirfd = c->pfd;
743 c->pfd = -1;
745 switch (check_path(c, c->iri.path, &c->pfd)) {
746 case FILE_EXECUTABLE:
747 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
748 start_cgi(c->iri.path, "", c);
749 break;
752 /* fallthrough */
754 case FILE_EXISTS:
755 load_file(c);
756 break;
758 case FILE_DIRECTORY:
759 start_reply(c, TEMP_REDIRECT, c->sbuf);
760 break;
762 case FILE_MISSING:
763 *before_file = '\0';
765 if (!vhost_auto_index(c->host, c->iri.path)) {
766 start_reply(c, NOT_FOUND, "not found");
767 break;
770 c->pfd = dirfd;
771 c->next = enter_handle_dirlist;
773 if ((c->dir = fdopendir(c->pfd)) == NULL) {
774 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
775 c->pfd, c->host->domain, c->iri.path, strerror(errno));
776 start_reply(c, TEMP_FAILURE, "internal server error");
777 return;
779 c->off = 0;
781 start_reply(c, SUCCESS, "text/gemini");
782 return;
784 default:
785 /* unreachable */
786 abort();
789 close(dirfd);
792 static void
793 redirect_canonical_dir(struct client *c)
795 size_t len;
797 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
798 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
799 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
801 if (len >= sizeof(c->sbuf)) {
802 start_reply(c, TEMP_FAILURE, "internal server error");
803 return;
806 start_reply(c, TEMP_REDIRECT, c->sbuf);
809 static void
810 enter_handle_dirlist(int fd, short ev, void *d)
812 struct client *c = d;
813 char b[PATH_MAX];
814 size_t l;
816 strlcpy(b, c->iri.path, sizeof(b));
817 l = snprintf(c->sbuf, sizeof(c->sbuf),
818 "# Index of %s\n\n", b);
819 if (l >= sizeof(c->sbuf)) {
820 /* this is impossible, given that we have enough space
821 * in c->sbuf to hold the ancilliary string plus the
822 * full path; but it wouldn't read nice without some
823 * error checking, and I'd like to avoid a strlen. */
824 close_conn(fd, ev, c);
825 return;
828 c->len = l;
829 handle_dirlist(fd, ev, c);
832 static void
833 handle_dirlist(int fd, short ev, void *d)
835 struct client *c = d;
836 ssize_t r;
838 while (c->len > 0) {
839 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
840 case -1:
841 close_conn(fd, ev, c);
842 return;
843 case TLS_WANT_POLLOUT:
844 reschedule_read(fd, c, &handle_dirlist);
845 return;
846 case TLS_WANT_POLLIN:
847 reschedule_write(fd, c, &handle_dirlist);
848 return;
849 default:
850 c->off += r;
851 c->len -= r;
855 send_directory_listing(fd, ev, c);
858 static int
859 read_next_dir_entry(struct client *c)
861 struct dirent *d;
863 do {
864 errno = 0;
865 if ((d = readdir(c->dir)) == NULL) {
866 if (errno != 0)
867 log_err(c, "readdir: %s", strerror(errno));
868 return 0;
870 } while (!strcmp(d->d_name, "."));
872 /* XXX: url escape */
873 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
874 d->d_name, d->d_name);
875 c->len = strlen(c->sbuf);
876 c->off = 0;
878 return 1;
881 static void
882 send_directory_listing(int fd, short ev, void *d)
884 struct client *c = d;
885 ssize_t r;
887 while (1) {
888 if (c->len == 0) {
889 if (!read_next_dir_entry(c))
890 goto end;
893 while (c->len > 0) {
894 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
895 case -1:
896 goto end;
898 case TLS_WANT_POLLOUT:
899 reschedule_read(fd, c, &send_directory_listing);
900 return;
902 case TLS_WANT_POLLIN:
903 reschedule_write(fd, c, &send_directory_listing);
904 return;
906 default:
907 c->off += r;
908 c->len -= r;
909 break;
914 end:
915 close_conn(fd, ev, d);
918 /* accumulate the meta line from the cgi script. */
919 static void
920 handle_cgi_reply(int fd, short ev, void *d)
922 struct client *c = d;
923 void *buf, *e;
924 size_t len;
925 ssize_t r;
928 buf = c->sbuf + c->len;
929 len = sizeof(c->sbuf) - c->len;
931 r = read(c->pfd, buf, len);
932 if (r == 0 || r == -1) {
933 start_reply(c, CGI_ERROR, "CGI error");
934 return;
937 c->len += r;
939 /* TODO: error if the CGI script don't reply correctly */
940 e = strchr(c->sbuf, '\n');
941 if (e != NULL || c->len == sizeof(c->sbuf)) {
942 log_request(c, c->sbuf, c->len);
944 c->off = 0;
945 handle_cgi(fd, ev, c);
946 return;
949 reschedule_read(fd, c, &handle_cgi_reply);
952 static void
953 handle_cgi(int fd, short ev, void *d)
955 struct client *c = d;
956 ssize_t r;
958 while (1) {
959 if (c->len == 0) {
960 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
961 case 0:
962 goto end;
963 case -1:
964 if (errno == EAGAIN || errno == EWOULDBLOCK) {
965 reschedule_read(c->pfd, c, &handle_cgi);
966 return;
968 goto end;
969 default:
970 c->len = r;
971 c->off = 0;
975 while (c->len > 0) {
976 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
977 case -1:
978 goto end;
980 case TLS_WANT_POLLOUT:
981 reschedule_read(c->fd, c, &handle_cgi);
982 return;
984 case TLS_WANT_POLLIN:
985 reschedule_write(c->fd, c, &handle_cgi);
986 return;
988 default:
989 c->off += r;
990 c->len -= r;
991 break;
996 end:
997 close_conn(c->fd, ev, d);
1000 static void
1001 close_conn(int fd, short ev, void *d)
1003 struct client *c = d;
1005 switch (tls_close(c->ctx)) {
1006 case TLS_WANT_POLLIN:
1007 reschedule_read(fd, c, &close_conn);
1008 return;
1009 case TLS_WANT_POLLOUT:
1010 reschedule_read(fd, c, &close_conn);
1011 return;
1014 connected_clients--;
1016 tls_free(c->ctx);
1017 c->ctx = NULL;
1019 if (c->buf != MAP_FAILED)
1020 munmap(c->buf, c->len);
1022 if (c->pfd != -1)
1023 close(c->pfd);
1025 if (c->dir != NULL)
1026 closedir(c->dir);
1028 close(c->fd);
1029 c->fd = -1;
1032 static void
1033 do_accept(int sock, short et, void *d)
1035 struct client *c;
1036 struct server *s = d;
1037 struct sockaddr_storage addr;
1038 struct sockaddr *saddr;
1039 socklen_t len;
1040 int i, fd;
1042 (void)et;
1045 saddr = (struct sockaddr*)&addr;
1046 len = sizeof(addr);
1047 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
1048 if (errno == EWOULDBLOCK || errno == EAGAIN)
1049 return;
1050 fatal("accept: %s", strerror(errno));
1053 for (i = 0; i < MAX_USERS; ++i) {
1054 c = &s->clients[i];
1055 if (c->fd == -1) {
1056 memset(c, 0, sizeof(*c));
1057 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1058 break; /* goodbye fd! */
1060 c->fd = fd;
1061 c->pfd = -1;
1062 c->buf = MAP_FAILED;
1063 c->dir = NULL;
1064 c->addr = addr;
1066 reschedule_read(fd, c, &handle_handshake);
1067 connected_clients++;
1068 return;
1072 close(fd);
1075 static void
1076 handle_sighup(int fd, short ev, void *d)
1078 struct server_events *events = d;
1080 (void)fd;
1081 (void)ev;
1083 event_del(&events->e4);
1084 if (events->has_ipv6)
1085 event_del(&events->e6);
1086 signal_del(&events->sighup);
1089 static void
1090 handle_siginfo(int fd, short ev, void *d)
1092 (void)fd;
1093 (void)ev;
1094 (void)d;
1096 log_info(NULL, "%d connected clients", connected_clients);
1099 void
1100 loop(struct tls *ctx, int sock4, int sock6)
1102 struct server_events events;
1103 struct server server;
1104 struct event info;
1105 size_t i;
1107 event_init();
1109 memset(&events, 0, sizeof(events));
1110 memset(&server, 0, sizeof(server));
1111 for (i = 0; i < MAX_USERS; ++i)
1112 server.clients[i].fd = -1;
1114 event_set(&events.e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1115 event_add(&events.e4, NULL);
1117 if (sock6 != -1) {
1118 events.has_ipv6 = 1;
1119 event_set(&events.e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1120 event_add(&events.e6, NULL);
1123 signal_set(&events.sighup, SIGHUP, &handle_sighup, &events);
1124 signal_add(&events.sighup, NULL);
1126 #ifdef SIGINFO
1127 signal_set(&info, SIGINFO, &handle_siginfo, NULL);
1128 signal_add(&info, NULL);
1129 #endif
1130 signal_set(&info, SIGUSR2, &handle_siginfo, NULL);
1131 signal_add(&info, NULL);
1133 server.ctx = ctx;
1135 sandbox();
1136 event_dispatch();
1137 _exit(0);