2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
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.
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.
30 int connected_clients;
33 check_path(struct client *c, const char *path, int *fd)
38 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
39 O_RDONLY | O_NOFOLLOW)) == -1) {
43 if (fstat(*fd, &sb) == -1) {
44 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
48 if (S_ISDIR(sb.st_mode))
49 return FILE_DIRECTORY;
51 if (sb.st_mode & S_IXUSR)
52 return FILE_EXECUTABLE;
58 open_file(struct pollfd *fds, struct client *c)
60 switch (check_path(c, c->iri.path, &c->fd)) {
62 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi))
63 return start_cgi(c->iri.path, "", c->iri.query, fds, c);
68 if ((c->len = filesize(c->fd)) == -1) {
69 LOGE(c, "failed to get file size for %s", c->iri.path);
74 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
75 c->fd, 0)) == MAP_FAILED) {
76 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
81 if (!start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path)))
93 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi))
94 return check_for_cgi(c->iri.path, c->iri.query, fds, c);
96 if (!start_reply(fds, c, NOT_FOUND, "not found"))
109 * the inverse of this algorithm, i.e. starting from the start of the
110 * path + strlen(cgi), and checking if each component, should be
111 * faster. But it's tedious to write. This does the opposite: starts
112 * from the end and strip one component at a time, until either an
113 * executable is found or we emptied the path.
116 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
119 end = strchr(path, '\0');
121 /* NB: assume CGI is enabled and path matches cgi */
124 /* go up one level. UNIX paths are simple and POSIX
125 * dirname, with its ambiguities on if the given path
126 * is changed or not, gives me headaches. */
131 switch (check_path(c, path, &c->fd)) {
132 case FILE_EXECUTABLE:
133 return start_cgi(path, end+1, query, fds,c);
145 if (!start_reply(fds, c, NOT_FOUND, "not found"))
152 mark_nonblock(int fd)
156 if ((flags = fcntl(fd, F_GETFL)) == -1)
157 fatal("fcntl(F_GETFL): %s", strerror(errno));
158 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
159 fatal("fcntl(F_SETFL): %s", strerror(errno));
163 handle_handshake(struct pollfd *fds, struct client *c)
166 const char *servname;
168 switch (tls_handshake(c->ctx)) {
169 case 0: /* success */
170 case -1: /* already handshaked */
172 case TLS_WANT_POLLIN:
173 fds->events = POLLIN;
175 case TLS_WANT_POLLOUT:
176 fds->events = POLLOUT;
183 servname = tls_conn_servername(c->ctx);
185 for (h = hosts; h->domain != NULL; ++h) {
186 if (!strcmp(h->domain, "*"))
189 if (servname != NULL && !fnmatch(h->domain, servname, 0))
193 if (h->domain != NULL) {
196 handle_open_conn(fds, c);
200 if (servname != NULL)
201 strncpy(c->req, servname, sizeof(c->req));
203 strncpy(c->req, "null", sizeof(c->req));
205 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
211 handle_open_conn(struct pollfd *fds, struct client *c)
213 const char *parse_err = "invalid request";
215 bzero(c->req, sizeof(c->req));
216 bzero(&c->iri, sizeof(c->iri));
218 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
220 LOGE(c, "tls_read: %s", tls_error(c->ctx));
224 case TLS_WANT_POLLIN:
225 fds->events = POLLIN;
228 case TLS_WANT_POLLOUT:
229 fds->events = POLLOUT;
233 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
234 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
240 /* XXX: we should check that the SNI matches the requested host */
241 if (strcmp(c->iri.schema, "gemini") || c->iri.port_no != conf.port) {
242 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
252 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
254 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
259 c->state = S_INITIALIZING;
261 snprintf(buf, sizeof(buf), "%d ", code);
262 strlcat(buf, meta, sizeof(buf));
263 if (!strcmp(meta, "text/gemini") && c->host->lang != NULL) {
264 strlcat(buf, "; lang=", sizeof(buf));
265 strlcat(buf, c->host->lang, sizeof(buf));
268 len = strlcat(buf, "\r\n", sizeof(buf));
269 assert(len < sizeof(buf));
271 switch (tls_write(c->ctx, buf, len)) {
272 case TLS_WANT_POLLIN:
273 pfd->events = POLLIN;
275 case TLS_WANT_POLLOUT:
276 pfd->events = POLLOUT;
279 log_request(c, buf, sizeof(buf));
285 start_cgi(const char *spath, const char *relpath, const char *query,
286 struct pollfd *fds, struct client *c)
288 char addr[NI_MAXHOST];
289 const char *ruser, *cissuer, *chash;
292 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
299 if (tls_peer_cert_provided(c->ctx)) {
300 ruser = tls_peer_cert_subject(c->ctx);
301 cissuer = tls_peer_cert_issuer(c->ctx);
302 chash = tls_peer_cert_hash(c->ctx);
309 if (!send_string(exfd, spath)
310 || !send_string(exfd, relpath)
311 || !send_string(exfd, query)
312 || !send_string(exfd, addr)
313 || !send_string(exfd, ruser)
314 || !send_string(exfd, cissuer)
315 || !send_string(exfd, chash)
316 || !send_vhost(exfd, c->host))
320 if ((c->fd = recv_fd(exfd)) == -1) {
321 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
327 c->state = S_SENDING;
328 cgi_poll_on_child(fds, c);
330 /* handle_cgi(fds, c); */
334 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
335 fatal("cannot talk to the executor process");
339 send_file(struct pollfd *fds, struct client *c)
343 len = (c->buf + c->len) - c->i;
346 switch (ret = tls_write(c->ctx, c->i, len)) {
348 LOGE(c, "tls_write: %s", tls_error(c->ctx));
352 case TLS_WANT_POLLIN:
353 fds->events = POLLIN;
356 case TLS_WANT_POLLOUT:
357 fds->events = POLLOUT;
371 send_dir(struct pollfd *fds, struct client *c)
375 /* guard against a re-entrant call:
377 * open_file -> send_dir -> open_file -> send_dir
379 * this can happen only if:
381 * - user requested a dir, say foo/
382 * - we try to serve foo/index.gmi
383 * - foo/index.gmi is a directory.
385 * It's an unlikely case, but can happen. We then redirect
388 if (c->iri.path == c->sbuf) {
389 if (!start_reply(fds, c, TEMP_REDIRECT, c->sbuf))
395 len = strlen(c->iri.path);
396 if (len > 0 && c->iri.path[len-1] != '/') {
397 /* redirect to url with the trailing / */
398 strlcpy(c->sbuf, c->iri.path, sizeof(c->sbuf));
399 strlcat(c->sbuf, "/", sizeof(c->sbuf));
400 if (!start_reply(fds, c, TEMP_REDIRECT, c->sbuf))
406 strlcpy(c->sbuf, c->iri.path, sizeof(c->sbuf));
408 strlcat(c->sbuf, "/", sizeof(c->sbuf));
409 len = strlcat(c->sbuf, "index.gmi", sizeof(c->sbuf));
411 if (len >= sizeof(c->sbuf)) {
412 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
419 c->iri.path = c->sbuf;
424 cgi_poll_on_child(struct pollfd *fds, struct client *c)
428 if (c->waiting_on_child)
430 c->waiting_on_child = 1;
432 fds->events = POLLIN;
440 cgi_poll_on_client(struct pollfd *fds, struct client *c)
444 if (!c->waiting_on_child)
446 c->waiting_on_child = 0;
454 handle_cgi(struct pollfd *fds, struct client *c)
458 /* ensure c->fd is the child and fds->fd the client */
459 cgi_poll_on_client(fds, c);
463 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
466 if (errno == EAGAIN || errno == EWOULDBLOCK) {
467 cgi_poll_on_child(fds, c);
475 /* XXX: if we haven't still read a whole
476 * reply line, we should go back to poll! */
479 log_request(c, c->sbuf, sizeof(c->sbuf));
484 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
488 case TLS_WANT_POLLOUT:
489 fds->events = POLLOUT;
492 case TLS_WANT_POLLIN:
493 fds->events = POLLIN;
509 goodbye(struct pollfd *pfd, struct client *c)
511 c->state = S_CLOSING;
513 switch (tls_close(c->ctx)) {
514 case TLS_WANT_POLLIN:
515 pfd->events = POLLIN;
517 case TLS_WANT_POLLOUT:
518 pfd->events = POLLOUT;
527 if (c->buf != MAP_FAILED)
528 munmap(c->buf, c->len);
538 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
541 struct sockaddr_storage addr;
545 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
546 if (errno == EWOULDBLOCK)
548 fatal("accept: %s", strerror(errno));
553 for (i = 0; i < MAX_USERS; ++i) {
554 if (fds[i].fd == -1) {
555 bzero(&clients[i], sizeof(struct client));
556 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
557 break; /* goodbye fd! */
560 fds[i].events = POLLIN;
562 clients[i].state = S_HANDSHAKE;
564 clients[i].child = 0;
565 clients[i].waiting_on_child = 0;
566 clients[i].buf = MAP_FAILED;
567 clients[i].addr = addr;
578 handle(struct pollfd *fds, struct client *client)
580 switch (client->state) {
582 handle_handshake(fds, client);
586 handle_open_conn(fds, client);
590 if (!start_reply(fds, client, client->code, client->meta))
593 if (client->code != SUCCESS) {
594 /* we don't need a body */
595 goodbye(fds, client);
599 client->state = S_SENDING;
605 handle_cgi(fds, client);
607 send_file(fds, client);
611 goodbye(fds, client);
621 loop(struct tls *ctx, int sock4, int sock6)
624 struct client clients[MAX_USERS];
625 struct pollfd fds[MAX_USERS];
627 connected_clients = 0;
629 for (i = 0; i < MAX_USERS; ++i) {
631 fds[i].events = POLLIN;
632 bzero(&clients[i], sizeof(struct client));
639 if (poll(fds, MAX_USERS, INFTIM) == -1) {
640 if (errno == EINTR) {
641 fprintf(stderr, "connected clients: %d\n",
645 fatal("poll: %s", strerror(errno));
648 for (i = 0; i < MAX_USERS; i++) {
649 if (fds[i].revents == 0)
652 if (fds[i].revents & (POLLERR|POLLNVAL))
653 fatal("bad fd %d: %s", fds[i].fd,
656 if (fds[i].revents & POLLHUP) {
657 /* fds[i] may be the fd of the stdin
658 * of a cgi script that has exited. */
659 if (!clients[i].waiting_on_child) {
660 goodbye(&fds[i], &clients[i]);
665 if (fds[i].fd == sock4)
666 do_accept(sock4, ctx, fds, clients);
667 else if (fds[i].fd == sock6)
668 do_accept(sock6, ctx, fds, clients);
670 handle(&fds[i], &clients[i]);