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.
29 int connected_clients;
32 check_path(struct client *c, const char *path, int *fd)
37 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
38 O_RDONLY | O_NOFOLLOW)) == -1) {
42 if (fstat(*fd, &sb) == -1) {
43 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
47 if (S_ISDIR(sb.st_mode))
48 return FILE_DIRECTORY;
50 if (sb.st_mode & S_IXUSR)
51 return FILE_EXECUTABLE;
57 open_file(struct pollfd *fds, struct client *c)
59 switch (check_path(c, c->iri.path, &c->fd)) {
61 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi))
62 return start_cgi(c->iri.path, "", c->iri.query, fds, c);
67 if ((c->len = filesize(c->fd)) == -1) {
68 LOGE(c, "failed to get file size for %s", c->iri.path);
73 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
74 c->fd, 0)) == MAP_FAILED) {
75 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
80 if (!start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path)))
92 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi))
93 return check_for_cgi(c->iri.path, c->iri.query, fds, c);
95 if (!start_reply(fds, c, NOT_FOUND, "not found"))
108 * the inverse of this algorithm, i.e. starting from the start of the
109 * path + strlen(cgi), and checking if each component, should be
110 * faster. But it's tedious to write. This does the opposite: starts
111 * from the end and strip one component at a time, until either an
112 * executable is found or we emptied the path.
115 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
118 end = strchr(path, '\0');
120 /* NB: assume CGI is enabled and path matches cgi */
123 /* go up one level. UNIX paths are simple and POSIX
124 * dirname, with its ambiguities on if the given path
125 * is changed or not, gives me headaches. */
130 switch (check_path(c, path, &c->fd)) {
131 case FILE_EXECUTABLE:
132 return start_cgi(path, end+1, query, fds,c);
144 if (!start_reply(fds, c, NOT_FOUND, "not found"))
151 mark_nonblock(int fd)
155 if ((flags = fcntl(fd, F_GETFL)) == -1)
156 fatal("fcntl(F_GETFL): %s", strerror(errno));
157 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
158 fatal("fcntl(F_SETFL): %s", strerror(errno));
162 handle_handshake(struct pollfd *fds, struct client *c)
165 const char *servname;
167 switch (tls_handshake(c->ctx)) {
168 case 0: /* success */
169 case -1: /* already handshaked */
171 case TLS_WANT_POLLIN:
172 fds->events = POLLIN;
174 case TLS_WANT_POLLOUT:
175 fds->events = POLLOUT;
182 servname = tls_conn_servername(c->ctx);
183 if (servname == NULL)
186 for (h = hosts; h->domain != NULL; ++h) {
187 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
191 if (h->domain != NULL) {
194 handle_open_conn(fds, c);
199 /* XXX: check the correct response */
200 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
206 handle_open_conn(struct pollfd *fds, struct client *c)
208 const char *parse_err = "invalid request";
210 bzero(c->req, sizeof(c->req));
211 bzero(&c->iri, sizeof(c->iri));
213 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
215 LOGE(c, "tls_read: %s", tls_error(c->ctx));
219 case TLS_WANT_POLLIN:
220 fds->events = POLLIN;
223 case TLS_WANT_POLLOUT:
224 fds->events = POLLOUT;
228 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
229 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
235 /* XXX: we should check that the SNI matches the requested host */
236 if (strcmp(c->iri.schema, "gemini") || c->iri.port_no != conf.port) {
237 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
247 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
249 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
254 c->state = S_INITIALIZING;
256 snprintf(buf, sizeof(buf), "%d ", code);
257 strlcat(buf, meta, sizeof(buf));
258 if (!strcmp(meta, "text/gemini") && c->host->lang != NULL) {
259 strlcat(buf, "; lang=", sizeof(buf));
260 strlcat(buf, c->host->lang, sizeof(buf));
263 len = strlcat(buf, "\r\n", sizeof(buf));
264 assert(len < sizeof(buf));
266 switch (tls_write(c->ctx, buf, len)) {
267 case TLS_WANT_POLLIN:
268 pfd->events = POLLIN;
270 case TLS_WANT_POLLOUT:
271 pfd->events = POLLOUT;
274 log_request(c, buf, sizeof(buf));
280 start_cgi(const char *spath, const char *relpath, const char *query,
281 struct pollfd *fds, struct client *c)
283 char addr[NI_MAXHOST];
284 const char *ruser, *cissuer, *chash;
287 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
294 if (tls_peer_cert_provided(c->ctx)) {
295 ruser = tls_peer_cert_subject(c->ctx);
296 cissuer = tls_peer_cert_issuer(c->ctx);
297 chash = tls_peer_cert_hash(c->ctx);
304 if (!send_string(exfd, spath)
305 || !send_string(exfd, relpath)
306 || !send_string(exfd, query)
307 || !send_string(exfd, addr)
308 || !send_string(exfd, ruser)
309 || !send_string(exfd, cissuer)
310 || !send_string(exfd, chash)
311 || !send_vhost(exfd, c->host))
315 if ((c->fd = recv_fd(exfd)) == -1) {
316 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
322 c->state = S_SENDING;
323 cgi_poll_on_child(fds, c);
325 /* handle_cgi(fds, c); */
329 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
330 fatal("cannot talk to the executor process");
334 send_file(struct pollfd *fds, struct client *c)
338 len = (c->buf + c->len) - c->i;
341 switch (ret = tls_write(c->ctx, c->i, len)) {
343 LOGE(c, "tls_write: %s", tls_error(c->ctx));
347 case TLS_WANT_POLLIN:
348 fds->events = POLLIN;
351 case TLS_WANT_POLLOUT:
352 fds->events = POLLOUT;
366 send_dir(struct pollfd *fds, struct client *c)
370 /* guard against a re-entrant call:
372 * open_file -> send_dir -> open_file -> send_dir
374 * this can happen only if:
376 * - user requested a dir, say foo/
377 * - we try to serve foo/index.gmi
378 * - foo/index.gmi is a directory.
380 * It's an unlikely case, but can happen. We then redirect
383 if (c->iri.path == c->sbuf) {
384 if (!start_reply(fds, c, TEMP_REDIRECT, c->sbuf))
390 len = strlen(c->iri.path);
391 if (len > 0 && c->iri.path[len-1] != '/') {
392 /* redirect to url with the trailing / */
393 strlcpy(c->sbuf, c->iri.path, sizeof(c->sbuf));
394 strlcat(c->sbuf, "/", sizeof(c->sbuf));
395 if (!start_reply(fds, c, TEMP_REDIRECT, c->sbuf))
401 strlcpy(c->sbuf, c->iri.path, sizeof(c->sbuf));
403 strlcat(c->sbuf, "/", sizeof(c->sbuf));
404 len = strlcat(c->sbuf, "index.gmi", sizeof(c->sbuf));
406 if (len >= sizeof(c->sbuf)) {
407 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
414 c->iri.path = c->sbuf;
419 cgi_poll_on_child(struct pollfd *fds, struct client *c)
423 if (c->waiting_on_child)
425 c->waiting_on_child = 1;
427 fds->events = POLLIN;
435 cgi_poll_on_client(struct pollfd *fds, struct client *c)
439 if (!c->waiting_on_child)
441 c->waiting_on_child = 0;
449 handle_cgi(struct pollfd *fds, struct client *c)
453 /* ensure c->fd is the child and fds->fd the client */
454 cgi_poll_on_client(fds, c);
458 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
461 if (errno == EAGAIN || errno == EWOULDBLOCK) {
462 cgi_poll_on_child(fds, c);
470 /* XXX: if we haven't still read a whole
471 * reply line, we should go back to poll! */
474 log_request(c, c->sbuf, sizeof(c->sbuf));
479 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
483 case TLS_WANT_POLLOUT:
484 fds->events = POLLOUT;
487 case TLS_WANT_POLLIN:
488 fds->events = POLLIN;
504 goodbye(struct pollfd *pfd, struct client *c)
506 c->state = S_CLOSING;
508 switch (tls_close(c->ctx)) {
509 case TLS_WANT_POLLIN:
510 pfd->events = POLLIN;
512 case TLS_WANT_POLLOUT:
513 pfd->events = POLLOUT;
522 if (c->buf != MAP_FAILED)
523 munmap(c->buf, c->len);
533 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
536 struct sockaddr_storage addr;
540 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
541 if (errno == EWOULDBLOCK)
543 fatal("accept: %s", strerror(errno));
548 for (i = 0; i < MAX_USERS; ++i) {
549 if (fds[i].fd == -1) {
550 bzero(&clients[i], sizeof(struct client));
551 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
552 break; /* goodbye fd! */
555 fds[i].events = POLLIN;
557 clients[i].state = S_HANDSHAKE;
559 clients[i].child = 0;
560 clients[i].waiting_on_child = 0;
561 clients[i].buf = MAP_FAILED;
562 clients[i].addr = addr;
573 handle(struct pollfd *fds, struct client *client)
575 switch (client->state) {
577 handle_handshake(fds, client);
581 handle_open_conn(fds, client);
585 if (!start_reply(fds, client, client->code, client->meta))
588 if (client->code != SUCCESS) {
589 /* we don't need a body */
590 goodbye(fds, client);
594 client->state = S_SENDING;
600 handle_cgi(fds, client);
602 send_file(fds, client);
606 goodbye(fds, client);
616 loop(struct tls *ctx, int sock4, int sock6)
619 struct client clients[MAX_USERS];
620 struct pollfd fds[MAX_USERS];
622 connected_clients = 0;
624 for (i = 0; i < MAX_USERS; ++i) {
626 fds[i].events = POLLIN;
627 bzero(&clients[i], sizeof(struct client));
634 if (poll(fds, MAX_USERS, INFTIM) == -1) {
635 if (errno == EINTR) {
636 fprintf(stderr, "connected clients: %d\n",
640 fatal("poll: %s", strerror(errno));
643 for (i = 0; i < MAX_USERS; i++) {
644 if (fds[i].revents == 0)
647 if (fds[i].revents & (POLLERR|POLLNVAL))
648 fatal("bad fd %d: %s", fds[i].fd,
651 if (fds[i].revents & POLLHUP) {
652 /* fds[i] may be the fd of the stdin
653 * of a cgi script that has exited. */
654 if (!clients[i].waiting_on_child) {
655 goodbye(&fds[i], &clients[i]);
660 if (fds[i].fd == sock4)
661 do_accept(sock4, ctx, fds, clients);
662 else if (fds[i].fd == sock6)
663 do_accept(sock6, ctx, fds, clients);
665 handle(&fds[i], &clients[i]);