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)
42 else if (*path == '/')
43 /* in send_dir we add an initial / (to be
44 * redirect-friendly), but here we want to skip it */
49 if ((*fd = openat(c->host->dirfd, p, O_RDONLY | O_NOFOLLOW)) == -1) {
53 if (fstat(*fd, &sb) == -1) {
54 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
58 if (S_ISDIR(sb.st_mode))
59 return FILE_DIRECTORY;
61 if (sb.st_mode & S_IXUSR)
62 return FILE_EXECUTABLE;
68 open_file(struct pollfd *fds, struct client *c)
70 switch (check_path(c, c->iri.path, &c->fd)) {
72 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi))
73 return start_cgi(c->iri.path, "", c->iri.query, fds, c);
78 if ((c->len = filesize(c->fd)) == -1) {
79 LOGE(c, "failed to get file size for %s", c->iri.path);
84 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
85 c->fd, 0)) == MAP_FAILED) {
86 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
91 if (!start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path)))
103 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi))
104 return check_for_cgi(c->iri.path, c->iri.query, fds, c);
105 goodbye(fds, c, NOT_FOUND, "not found");
116 * the inverse of this algorithm, i.e. starting from the start of the
117 * path + strlen(cgi), and checking if each component, should be
118 * faster. But it's tedious to write. This does the opposite: starts
119 * from the end and strip one component at a time, until either an
120 * executable is found or we emptied the path.
123 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
126 end = strchr(path, '\0');
128 /* NB: assume CGI is enabled and path matches cgi */
131 /* go up one level. UNIX paths are simple and POSIX
132 * dirname, with its ambiguities on if the given path
133 * is changed or not, gives me headaches. */
138 switch (check_path(c, path, &c->fd)) {
139 case FILE_EXECUTABLE:
140 return start_cgi(path, end+1, query, fds,c);
152 goodbye(fds, c, NOT_FOUND, "not found");
157 mark_nonblock(int fd)
161 if ((flags = fcntl(fd, F_GETFL)) == -1)
162 fatal("fcntl(F_GETFL): %s", strerror(errno));
163 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
164 fatal("fcntl(F_SETFL): %s", strerror(errno));
168 handle_handshake(struct pollfd *fds, struct client *c)
171 const char *servname;
173 switch (tls_handshake(c->ctx)) {
174 case 0: /* success */
175 case -1: /* already handshaked */
177 case TLS_WANT_POLLIN:
178 fds->events = POLLIN;
180 case TLS_WANT_POLLOUT:
181 fds->events = POLLOUT;
188 servname = tls_conn_servername(c->ctx);
190 for (h = hosts; h->domain != NULL; ++h) {
191 if (!strcmp(h->domain, "*"))
194 if (servname != NULL && !fnmatch(h->domain, servname, 0))
198 if (h->domain != NULL) {
201 handle_open_conn(fds, c);
205 if (servname != NULL)
206 strncpy(c->req, servname, sizeof(c->req));
208 strncpy(c->req, "null", sizeof(c->req));
210 goodbye(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
214 handle_open_conn(struct pollfd *fds, struct client *c)
216 const char *parse_err = "invalid request";
218 bzero(c->req, sizeof(c->req));
219 bzero(&c->iri, sizeof(c->iri));
221 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
223 LOGE(c, "tls_read: %s", tls_error(c->ctx));
227 case TLS_WANT_POLLIN:
228 fds->events = POLLIN;
231 case TLS_WANT_POLLOUT:
232 fds->events = POLLOUT;
236 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
237 goodbye(fds, c, BAD_REQUEST, parse_err);
241 /* XXX: we should check that the SNI matches the requested host */
242 if (strcmp(c->iri.schema, "gemini") || c->iri.port_no != conf.port) {
243 goodbye(fds, c, PROXY_REFUSED, "won't proxy request");
251 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
253 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
258 c->state = S_INITIALIZING;
260 snprintf(buf, sizeof(buf), "%d ", code);
261 strlcat(buf, meta, sizeof(buf));
262 if (!strcmp(meta, "text/gemini") && c->host->lang != NULL) {
263 strlcat(buf, "; lang=", sizeof(buf));
264 strlcat(buf, c->host->lang, sizeof(buf));
267 len = strlcat(buf, "\r\n", sizeof(buf));
268 assert(len < sizeof(buf));
270 switch (tls_write(c->ctx, buf, len)) {
271 case TLS_WANT_POLLIN:
272 pfd->events = POLLIN;
274 case TLS_WANT_POLLOUT:
275 pfd->events = POLLOUT;
278 log_request(c, buf, sizeof(buf));
284 start_cgi(const char *spath, const char *relpath, const char *query,
285 struct pollfd *fds, struct client *c)
287 char addr[NI_MAXHOST];
288 const char *ruser, *cissuer, *chash;
291 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
298 if (tls_peer_cert_provided(c->ctx)) {
299 ruser = tls_peer_cert_subject(c->ctx);
300 cissuer = tls_peer_cert_issuer(c->ctx);
301 chash = tls_peer_cert_hash(c->ctx);
308 if (!send_string(exfd, spath)
309 || !send_string(exfd, relpath)
310 || !send_string(exfd, query)
311 || !send_string(exfd, addr)
312 || !send_string(exfd, ruser)
313 || !send_string(exfd, cissuer)
314 || !send_string(exfd, chash)
315 || !send_vhost(exfd, c->host))
319 if ((c->fd = recv_fd(exfd)) == -1) {
320 goodbye(fds, c, TEMP_FAILURE, "internal server error");
324 c->state = S_SENDING;
325 cgi_poll_on_child(fds, c);
327 /* handle_cgi(fds, c); */
331 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
332 fatal("cannot talk to the executor process");
336 send_file(struct pollfd *fds, struct client *c)
340 /* ensure the correct state */
341 c->state = S_SENDING;
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 goodbye(fds, c, TEMP_REDIRECT, c->sbuf);
393 strlcpy(c->sbuf, "/", sizeof(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 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
399 strlcat(c->sbuf, "/", sizeof(c->sbuf));
400 goodbye(fds, c, TEMP_REDIRECT, c->sbuf);
404 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
406 if (!ends_with(c->sbuf, "/"))
407 strlcat(c->sbuf, "/", sizeof(c->sbuf));
409 len = strlcat(c->sbuf, "index.gmi", sizeof(c->sbuf));
411 if (len >= sizeof(c->sbuf)) {
412 goodbye(fds, c, TEMP_FAILURE, "internal server error");
417 c->iri.path = c->sbuf;
422 cgi_poll_on_child(struct pollfd *fds, struct client *c)
426 if (c->waiting_on_child)
428 c->waiting_on_child = 1;
430 fds->events = POLLIN;
438 cgi_poll_on_client(struct pollfd *fds, struct client *c)
442 if (!c->waiting_on_child)
444 c->waiting_on_child = 0;
452 handle_cgi(struct pollfd *fds, struct client *c)
456 /* ensure c->fd is the child and fds->fd the client */
457 cgi_poll_on_client(fds, c);
461 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
464 if (errno == EAGAIN || errno == EWOULDBLOCK) {
465 cgi_poll_on_child(fds, c);
473 /* XXX: if we haven't still read a whole
474 * reply line, we should go back to poll! */
477 log_request(c, c->sbuf, sizeof(c->sbuf));
482 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
486 case TLS_WANT_POLLOUT:
487 fds->events = POLLOUT;
490 case TLS_WANT_POLLIN:
491 fds->events = POLLIN;
507 close_conn(struct pollfd *pfd, struct client *c)
509 c->state = S_CLOSING;
511 switch (tls_close(c->ctx)) {
512 case TLS_WANT_POLLIN:
513 pfd->events = POLLIN;
515 case TLS_WANT_POLLOUT:
516 pfd->events = POLLOUT;
525 if (c->buf != MAP_FAILED)
526 munmap(c->buf, c->len);
536 goodbye(struct pollfd *fds, struct client *c, int code, const char *meta)
538 if (!start_reply(fds, c, code, meta))
544 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
547 struct sockaddr_storage addr;
551 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
552 if (errno == EWOULDBLOCK)
554 fatal("accept: %s", strerror(errno));
559 for (i = 0; i < MAX_USERS; ++i) {
560 if (fds[i].fd == -1) {
561 bzero(&clients[i], sizeof(struct client));
562 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
563 break; /* goodbye fd! */
566 fds[i].events = POLLIN;
568 clients[i].state = S_HANDSHAKE;
570 clients[i].child = 0;
571 clients[i].waiting_on_child = 0;
572 clients[i].buf = MAP_FAILED;
573 clients[i].addr = addr;
584 handle(struct pollfd *fds, struct client *client)
586 switch (client->state) {
588 handle_handshake(fds, client);
592 handle_open_conn(fds, client);
596 if (!start_reply(fds, client, client->code, client->meta))
599 if (client->code != SUCCESS) {
600 /* we don't need a body */
601 close_conn(fds, client);
605 client->state = S_SENDING;
611 handle_cgi(fds, client);
613 send_file(fds, client);
617 close_conn(fds, client);
627 loop(struct tls *ctx, int sock4, int sock6)
630 struct client clients[MAX_USERS];
631 struct pollfd fds[MAX_USERS];
633 connected_clients = 0;
635 for (i = 0; i < MAX_USERS; ++i) {
637 fds[i].events = POLLIN;
638 bzero(&clients[i], sizeof(struct client));
645 if (poll(fds, MAX_USERS, INFTIM) == -1) {
646 if (errno == EINTR) {
647 fprintf(stderr, "connected clients: %d\n",
651 fatal("poll: %s", strerror(errno));
654 for (i = 0; i < MAX_USERS; i++) {
655 if (fds[i].revents == 0)
658 if (fds[i].revents & (POLLERR|POLLNVAL))
659 fatal("bad fd %d: %s", fds[i].fd,
662 if (fds[i].revents & POLLHUP) {
663 /* fds[i] may be the fd of the stdin
664 * of a cgi script that has exited. */
665 if (!clients[i].waiting_on_child) {
666 close_conn(&fds[i], &clients[i]);
671 if (fds[i].fd == sock4)
672 do_accept(sock4, ctx, fds, clients);
673 else if (fds[i].fd == sock6)
674 do_accept(sock6, ctx, fds, clients);
676 handle(&fds[i], &clients[i]);