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 <fcntl.h>
25 #include <fnmatch.h>
26 #include <limits.h>
27 #include <string.h>
29 #include "gmid.h"
31 int connected_clients;
33 static int check_path(struct client*, const char*, int*);
34 static void open_file(struct pollfd*, struct client*);
35 static void load_file(struct pollfd*, struct client*);
36 static void check_for_cgi(struct pollfd*, struct client*);
37 static void handle_handshake(struct pollfd*, struct client*);
38 static int apply_block_return(struct pollfd*, struct client*);
39 static void handle_open_conn(struct pollfd*, struct client*);
40 static void start_reply(struct pollfd*, struct client*, int, const char*);
41 static void handle_start_reply(struct pollfd*, struct client*);
42 static void start_cgi(const char*, const char*, struct pollfd*, struct client*);
43 static void send_file(struct pollfd*, struct client*);
44 static void open_dir(struct pollfd*, struct client*);
45 static void redirect_canonical_dir(struct pollfd*, struct client*);
46 static void enter_handle_dirlist(struct pollfd*, struct client*);
47 static void handle_dirlist(struct pollfd*, struct client*);
48 static int read_next_dir_entry(struct client*);
49 static void send_directory_listing(struct pollfd*, struct client*);
50 static void cgi_poll_on_child(struct pollfd*, struct client*);
51 static void cgi_poll_on_client(struct pollfd*, struct client*);
52 static void handle_cgi_reply(struct pollfd*, struct client*);
53 static void handle_cgi(struct pollfd*, struct client*);
54 static void close_conn(struct pollfd*, struct client*);
55 static void do_accept(int, struct tls*, struct pollfd*, struct client*);
57 const char *
58 vhost_lang(struct vhost *v, const char *path)
59 {
60 struct location *loc;
62 if (v == NULL || path == NULL)
63 return NULL;
65 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
66 if (loc->lang != NULL) {
67 if (!fnmatch(loc->match, path, 0))
68 return loc->lang;
69 }
70 }
72 return v->locations[0].lang;
73 }
75 const char *
76 vhost_default_mime(struct vhost *v, const char *path)
77 {
78 struct location *loc;
79 const char *default_mime = "application/octet-stream";
81 if (v == NULL || path == NULL)
82 return default_mime;
84 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
85 if (loc->default_mime != NULL) {
86 if (!fnmatch(loc->match, path, 0))
87 return loc->default_mime;
88 }
89 }
91 if (v->locations[0].default_mime != NULL)
92 return v->locations[0].default_mime;
93 return default_mime;
94 }
96 const char *
97 vhost_index(struct vhost *v, const char *path)
98 {
99 struct location *loc;
100 const char *index = "index.gmi";
102 if (v == NULL || path == NULL)
103 return index;
105 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
106 if (loc->index != NULL) {
107 if (!fnmatch(loc->match, path, 0))
108 return loc->index;
112 if (v->locations[0].index != NULL)
113 return v->locations[0].index;
114 return index;
117 int
118 vhost_auto_index(struct vhost *v, const char *path)
120 struct location *loc;
122 if (v == NULL || path == NULL)
123 return 0;
125 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
126 if (loc->auto_index != 0) {
127 if (!fnmatch(loc->match, path, 0))
128 return loc->auto_index == 1;
132 return v->locations[0].auto_index == 1;
135 int
136 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
138 struct location *loc;
140 if (v == NULL || path == NULL)
141 return 0;
143 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
144 if (loc->block_code != 0) {
145 if (!fnmatch(loc->match, path, 0)) {
146 *code = loc->block_code;
147 *fmt = loc->block_fmt;
148 return 1;
153 *code = v->locations[0].block_code;
154 *fmt = v->locations[0].block_fmt;
155 return v->locations[0].block_code != 0;
158 int
159 vhost_strip(struct vhost *v, const char *path)
161 struct location *loc;
163 if (v == NULL || path == NULL)
164 return 0;
166 for (loc = &v->locations[1]; loc->match != NULL; ++loc) {
167 if (loc->strip != 0) {
168 if (!fnmatch(loc->match, path, 0))
169 return loc->strip;
173 return v->locations[0].strip;
176 static int
177 check_path(struct client *c, const char *path, int *fd)
179 struct stat sb;
180 const char *p;
181 int flags;
183 assert(path != NULL);
185 if (*path == '\0')
186 p = ".";
187 else if (*path == '/')
188 /* in send_dir we add an initial / (to be
189 * redirect-friendly), but here we want to skip it */
190 p = path+1;
191 else
192 p = path;
194 flags = O_RDONLY | O_NOFOLLOW;
196 if (*fd == -1 && (*fd = openat(c->host->dirfd, p, flags)) == -1)
197 return FILE_MISSING;
199 if (fstat(*fd, &sb) == -1) {
200 log_notice(c, "failed stat for %s: %s", path, strerror(errno));
201 return FILE_MISSING;
204 if (S_ISDIR(sb.st_mode))
205 return FILE_DIRECTORY;
207 if (sb.st_mode & S_IXUSR)
208 return FILE_EXECUTABLE;
210 return FILE_EXISTS;
213 static void
214 open_file(struct pollfd *fds, struct client *c)
216 switch (check_path(c, c->iri.path, &c->fd)) {
217 case FILE_EXECUTABLE:
218 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
219 start_cgi(c->iri.path, "", fds, c);
220 return;
223 /* fallthrough */
225 case FILE_EXISTS:
226 load_file(fds, c);
227 return;
229 case FILE_DIRECTORY:
230 open_dir(fds, c);
231 return;
233 case FILE_MISSING:
234 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
235 check_for_cgi(fds, c);
236 return;
238 start_reply(fds, c, NOT_FOUND, "not found");
239 return;
241 default:
242 /* unreachable */
243 abort();
247 static void
248 load_file(struct pollfd *fds, struct client *c)
250 if ((c->len = filesize(c->fd)) == -1) {
251 log_err(c, "failed to get file size for %s: %s",
252 c->iri.path, strerror(errno));
253 start_reply(fds, c, TEMP_FAILURE, "internal server error");
254 return;
257 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
258 c->fd, 0)) == MAP_FAILED) {
259 log_err(c, "mmap: %s: %s", c->iri.path, strerror(errno));
260 start_reply(fds, c, TEMP_FAILURE, "internal server error");
261 return;
263 c->i = c->buf;
264 c->next = send_file;
265 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
268 /*
269 * the inverse of this algorithm, i.e. starting from the start of the
270 * path + strlen(cgi), and checking if each component, should be
271 * faster. But it's tedious to write. This does the opposite: starts
272 * from the end and strip one component at a time, until either an
273 * executable is found or we emptied the path.
274 */
275 static void
276 check_for_cgi(struct pollfd *fds, struct client *c)
278 char path[PATH_MAX];
279 char *end;
281 strlcpy(path, c->iri.path, sizeof(path));
282 end = strchr(path, '\0');
284 /* NB: assume CGI is enabled and path matches cgi */
286 while (end > path) {
287 /* go up one level. UNIX paths are simple and POSIX
288 * dirname, with its ambiguities on if the given path
289 * is changed or not, gives me headaches. */
290 while (*end != '/')
291 end--;
292 *end = '\0';
294 switch (check_path(c, path, &c->fd)) {
295 case FILE_EXECUTABLE:
296 start_cgi(path, end+1, fds, c);
297 return;
298 case FILE_MISSING:
299 break;
300 default:
301 goto err;
304 *end = '/';
305 end--;
308 err:
309 start_reply(fds, c, NOT_FOUND, "not found");
310 return;
313 void
314 mark_nonblock(int fd)
316 int flags;
318 if ((flags = fcntl(fd, F_GETFL)) == -1)
319 fatal("fcntl(F_GETFL): %s", strerror(errno));
320 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
321 fatal("fcntl(F_SETFL): %s", strerror(errno));
324 static void
325 handle_handshake(struct pollfd *fds, struct client *c)
327 struct vhost *h;
328 const char *servname;
329 const char *parse_err = "unknown error";
331 switch (tls_handshake(c->ctx)) {
332 case 0: /* success */
333 case -1: /* already handshaked */
334 break;
335 case TLS_WANT_POLLIN:
336 fds->events = POLLIN;
337 return;
338 case TLS_WANT_POLLOUT:
339 fds->events = POLLOUT;
340 return;
341 default:
342 /* unreachable */
343 abort();
346 servname = tls_conn_servername(c->ctx);
347 if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
348 log_info(c, "puny_decode: %s", parse_err);
349 goto err;
352 for (h = hosts; h->domain != NULL; ++h) {
353 if (!fnmatch(h->domain, c->domain, 0))
354 break;
357 log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
358 servname != NULL ? servname : "(null)",
359 c->domain,
360 h->domain != NULL ? h->domain : "(null)");
362 if (h->domain != NULL) {
363 c->host = h;
364 c->state = handle_open_conn;
365 c->state(fds, c);
366 return;
369 err:
370 if (servname != NULL)
371 strncpy(c->req, servname, sizeof(c->req));
372 else
373 strncpy(c->req, "null", sizeof(c->req));
375 start_reply(fds, c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
378 /* 1 if a matching `block return' (and apply it), 0 otherwise */
379 static int
380 apply_block_return(struct pollfd *fds, struct client *c)
382 char *t, *path, buf[32];
383 const char *fmt;
384 int strip, code;
385 size_t i;
387 if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
388 return 0;
390 strip = vhost_strip(c->host, c->iri.path);
391 path = c->iri.path;
392 while (strip > 0) {
393 if ((t = strchr(path, '/')) == NULL) {
394 path = strchr(path, '\0');
395 break;
397 path = t;
398 strip--;
401 memset(buf, 0, sizeof(buf));
402 for (i = 0; *fmt; ++fmt) {
403 if (i == sizeof(buf)-1 || *fmt == '%') {
404 strlcat(c->sbuf, buf, sizeof(c->sbuf));
405 memset(buf, 0, sizeof(buf));
406 i = 0;
409 if (*fmt != '%') {
410 buf[i++] = *fmt;
411 continue;
414 switch (*++fmt) {
415 case '%':
416 strlcat(c->sbuf, "%", sizeof(c->sbuf));
417 break;
418 case 'p':
419 strlcat(c->sbuf, path, sizeof(c->sbuf));
420 break;
421 case 'q':
422 strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
423 break;
424 case 'P':
425 snprintf(buf, sizeof(buf), "%d", conf.port);
426 strlcat(c->sbuf, buf, sizeof(c->sbuf));
427 memset(buf, 0, sizeof(buf));
428 break;
429 case 'N':
430 strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
431 break;
432 default:
433 fatal("%s: unknown fmt specifier %c",
434 __func__, *fmt);
438 if (i != 0)
439 strlcat(c->sbuf, buf, sizeof(c->sbuf));
441 start_reply(fds, c, code, c->sbuf);
442 return 1;
445 static void
446 handle_open_conn(struct pollfd *fds, struct client *c)
448 const char *parse_err = "invalid request";
449 char decoded[DOMAIN_NAME_LEN];
451 bzero(c->req, sizeof(c->req));
452 bzero(&c->iri, sizeof(c->iri));
454 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
455 case -1:
456 log_err(c, "tls_read: %s", tls_error(c->ctx));
457 close_conn(fds, c);
458 return;
460 case TLS_WANT_POLLIN:
461 fds->events = POLLIN;
462 return;
464 case TLS_WANT_POLLOUT:
465 fds->events = POLLOUT;
466 return;
469 if (!trim_req_iri(c->req, &parse_err)
470 || !parse_iri(c->req, &c->iri, &parse_err)
471 || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
472 log_info(c, "iri parse error: %s", parse_err);
473 start_reply(fds, c, BAD_REQUEST, "invalid request");
474 return;
477 if (c->iri.port_no != conf.port
478 || strcmp(c->iri.schema, "gemini")
479 || strcmp(decoded, c->domain)) {
480 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
481 return;
484 if (apply_block_return(fds, c))
485 return;
487 if (c->host->entrypoint != NULL) {
488 start_cgi(c->host->entrypoint, c->iri.path, fds, c);
489 return;
492 open_file(fds, c);
495 static void
496 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
498 c->code = code;
499 c->meta = meta;
500 c->state = handle_start_reply;
501 handle_start_reply(pfd, c);
504 static void
505 handle_start_reply(struct pollfd *pfd, struct client *c)
507 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
508 const char *lang;
509 size_t len;
511 lang = vhost_lang(c->host, c->iri.path);
513 snprintf(buf, sizeof(buf), "%d ", c->code);
514 strlcat(buf, c->meta, sizeof(buf));
515 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
516 strlcat(buf, "; lang=", sizeof(buf));
517 strlcat(buf, lang, sizeof(buf));
520 len = strlcat(buf, "\r\n", sizeof(buf));
521 assert(len < sizeof(buf));
523 switch (tls_write(c->ctx, buf, len)) {
524 case -1:
525 close_conn(pfd, c);
526 return;
527 case TLS_WANT_POLLIN:
528 pfd->events = POLLIN;
529 return;
530 case TLS_WANT_POLLOUT:
531 pfd->events = POLLOUT;
532 return;
535 log_request(c, buf, sizeof(buf));
537 /* we don't need a body */
538 if (c->code != SUCCESS) {
539 close_conn(pfd, c);
540 return;
543 /* advance the state machine */
544 c->state = c->next;
545 c->state(pfd, c);
548 static void
549 start_cgi(const char *spath, const char *relpath,
550 struct pollfd *fds, struct client *c)
552 char addr[NI_MAXHOST];
553 const char *ruser, *cissuer, *chash;
554 int e;
556 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
557 addr, sizeof(addr),
558 NULL, 0,
559 NI_NUMERICHOST);
560 if (e != 0)
561 goto err;
563 if (tls_peer_cert_provided(c->ctx)) {
564 ruser = tls_peer_cert_subject(c->ctx);
565 cissuer = tls_peer_cert_issuer(c->ctx);
566 chash = tls_peer_cert_hash(c->ctx);
567 } else {
568 ruser = NULL;
569 cissuer = NULL;
570 chash = NULL;
573 if (!send_iri(exfd, &c->iri)
574 || !send_string(exfd, spath)
575 || !send_string(exfd, relpath)
576 || !send_string(exfd, addr)
577 || !send_string(exfd, ruser)
578 || !send_string(exfd, cissuer)
579 || !send_string(exfd, chash)
580 || !send_vhost(exfd, c->host))
581 goto err;
583 close(c->fd);
584 if ((c->fd = recv_fd(exfd)) == -1) {
585 start_reply(fds, c, TEMP_FAILURE, "internal server error");
586 return;
589 cgi_poll_on_child(fds, c);
590 c->state = handle_cgi_reply;
591 return;
593 err:
594 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
595 fatal("cannot talk to the executor process");
598 static void
599 send_file(struct pollfd *fds, struct client *c)
601 ssize_t ret, len;
603 len = (c->buf + c->len) - c->i;
605 while (len > 0) {
606 switch (ret = tls_write(c->ctx, c->i, len)) {
607 case -1:
608 log_err(c, "tls_write: %s", tls_error(c->ctx));
609 close_conn(fds, c);
610 return;
612 case TLS_WANT_POLLIN:
613 fds->events = POLLIN;
614 return;
616 case TLS_WANT_POLLOUT:
617 fds->events = POLLOUT;
618 return;
620 default:
621 c->i += ret;
622 len -= ret;
623 break;
627 close_conn(fds, c);
630 static void
631 open_dir(struct pollfd *fds, struct client *c)
633 size_t len;
634 int dirfd;
635 char *before_file;
637 len = strlen(c->iri.path);
638 if (len > 0 && !ends_with(c->iri.path, "/")) {
639 redirect_canonical_dir(fds, c);
640 return;
643 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
644 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
645 if (!ends_with(c->sbuf, "/"))
646 strlcat(c->sbuf, "/", sizeof(c->sbuf));
647 before_file = strchr(c->sbuf, '\0');
648 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
649 sizeof(c->sbuf));
650 if (len >= sizeof(c->sbuf)) {
651 start_reply(fds, c, TEMP_FAILURE, "internal server error");
652 return;
655 c->iri.path = c->sbuf;
657 /* close later unless we have to generate the dir listing */
658 dirfd = c->fd;
659 c->fd = -1;
661 switch (check_path(c, c->iri.path, &c->fd)) {
662 case FILE_EXECUTABLE:
663 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
664 start_cgi(c->iri.path, "", fds, c);
665 break;
668 /* fallthrough */
670 case FILE_EXISTS:
671 load_file(fds, c);
672 break;
674 case FILE_DIRECTORY:
675 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
676 break;
678 case FILE_MISSING:
679 *before_file = '\0';
681 if (!vhost_auto_index(c->host, c->iri.path)) {
682 start_reply(fds, c, NOT_FOUND, "not found");
683 break;
686 c->fd = dirfd;
687 c->next = enter_handle_dirlist;
689 if ((c->dir = fdopendir(c->fd)) == NULL) {
690 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
691 c->fd, c->host->domain, c->iri.path, strerror(errno));
692 start_reply(fds, c, TEMP_FAILURE, "internal server error");
693 return;
695 c->off = 0;
697 start_reply(fds, c, SUCCESS, "text/gemini");
698 return;
700 default:
701 /* unreachable */
702 abort();
705 close(dirfd);
708 static void
709 redirect_canonical_dir(struct pollfd *fds, struct client *c)
711 size_t len;
713 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
714 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
715 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
717 if (len >= sizeof(c->sbuf)) {
718 start_reply(fds, c, TEMP_FAILURE, "internal server error");
719 return;
722 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
725 static void
726 enter_handle_dirlist(struct pollfd *fds, struct client *c)
728 char b[PATH_MAX];
729 size_t l;
731 strlcpy(b, c->iri.path, sizeof(b));
732 l = snprintf(c->sbuf, sizeof(c->sbuf),
733 "# Index of %s\n\n", b);
734 if (l >= sizeof(c->sbuf)) {
735 /* this is impossible, given that we have enough space
736 * in c->sbuf to hold the ancilliary string plus the
737 * full path; but it wouldn't read nice without some
738 * error checking, and I'd like to avoid a strlen. */
739 close_conn(fds, c);
740 return;
742 c->len = l;
744 c->state = handle_dirlist;
745 handle_dirlist(fds, c);
748 static void
749 handle_dirlist(struct pollfd *fds, struct client *c)
751 ssize_t r;
753 while (c->len > 0) {
754 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
755 case -1:
756 close_conn(fds, c);
757 return;
758 case TLS_WANT_POLLOUT:
759 fds->events = POLLOUT;
760 return;
761 case TLS_WANT_POLLIN:
762 fds->events = POLLIN;
763 return;
764 default:
765 c->off += r;
766 c->len -= r;
770 c->state = send_directory_listing;
771 send_directory_listing(fds, c);
774 static int
775 read_next_dir_entry(struct client *c)
777 struct dirent *d;
779 do {
780 errno = 0;
781 if ((d = readdir(c->dir)) == NULL) {
782 if (errno != 0)
783 log_err(c, "readdir: %s", strerror(errno));
784 return 0;
786 } while (!strcmp(d->d_name, "."));
788 /* XXX: url escape */
789 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
790 d->d_name, d->d_name);
791 c->len = strlen(c->sbuf);
792 c->off = 0;
794 return 1;
797 static void
798 send_directory_listing(struct pollfd *fds, struct client *c)
800 ssize_t r;
802 while (1) {
803 if (c->len == 0) {
804 if (!read_next_dir_entry(c))
805 goto end;
808 while (c->len > 0) {
809 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
810 case -1:
811 goto end;
813 case TLS_WANT_POLLOUT:
814 fds->events = POLLOUT;
815 return;
817 case TLS_WANT_POLLIN:
818 fds->events = POLLIN;
819 return;
821 default:
822 c->off += r;
823 c->len -= r;
824 break;
829 end:
830 close_conn(fds, c);
833 static inline void
834 cgi_poll_on_child(struct pollfd *fds, struct client *c)
836 int fd;
838 if (c->waiting_on_child)
839 return;
840 c->waiting_on_child = 1;
842 fds->events = POLLIN;
844 fd = fds->fd;
845 fds->fd = c->fd;
846 c->fd = fd;
849 static inline void
850 cgi_poll_on_client(struct pollfd *fds, struct client *c)
852 int fd;
854 if (!c->waiting_on_child)
855 return;
856 c->waiting_on_child = 0;
858 fd = fds->fd;
859 fds->fd = c->fd;
860 c->fd = fd;
863 /* accumulate the meta line from the cgi script. */
864 static void
865 handle_cgi_reply(struct pollfd *fds, struct client *c)
867 void *buf, *e;
868 size_t len;
869 ssize_t r;
871 buf = c->sbuf + c->len;
872 len = sizeof(c->sbuf) - c->len;
874 /* we're polling on the child! */
875 r = read(fds->fd, buf, len);
876 if (r == 0 || r == -1) {
877 cgi_poll_on_client(fds, c);
878 start_reply(fds, c, CGI_ERROR, "CGI error");
879 return;
882 c->len += r;
884 /* TODO: error if the CGI script don't reply correctly */
885 e = strchr(c->sbuf, '\n');
886 if (e != NULL || c->len == sizeof(c->sbuf)) {
887 log_request(c, c->sbuf, c->len);
889 c->off = 0;
890 c->state = handle_cgi;
891 c->state(fds, c);
892 return;
896 static void
897 handle_cgi(struct pollfd *fds, struct client *c)
899 ssize_t r;
901 /* ensure c->fd is the child and fds->fd the client */
902 cgi_poll_on_client(fds, c);
904 while (1) {
905 if (c->len == 0) {
906 switch (r = read(c->fd, c->sbuf, sizeof(c->sbuf))) {
907 case 0:
908 goto end;
909 case -1:
910 if (errno == EAGAIN || errno == EWOULDBLOCK) {
911 cgi_poll_on_child(fds, c);
912 return;
914 goto end;
915 default:
916 c->len = r;
917 c->off = 0;
921 while (c->len > 0) {
922 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
923 case -1:
924 goto end;
926 case TLS_WANT_POLLOUT:
927 fds->events = POLLOUT;
928 return;
930 case TLS_WANT_POLLIN:
931 fds->events = POLLIN;
932 return;
934 default:
935 c->off += r;
936 c->len -= r;
937 break;
942 end:
943 close_conn(fds, c);
946 static void
947 close_conn(struct pollfd *pfd, struct client *c)
949 c->state = close_conn;
951 switch (tls_close(c->ctx)) {
952 case TLS_WANT_POLLIN:
953 pfd->events = POLLIN;
954 return;
955 case TLS_WANT_POLLOUT:
956 pfd->events = POLLOUT;
957 return;
960 connected_clients--;
962 tls_free(c->ctx);
963 c->ctx = NULL;
965 if (c->buf != MAP_FAILED)
966 munmap(c->buf, c->len);
968 if (c->fd != -1)
969 close(c->fd);
971 if (c->dir != NULL)
972 closedir(c->dir);
974 close(pfd->fd);
975 pfd->fd = -1;
978 static void
979 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
981 int i, fd;
982 struct sockaddr_storage addr;
983 socklen_t len;
985 len = sizeof(addr);
986 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
987 if (errno == EWOULDBLOCK || errno == EAGAIN)
988 return;
989 fatal("accept: %s", strerror(errno));
992 mark_nonblock(fd);
994 for (i = 0; i < MAX_USERS; ++i) {
995 if (fds[i].fd == -1) {
996 bzero(&clients[i], sizeof(struct client));
997 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
998 break; /* goodbye fd! */
1000 fds[i].fd = fd;
1001 fds[i].events = POLLIN;
1003 clients[i].state = handle_handshake;
1004 clients[i].next = send_file;
1005 clients[i].fd = -1;
1006 clients[i].waiting_on_child = 0;
1007 clients[i].buf = MAP_FAILED;
1008 clients[i].dir = NULL;
1009 clients[i].addr = addr;
1011 connected_clients++;
1012 return;
1016 close(fd);
1019 void
1020 loop(struct tls *ctx, int sock4, int sock6)
1022 int i, n;
1023 struct client clients[MAX_USERS];
1024 struct pollfd fds[MAX_USERS];
1026 for (i = 0; i < MAX_USERS; ++i) {
1027 fds[i].fd = -1;
1028 fds[i].events = POLLIN;
1029 bzero(&clients[i], sizeof(struct client));
1032 fds[0].fd = sock4;
1033 fds[1].fd = sock6;
1035 for (;;) {
1036 if ((n = poll(fds, MAX_USERS, INFTIM)) == -1) {
1037 if (errno == EINTR) {
1038 fprintf(stderr, "connected clients: %d\n",
1039 connected_clients);
1040 } else
1041 fatal("poll: %s", strerror(errno));
1044 for (i = 0; i < MAX_USERS && n > 0; i++) {
1045 if (fds[i].revents == 0)
1046 continue;
1048 if (fds[i].revents & (POLLERR|POLLNVAL))
1049 fatal("bad fd %d: %s", fds[i].fd,
1050 strerror(errno));
1052 n--;
1054 if (fds[i].revents & POLLHUP) {
1055 /* fds[i] may be the fd of the stdin
1056 * of a cgi script that has exited. */
1057 if (!clients[i].waiting_on_child) {
1058 close_conn(&fds[i], &clients[i]);
1059 continue;
1063 if (fds[i].fd == sock4)
1064 do_accept(sock4, ctx, fds, clients);
1065 else if (fds[i].fd == sock6)
1066 do_accept(sock6, ctx, fds, clients);
1067 else
1068 clients[i].state(&fds[i], &clients[i]);
1071 if (hupped) {
1072 if (connected_clients == 0)
1073 return;
1075 fds[0].fd = -1;
1076 if (sock6 != -1)
1077 fds[1].fd = -1;