Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
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.
7 *
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.
15 */
17 #include <sys/mman.h>
18 #include <sys/stat.h>
20 #include <netdb.h>
22 #include <assert.h>
23 #include <err.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <string.h>
28 #include "gmid.h"
30 int connected_clients;
32 int
33 check_path(struct client *c, const char *path, int *fd)
34 {
35 struct stat sb;
37 assert(path != NULL);
38 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
39 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
40 return FILE_MISSING;
41 }
43 if (fstat(*fd, &sb) == -1) {
44 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
45 return FILE_MISSING;
46 }
48 if (S_ISDIR(sb.st_mode))
49 return FILE_DIRECTORY;
51 if (sb.st_mode & S_IXUSR)
52 return FILE_EXECUTABLE;
54 return FILE_EXISTS;
55 }
57 int
58 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
59 {
60 switch (check_path(c, fpath, &c->fd)) {
61 case FILE_EXECUTABLE:
62 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
63 return start_cgi(fpath, "", query, fds, c);
65 /* fallthrough */
67 case FILE_EXISTS:
68 if ((c->len = filesize(c->fd)) == -1) {
69 LOGE(c, "failed to get file size for %s", fpath);
70 goodbye(fds, c);
71 return 0;
72 }
74 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
75 c->fd, 0)) == MAP_FAILED) {
76 warn("mmap: %s", fpath);
77 goodbye(fds, c);
78 return 0;
79 }
80 c->i = c->buf;
81 return start_reply(fds, c, SUCCESS, mime(fpath));
83 case FILE_DIRECTORY:
84 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
85 close(c->fd);
86 c->fd = -1;
87 send_dir(fpath, fds, c);
88 return 0;
90 case FILE_MISSING:
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"))
95 return 0;
96 goodbye(fds, c);
97 return 0;
99 default:
100 /* unreachable */
101 abort();
106 /*
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.
112 */
113 int
114 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
116 char *end;
117 end = strchr(path, '\0');
119 /* NB: assume CGI is enabled and path matches cgi */
121 while (end > path) {
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. */
125 while (*end != '/')
126 end--;
127 *end = '\0';
129 switch (check_path(c, path, &c->fd)) {
130 case FILE_EXECUTABLE:
131 return start_cgi(path, end+1, query, fds,c);
132 case FILE_MISSING:
133 break;
134 default:
135 goto err;
138 *end = '/';
139 end--;
142 err:
143 if (!start_reply(fds, c, NOT_FOUND, "not found"))
144 return 0;
145 goodbye(fds, c);
146 return 0;
149 void
150 mark_nonblock(int fd)
152 int flags;
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));
160 void
161 handle_handshake(struct pollfd *fds, struct client *c)
163 struct vhost *h;
164 const char *servname;
166 switch (tls_handshake(c->ctx)) {
167 case 0: /* success */
168 case -1: /* already handshaked */
169 break;
170 case TLS_WANT_POLLIN:
171 fds->events = POLLIN;
172 return;
173 case TLS_WANT_POLLOUT:
174 fds->events = POLLOUT;
175 return;
176 default:
177 /* unreachable */
178 abort();
181 servname = tls_conn_servername(c->ctx);
182 if (servname == NULL)
183 goto hostnotfound;
185 for (h = hosts; h->domain != NULL; ++h) {
186 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
187 break;
190 if (h->domain != NULL) {
191 c->state = S_OPEN;
192 c->host = h;
193 handle_open_conn(fds, c);
194 return;
197 hostnotfound:
198 /* XXX: check the correct response */
199 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
200 return;
201 goodbye(fds, c);
204 void
205 handle_open_conn(struct pollfd *fds, struct client *c)
207 char buf[GEMINI_URL_LEN];
208 const char *parse_err = "invalid request";
209 struct iri iri;
211 bzero(buf, sizeof(buf));
213 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
214 case -1:
215 LOGE(c, "tls_read: %s", tls_error(c->ctx));
216 goodbye(fds, c);
217 return;
219 case TLS_WANT_POLLIN:
220 fds->events = POLLIN;
221 return;
223 case TLS_WANT_POLLOUT:
224 fds->events = POLLOUT;
225 return;
228 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
229 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
230 return;
231 goodbye(fds, c);
232 return;
235 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
236 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
237 return;
238 goodbye(fds, c);
239 return;
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);
250 int
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 */
254 int len;
256 client->code = code;
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;
266 return 0;
267 case TLS_WANT_POLLOUT:
268 pfd->events = POLLOUT;
269 return 0;
270 default:
271 return 1;
275 int
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;
281 int e;
283 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
284 addr, sizeof(addr),
285 NULL, 0,
286 NI_NUMERICHOST);
287 if (e != 0)
288 goto err;
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);
294 } else {
295 ruser = NULL;
296 cissuer = NULL;
297 chash = NULL;
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))
308 goto err;
310 close(c->fd);
311 if ((c->fd = recv_fd(exfd)) == -1) {
312 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
313 return 0;
314 goodbye(fds, c);
315 return 0;
317 c->child = 1;
318 c->state = S_SENDING;
319 cgi_poll_on_child(fds, c);
320 /* handle_cgi(fds, c); */
321 return 0;
323 err:
324 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
325 err(1, "cannot talk to the executor process");
328 void
329 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
331 ssize_t ret, len;
333 if (c->fd == -1) {
334 if (!open_file(path, query, fds, c))
335 return;
336 c->state = S_SENDING;
339 len = (c->buf + c->len) - c->i;
341 while (len > 0) {
342 switch (ret = tls_write(c->ctx, c->i, len)) {
343 case -1:
344 LOGE(c, "tls_write: %s", tls_error(c->ctx));
345 goodbye(fds, c);
346 return;
348 case TLS_WANT_POLLIN:
349 fds->events = POLLIN;
350 return;
352 case TLS_WANT_POLLOUT:
353 fds->events = POLLOUT;
354 return;
356 default:
357 c->i += ret;
358 len -= ret;
359 break;
363 goodbye(fds, c);
366 void
367 send_dir(char *path, struct pollfd *fds, struct client *client)
369 char fpath[PATHBUF];
370 size_t len;
372 bzero(fpath, PATHBUF);
374 if (path[0] != '.')
375 fpath[0] = '.';
377 /* this cannot fail since sizeof(fpath) > maxlen of path */
378 strlcat(fpath, path, PATHBUF);
379 len = strlen(fpath);
381 /* add a trailing / in case. */
382 if (fpath[len-1] != '/') {
383 fpath[len] = '/';
386 strlcat(fpath, "index.gmi", sizeof(fpath));
388 send_file(fpath, NULL, fds, client);
391 void
392 cgi_poll_on_child(struct pollfd *fds, struct client *c)
394 int fd;
396 if (c->waiting_on_child)
397 return;
398 c->waiting_on_child = 1;
400 fds->events = POLLIN;
402 fd = fds->fd;
403 fds->fd = c->fd;
404 c->fd = fd;
407 void
408 cgi_poll_on_client(struct pollfd *fds, struct client *c)
410 int fd;
412 if (!c->waiting_on_child)
413 return;
414 c->waiting_on_child = 0;
416 fd = fds->fd;
417 fds->fd = c->fd;
418 c->fd = fd;
421 void
422 handle_cgi(struct pollfd *fds, struct client *c)
424 ssize_t r;
426 /* ensure c->fd is the child and fds->fd the client */
427 cgi_poll_on_client(fds, c);
429 while (1) {
430 if (c->len == 0) {
431 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
432 goto end;
433 if (r == -1) {
434 if (errno == EAGAIN || errno == EWOULDBLOCK) {
435 cgi_poll_on_child(fds, c);
436 return;
438 goto end;
440 c->len = r;
441 c->off = 0;
444 while (c->len > 0) {
445 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
446 case -1:
447 goto end;
449 case TLS_WANT_POLLOUT:
450 fds->events = POLLOUT;
451 return;
453 case TLS_WANT_POLLIN:
454 fds->events = POLLIN;
455 return;
457 default:
458 c->off += r;
459 c->len -= r;
460 break;
465 end:
466 goodbye(fds, c);
469 void
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;
477 return;
478 case TLS_WANT_POLLOUT:
479 pfd->events = POLLOUT;
480 return;
483 connected_clients--;
485 tls_free(c->ctx);
486 c->ctx = NULL;
488 if (c->buf != MAP_FAILED)
489 munmap(c->buf, c->len);
491 if (c->fd != -1)
492 close(c->fd);
494 close(pfd->fd);
495 pfd->fd = -1;
498 void
499 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
501 int i, fd;
502 struct sockaddr_storage addr;
503 socklen_t len;
505 len = sizeof(addr);
506 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
507 if (errno == EWOULDBLOCK)
508 return;
509 fatal("accept: %s", strerror(errno));
512 mark_nonblock(fd);
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! */
520 fds[i].fd = fd;
521 fds[i].events = POLLIN;
523 clients[i].state = S_HANDSHAKE;
524 clients[i].fd = -1;
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;
531 connected_clients++;
532 return;
536 close(fd);
539 void
540 handle(struct pollfd *fds, struct client *client)
542 switch (client->state) {
543 case S_HANDSHAKE:
544 handle_handshake(fds, client);
545 break;
547 case S_OPEN:
548 handle_open_conn(fds, client);
549 break;
551 case S_INITIALIZING:
552 if (!start_reply(fds, client, client->code, client->meta))
553 return;
555 if (client->code != SUCCESS) {
556 /* we don't need a body */
557 goodbye(fds, client);
558 return;
561 client->state = S_SENDING;
563 /* fallthrough */
565 case S_SENDING:
566 if (client->child)
567 handle_cgi(fds, client);
568 else
569 send_file(NULL, NULL, fds, client);
570 break;
572 case S_CLOSING:
573 goodbye(fds, client);
574 break;
576 default:
577 /* unreachable */
578 abort();
582 void
583 loop(struct tls *ctx, int sock4, int sock6)
585 int i;
586 struct client clients[MAX_USERS];
587 struct pollfd fds[MAX_USERS];
589 connected_clients = 0;
591 for (i = 0; i < MAX_USERS; ++i) {
592 fds[i].fd = -1;
593 fds[i].events = POLLIN;
594 bzero(&clients[i], sizeof(struct client));
597 fds[0].fd = sock4;
598 fds[1].fd = sock6;
600 for (;;) {
601 if (poll(fds, MAX_USERS, INFTIM) == -1) {
602 if (errno == EINTR) {
603 warnx("connected clients: %d",
604 connected_clients);
605 continue;
607 fatal("poll: %s", strerror(errno));
610 for (i = 0; i < MAX_USERS; i++) {
611 if (fds[i].revents == 0)
612 continue;
614 if (fds[i].revents & (POLLERR|POLLNVAL))
615 fatal("bad fd %d: %s", fds[i].fd,
616 strerror(errno));
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]);
623 continue;
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);
631 else
632 handle(&fds[i], &clients[i]);