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 (!fnmatch(loc->match, path, 0)) {
67 if (loc->lang != NULL)
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 (!fnmatch(loc->match, path, 0)) {
86 if (loc->default_mime != NULL)
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 (!fnmatch(loc->match, path, 0)) {
107 if (loc->index != NULL)
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 (!fnmatch(loc->match, path, 0)) {
127 if (loc->auto_index != 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 (!fnmatch(loc->match, path, 0)) {
145 if (loc->block_code != 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 (!fnmatch(loc->match, path, 0)) {
168 if (loc->strip != 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 LOGN(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 LOGE(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 LOGW(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 LOGI(c, "%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 /* LOGD(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 LOGE(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 LOGI(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 open_file(fds, c);
488 static void
489 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
491 c->code = code;
492 c->meta = meta;
493 c->state = handle_start_reply;
494 handle_start_reply(pfd, c);
497 static void
498 handle_start_reply(struct pollfd *pfd, struct client *c)
500 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
501 const char *lang;
502 size_t len;
504 lang = vhost_lang(c->host, c->iri.path);
506 snprintf(buf, sizeof(buf), "%d ", c->code);
507 strlcat(buf, c->meta, sizeof(buf));
508 if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
509 strlcat(buf, "; lang=", sizeof(buf));
510 strlcat(buf, lang, sizeof(buf));
513 len = strlcat(buf, "\r\n", sizeof(buf));
514 assert(len < sizeof(buf));
516 switch (tls_write(c->ctx, buf, len)) {
517 case -1:
518 close_conn(pfd, c);
519 return;
520 case TLS_WANT_POLLIN:
521 pfd->events = POLLIN;
522 return;
523 case TLS_WANT_POLLOUT:
524 pfd->events = POLLOUT;
525 return;
528 log_request(c, buf, sizeof(buf));
530 /* we don't need a body */
531 if (c->code != SUCCESS) {
532 close_conn(pfd, c);
533 return;
536 /* advance the state machine */
537 c->state = c->next;
538 c->state(pfd, c);
541 static void
542 start_cgi(const char *spath, const char *relpath,
543 struct pollfd *fds, struct client *c)
545 char addr[NI_MAXHOST];
546 const char *ruser, *cissuer, *chash;
547 int e;
549 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
550 addr, sizeof(addr),
551 NULL, 0,
552 NI_NUMERICHOST);
553 if (e != 0)
554 goto err;
556 if (tls_peer_cert_provided(c->ctx)) {
557 ruser = tls_peer_cert_subject(c->ctx);
558 cissuer = tls_peer_cert_issuer(c->ctx);
559 chash = tls_peer_cert_hash(c->ctx);
560 } else {
561 ruser = NULL;
562 cissuer = NULL;
563 chash = NULL;
566 if (!send_iri(exfd, &c->iri)
567 || !send_string(exfd, spath)
568 || !send_string(exfd, relpath)
569 || !send_string(exfd, addr)
570 || !send_string(exfd, ruser)
571 || !send_string(exfd, cissuer)
572 || !send_string(exfd, chash)
573 || !send_vhost(exfd, c->host))
574 goto err;
576 close(c->fd);
577 if ((c->fd = recv_fd(exfd)) == -1) {
578 start_reply(fds, c, TEMP_FAILURE, "internal server error");
579 return;
582 cgi_poll_on_child(fds, c);
583 c->state = handle_cgi_reply;
584 return;
586 err:
587 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
588 fatal("cannot talk to the executor process");
591 static void
592 send_file(struct pollfd *fds, struct client *c)
594 ssize_t ret, len;
596 len = (c->buf + c->len) - c->i;
598 while (len > 0) {
599 switch (ret = tls_write(c->ctx, c->i, len)) {
600 case -1:
601 LOGE(c, "tls_write: %s", tls_error(c->ctx));
602 close_conn(fds, c);
603 return;
605 case TLS_WANT_POLLIN:
606 fds->events = POLLIN;
607 return;
609 case TLS_WANT_POLLOUT:
610 fds->events = POLLOUT;
611 return;
613 default:
614 c->i += ret;
615 len -= ret;
616 break;
620 close_conn(fds, c);
623 static void
624 open_dir(struct pollfd *fds, struct client *c)
626 size_t len;
627 int dirfd;
628 char *before_file;
630 len = strlen(c->iri.path);
631 if (len > 0 && !ends_with(c->iri.path, "/")) {
632 redirect_canonical_dir(fds, c);
633 return;
636 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
637 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
638 if (!ends_with(c->sbuf, "/"))
639 strlcat(c->sbuf, "/", sizeof(c->sbuf));
640 before_file = strchr(c->sbuf, '\0');
641 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
642 sizeof(c->sbuf));
643 if (len >= sizeof(c->sbuf)) {
644 start_reply(fds, c, TEMP_FAILURE, "internal server error");
645 return;
648 c->iri.path = c->sbuf;
650 /* close later unless we have to generate the dir listing */
651 dirfd = c->fd;
652 c->fd = -1;
654 switch (check_path(c, c->iri.path, &c->fd)) {
655 case FILE_EXECUTABLE:
656 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
657 start_cgi(c->iri.path, "", fds, c);
658 break;
661 /* fallthrough */
663 case FILE_EXISTS:
664 load_file(fds, c);
665 break;
667 case FILE_DIRECTORY:
668 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
669 break;
671 case FILE_MISSING:
672 *before_file = '\0';
674 if (!vhost_auto_index(c->host, c->iri.path)) {
675 start_reply(fds, c, NOT_FOUND, "not found");
676 break;
679 c->fd = dirfd;
680 c->next = enter_handle_dirlist;
682 if ((c->dir = fdopendir(c->fd)) == NULL) {
683 LOGE(c, "can't fdopendir(%d) (vhost:%s) %s: %s",
684 c->fd, c->host->domain, c->iri.path, strerror(errno));
685 start_reply(fds, c, TEMP_FAILURE, "internal server error");
686 return;
688 c->off = 0;
690 start_reply(fds, c, SUCCESS, "text/gemini");
691 return;
693 default:
694 /* unreachable */
695 abort();
698 close(dirfd);
701 static void
702 redirect_canonical_dir(struct pollfd *fds, struct client *c)
704 size_t len;
706 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
707 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
708 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
710 if (len >= sizeof(c->sbuf)) {
711 start_reply(fds, c, TEMP_FAILURE, "internal server error");
712 return;
715 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
718 static void
719 enter_handle_dirlist(struct pollfd *fds, struct client *c)
721 char b[PATH_MAX];
722 size_t l;
724 strlcpy(b, c->iri.path, sizeof(b));
725 l = snprintf(c->sbuf, sizeof(c->sbuf),
726 "# Index of %s\n\n", b);
727 if (l >= sizeof(c->sbuf)) {
728 /* this is impossible, given that we have enough space
729 * in c->sbuf to hold the ancilliary string plus the
730 * full path; but it wouldn't read nice without some
731 * error checking, and I'd like to avoid a strlen. */
732 close_conn(fds, c);
733 return;
735 c->len = l;
737 c->state = handle_dirlist;
738 handle_dirlist(fds, c);
741 static void
742 handle_dirlist(struct pollfd *fds, struct client *c)
744 ssize_t r;
746 while (c->len > 0) {
747 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
748 case -1:
749 close_conn(fds, c);
750 return;
751 case TLS_WANT_POLLOUT:
752 fds->events = POLLOUT;
753 return;
754 case TLS_WANT_POLLIN:
755 fds->events = POLLIN;
756 return;
757 default:
758 c->off += r;
759 c->len -= r;
763 c->state = send_directory_listing;
764 send_directory_listing(fds, c);
767 static int
768 read_next_dir_entry(struct client *c)
770 struct dirent *d;
772 do {
773 errno = 0;
774 if ((d = readdir(c->dir)) == NULL) {
775 if (errno != 0)
776 LOGE(c, "readdir: %s", strerror(errno));
777 return 0;
779 } while (!strcmp(d->d_name, "."));
781 /* XXX: url escape */
782 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
783 d->d_name, d->d_name);
784 c->len = strlen(c->sbuf);
785 c->off = 0;
787 return 1;
790 static void
791 send_directory_listing(struct pollfd *fds, struct client *c)
793 ssize_t r;
795 while (1) {
796 if (c->len == 0) {
797 if (!read_next_dir_entry(c))
798 goto end;
801 while (c->len > 0) {
802 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
803 case -1:
804 goto end;
806 case TLS_WANT_POLLOUT:
807 fds->events = POLLOUT;
808 return;
810 case TLS_WANT_POLLIN:
811 fds->events = POLLIN;
812 return;
814 default:
815 c->off += r;
816 c->len -= r;
817 break;
822 end:
823 close_conn(fds, c);
826 static inline void
827 cgi_poll_on_child(struct pollfd *fds, struct client *c)
829 int fd;
831 if (c->waiting_on_child)
832 return;
833 c->waiting_on_child = 1;
835 fds->events = POLLIN;
837 fd = fds->fd;
838 fds->fd = c->fd;
839 c->fd = fd;
842 static inline void
843 cgi_poll_on_client(struct pollfd *fds, struct client *c)
845 int fd;
847 if (!c->waiting_on_child)
848 return;
849 c->waiting_on_child = 0;
851 fd = fds->fd;
852 fds->fd = c->fd;
853 c->fd = fd;
856 /* accumulate the meta line from the cgi script. */
857 static void
858 handle_cgi_reply(struct pollfd *fds, struct client *c)
860 void *buf, *e;
861 size_t len;
862 ssize_t r;
864 buf = c->sbuf + c->len;
865 len = sizeof(c->sbuf) - c->len;
867 /* we're polling on the child! */
868 r = read(fds->fd, buf, len);
869 if (r == 0 || r == -1) {
870 cgi_poll_on_client(fds, c);
871 start_reply(fds, c, CGI_ERROR, "CGI error");
872 return;
875 c->len += r;
877 /* TODO: error if the CGI script don't reply correctly */
878 e = strchr(c->sbuf, '\n');
879 if (e != NULL || c->len == sizeof(c->sbuf)) {
880 log_request(c, c->sbuf, c->len);
882 c->off = 0;
883 c->state = handle_cgi;
884 c->state(fds, c);
885 return;
889 static void
890 handle_cgi(struct pollfd *fds, struct client *c)
892 ssize_t r;
894 /* ensure c->fd is the child and fds->fd the client */
895 cgi_poll_on_client(fds, c);
897 while (1) {
898 if (c->len == 0) {
899 switch (r = read(c->fd, c->sbuf, sizeof(c->sbuf))) {
900 case 0:
901 goto end;
902 case -1:
903 if (errno == EAGAIN || errno == EWOULDBLOCK) {
904 cgi_poll_on_child(fds, c);
905 return;
907 goto end;
908 default:
909 c->len = r;
910 c->off = 0;
914 while (c->len > 0) {
915 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
916 case -1:
917 goto end;
919 case TLS_WANT_POLLOUT:
920 fds->events = POLLOUT;
921 return;
923 case TLS_WANT_POLLIN:
924 fds->events = POLLIN;
925 return;
927 default:
928 c->off += r;
929 c->len -= r;
930 break;
935 end:
936 close_conn(fds, c);
939 static void
940 close_conn(struct pollfd *pfd, struct client *c)
942 c->state = close_conn;
944 switch (tls_close(c->ctx)) {
945 case TLS_WANT_POLLIN:
946 pfd->events = POLLIN;
947 return;
948 case TLS_WANT_POLLOUT:
949 pfd->events = POLLOUT;
950 return;
953 connected_clients--;
955 tls_free(c->ctx);
956 c->ctx = NULL;
958 if (c->buf != MAP_FAILED)
959 munmap(c->buf, c->len);
961 if (c->fd != -1)
962 close(c->fd);
964 if (c->dir != NULL)
965 closedir(c->dir);
967 close(pfd->fd);
968 pfd->fd = -1;
971 static void
972 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
974 int i, fd;
975 struct sockaddr_storage addr;
976 socklen_t len;
978 len = sizeof(addr);
979 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
980 if (errno == EWOULDBLOCK)
981 return;
982 fatal("accept: %s", strerror(errno));
985 mark_nonblock(fd);
987 for (i = 0; i < MAX_USERS; ++i) {
988 if (fds[i].fd == -1) {
989 bzero(&clients[i], sizeof(struct client));
990 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
991 break; /* goodbye fd! */
993 fds[i].fd = fd;
994 fds[i].events = POLLIN;
996 clients[i].state = handle_handshake;
997 clients[i].next = send_file;
998 clients[i].fd = -1;
999 clients[i].waiting_on_child = 0;
1000 clients[i].buf = MAP_FAILED;
1001 clients[i].dir = NULL;
1002 clients[i].addr = addr;
1004 connected_clients++;
1005 return;
1009 close(fd);
1012 void
1013 loop(struct tls *ctx, int sock4, int sock6)
1015 int i, n;
1016 struct client clients[MAX_USERS];
1017 struct pollfd fds[MAX_USERS];
1019 for (i = 0; i < MAX_USERS; ++i) {
1020 fds[i].fd = -1;
1021 fds[i].events = POLLIN;
1022 bzero(&clients[i], sizeof(struct client));
1025 fds[0].fd = sock4;
1026 fds[1].fd = sock6;
1028 for (;;) {
1029 if ((n = poll(fds, MAX_USERS, INFTIM)) == -1) {
1030 if (errno == EINTR) {
1031 fprintf(stderr, "connected clients: %d\n",
1032 connected_clients);
1033 } else
1034 fatal("poll: %s", strerror(errno));
1037 for (i = 0; i < MAX_USERS && n > 0; i++) {
1038 if (fds[i].revents == 0)
1039 continue;
1041 if (fds[i].revents & (POLLERR|POLLNVAL))
1042 fatal("bad fd %d: %s", fds[i].fd,
1043 strerror(errno));
1045 n--;
1047 if (fds[i].revents & POLLHUP) {
1048 /* fds[i] may be the fd of the stdin
1049 * of a cgi script that has exited. */
1050 if (!clients[i].waiting_on_child) {
1051 close_conn(&fds[i], &clients[i]);
1052 continue;
1056 if (fds[i].fd == sock4)
1057 do_accept(sock4, ctx, fds, clients);
1058 else if (fds[i].fd == sock6)
1059 do_accept(sock6, ctx, fds, clients);
1060 else
1061 clients[i].state(&fds[i], &clients[i]);
1064 if (hupped) {
1065 if (connected_clients == 0)
1066 return;
1068 fds[0].fd = -1;
1069 if (sock6 != -1)
1070 fds[1].fd = -1;