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(char *fpath, char *query, struct pollfd *fds, struct client *c)
60 switch (check_path(c, fpath, &c->fd)) {
62 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
63 return start_cgi(fpath, "", query, fds, c);
68 if ((c->len = filesize(c->fd)) == -1) {
69 LOGE(c, "failed to get file size for %s", fpath);
74 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
75 c->fd, 0)) == MAP_FAILED) {
76 warn("mmap: %s", fpath);
81 return start_reply(fds, c, SUCCESS, mime(fpath));
84 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
87 send_dir(fpath, fds, c);
91 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
92 return check_for_cgi(fpath, query, fds, c);
94 if (!start_reply(fds, c, NOT_FOUND, "not found"))
107 * the inverse of this algorithm, i.e. starting from the start of the
108 * path + strlen(cgi), and checking if each component, should be
109 * faster. But it's tedious to write. This does the opposite: starts
110 * from the end and strip one component at a time, until either an
111 * executable is found or we emptied the path.
114 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
117 end = strchr(path, '\0');
119 /* NB: assume CGI is enabled and path matches cgi */
122 /* go up one level. UNIX paths are simple and POSIX
123 * dirname, with its ambiguities on if the given path
124 * is changed or not, gives me headaches. */
129 switch (check_path(c, path, &c->fd)) {
130 case FILE_EXECUTABLE:
131 return start_cgi(path, end+1, query, fds,c);
143 if (!start_reply(fds, c, NOT_FOUND, "not found"))
150 mark_nonblock(int fd)
154 if ((flags = fcntl(fd, F_GETFL)) == -1)
155 fatal("fcntl(F_GETFL): %s", strerror(errno));
156 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
157 fatal("fcntl(F_SETFL): %s", strerror(errno));
161 handle_handshake(struct pollfd *fds, struct client *c)
164 const char *servname;
166 switch (tls_handshake(c->ctx)) {
167 case 0: /* success */
168 case -1: /* already handshaked */
170 case TLS_WANT_POLLIN:
171 fds->events = POLLIN;
173 case TLS_WANT_POLLOUT:
174 fds->events = POLLOUT;
181 servname = tls_conn_servername(c->ctx);
182 if (servname == NULL)
185 for (h = hosts; h->domain != NULL; ++h) {
186 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
190 if (h->domain != NULL) {
193 handle_open_conn(fds, c);
198 /* XXX: check the correct response */
199 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
205 handle_open_conn(struct pollfd *fds, struct client *c)
207 char buf[GEMINI_URL_LEN];
208 const char *parse_err = "invalid request";
211 bzero(buf, sizeof(buf));
213 switch (tls_read(c->ctx, buf, sizeof(buf)-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(buf) || !parse_iri(buf, &iri, &parse_err)) {
229 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
235 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
236 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
242 LOGI(c, "GET %s%s%s",
243 *iri.path ? iri.path : "/",
244 *iri.query ? "?" : "",
245 *iri.query ? iri.query : "");
247 send_file(iri.path, iri.query, fds, c);
251 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
253 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
257 client->meta = reason;
258 client->state = S_INITIALIZING;
260 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
261 assert(len < (int)sizeof(buf));
263 switch (tls_write(client->ctx, buf, len)) {
264 case TLS_WANT_POLLIN:
265 pfd->events = POLLIN;
267 case TLS_WANT_POLLOUT:
268 pfd->events = POLLOUT;
276 start_cgi(const char *spath, const char *relpath, const char *query,
277 struct pollfd *fds, struct client *c)
279 char addr[NI_MAXHOST];
280 const char *ruser, *cissuer, *chash;
283 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
290 if (tls_peer_cert_provided(c->ctx)) {
291 ruser = tls_peer_cert_subject(c->ctx);
292 cissuer = tls_peer_cert_issuer(c->ctx);
293 chash = tls_peer_cert_hash(c->ctx);
300 if (!send_string(exfd, spath)
301 || !send_string(exfd, relpath)
302 || !send_string(exfd, query)
303 || !send_string(exfd, addr)
304 || !send_string(exfd, ruser)
305 || !send_string(exfd, cissuer)
306 || !send_string(exfd, chash)
307 || !send_vhost(exfd, c->host))
311 if ((c->fd = recv_fd(exfd)) == -1) {
312 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
318 c->state = S_SENDING;
319 cgi_poll_on_child(fds, c);
320 /* handle_cgi(fds, c); */
324 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
325 err(1, "cannot talk to the executor process");
329 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
334 if (!open_file(path, query, fds, c))
336 c->state = S_SENDING;
339 len = (c->buf + c->len) - c->i;
342 switch (ret = tls_write(c->ctx, c->i, len)) {
344 LOGE(c, "tls_write: %s", tls_error(c->ctx));
348 case TLS_WANT_POLLIN:
349 fds->events = POLLIN;
352 case TLS_WANT_POLLOUT:
353 fds->events = POLLOUT;
367 send_dir(char *path, struct pollfd *fds, struct client *client)
372 bzero(fpath, PATHBUF);
377 /* this cannot fail since sizeof(fpath) > maxlen of path */
378 strlcat(fpath, path, PATHBUF);
381 /* add a trailing / in case. */
382 if (fpath[len-1] != '/') {
386 strlcat(fpath, "index.gmi", sizeof(fpath));
388 send_file(fpath, NULL, fds, client);
392 cgi_poll_on_child(struct pollfd *fds, struct client *c)
396 if (c->waiting_on_child)
398 c->waiting_on_child = 1;
400 fds->events = POLLIN;
408 cgi_poll_on_client(struct pollfd *fds, struct client *c)
412 if (!c->waiting_on_child)
414 c->waiting_on_child = 0;
422 handle_cgi(struct pollfd *fds, struct client *c)
426 /* ensure c->fd is the child and fds->fd the client */
427 cgi_poll_on_client(fds, c);
431 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
434 if (errno == EAGAIN || errno == EWOULDBLOCK) {
435 cgi_poll_on_child(fds, c);
445 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
449 case TLS_WANT_POLLOUT:
450 fds->events = POLLOUT;
453 case TLS_WANT_POLLIN:
454 fds->events = POLLIN;
470 goodbye(struct pollfd *pfd, struct client *c)
472 c->state = S_CLOSING;
474 switch (tls_close(c->ctx)) {
475 case TLS_WANT_POLLIN:
476 pfd->events = POLLIN;
478 case TLS_WANT_POLLOUT:
479 pfd->events = POLLOUT;
488 if (c->buf != MAP_FAILED)
489 munmap(c->buf, c->len);
499 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
502 struct sockaddr_storage addr;
506 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
507 if (errno == EWOULDBLOCK)
509 fatal("accept: %s", strerror(errno));
514 for (i = 0; i < MAX_USERS; ++i) {
515 if (fds[i].fd == -1) {
516 bzero(&clients[i], sizeof(struct client));
517 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
518 break; /* goodbye fd! */
521 fds[i].events = POLLIN;
523 clients[i].state = S_HANDSHAKE;
525 clients[i].child = 0;
526 clients[i].waiting_on_child = 0;
527 clients[i].buf = MAP_FAILED;
528 clients[i].af = AF_INET;
529 clients[i].addr = addr;
540 handle(struct pollfd *fds, struct client *client)
542 switch (client->state) {
544 handle_handshake(fds, client);
548 handle_open_conn(fds, client);
552 if (!start_reply(fds, client, client->code, client->meta))
555 if (client->code != SUCCESS) {
556 /* we don't need a body */
557 goodbye(fds, client);
561 client->state = S_SENDING;
567 handle_cgi(fds, client);
569 send_file(NULL, NULL, fds, client);
573 goodbye(fds, client);
583 loop(struct tls *ctx, int sock4, int sock6)
586 struct client clients[MAX_USERS];
587 struct pollfd fds[MAX_USERS];
589 connected_clients = 0;
591 for (i = 0; i < MAX_USERS; ++i) {
593 fds[i].events = POLLIN;
594 bzero(&clients[i], sizeof(struct client));
601 if (poll(fds, MAX_USERS, INFTIM) == -1) {
602 if (errno == EINTR) {
603 warnx("connected clients: %d",
607 fatal("poll: %s", strerror(errno));
610 for (i = 0; i < MAX_USERS; i++) {
611 if (fds[i].revents == 0)
614 if (fds[i].revents & (POLLERR|POLLNVAL))
615 fatal("bad fd %d: %s", fds[i].fd,
618 if (fds[i].revents & POLLHUP) {
619 /* fds[i] may be the fd of the stdin
620 * of a cgi script that has exited. */
621 if (!clients[i].waiting_on_child) {
622 goodbye(&fds[i], &clients[i]);
627 if (fds[i].fd == sock4)
628 do_accept(sock4, ctx, fds, clients);
629 else if (fds[i].fd == sock6)
630 do_accept(sock6, ctx, fds, clients);
632 handle(&fds[i], &clients[i]);