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 vhost_lang(struct vhost *v, const char *path)
36 const char *lang = NULL;
38 for (loc = v->locations; loc->match != NULL; ++loc) {
39 if (!fnmatch(loc->match, path, 0)) {
40 if (loc->lang != NULL)
49 vhost_default_mime(struct vhost *v, const char *path)
52 const char *default_mime = "application/octet-stream";
54 for (loc = v->locations; loc->match != NULL; ++loc) {
55 if (!fnmatch(loc->match, path, 0)) {
56 if (loc->default_mime != NULL)
57 default_mime = loc->default_mime;
65 vhost_index(struct vhost *v, const char *path)
68 const char *index = "index.gmi";
70 for (loc = v->locations; loc->match != NULL; ++loc) {
71 if (!fnmatch(loc->match, path, 0)) {
72 if (loc->index != NULL)
81 check_path(struct client *c, const char *path, int *fd)
90 else if (*path == '/')
91 /* in send_dir we add an initial / (to be
92 * redirect-friendly), but here we want to skip it */
97 if ((*fd = openat(c->host->dirfd, p, O_RDONLY | O_NOFOLLOW)) == -1) {
101 if (fstat(*fd, &sb) == -1) {
102 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
106 if (S_ISDIR(sb.st_mode))
107 return FILE_DIRECTORY;
109 if (sb.st_mode & S_IXUSR)
110 return FILE_EXECUTABLE;
116 open_file(struct pollfd *fds, struct client *c)
118 switch (check_path(c, c->iri.path, &c->fd)) {
119 case FILE_EXECUTABLE:
120 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
121 start_cgi(c->iri.path, "", c->iri.query, fds, c);
128 if ((c->len = filesize(c->fd)) == -1) {
129 LOGE(c, "failed to get file size for %s", c->iri.path);
134 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
135 c->fd, 0)) == MAP_FAILED) {
136 LOGW(c, "mmap: %s: %s", c->iri.path, strerror(errno));
141 c->next = S_SENDING_FILE;
142 start_reply(fds, c, SUCCESS, mime(c->host, c->iri.path));
152 if (c->host->cgi != NULL && starts_with(c->iri.path, c->host->cgi)) {
153 check_for_cgi(c->iri.path, c->iri.query, fds, c);
156 start_reply(fds, c, NOT_FOUND, "not found");
167 * the inverse of this algorithm, i.e. starting from the start of the
168 * path + strlen(cgi), and checking if each component, should be
169 * faster. But it's tedious to write. This does the opposite: starts
170 * from the end and strip one component at a time, until either an
171 * executable is found or we emptied the path.
174 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
177 end = strchr(path, '\0');
179 /* NB: assume CGI is enabled and path matches cgi */
182 /* go up one level. UNIX paths are simple and POSIX
183 * dirname, with its ambiguities on if the given path
184 * is changed or not, gives me headaches. */
189 switch (check_path(c, path, &c->fd)) {
190 case FILE_EXECUTABLE:
191 start_cgi(path, end+1, query, fds,c);
204 start_reply(fds, c, NOT_FOUND, "not found");
209 mark_nonblock(int fd)
213 if ((flags = fcntl(fd, F_GETFL)) == -1)
214 fatal("fcntl(F_GETFL): %s", strerror(errno));
215 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
216 fatal("fcntl(F_SETFL): %s", strerror(errno));
220 handle_handshake(struct pollfd *fds, struct client *c)
223 const char *servname;
225 switch (tls_handshake(c->ctx)) {
226 case 0: /* success */
227 case -1: /* already handshaked */
229 case TLS_WANT_POLLIN:
230 fds->events = POLLIN;
232 case TLS_WANT_POLLOUT:
233 fds->events = POLLOUT;
240 servname = tls_conn_servername(c->ctx);
242 for (h = hosts; h->domain != NULL; ++h) {
243 if (!strcmp(h->domain, "*"))
246 if (servname != NULL && !fnmatch(h->domain, servname, 0))
250 if (h->domain != NULL) {
253 handle_open_conn(fds, c);
257 if (servname != NULL)
258 strncpy(c->req, servname, sizeof(c->req));
260 strncpy(c->req, "null", sizeof(c->req));
262 start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI");
266 handle_open_conn(struct pollfd *fds, struct client *c)
268 const char *parse_err = "invalid request";
270 bzero(c->req, sizeof(c->req));
271 bzero(&c->iri, sizeof(c->iri));
273 switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
275 LOGE(c, "tls_read: %s", tls_error(c->ctx));
279 case TLS_WANT_POLLIN:
280 fds->events = POLLIN;
283 case TLS_WANT_POLLOUT:
284 fds->events = POLLOUT;
288 if (!trim_req_iri(c->req) || !parse_iri(c->req, &c->iri, &parse_err)) {
289 start_reply(fds, c, BAD_REQUEST, parse_err);
293 /* XXX: we should check that the SNI matches the requested host */
294 if (strcmp(c->iri.schema, "gemini") || c->iri.port_no != conf.port) {
295 start_reply(fds, c, PROXY_REFUSED, "won't proxy request");
303 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
305 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
311 c->state = S_INITIALIZING;
313 lang = vhost_lang(c->host, c->iri.path);
315 snprintf(buf, sizeof(buf), "%d ", code);
316 strlcat(buf, meta, sizeof(buf));
317 if (!strcmp(meta, "text/gemini") && lang != NULL) {
318 strlcat(buf, "; lang=", sizeof(buf));
319 strlcat(buf, lang, sizeof(buf));
322 len = strlcat(buf, "\r\n", sizeof(buf));
323 assert(len < sizeof(buf));
325 switch (tls_write(c->ctx, buf, len)) {
329 case TLS_WANT_POLLIN:
330 pfd->events = POLLIN;
332 case TLS_WANT_POLLOUT:
333 pfd->events = POLLOUT;
337 log_request(c, buf, sizeof(buf));
339 /* we don't need a body */
340 if (c->code != SUCCESS) {
345 /* advance the state machine */
351 start_cgi(const char *spath, const char *relpath, const char *query,
352 struct pollfd *fds, struct client *c)
354 char addr[NI_MAXHOST];
355 const char *ruser, *cissuer, *chash;
358 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
365 if (tls_peer_cert_provided(c->ctx)) {
366 ruser = tls_peer_cert_subject(c->ctx);
367 cissuer = tls_peer_cert_issuer(c->ctx);
368 chash = tls_peer_cert_hash(c->ctx);
375 if (!send_string(exfd, spath)
376 || !send_string(exfd, relpath)
377 || !send_string(exfd, query)
378 || !send_string(exfd, addr)
379 || !send_string(exfd, ruser)
380 || !send_string(exfd, cissuer)
381 || !send_string(exfd, chash)
382 || !send_vhost(exfd, c->host))
386 if ((c->fd = recv_fd(exfd)) == -1) {
387 start_reply(fds, c, TEMP_FAILURE, "internal server error");
390 c->state = S_SENDING_CGI;
391 cgi_poll_on_child(fds, c);
393 /* handle_cgi(fds, c); */
397 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
398 fatal("cannot talk to the executor process");
402 send_file(struct pollfd *fds, struct client *c)
406 /* ensure the correct state */
407 c->state = S_SENDING_FILE;
409 len = (c->buf + c->len) - c->i;
412 switch (ret = tls_write(c->ctx, c->i, len)) {
414 LOGE(c, "tls_write: %s", tls_error(c->ctx));
418 case TLS_WANT_POLLIN:
419 fds->events = POLLIN;
422 case TLS_WANT_POLLOUT:
423 fds->events = POLLOUT;
437 send_dir(struct pollfd *fds, struct client *c)
441 /* guard against a re-entrant call: open_file -> send_dir ->
442 * open_file -> send_dir. This can happen only if:
444 * - user requested a dir, say foo/
445 * - we try to serve foo/$INDEX
446 * - foo/$INDEX is a directory.
448 if (c->iri.path == c->sbuf) {
449 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
453 strlcpy(c->sbuf, "/", sizeof(c->sbuf));
455 len = strlen(c->iri.path);
456 if (len > 0 && c->iri.path[len-1] != '/') {
457 /* redirect to url with the trailing / */
458 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
459 strlcat(c->sbuf, "/", sizeof(c->sbuf));
460 start_reply(fds, c, TEMP_REDIRECT, c->sbuf);
464 strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
466 if (!ends_with(c->sbuf, "/"))
467 strlcat(c->sbuf, "/", sizeof(c->sbuf));
469 len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
472 if (len >= sizeof(c->sbuf)) {
473 start_reply(fds, c, TEMP_FAILURE, "internal server error");
478 c->iri.path = c->sbuf;
483 cgi_poll_on_child(struct pollfd *fds, struct client *c)
487 if (c->waiting_on_child)
489 c->waiting_on_child = 1;
491 fds->events = POLLIN;
499 cgi_poll_on_client(struct pollfd *fds, struct client *c)
503 if (!c->waiting_on_child)
505 c->waiting_on_child = 0;
512 /* handle the read from the child process. Return like read(2) */
514 read_from_cgi(struct client *c)
520 /* if we haven't read a whole response line, we want to
521 * continue reading. */
524 buf = c->sbuf + c->len;
525 len = sizeof(c->sbuf) - c->len;
528 len = sizeof(c->sbuf);
531 r = read(c->fd, buf, len);
532 if (r == 0 || r == -1)
541 if (strchr(c->sbuf, '\n') || c->len == sizeof(c->sbuf)) {
543 log_request(c, c->sbuf, c->len);
550 handle_cgi(struct pollfd *fds, struct client *c)
554 /* ensure c->fd is the child and fds->fd the client */
555 cgi_poll_on_client(fds, c);
558 if (c->code == -1 || c->len == 0) {
559 switch (r = read_from_cgi(c)) {
564 if (errno == EAGAIN || errno == EWOULDBLOCK) {
565 cgi_poll_on_child(fds, c);
573 cgi_poll_on_child(fds, c);
578 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
582 case TLS_WANT_POLLOUT:
583 fds->events = POLLOUT;
586 case TLS_WANT_POLLIN:
587 fds->events = POLLIN;
603 close_conn(struct pollfd *pfd, struct client *c)
605 c->state = S_CLOSING;
607 switch (tls_close(c->ctx)) {
608 case TLS_WANT_POLLIN:
609 pfd->events = POLLIN;
611 case TLS_WANT_POLLOUT:
612 pfd->events = POLLOUT;
621 if (c->buf != MAP_FAILED)
622 munmap(c->buf, c->len);
632 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
635 struct sockaddr_storage addr;
639 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
640 if (errno == EWOULDBLOCK)
642 fatal("accept: %s", strerror(errno));
647 for (i = 0; i < MAX_USERS; ++i) {
648 if (fds[i].fd == -1) {
649 bzero(&clients[i], sizeof(struct client));
650 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
651 break; /* goodbye fd! */
654 fds[i].events = POLLIN;
656 clients[i].state = S_HANDSHAKE;
657 clients[i].next = S_SENDING_FILE;
659 clients[i].waiting_on_child = 0;
660 clients[i].buf = MAP_FAILED;
661 clients[i].addr = addr;
672 handle(struct pollfd *fds, struct client *client)
674 switch (client->state) {
676 handle_handshake(fds, client);
680 handle_open_conn(fds, client);
684 start_reply(fds, client, client->code, client->meta);
688 send_file(fds, client);
692 handle_cgi(fds, client);
696 close_conn(fds, client);
706 loop(struct tls *ctx, int sock4, int sock6)
709 struct client clients[MAX_USERS];
710 struct pollfd fds[MAX_USERS];
712 connected_clients = 0;
714 for (i = 0; i < MAX_USERS; ++i) {
716 fds[i].events = POLLIN;
717 bzero(&clients[i], sizeof(struct client));
724 if (poll(fds, MAX_USERS, INFTIM) == -1) {
725 if (errno == EINTR) {
726 fprintf(stderr, "connected clients: %d\n",
730 fatal("poll: %s", strerror(errno));
733 for (i = 0; i < MAX_USERS; i++) {
734 if (fds[i].revents == 0)
737 if (fds[i].revents & (POLLERR|POLLNVAL))
738 fatal("bad fd %d: %s", fds[i].fd,
741 if (fds[i].revents & POLLHUP) {
742 /* fds[i] may be the fd of the stdin
743 * of a cgi script that has exited. */
744 if (!clients[i].waiting_on_child) {
745 close_conn(&fds[i], &clients[i]);
750 if (fds[i].fd == sock4)
751 do_accept(sock4, ctx, fds, clients);
752 else if (fds[i].fd == sock6)
753 do_accept(sock6, ctx, fds, clients);
755 handle(&fds[i], &clients[i]);