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 int e;
555 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
556 addr, sizeof(addr),
557 NULL, 0,
558 NI_NUMERICHOST);
559 if (e != 0)
560 goto err;
562 if (!send_iri(exfd, &c->iri)
563 || !send_string(exfd, spath)
564 || !send_string(exfd, relpath)
565 || !send_string(exfd, addr)
566 || !send_string(exfd, tls_peer_cert_subject(c->ctx))
567 || !send_string(exfd, tls_peer_cert_issuer(c->ctx))
568 || !send_string(exfd, tls_peer_cert_hash(c->ctx))
569 || !send_time(exfd, tls_peer_cert_notbefore(c->ctx))
570 || !send_time(exfd, tls_peer_cert_notafter(c->ctx))
571 || !send_vhost(exfd, c->host))
572 goto err;
574 close(c->fd);
575 if ((c->fd = recv_fd(exfd)) == -1) {
576 start_reply(fds, c, TEMP_FAILURE, "internal server error");
577 return;
580 cgi_poll_on_child(fds, c);
581 c->state = handle_cgi_reply;
582 return;
584 err:
585 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
586 fatal("cannot talk to the executor process");
589 static void
590 send_file(struct pollfd *fds, struct client *c)
592 ssize_t ret, len;
594 len = (c->buf + c->len) - c->i;
596 while (len > 0) {
597 switch (ret = tls_write(c->ctx, c->i, len)) {
598 case -1:
599 log_err(c, "tls_write: %s", tls_error(c->ctx));
600 close_conn(fds, c);
601 return;
603 case TLS_WANT_POLLIN:
604 fds->events = POLLIN;
605 return;
607 case TLS_WANT_POLLOUT:
608 fds->events = POLLOUT;
609 return;
611 default:
612 c->i += ret;
613 len -= ret;
614 break;
618 close_conn(fds, c);
621 static void
622 open_dir(struct pollfd *fds, struct client *c)
624 size_t len;
625 int dirfd;
626 char *before_file;
628 len = strlen(c->iri.path);
629 if (len > 0 && !ends_with(c->iri.path, "/")) {
630 redirect_canonical_dir(fds, c);
631 return;
634 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
635 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
636 if (!ends_with(c->sbuf, "/"))
637 strlcat(c->sbuf, "/", sizeof(c->sbuf));
638 before_file = strchr(c->sbuf, '\0');
639 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
640 sizeof(c->sbuf));
641 if (len >= sizeof(c->sbuf)) {
642 start_reply(fds, c, TEMP_FAILURE, "internal server error");
643 return;
646 c->iri.path = c->sbuf;
648 /* close later unless we have to generate the dir listing */
649 dirfd = c->fd;
650 c->fd = -1;
652 switch (check_path(c, c->iri.path, &c->fd)) {
653 case FILE_EXECUTABLE:
654 if (c->host->cgi != NULL && !fnmatch(c->host->cgi, c->iri.path, 0)) {
655 start_cgi(c->iri.path, "", fds, c);
656 break;
659 /* fallthrough */
661 case FILE_EXISTS:
662 load_file(fds, c);
663 break;
665 case FILE_DIRECTORY:
666 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
667 break;
669 case FILE_MISSING:
670 *before_file = '\0';
672 if (!vhost_auto_index(c->host, c->iri.path)) {
673 start_reply(fds, c, NOT_FOUND, "not found");
674 break;
677 c->fd = dirfd;
678 c->next = enter_handle_dirlist;
680 if ((c->dir = fdopendir(c->fd)) == NULL) {
681 log_err(c, "fdopendir(%d) (vhost:%s) %s: %s",
682 c->fd, c->host->domain, c->iri.path, strerror(errno));
683 start_reply(fds, c, TEMP_FAILURE, "internal server error");
684 return;
686 c->off = 0;
688 start_reply(fds, c, SUCCESS, "text/gemini");
689 return;
691 default:
692 /* unreachable */
693 abort();
696 close(dirfd);
699 static void
700 redirect_canonical_dir(struct pollfd *fds, struct client *c)
702 size_t len;
704 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
705 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
706 len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
708 if (len >= sizeof(c->sbuf)) {
709 start_reply(fds, c, TEMP_FAILURE, "internal server error");
710 return;
713 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
716 static void
717 enter_handle_dirlist(struct pollfd *fds, struct client *c)
719 char b[PATH_MAX];
720 size_t l;
722 strlcpy(b, c->iri.path, sizeof(b));
723 l = snprintf(c->sbuf, sizeof(c->sbuf),
724 "# Index of %s\n\n", b);
725 if (l >= sizeof(c->sbuf)) {
726 /* this is impossible, given that we have enough space
727 * in c->sbuf to hold the ancilliary string plus the
728 * full path; but it wouldn't read nice without some
729 * error checking, and I'd like to avoid a strlen. */
730 close_conn(fds, c);
731 return;
733 c->len = l;
735 c->state = handle_dirlist;
736 handle_dirlist(fds, c);
739 static void
740 handle_dirlist(struct pollfd *fds, struct client *c)
742 ssize_t r;
744 while (c->len > 0) {
745 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
746 case -1:
747 close_conn(fds, c);
748 return;
749 case TLS_WANT_POLLOUT:
750 fds->events = POLLOUT;
751 return;
752 case TLS_WANT_POLLIN:
753 fds->events = POLLIN;
754 return;
755 default:
756 c->off += r;
757 c->len -= r;
761 c->state = send_directory_listing;
762 send_directory_listing(fds, c);
765 static int
766 read_next_dir_entry(struct client *c)
768 struct dirent *d;
770 do {
771 errno = 0;
772 if ((d = readdir(c->dir)) == NULL) {
773 if (errno != 0)
774 log_err(c, "readdir: %s", strerror(errno));
775 return 0;
777 } while (!strcmp(d->d_name, "."));
779 /* XXX: url escape */
780 snprintf(c->sbuf, sizeof(c->sbuf), "=> %s %s\n",
781 d->d_name, d->d_name);
782 c->len = strlen(c->sbuf);
783 c->off = 0;
785 return 1;
788 static void
789 send_directory_listing(struct pollfd *fds, struct client *c)
791 ssize_t r;
793 while (1) {
794 if (c->len == 0) {
795 if (!read_next_dir_entry(c))
796 goto end;
799 while (c->len > 0) {
800 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
801 case -1:
802 goto end;
804 case TLS_WANT_POLLOUT:
805 fds->events = POLLOUT;
806 return;
808 case TLS_WANT_POLLIN:
809 fds->events = POLLIN;
810 return;
812 default:
813 c->off += r;
814 c->len -= r;
815 break;
820 end:
821 close_conn(fds, c);
824 static inline void
825 cgi_poll_on_child(struct pollfd *fds, struct client *c)
827 int fd;
829 if (c->waiting_on_child)
830 return;
831 c->waiting_on_child = 1;
833 fds->events = POLLIN;
835 fd = fds->fd;
836 fds->fd = c->fd;
837 c->fd = fd;
840 static inline void
841 cgi_poll_on_client(struct pollfd *fds, struct client *c)
843 int fd;
845 if (!c->waiting_on_child)
846 return;
847 c->waiting_on_child = 0;
849 fd = fds->fd;
850 fds->fd = c->fd;
851 c->fd = fd;
854 /* accumulate the meta line from the cgi script. */
855 static void
856 handle_cgi_reply(struct pollfd *fds, struct client *c)
858 void *buf, *e;
859 size_t len;
860 ssize_t r;
862 buf = c->sbuf + c->len;
863 len = sizeof(c->sbuf) - c->len;
865 /* we're polling on the child! */
866 r = read(fds->fd, buf, len);
867 if (r == 0 || r == -1) {
868 cgi_poll_on_client(fds, c);
869 start_reply(fds, c, CGI_ERROR, "CGI error");
870 return;
873 c->len += r;
875 /* TODO: error if the CGI script don't reply correctly */
876 e = strchr(c->sbuf, '\n');
877 if (e != NULL || c->len == sizeof(c->sbuf)) {
878 log_request(c, c->sbuf, c->len);
880 c->off = 0;
881 c->state = handle_cgi;
882 c->state(fds, c);
883 return;
887 static void
888 handle_cgi(struct pollfd *fds, struct client *c)
890 ssize_t r;
892 /* ensure c->fd is the child and fds->fd the client */
893 cgi_poll_on_client(fds, c);
895 while (1) {
896 if (c->len == 0) {
897 switch (r = read(c->fd, c->sbuf, sizeof(c->sbuf))) {
898 case 0:
899 goto end;
900 case -1:
901 if (errno == EAGAIN || errno == EWOULDBLOCK) {
902 cgi_poll_on_child(fds, c);
903 return;
905 goto end;
906 default:
907 c->len = r;
908 c->off = 0;
912 while (c->len > 0) {
913 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
914 case -1:
915 goto end;
917 case TLS_WANT_POLLOUT:
918 fds->events = POLLOUT;
919 return;
921 case TLS_WANT_POLLIN:
922 fds->events = POLLIN;
923 return;
925 default:
926 c->off += r;
927 c->len -= r;
928 break;
933 end:
934 close_conn(fds, c);
937 static void
938 close_conn(struct pollfd *pfd, struct client *c)
940 c->state = close_conn;
942 switch (tls_close(c->ctx)) {
943 case TLS_WANT_POLLIN:
944 pfd->events = POLLIN;
945 return;
946 case TLS_WANT_POLLOUT:
947 pfd->events = POLLOUT;
948 return;
951 connected_clients--;
953 tls_free(c->ctx);
954 c->ctx = NULL;
956 if (c->buf != MAP_FAILED)
957 munmap(c->buf, c->len);
959 if (c->fd != -1)
960 close(c->fd);
962 if (c->dir != NULL)
963 closedir(c->dir);
965 close(pfd->fd);
966 pfd->fd = -1;
969 static void
970 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
972 int i, fd;
973 struct sockaddr_storage addr;
974 socklen_t len;
976 len = sizeof(addr);
977 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
978 if (errno == EWOULDBLOCK || errno == EAGAIN)
979 return;
980 fatal("accept: %s", strerror(errno));
983 mark_nonblock(fd);
985 for (i = 0; i < MAX_USERS; ++i) {
986 if (fds[i].fd == -1) {
987 bzero(&clients[i], sizeof(struct client));
988 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
989 break; /* goodbye fd! */
991 fds[i].fd = fd;
992 fds[i].events = POLLIN;
994 clients[i].state = handle_handshake;
995 clients[i].next = send_file;
996 clients[i].fd = -1;
997 clients[i].waiting_on_child = 0;
998 clients[i].buf = MAP_FAILED;
999 clients[i].dir = NULL;
1000 clients[i].addr = addr;
1002 connected_clients++;
1003 return;
1007 close(fd);
1010 void
1011 loop(struct tls *ctx, int sock4, int sock6)
1013 int i, n;
1014 struct client clients[MAX_USERS];
1015 struct pollfd fds[MAX_USERS];
1017 for (i = 0; i < MAX_USERS; ++i) {
1018 fds[i].fd = -1;
1019 fds[i].events = POLLIN;
1020 bzero(&clients[i], sizeof(struct client));
1023 fds[0].fd = sock4;
1024 fds[1].fd = sock6;
1026 for (;;) {
1027 if ((n = poll(fds, MAX_USERS, INFTIM)) == -1) {
1028 if (errno == EINTR) {
1029 log_info(NULL, "%d connected clients",
1030 connected_clients);
1031 } else
1032 fatal("poll: %s", strerror(errno));
1035 for (i = 0; i < MAX_USERS && n > 0; i++) {
1036 if (fds[i].revents == 0)
1037 continue;
1039 if (fds[i].revents & (POLLERR|POLLNVAL))
1040 fatal("bad fd %d: %s", fds[i].fd,
1041 strerror(errno));
1043 n--;
1045 if (fds[i].revents & POLLHUP) {
1046 /* fds[i] may be the fd of the stdin
1047 * of a cgi script that has exited. */
1048 if (!clients[i].waiting_on_child) {
1049 close_conn(&fds[i], &clients[i]);
1050 continue;
1054 if (fds[i].fd == sock4)
1055 do_accept(sock4, ctx, fds, clients);
1056 else if (fds[i].fd == sock6)
1057 do_accept(sock6, ctx, fds, clients);
1058 else
1059 clients[i].state(&fds[i], &clients[i]);
1062 if (hupped) {
1063 if (connected_clients == 0)
1064 return;
1066 fds[0].fd = -1;
1067 if (sock6 != -1)
1068 fds[1].fd = -1;