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 event e4, e6, sighup, siginfo, sigusr2;
38 int has_ipv6, has_siginfo;
40 int connected_clients;
42 static inline int matches(const char*, const char*);
44 static inline void reschedule_read(int, struct client*, statefn);
45 static inline void reschedule_write(int, struct client*, statefn);
47 static int check_path(struct client*, const char*, int*);
48 static void open_file(struct client*);
49 static void load_file(struct client*);
50 static void check_for_cgi(struct client*);
51 static void handle_handshake(int, short, void*);
52 static char *strip_path(char*, int);
53 static void fmt_sbuf(const char*, struct client*, const char*);
54 static int apply_block_return(struct client*);
55 static int apply_require_ca(struct client*);
56 static void handle_open_conn(int, short, void*);
57 static void start_reply(struct client*, int, const char*);
58 static void handle_start_reply(int, short, void*);
59 static void start_cgi(const char*, const char*, struct client*);
60 static void send_file(int, short, void*);
61 static void open_dir(struct client*);
62 static void redirect_canonical_dir(struct client*);
63 static void enter_handle_dirlist(int, short, void*);
64 static void handle_dirlist(int, short, void*);
65 static int read_next_dir_entry(struct client*);
66 static void send_directory_listing(int, short, void*);
67 static void handle_cgi_reply(int, short, void*);
68 static void handle_cgi(int, short, void*);
69 static void close_conn(int, short, void*);
70 static void do_accept(int, short, void*);
71 static void handle_sighup(int, short, void*);
73 static inline int
74 matches(const char *pattern, const char *path)
75 {
76 if (*path == '/')
77 path++;
78 return !fnmatch(pattern, path, 0);
79 }
81 static inline void
82 reschedule_read(int fd, struct client *c, statefn fn)
83 {
84 event_once(fd, EV_READ, fn, c, NULL);
85 }
87 void
88 reschedule_write(int fd, struct client *c, statefn fn)
89 {
90 event_once(fd, EV_WRITE, fn, c, NULL);
91 }
93 const char *
94 vhost_lang(struct vhost *v, const char *path)
95 {
96 struct location *loc;
98 if (v == NULL || path == NULL)
99 return NULL;
101 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
102 if (loc->lang != NULL) {
103 if (matches(loc->match, path))
104 return loc->lang;
108 return v->locations[0].lang;
111 const char *
112 vhost_default_mime(struct vhost *v, const char *path)
114 struct location *loc;
115 const char *default_mime = "application/octet-stream";
117 if (v == NULL || path == NULL)
118 return default_mime;
120 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
121 if (loc->default_mime != NULL) {
122 if (matches(loc->match, path))
123 return loc->default_mime;
127 if (v->locations[0].default_mime != NULL)
128 return v->locations[0].default_mime;
129 return default_mime;
132 const char *
133 vhost_index(struct vhost *v, const char *path)
135 struct location *loc;
136 const char *index = "index.gmi";
138 if (v == NULL || path == NULL)
139 return index;
141 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
142 if (loc->index != NULL) {
143 if (matches(loc->match, path))
144 return loc->index;
148 if (v->locations[0].index != NULL)
149 return v->locations[0].index;
150 return index;
153 int
154 vhost_auto_index(struct vhost *v, const char *path)
156 struct location *loc;
158 if (v == NULL || path == NULL)
159 return 0;
161 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
162 if (loc->auto_index != 0) {
163 if (matches(loc->match, path))
164 return loc->auto_index == 1;
168 return v->locations[0].auto_index == 1;
171 int
172 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
174 struct location *loc;
176 if (v == NULL || path == NULL)
177 return 0;
179 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
180 if (loc->block_code != 0) {
181 if (matches(loc->match, path)) {
182 *code = loc->block_code;
183 *fmt = loc->block_fmt;
184 return 1;
189 *code = v->locations[0].block_code;
190 *fmt = v->locations[0].block_fmt;
191 return v->locations[0].block_code != 0;
194 int
195 vhost_strip(struct vhost *v, const char *path)
197 struct location *loc;
199 if (v == NULL || path == NULL)
200 return 0;
202 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
203 if (loc->strip != 0) {
204 if (matches(loc->match, path))
205 return loc->strip;
209 return v->locations[0].strip;
212 X509_STORE *
213 vhost_require_ca(struct vhost *v, const char *path)
215 struct location *loc;
217 if (v == NULL || path == NULL)
218 return NULL;
220 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
221 if (loc->reqca != NULL) {
222 if (matches(loc->match, path))
223 return loc->reqca;
227 return v->locations[0].reqca;
230 static int
231 check_path(struct client *c, const char *path, int *fd)
233 struct stat sb;
234 const char *p;
235 int flags;
237 assert(path != NULL);
239 if (*path == '\0')
240 p = ".";
241 else if (*path == '/')
242 /* in send_dir we add an initial / (to be
243 * redirect-friendly), but here we want to skip it */
244 p = path+1;
245 else
246 p = path;
248 flags = O_RDONLY | O_NOFOLLOW;
250 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
251 return FILE_MISSING;
253 if (fstat(*fd, &sb) == -1) {
254 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
255 return FILE_MISSING;
258 if (S_ISDIR(sb.st_mode))
259 return FILE_DIRECTORY;
261 if (sb.st_mode & S_IXUSR)
262 return FILE_EXECUTABLE;
264 return FILE_EXISTS;
267 static void
268 open_file(struct client *c)
270 switch (check_path(c, c->iri.path, &c->pfd)) {
271 case FILE_EXECUTABLE:
272 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
273 start_cgi(c->iri.path, "", c);
274 return;
277 /* fallthrough */
279 case FILE_EXISTS:
280 load_file(c);
281 return;
283 case FILE_DIRECTORY:
284 open_dir(c);
285 return;
287 case FILE_MISSING:
288 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
289 check_for_cgi(c);
290 return;
292 start_reply(c, NOT_FOUND, "not found");
293 return;
295 default:
296 /* unreachable */
297 abort();
301 static void
302 load_file(struct client *c)
304 if ((c->len = filesize(c->pfd)) == -1) {
305 log_err(c, "failed to get file size for %s: %s",
306 c->iri.path, strerror(errno));
307 start_reply(c, TEMP_FAILURE, "internal server error");
308 return;
311 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
312 c->pfd, 0)) == MAP_FAILED) {
313 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
314 start_reply(c, TEMP_FAILURE, "internal server error");
315 return;
317 c->i = c->buf;
318 c->next = send_file;
319 start_reply(c, SUCCESS, mime(c->host, c->iri.path));
322 /*
323 * the inverse of this algorithm, i.e. starting from the start of the
324 * path + strlen(cgi), and checking if each component, should be
325 * faster. But it's tedious to write. This does the opposite: starts
326 * from the end and strip one component at a time, until either an
327 * executable is found or we emptied the path.
328 */
329 static void
330 check_for_cgi(struct client *c)
332 char path[PATH_MAX];
333 char *end;
335 strlcpy(path, c->iri.path, sizeof(path));
336 end = strchr(path, '\0');
338 while (end > path) {
339 /* go up one level. UNIX paths are simple and POSIX
340 * dirname, with its ambiguities on if the given path
341 * is changed or not, gives me headaches. */
342 while (*end != '/')
343 end--;
344 *end = '\0';
346 switch (check_path(c, path, &c->pfd)) {
347 case FILE_EXECUTABLE:
348 start_cgi(path, end+1, c);
349 return;
350 case FILE_MISSING:
351 break;
352 default:
353 goto err;
356 *end = '/';
357 end--;
360 err:
361 start_reply(c, NOT_FOUND, "not found");
362 return;
365 void
366 mark_nonblock(int fd)
368 int flags;
370 if ((flags = fcntl(fd, F_GETFL)) == -1)
371 fatal("fcntl(F_GETFL): %s", strerror(errno));
372 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
373 fatal("fcntl(F_SETFL): %s", strerror(errno));
376 static void
377 handle_handshake(int fd, short ev, void *d)
379 struct client *c = d;
380 struct vhost *h;
381 const char *servname;
382 const char *parse_err = "unknown error";
384 switch (tls_handshake(c->ctx)) {
385 case 0: /* success */
386 case -1: /* already handshaked */
387 break;
388 case TLS_WANT_POLLIN:
389 reschedule_read(fd, c, &handle_handshake);
390 return;
391 case TLS_WANT_POLLOUT:
392 reschedule_write(fd, c, &handle_handshake);
393 return;
394 default:
395 /* unreachable */
396 abort();
399 servname = tls_conn_servername(c->ctx);
400 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
401 log_info(c, "puny_decode: %s", parse_err);
402 goto err;
405 for (h = hosts; h->domain != NULL; ++h) {
406 if (!fnmatch(h->domain, c->domain, 0))
407 break;
410 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
411 servname != NULL ? servname : "(null)",
412 c->domain,
413 h->domain != NULL ? h->domain : "(null)");
415 if (h->domain != NULL) {
416 c->host = h;
417 handle_open_conn(fd, ev, c);
418 return;
421 err:
422 if (servname != NULL)
423 strncpy(c->req, servname, sizeof(c->req));
424 else
425 strncpy(c->req, "null", sizeof(c->req));
427 start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
430 static char *
431 strip_path(char *path, int strip)
433 char *t;
435 while (strip > 0) {
436 if ((t = strchr(path, '/')) == NULL) {
437 path = strchr(path, '\0');
438 break;
440 path = t;
441 strip--;
444 return path;
447 static void
448 fmt_sbuf(const char *fmt, struct client *c, const char *path)
450 size_t i;
451 char buf[32];
453 memset(buf, 0, sizeof(buf));
454 for (i = 0; *fmt; ++fmt) {
455 if (i == sizeof(buf)-1 || *fmt == '%') {
456 strlcat(c->sbuf, buf, sizeof(c->sbuf));
457 memset(buf, 0, sizeof(buf));
458 i = 0;
461 if (*fmt != '%') {
462 buf[i++] = *fmt;
463 continue;
466 switch (*++fmt) {
467 case '%':
468 strlcat(c->sbuf, "%", sizeof(c->sbuf));
469 break;
470 case 'p':
471 strlcat(c->sbuf, path, sizeof(c->sbuf));
472 break;
473 case 'q':
474 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
475 break;
476 case 'P':
477 snprintf(buf, sizeof(buf), "%d", conf.port);
478 strlcat(c->sbuf, buf, sizeof(c->sbuf));
479 memset(buf, 0, sizeof(buf));
480 break;
481 case 'N':
482 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
483 break;
484 default:
485 fatal("%s: unknown fmt specifier %c",
486 __func__, *fmt);
490 if (i != 0)
491 strlcat(c->sbuf, buf, sizeof(c->sbuf));
494 /* 1 if a matching `block return' (and apply it), 0 otherwise */
495 static int
496 apply_block_return(struct client *c)
498 const char *fmt, *path;
499 int code;
501 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
502 return 0;
504 path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
505 fmt_sbuf(fmt, c, path);
507 start_reply(c, code, c->sbuf);
508 return 1;
511 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
512 static int
513 apply_require_ca(struct client *c)
515 X509_STORE *store;
516 const uint8_t *cert;
517 size_t len;
519 if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
520 return 0;
522 if (!tls_peer_cert_provided(c->ctx)) {
523 start_reply(c, CLIENT_CERT_REQ, "client certificate required");
524 return 1;
527 cert = tls_peer_cert_chain_pem(c->ctx, &len);
528 if (!validate_against_ca(store, cert, len)) {
529 start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
530 return 1;
533 return 0;
536 static void
537 handle_open_conn(int fd, short ev, void *d)
539 struct client *c = d;
540 const char *parse_err = "invalid request";
541 char decoded[DOMAIN_NAME_LEN];
543 bzero(c->req, sizeof(c->req));
544 bzero(&c->iri, sizeof(c->iri));
546 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
547 case -1:
548 log_err(c, "tls_read: %s", tls_error(c->ctx));
549 close_conn(fd, ev, c);
550 return;
552 case TLS_WANT_POLLIN:
553 reschedule_read(fd, c, &handle_open_conn);
554 return;
556 case TLS_WANT_POLLOUT:
557 reschedule_write(fd, c, &handle_open_conn);
558 return;
561 if (!trim_req_iri(c->req, &parse_err)
562 || !parse_iri(c->req, &c->iri, &parse_err)
563 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
564 log_info(c, "iri parse error: %s", parse_err);
565 start_reply(c, BAD_REQUEST, "invalid request");
566 return;
569 if (c->iri.port_no != conf.port
570 || strcmp(c->iri.schema, "gemini")
571 || strcmp(decoded, c->domain)) {
572 start_reply(c, PROXY_REFUSED, "won't proxy request");
573 return;
576 if (apply_require_ca(c))
577 return;
579 if (apply_block_return(c))
580 return;
582 if (c->host->entrypoint != NULL) {
583 start_cgi(c->host->entrypoint, c->iri.path, c);
584 return;
587 open_file(c);
590 static void
591 start_reply(struct client *c, int code, const char *meta)
593 c->code = code;
594 c->meta = meta;
595 handle_start_reply(c->fd, 0, c);
598 static void
599 handle_start_reply(int fd, short ev, void *d)
601 struct client *c = d;
602 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
603 const char *lang;
604 size_t len;
606 lang = vhost_lang(c->host, c->iri.path);
608 snprintf(buf, sizeof(buf), "%d ", c->code);
609 strlcat(buf, c->meta, sizeof(buf));
610 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
611 strlcat(buf, "; lang=", sizeof(buf));
612 strlcat(buf, lang, sizeof(buf));
615 len = strlcat(buf, "\r\n", sizeof(buf));
616 assert(len < sizeof(buf));
618 switch (tls_write(c->ctx, buf, len)) {
619 case -1:
620 close_conn(fd, ev, c);
621 return;
622 case TLS_WANT_POLLIN:
623 reschedule_read(fd, c, &handle_start_reply);
624 return;
625 case TLS_WANT_POLLOUT:
626 reschedule_write(fd, c, &handle_start_reply);
627 return;
630 log_request(c, buf, sizeof(buf));
632 if (c->code != SUCCESS)
633 close_conn(fd, ev, c);
634 else
635 c->next(fd, ev, c);
638 static void
639 start_cgi(const char *spath, const char *relpath, struct client *c)
641 char addr[NI_MAXHOST];
642 int e;
644 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
645 addr, sizeof(addr),
646 NULL, 0,
647 NI_NUMERICHOST);
648 if (e != 0)
649 goto err;
651 if (!send_iri(exfd, &c->iri)
652 || !send_string(exfd, spath)
653 || !send_string(exfd, relpath)
654 || !send_string(exfd, addr)
655 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
656 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
657 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
658 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
659 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
660 || !send_vhost(exfd, c->host))
661 goto err;
663 close(c->pfd);
664 if ((c->pfd = recv_fd(exfd)) == -1) {
665 start_reply(c, TEMP_FAILURE, "internal server error");
666 return;
669 reschedule_read(c->pfd, c, &handle_cgi_reply);
670 return;
672 err:
673 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
674 fatal("cannot talk to the executor process");
677 static void
678 send_file(int fd, short ev, void *d)
680 struct client *c = d;
681 ssize_t ret, len;
683 len = (c->buf + c->len) - c->i;
685 while (len > 0) {
686 switch (ret = tls_write(c->ctx, c->i, len)) {
687 case -1:
688 log_err(c, "tls_write: %s", tls_error(c->ctx));
689 close_conn(fd, ev, c);
690 return;
692 case TLS_WANT_POLLIN:
693 reschedule_read(fd, c, &send_file);
694 return;
696 case TLS_WANT_POLLOUT:
697 reschedule_write(fd, c, &send_file);
698 return;
700 default:
701 c->i += ret;
702 len -= ret;
703 break;
707 close_conn(fd, ev, c);
710 static void
711 open_dir(struct client *c)
713 size_t len;
714 int dirfd;
715 char *before_file;
717 len = strlen(c->iri.path);
718 if (len > 0 && !ends_with(c->iri.path, "/")) {
719 redirect_canonical_dir(c);
720 return;
723 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
724 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
725 if (!ends_with(c->sbuf, "/"))
726 strlcat(c->sbuf, "/", sizeof(c->sbuf));
727 before_file = strchr(c->sbuf, '\0');
728 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
729 sizeof(c->sbuf));
730 if (len >= sizeof(c->sbuf)) {
731 start_reply(c, TEMP_FAILURE, "internal server error");
732 return;
735 c->iri.path = c->sbuf;
737 /* close later unless we have to generate the dir listing */
738 dirfd = c->pfd;
739 c->pfd = -1;
741 switch (check_path(c, c->iri.path, &c->pfd)) {
742 case FILE_EXECUTABLE:
743 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
744 start_cgi(c->iri.path, "", c);
745 break;
748 /* fallthrough */
750 case FILE_EXISTS:
751 load_file(c);
752 break;
754 case FILE_DIRECTORY:
755 start_reply(c, TEMP_REDIRECT, c->sbuf);
756 break;
758 case FILE_MISSING:
759 *before_file = '\0';
761 if (!vhost_auto_index(c->host, c->iri.path)) {
762 start_reply(c, NOT_FOUND, "not found");
763 break;
766 c->pfd = dirfd;
767 c->next = enter_handle_dirlist;
769 if ((c->dir = fdopendir(c->pfd)) == NULL) {
770 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
771 c->pfd, c->host->domain, c->iri.path, strerror(errno));
772 start_reply(c, TEMP_FAILURE, "internal server error");
773 return;
775 c->off = 0;
777 start_reply(c, SUCCESS, "text/gemini");
778 return;
780 default:
781 /* unreachable */
782 abort();
785 close(dirfd);
788 static void
789 redirect_canonical_dir(struct client *c)
791 size_t len;
793 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
794 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
795 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
797 if (len >= sizeof(c->sbuf)) {
798 start_reply(c, TEMP_FAILURE, "internal server error");
799 return;
802 start_reply(c, TEMP_REDIRECT, c->sbuf);
805 static void
806 enter_handle_dirlist(int fd, short ev, void *d)
808 struct client *c = d;
809 char b[PATH_MAX];
810 size_t l;
812 strlcpy(b, c->iri.path, sizeof(b));
813 l = snprintf(c->sbuf, sizeof(c->sbuf),
814 "# Index of %s\n\n", b);
815 if (l >= sizeof(c->sbuf)) {
816 /* this is impossible, given that we have enough space
817 * in c->sbuf to hold the ancilliary string plus the
818 * full path; but it wouldn't read nice without some
819 * error checking, and I'd like to avoid a strlen. */
820 close_conn(fd, ev, c);
821 return;
824 c->len = l;
825 handle_dirlist(fd, ev, c);
828 static void
829 handle_dirlist(int fd, short ev, void *d)
831 struct client *c = d;
832 ssize_t r;
834 while (c->len > 0) {
835 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
836 case -1:
837 close_conn(fd, ev, c);
838 return;
839 case TLS_WANT_POLLOUT:
840 reschedule_read(fd, c, &handle_dirlist);
841 return;
842 case TLS_WANT_POLLIN:
843 reschedule_write(fd, c, &handle_dirlist);
844 return;
845 default:
846 c->off += r;
847 c->len -= r;
851 send_directory_listing(fd, ev, c);
854 static int
855 read_next_dir_entry(struct client *c)
857 struct dirent *d;
859 do {
860 errno = 0;
861 if ((d = readdir(c->dir)) == NULL) {
862 if (errno != 0)
863 log_err(c, "readdir: %s", strerror(errno));
864 return 0;
866 } while (!strcmp(d->d_name, "."));
868 /* XXX: url escape */
869 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
870 d->d_name, d->d_name);
871 c->len = strlen(c->sbuf);
872 c->off = 0;
874 return 1;
877 static void
878 send_directory_listing(int fd, short ev, void *d)
880 struct client *c = d;
881 ssize_t r;
883 while (1) {
884 if (c->len == 0) {
885 if (!read_next_dir_entry(c))
886 goto end;
889 while (c->len > 0) {
890 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
891 case -1:
892 goto end;
894 case TLS_WANT_POLLOUT:
895 reschedule_read(fd, c, &send_directory_listing);
896 return;
898 case TLS_WANT_POLLIN:
899 reschedule_write(fd, c, &send_directory_listing);
900 return;
902 default:
903 c->off += r;
904 c->len -= r;
905 break;
910 end:
911 close_conn(fd, ev, d);
914 /* accumulate the meta line from the cgi script. */
915 static void
916 handle_cgi_reply(int fd, short ev, void *d)
918 struct client *c = d;
919 void *buf, *e;
920 size_t len;
921 ssize_t r;
924 buf = c->sbuf + c->len;
925 len = sizeof(c->sbuf) - c->len;
927 r = read(c->pfd, buf, len);
928 if (r == 0 || r == -1) {
929 start_reply(c, CGI_ERROR, "CGI error");
930 return;
933 c->len += r;
935 /* TODO: error if the CGI script don't reply correctly */
936 e = strchr(c->sbuf, '\n');
937 if (e != NULL || c->len == sizeof(c->sbuf)) {
938 log_request(c, c->sbuf, c->len);
940 c->off = 0;
941 handle_cgi(fd, ev, c);
942 return;
945 reschedule_read(fd, c, &handle_cgi_reply);
948 static void
949 handle_cgi(int fd, short ev, void *d)
951 struct client *c = d;
952 ssize_t r;
954 while (1) {
955 if (c->len == 0) {
956 switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
957 case 0:
958 goto end;
959 case -1:
960 if (errno == EAGAIN || errno == EWOULDBLOCK) {
961 reschedule_read(c->pfd, c, &handle_cgi);
962 return;
964 goto end;
965 default:
966 c->len = r;
967 c->off = 0;
971 while (c->len > 0) {
972 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
973 case -1:
974 goto end;
976 case TLS_WANT_POLLOUT:
977 reschedule_read(c->fd, c, &handle_cgi);
978 return;
980 case TLS_WANT_POLLIN:
981 reschedule_write(c->fd, c, &handle_cgi);
982 return;
984 default:
985 c->off += r;
986 c->len -= r;
987 break;
992 end:
993 close_conn(c->fd, ev, d);
996 static void
997 close_conn(int fd, short ev, void *d)
999 struct client *c = d;
1001 switch (tls_close(c->ctx)) {
1002 case TLS_WANT_POLLIN:
1003 reschedule_read(fd, c, &close_conn);
1004 return;
1005 case TLS_WANT_POLLOUT:
1006 reschedule_read(fd, c, &close_conn);
1007 return;
1010 connected_clients--;
1012 tls_free(c->ctx);
1013 c->ctx = NULL;
1015 if (c->buf != MAP_FAILED)
1016 munmap(c->buf, c->len);
1018 if (c->pfd != -1)
1019 close(c->pfd);
1021 if (c->dir != NULL)
1022 closedir(c->dir);
1024 close(c->fd);
1025 c->fd = -1;
1028 static void
1029 do_accept(int sock, short et, void *d)
1031 struct client *c;
1032 struct server *s = d;
1033 struct sockaddr_storage addr;
1034 struct sockaddr *saddr;
1035 socklen_t len;
1036 int i, fd;
1038 (void)et;
1041 saddr = (struct sockaddr*)&addr;
1042 len = sizeof(addr);
1043 if ((fd = accept4(sock, saddr, &len, SOCK_NONBLOCK)) == -1) {
1044 if (errno == EWOULDBLOCK || errno == EAGAIN)
1045 return;
1046 fatal("accept: %s", strerror(errno));
1049 for (i = 0; i < MAX_USERS; ++i) {
1050 c = &s->clients[i];
1051 if (c->fd == -1) {
1052 memset(c, 0, sizeof(*c));
1053 if (tls_accept_socket(s->ctx, &c->ctx, fd) == -1)
1054 break; /* goodbye fd! */
1056 c->fd = fd;
1057 c->pfd = -1;
1058 c->buf = MAP_FAILED;
1059 c->dir = NULL;
1060 c->addr = addr;
1062 reschedule_read(fd, c, &handle_handshake);
1063 connected_clients++;
1064 return;
1068 close(fd);
1071 static void
1072 handle_sighup(int fd, short ev, void *d)
1074 (void)fd;
1075 (void)ev;
1077 event_del(&e4);
1078 if (has_ipv6)
1079 event_del(&e6);
1080 if (has_siginfo)
1081 signal_del(&siginfo);
1082 signal_del(&sigusr2);
1083 signal_del(&sighup);
1086 static void
1087 handle_siginfo(int fd, short ev, void *d)
1089 (void)fd;
1090 (void)ev;
1091 (void)d;
1093 log_info(NULL, "%d connected clients", connected_clients);
1096 void
1097 loop(struct tls *ctx, int sock4, int sock6)
1099 struct server server;
1100 size_t i;
1102 event_init();
1104 memset(&server, 0, sizeof(server));
1105 for (i = 0; i < MAX_USERS; ++i)
1106 server.clients[i].fd = -1;
1108 event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, &server);
1109 event_add(&e4, NULL);
1111 if (sock6 != -1) {
1112 has_ipv6 = 1;
1113 event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, &server);
1114 event_add(&e6, NULL);
1117 signal_set(&sighup, SIGHUP, &handle_sighup, NULL);
1118 signal_add(&sighup, NULL);
1120 #ifdef SIGINFO
1121 has_siginfo = 1;
1122 signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1123 signal_add(&siginfo, NULL);
1124 #endif
1125 signal_set(&sigusr2, SIGINFO, &handle_siginfo, NULL);
1126 signal_add(&sigusr2, NULL);
1128 server.ctx = ctx;
1130 sandbox();
1131 event_dispatch();
1132 _exit(0);