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(char *fpath, char *query, struct pollfd *fds, struct client *c)
59 switch (check_path(c, fpath, &c->fd)) {
61 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
62 return start_cgi(fpath, "", query, fds, c);
67 if ((c->len = filesize(c->fd)) == -1) {
68 LOGE(c, "failed to get file size for %s", fpath);
73 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
74 c->fd, 0)) == MAP_FAILED) {
75 LOGW(c, "mmap: %s: %s", fpath, strerror(errno));
80 return start_reply(fds, c, SUCCESS, mime(fpath));
83 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
86 send_dir(fpath, fds, c);
90 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
91 return check_for_cgi(fpath, query, fds, c);
93 if (!start_reply(fds, c, NOT_FOUND, "not found"))
106 * the inverse of this algorithm, i.e. starting from the start of the
107 * path + strlen(cgi), and checking if each component, should be
108 * faster. But it's tedious to write. This does the opposite: starts
109 * from the end and strip one component at a time, until either an
110 * executable is found or we emptied the path.
113 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
116 end = strchr(path, '\0');
118 /* NB: assume CGI is enabled and path matches cgi */
121 /* go up one level. UNIX paths are simple and POSIX
122 * dirname, with its ambiguities on if the given path
123 * is changed or not, gives me headaches. */
128 switch (check_path(c, path, &c->fd)) {
129 case FILE_EXECUTABLE:
130 return start_cgi(path, end+1, query, fds,c);
142 if (!start_reply(fds, c, NOT_FOUND, "not found"))
149 mark_nonblock(int fd)
153 if ((flags = fcntl(fd, F_GETFL)) == -1)
154 fatal("fcntl(F_GETFL): %s", strerror(errno));
155 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
156 fatal("fcntl(F_SETFL): %s", strerror(errno));
160 handle_handshake(struct pollfd *fds, struct client *c)
163 const char *servname;
165 switch (tls_handshake(c->ctx)) {
166 case 0: /* success */
167 case -1: /* already handshaked */
169 case TLS_WANT_POLLIN:
170 fds->events = POLLIN;
172 case TLS_WANT_POLLOUT:
173 fds->events = POLLOUT;
180 servname = tls_conn_servername(c->ctx);
181 if (servname == NULL)
184 for (h = hosts; h->domain != NULL; ++h) {
185 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
189 if (h->domain != NULL) {
192 handle_open_conn(fds, c);
197 /* XXX: check the correct response */
198 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
204 handle_open_conn(struct pollfd *fds, struct client *c)
206 char buf[GEMINI_URL_LEN];
207 const char *parse_err = "invalid request";
210 bzero(buf, sizeof(buf));
212 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
214 LOGE(c, "tls_read: %s", tls_error(c->ctx));
218 case TLS_WANT_POLLIN:
219 fds->events = POLLIN;
222 case TLS_WANT_POLLOUT:
223 fds->events = POLLOUT;
227 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
228 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
234 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
235 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
241 LOGI(c, "GET %s%s%s",
242 *iri.path ? iri.path : "/",
243 *iri.query ? "?" : "",
244 *iri.query ? iri.query : "");
246 send_file(iri.path, iri.query, fds, c);
250 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
252 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
256 client->meta = reason;
257 client->state = S_INITIALIZING;
259 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
260 assert(len < (int)sizeof(buf));
262 switch (tls_write(client->ctx, buf, len)) {
263 case TLS_WANT_POLLIN:
264 pfd->events = POLLIN;
266 case TLS_WANT_POLLOUT:
267 pfd->events = POLLOUT;
275 start_cgi(const char *spath, const char *relpath, const char *query,
276 struct pollfd *fds, struct client *c)
278 char addr[NI_MAXHOST];
279 const char *ruser, *cissuer, *chash;
282 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
289 if (tls_peer_cert_provided(c->ctx)) {
290 ruser = tls_peer_cert_subject(c->ctx);
291 cissuer = tls_peer_cert_issuer(c->ctx);
292 chash = tls_peer_cert_hash(c->ctx);
299 if (!send_string(exfd, spath)
300 || !send_string(exfd, relpath)
301 || !send_string(exfd, query)
302 || !send_string(exfd, addr)
303 || !send_string(exfd, ruser)
304 || !send_string(exfd, cissuer)
305 || !send_string(exfd, chash)
306 || !send_vhost(exfd, c->host))
310 if ((c->fd = recv_fd(exfd)) == -1) {
311 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
317 c->state = S_SENDING;
318 cgi_poll_on_child(fds, c);
319 /* handle_cgi(fds, c); */
323 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
324 fatal("cannot talk to the executor process");
328 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
333 if (!open_file(path, query, fds, c))
335 c->state = S_SENDING;
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(char *path, struct pollfd *fds, struct client *client)
371 bzero(fpath, PATHBUF);
376 /* this cannot fail since sizeof(fpath) > maxlen of path */
377 strlcat(fpath, path, PATHBUF);
380 /* add a trailing / in case. */
381 if (fpath[len-1] != '/') {
385 strlcat(fpath, "index.gmi", sizeof(fpath));
387 send_file(fpath, NULL, fds, client);
391 cgi_poll_on_child(struct pollfd *fds, struct client *c)
395 if (c->waiting_on_child)
397 c->waiting_on_child = 1;
399 fds->events = POLLIN;
407 cgi_poll_on_client(struct pollfd *fds, struct client *c)
411 if (!c->waiting_on_child)
413 c->waiting_on_child = 0;
421 handle_cgi(struct pollfd *fds, struct client *c)
425 /* ensure c->fd is the child and fds->fd the client */
426 cgi_poll_on_client(fds, c);
430 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
433 if (errno == EAGAIN || errno == EWOULDBLOCK) {
434 cgi_poll_on_child(fds, c);
444 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
448 case TLS_WANT_POLLOUT:
449 fds->events = POLLOUT;
452 case TLS_WANT_POLLIN:
453 fds->events = POLLIN;
469 goodbye(struct pollfd *pfd, struct client *c)
471 c->state = S_CLOSING;
473 switch (tls_close(c->ctx)) {
474 case TLS_WANT_POLLIN:
475 pfd->events = POLLIN;
477 case TLS_WANT_POLLOUT:
478 pfd->events = POLLOUT;
487 if (c->buf != MAP_FAILED)
488 munmap(c->buf, c->len);
498 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
501 struct sockaddr_storage addr;
505 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
506 if (errno == EWOULDBLOCK)
508 fatal("accept: %s", strerror(errno));
513 for (i = 0; i < MAX_USERS; ++i) {
514 if (fds[i].fd == -1) {
515 bzero(&clients[i], sizeof(struct client));
516 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
517 break; /* goodbye fd! */
520 fds[i].events = POLLIN;
522 clients[i].state = S_HANDSHAKE;
524 clients[i].child = 0;
525 clients[i].waiting_on_child = 0;
526 clients[i].buf = MAP_FAILED;
527 clients[i].af = AF_INET;
528 clients[i].addr = addr;
539 handle(struct pollfd *fds, struct client *client)
541 switch (client->state) {
543 handle_handshake(fds, client);
547 handle_open_conn(fds, client);
551 if (!start_reply(fds, client, client->code, client->meta))
554 if (client->code != SUCCESS) {
555 /* we don't need a body */
556 goodbye(fds, client);
560 client->state = S_SENDING;
566 handle_cgi(fds, client);
568 send_file(NULL, NULL, fds, client);
572 goodbye(fds, client);
582 loop(struct tls *ctx, int sock4, int sock6)
585 struct client clients[MAX_USERS];
586 struct pollfd fds[MAX_USERS];
588 connected_clients = 0;
590 for (i = 0; i < MAX_USERS; ++i) {
592 fds[i].events = POLLIN;
593 bzero(&clients[i], sizeof(struct client));
600 if (poll(fds, MAX_USERS, INFTIM) == -1) {
601 if (errno == EINTR) {
602 fprintf(stderr, "connected clients: %d\n",
606 fatal("poll: %s", strerror(errno));
609 for (i = 0; i < MAX_USERS; i++) {
610 if (fds[i].revents == 0)
613 if (fds[i].revents & (POLLERR|POLLNVAL))
614 fatal("bad fd %d: %s", fds[i].fd,
617 if (fds[i].revents & POLLHUP) {
618 /* fds[i] may be the fd of the stdin
619 * of a cgi script that has exited. */
620 if (!clients[i].waiting_on_child) {
621 goodbye(&fds[i], &clients[i]);
626 if (fds[i].fd == sock4)
627 do_accept(sock4, ctx, fds, clients);
628 else if (fds[i].fd == sock6)
629 do_accept(sock6, ctx, fds, clients);
631 handle(&fds[i], &clients[i]);