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 start_cgi(c->iri.path, "", c->iri.query, fds, c);
80 if ((c->len = filesize(c->fd)) == -1) {
81 LOGE(c, "failed to get file size for %s", c->iri.path);
86 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
87 c->fd, 0)) == MAP_FAILED) {
88 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
93 c->next = S_SENDING_FILE;
94 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
104 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
105 check_for_cgi(c->iri.path, c->iri.query, fds, c);
108 start_reply(fds, c, NOT_FOUND, "not found");
119 * the inverse of this algorithm, i.e. starting from the start of the
120 * path + strlen(cgi), and checking if each component, should be
121 * faster. But it's tedious to write. This does the opposite: starts
122 * from the end and strip one component at a time, until either an
123 * executable is found or we emptied the path.
126 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
129 end = strchr(path, '\0');
131 /* NB: assume CGI is enabled and path matches cgi */
134 /* go up one level. UNIX paths are simple and POSIX
135 * dirname, with its ambiguities on if the given path
136 * is changed or not, gives me headaches. */
141 switch (check_path(c, path, &c->fd)) {
142 case FILE_EXECUTABLE:
143 start_cgi(path, end+1, query, fds,c);
156 start_reply(fds, c, NOT_FOUND, "not found");
161 mark_nonblock(int fd)
165 if ((flags = fcntl(fd, F_GETFL)) == -1)
166 fatal("fcntl(F_GETFL): %s", strerror(errno));
167 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
168 fatal("fcntl(F_SETFL): %s", strerror(errno));
172 handle_handshake(struct pollfd *fds, struct client *c)
175 const char *servname;
177 switch (tls_handshake(c->ctx)) {
178 case 0: /* success */
179 case -1: /* already handshaked */
181 case TLS_WANT_POLLIN:
182 fds->events = POLLIN;
184 case TLS_WANT_POLLOUT:
185 fds->events = POLLOUT;
192 servname = tls_conn_servername(c->ctx);
194 for (h = hosts; h->domain != NULL; ++h) {
195 if (!strcmp(h->domain, "*"))
198 if (servname != NULL && !fnmatch(h->domain, servname, 0))
202 if (h->domain != NULL) {
205 handle_open_conn(fds, c);
209 if (servname != NULL)
210 strncpy(c->req, servname, sizeof(c->req));
212 strncpy(c->req, "null", sizeof(c->req));
214 start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
218 handle_open_conn(struct pollfd *fds, struct client *c)
220 const char *parse_err = "invalid request";
222 bzero(c->req, sizeof(c->req));
223 bzero(&c->iri, sizeof(c->iri));
225 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
227 LOGE(c, "tls_read: %s", tls_error(c->ctx));
231 case TLS_WANT_POLLIN:
232 fds->events = POLLIN;
235 case TLS_WANT_POLLOUT:
236 fds->events = POLLOUT;
240 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
241 start_reply(fds, c, BAD_REQUEST, parse_err);
245 /* XXX: we should check that the SNI matches the requested host */
246 if (strcmp(c->iri.schema, "gemini") || c->iri.port_no != conf.port) {
247 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
255 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
257 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
262 c->state = S_INITIALIZING;
264 snprintf(buf, sizeof(buf), "%d ", code);
265 strlcat(buf, meta, sizeof(buf));
266 if (!strcmp(meta, "text/gemini") && c->host->lang != NULL) {
267 strlcat(buf, "; lang=", sizeof(buf));
268 strlcat(buf, c->host->lang, sizeof(buf));
271 len = strlcat(buf, "\r\n", sizeof(buf));
272 assert(len < sizeof(buf));
274 switch (tls_write(c->ctx, buf, len)) {
278 case TLS_WANT_POLLIN:
279 pfd->events = POLLIN;
281 case TLS_WANT_POLLOUT:
282 pfd->events = POLLOUT;
286 log_request(c, buf, sizeof(buf));
288 /* we don't need a body */
289 if (c->code != SUCCESS) {
294 /* advance the state machine */
300 start_cgi(const char *spath, const char *relpath, const char *query,
301 struct pollfd *fds, struct client *c)
303 char addr[NI_MAXHOST];
304 const char *ruser, *cissuer, *chash;
307 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
314 if (tls_peer_cert_provided(c->ctx)) {
315 ruser = tls_peer_cert_subject(c->ctx);
316 cissuer = tls_peer_cert_issuer(c->ctx);
317 chash = tls_peer_cert_hash(c->ctx);
324 if (!send_string(exfd, spath)
325 || !send_string(exfd, relpath)
326 || !send_string(exfd, query)
327 || !send_string(exfd, addr)
328 || !send_string(exfd, ruser)
329 || !send_string(exfd, cissuer)
330 || !send_string(exfd, chash)
331 || !send_vhost(exfd, c->host))
335 if ((c->fd = recv_fd(exfd)) == -1) {
336 start_reply(fds, c, TEMP_FAILURE, "internal server error");
339 c->state = S_SENDING_CGI;
340 cgi_poll_on_child(fds, c);
342 /* handle_cgi(fds, c); */
346 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
347 fatal("cannot talk to the executor process");
351 send_file(struct pollfd *fds, struct client *c)
355 /* ensure the correct state */
356 c->state = S_SENDING_FILE;
358 len = (c->buf + c->len) - c->i;
361 switch (ret = tls_write(c->ctx, c->i, len)) {
363 LOGE(c, "tls_write: %s", tls_error(c->ctx));
367 case TLS_WANT_POLLIN:
368 fds->events = POLLIN;
371 case TLS_WANT_POLLOUT:
372 fds->events = POLLOUT;
386 send_dir(struct pollfd *fds, struct client *c)
389 const char *index = "index.gmi";
391 /* guard against a re-entrant call: open_file -> send_dir ->
392 * open_file -> send_dir. This can happen only if:
394 * - user requested a dir, say foo/
395 * - we try to serve foo/$INDEX
396 * - foo/$INDEX is a directory.
398 if (c->iri.path == c->sbuf) {
399 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
403 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
405 len = strlen(c->iri.path);
406 if (len > 0 && c->iri.path[len-1] != '/') {
407 /* redirect to url with the trailing / */
408 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
409 strlcat(c->sbuf, "/", sizeof(c->sbuf));
410 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
414 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
416 if (!ends_with(c->sbuf, "/"))
417 strlcat(c->sbuf, "/", sizeof(c->sbuf));
419 if (c->host->index != NULL)
420 index = c->host->index;
421 len = strlcat(c->sbuf, index, sizeof(c->sbuf));
423 if (len >= sizeof(c->sbuf)) {
424 start_reply(fds, c, TEMP_FAILURE, "internal server error");
429 c->iri.path = c->sbuf;
434 cgi_poll_on_child(struct pollfd *fds, struct client *c)
438 if (c->waiting_on_child)
440 c->waiting_on_child = 1;
442 fds->events = POLLIN;
450 cgi_poll_on_client(struct pollfd *fds, struct client *c)
454 if (!c->waiting_on_child)
456 c->waiting_on_child = 0;
463 /* handle the read from the child process. Return like read(2) */
465 read_from_cgi(struct client *c)
471 /* if we haven't read a whole response line, we want to
472 * continue reading. */
475 buf = c->sbuf + c->len;
476 len = sizeof(c->sbuf) - c->len;
479 len = sizeof(c->sbuf);
482 r = read(c->fd, buf, len);
483 if (r == 0 || r == -1)
492 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
494 log_request(c, c->sbuf, c->len);
501 handle_cgi(struct pollfd *fds, struct client *c)
505 /* ensure c->fd is the child and fds->fd the client */
506 cgi_poll_on_client(fds, c);
509 if (c->code == -1 || c->len == 0) {
510 switch (r = read_from_cgi(c)) {
515 if (errno == EAGAIN || errno == EWOULDBLOCK) {
516 cgi_poll_on_child(fds, c);
524 cgi_poll_on_child(fds, c);
529 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
533 case TLS_WANT_POLLOUT:
534 fds->events = POLLOUT;
537 case TLS_WANT_POLLIN:
538 fds->events = POLLIN;
554 close_conn(struct pollfd *pfd, struct client *c)
556 c->state = S_CLOSING;
558 switch (tls_close(c->ctx)) {
559 case TLS_WANT_POLLIN:
560 pfd->events = POLLIN;
562 case TLS_WANT_POLLOUT:
563 pfd->events = POLLOUT;
572 if (c->buf != MAP_FAILED)
573 munmap(c->buf, c->len);
583 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
586 struct sockaddr_storage addr;
590 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
591 if (errno == EWOULDBLOCK)
593 fatal("accept: %s", strerror(errno));
598 for (i = 0; i < MAX_USERS; ++i) {
599 if (fds[i].fd == -1) {
600 bzero(&clients[i], sizeof(struct client));
601 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
602 break; /* goodbye fd! */
605 fds[i].events = POLLIN;
607 clients[i].state = S_HANDSHAKE;
608 clients[i].next = S_SENDING_FILE;
610 clients[i].waiting_on_child = 0;
611 clients[i].buf = MAP_FAILED;
612 clients[i].addr = addr;
623 handle(struct pollfd *fds, struct client *client)
625 switch (client->state) {
627 handle_handshake(fds, client);
631 handle_open_conn(fds, client);
635 start_reply(fds, client, client->code, client->meta);
639 send_file(fds, client);
643 handle_cgi(fds, client);
647 close_conn(fds, client);
657 loop(struct tls *ctx, int sock4, int sock6)
660 struct client clients[MAX_USERS];
661 struct pollfd fds[MAX_USERS];
663 connected_clients = 0;
665 for (i = 0; i < MAX_USERS; ++i) {
667 fds[i].events = POLLIN;
668 bzero(&clients[i], sizeof(struct client));
675 if (poll(fds, MAX_USERS, INFTIM) == -1) {
676 if (errno == EINTR) {
677 fprintf(stderr, "connected clients: %d\n",
681 fatal("poll: %s", strerror(errno));
684 for (i = 0; i < MAX_USERS; i++) {
685 if (fds[i].revents == 0)
688 if (fds[i].revents & (POLLERR|POLLNVAL))
689 fatal("bad fd %d: %s", fds[i].fd,
692 if (fds[i].revents & POLLHUP) {
693 /* fds[i] may be the fd of the stdin
694 * of a cgi script that has exited. */
695 if (!clients[i].waiting_on_child) {
696 close_conn(&fds[i], &clients[i]);
701 if (fds[i].fd == sock4)
702 do_accept(sock4, ctx, fds, clients);
703 else if (fds[i].fd == sock6)
704 do_accept(sock6, ctx, fds, clients);
706 handle(&fds[i], &clients[i]);