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 <errno.h>
24 #include <fcntl.h>
25 #include <string.h>
27 #include "gmid.h"
29 int connected_clients;
31 int
32 check_path(struct client *c, const char *path, int *fd)
33 {
34 struct stat sb;
36 assert(path != NULL);
37 if ((*fd = openat(c->host->dirfd, *path ? path : ".",
38 O_RDONLY | O_NOFOLLOW)) == -1) {
39 return FILE_MISSING;
40 }
42 if (fstat(*fd, &sb) == -1) {
43 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
44 return FILE_MISSING;
45 }
47 if (S_ISDIR(sb.st_mode))
48 return FILE_DIRECTORY;
50 if (sb.st_mode & S_IXUSR)
51 return FILE_EXECUTABLE;
53 return FILE_EXISTS;
54 }
56 int
57 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
58 {
59 switch (check_path(c, fpath, &c->fd)) {
60 case FILE_EXECUTABLE:
61 if (c->host->cgi != NULL && starts_with(fpath, c->host->cgi))
62 return start_cgi(fpath, "", query, fds, c);
64 /* fallthrough */
66 case FILE_EXISTS:
67 if ((c->len = filesize(c->fd)) == -1) {
68 LOGE(c, "failed to get file size for %s", fpath);
69 goodbye(fds, c);
70 return 0;
71 }
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));
76 goodbye(fds, c);
77 return 0;
78 }
79 c->i = c->buf;
80 return start_reply(fds, c, SUCCESS, mime(c->host, fpath));
82 case FILE_DIRECTORY:
83 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
84 close(c->fd);
85 c->fd = -1;
86 send_dir(fpath, fds, c);
87 return 0;
89 case FILE_MISSING:
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"))
94 return 0;
95 goodbye(fds, c);
96 return 0;
98 default:
99 /* unreachable */
100 abort();
105 /*
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.
111 */
112 int
113 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
115 char *end;
116 end = strchr(path, '\0');
118 /* NB: assume CGI is enabled and path matches cgi */
120 while (end > path) {
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. */
124 while (*end != '/')
125 end--;
126 *end = '\0';
128 switch (check_path(c, path, &c->fd)) {
129 case FILE_EXECUTABLE:
130 return start_cgi(path, end+1, query, fds,c);
131 case FILE_MISSING:
132 break;
133 default:
134 goto err;
137 *end = '/';
138 end--;
141 err:
142 if (!start_reply(fds, c, NOT_FOUND, "not found"))
143 return 0;
144 goodbye(fds, c);
145 return 0;
148 void
149 mark_nonblock(int fd)
151 int flags;
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));
159 void
160 handle_handshake(struct pollfd *fds, struct client *c)
162 struct vhost *h;
163 const char *servname;
165 switch (tls_handshake(c->ctx)) {
166 case 0: /* success */
167 case -1: /* already handshaked */
168 break;
169 case TLS_WANT_POLLIN:
170 fds->events = POLLIN;
171 return;
172 case TLS_WANT_POLLOUT:
173 fds->events = POLLOUT;
174 return;
175 default:
176 /* unreachable */
177 abort();
180 servname = tls_conn_servername(c->ctx);
181 if (servname == NULL)
182 goto hostnotfound;
184 for (h = hosts; h->domain != NULL; ++h) {
185 if (!strcmp(h->domain, servname) || !strcmp(h->domain, "*"))
186 break;
189 if (h->domain != NULL) {
190 c->state = S_OPEN;
191 c->host = h;
192 handle_open_conn(fds, c);
193 return;
196 hostnotfound:
197 /* XXX: check the correct response */
198 if (!start_reply(fds, c, BAD_REQUEST, "Wrong host or missing SNI"))
199 return;
200 goodbye(fds, c);
203 void
204 handle_open_conn(struct pollfd *fds, struct client *c)
206 char buf[GEMINI_URL_LEN];
207 const char *parse_err = "invalid request";
208 struct iri iri;
210 bzero(buf, sizeof(buf));
212 switch (tls_read(c->ctx, buf, sizeof(buf)-1)) {
213 case -1:
214 LOGE(c, "tls_read: %s", tls_error(c->ctx));
215 goodbye(fds, c);
216 return;
218 case TLS_WANT_POLLIN:
219 fds->events = POLLIN;
220 return;
222 case TLS_WANT_POLLOUT:
223 fds->events = POLLOUT;
224 return;
227 if (!trim_req_iri(buf) || !parse_iri(buf, &iri, &parse_err)) {
228 if (!start_reply(fds, c, BAD_REQUEST, parse_err))
229 return;
230 goodbye(fds, c);
231 return;
234 if (strcmp(iri.schema, "gemini") || iri.port_no != conf.port) {
235 if (!start_reply(fds, c, PROXY_REFUSED, "won't proxy request"))
236 return;
237 goodbye(fds, c);
238 return;
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);
249 int
250 start_reply(struct pollfd *pfd, struct client *c, int code, const char *meta)
252 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
253 int len;
255 c->code = code;
256 c->meta = meta;
257 c->state = S_INITIALIZING;
259 snprintf(buf, sizeof(buf), "%d ", code);
260 strlcat(buf, meta, sizeof(buf));
261 if (!strcmp(meta, "text/gemini") && c->host->lang != NULL) {
262 strlcat(buf, "; lang=", sizeof(buf));
263 strlcat(buf, c->host->lang, sizeof(buf));
266 len = strlcat(buf, "\r\n", sizeof(buf));
267 assert(len < (int)sizeof(buf));
269 switch (tls_write(c->ctx, buf, len)) {
270 case TLS_WANT_POLLIN:
271 pfd->events = POLLIN;
272 return 0;
273 case TLS_WANT_POLLOUT:
274 pfd->events = POLLOUT;
275 return 0;
276 default:
277 return 1;
281 int
282 start_cgi(const char *spath, const char *relpath, const char *query,
283 struct pollfd *fds, struct client *c)
285 char addr[NI_MAXHOST];
286 const char *ruser, *cissuer, *chash;
287 int e;
289 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
290 addr, sizeof(addr),
291 NULL, 0,
292 NI_NUMERICHOST);
293 if (e != 0)
294 goto err;
296 if (tls_peer_cert_provided(c->ctx)) {
297 ruser = tls_peer_cert_subject(c->ctx);
298 cissuer = tls_peer_cert_issuer(c->ctx);
299 chash = tls_peer_cert_hash(c->ctx);
300 } else {
301 ruser = NULL;
302 cissuer = NULL;
303 chash = NULL;
306 if (!send_string(exfd, spath)
307 || !send_string(exfd, relpath)
308 || !send_string(exfd, query)
309 || !send_string(exfd, addr)
310 || !send_string(exfd, ruser)
311 || !send_string(exfd, cissuer)
312 || !send_string(exfd, chash)
313 || !send_vhost(exfd, c->host))
314 goto err;
316 close(c->fd);
317 if ((c->fd = recv_fd(exfd)) == -1) {
318 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
319 return 0;
320 goodbye(fds, c);
321 return 0;
323 c->child = 1;
324 c->state = S_SENDING;
325 cgi_poll_on_child(fds, c);
326 /* handle_cgi(fds, c); */
327 return 0;
329 err:
330 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
331 fatal("cannot talk to the executor process");
334 void
335 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
337 ssize_t ret, len;
339 if (c->fd == -1) {
340 if (!open_file(path, query, fds, c))
341 return;
342 c->state = S_SENDING;
345 len = (c->buf + c->len) - c->i;
347 while (len > 0) {
348 switch (ret = tls_write(c->ctx, c->i, len)) {
349 case -1:
350 LOGE(c, "tls_write: %s", tls_error(c->ctx));
351 goodbye(fds, c);
352 return;
354 case TLS_WANT_POLLIN:
355 fds->events = POLLIN;
356 return;
358 case TLS_WANT_POLLOUT:
359 fds->events = POLLOUT;
360 return;
362 default:
363 c->i += ret;
364 len -= ret;
365 break;
369 goodbye(fds, c);
372 void
373 send_dir(char *path, struct pollfd *fds, struct client *client)
375 char fpath[PATHBUF];
376 size_t len;
378 bzero(fpath, PATHBUF);
380 if (path[0] != '.')
381 fpath[0] = '.';
383 /* this cannot fail since sizeof(fpath) > maxlen of path */
384 strlcat(fpath, path, PATHBUF);
385 len = strlen(fpath);
387 /* add a trailing / in case. */
388 if (fpath[len-1] != '/') {
389 fpath[len] = '/';
392 strlcat(fpath, "index.gmi", sizeof(fpath));
394 send_file(fpath, NULL, fds, client);
397 void
398 cgi_poll_on_child(struct pollfd *fds, struct client *c)
400 int fd;
402 if (c->waiting_on_child)
403 return;
404 c->waiting_on_child = 1;
406 fds->events = POLLIN;
408 fd = fds->fd;
409 fds->fd = c->fd;
410 c->fd = fd;
413 void
414 cgi_poll_on_client(struct pollfd *fds, struct client *c)
416 int fd;
418 if (!c->waiting_on_child)
419 return;
420 c->waiting_on_child = 0;
422 fd = fds->fd;
423 fds->fd = c->fd;
424 c->fd = fd;
427 void
428 handle_cgi(struct pollfd *fds, struct client *c)
430 ssize_t r;
432 /* ensure c->fd is the child and fds->fd the client */
433 cgi_poll_on_client(fds, c);
435 while (1) {
436 if (c->len == 0) {
437 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
438 goto end;
439 if (r == -1) {
440 if (errno == EAGAIN || errno == EWOULDBLOCK) {
441 cgi_poll_on_child(fds, c);
442 return;
444 goto end;
446 c->len = r;
447 c->off = 0;
450 while (c->len > 0) {
451 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
452 case -1:
453 goto end;
455 case TLS_WANT_POLLOUT:
456 fds->events = POLLOUT;
457 return;
459 case TLS_WANT_POLLIN:
460 fds->events = POLLIN;
461 return;
463 default:
464 c->off += r;
465 c->len -= r;
466 break;
471 end:
472 goodbye(fds, c);
475 void
476 goodbye(struct pollfd *pfd, struct client *c)
478 c->state = S_CLOSING;
480 switch (tls_close(c->ctx)) {
481 case TLS_WANT_POLLIN:
482 pfd->events = POLLIN;
483 return;
484 case TLS_WANT_POLLOUT:
485 pfd->events = POLLOUT;
486 return;
489 connected_clients--;
491 tls_free(c->ctx);
492 c->ctx = NULL;
494 if (c->buf != MAP_FAILED)
495 munmap(c->buf, c->len);
497 if (c->fd != -1)
498 close(c->fd);
500 close(pfd->fd);
501 pfd->fd = -1;
504 void
505 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
507 int i, fd;
508 struct sockaddr_storage addr;
509 socklen_t len;
511 len = sizeof(addr);
512 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
513 if (errno == EWOULDBLOCK)
514 return;
515 fatal("accept: %s", strerror(errno));
518 mark_nonblock(fd);
520 for (i = 0; i < MAX_USERS; ++i) {
521 if (fds[i].fd == -1) {
522 bzero(&clients[i], sizeof(struct client));
523 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
524 break; /* goodbye fd! */
526 fds[i].fd = fd;
527 fds[i].events = POLLIN;
529 clients[i].state = S_HANDSHAKE;
530 clients[i].fd = -1;
531 clients[i].child = 0;
532 clients[i].waiting_on_child = 0;
533 clients[i].buf = MAP_FAILED;
534 clients[i].af = AF_INET;
535 clients[i].addr = addr;
537 connected_clients++;
538 return;
542 close(fd);
545 void
546 handle(struct pollfd *fds, struct client *client)
548 switch (client->state) {
549 case S_HANDSHAKE:
550 handle_handshake(fds, client);
551 break;
553 case S_OPEN:
554 handle_open_conn(fds, client);
555 break;
557 case S_INITIALIZING:
558 if (!start_reply(fds, client, client->code, client->meta))
559 return;
561 if (client->code != SUCCESS) {
562 /* we don't need a body */
563 goodbye(fds, client);
564 return;
567 client->state = S_SENDING;
569 /* fallthrough */
571 case S_SENDING:
572 if (client->child)
573 handle_cgi(fds, client);
574 else
575 send_file(NULL, NULL, fds, client);
576 break;
578 case S_CLOSING:
579 goodbye(fds, client);
580 break;
582 default:
583 /* unreachable */
584 abort();
588 void
589 loop(struct tls *ctx, int sock4, int sock6)
591 int i;
592 struct client clients[MAX_USERS];
593 struct pollfd fds[MAX_USERS];
595 connected_clients = 0;
597 for (i = 0; i < MAX_USERS; ++i) {
598 fds[i].fd = -1;
599 fds[i].events = POLLIN;
600 bzero(&clients[i], sizeof(struct client));
603 fds[0].fd = sock4;
604 fds[1].fd = sock6;
606 for (;;) {
607 if (poll(fds, MAX_USERS, INFTIM) == -1) {
608 if (errno == EINTR) {
609 fprintf(stderr, "connected clients: %d\n",
610 connected_clients);
611 continue;
613 fatal("poll: %s", strerror(errno));
616 for (i = 0; i < MAX_USERS; i++) {
617 if (fds[i].revents == 0)
618 continue;
620 if (fds[i].revents & (POLLERR|POLLNVAL))
621 fatal("bad fd %d: %s", fds[i].fd,
622 strerror(errno));
624 if (fds[i].revents & POLLHUP) {
625 /* fds[i] may be the fd of the stdin
626 * of a cgi script that has exited. */
627 if (!clients[i].waiting_on_child) {
628 goodbye(&fds[i], &clients[i]);
629 continue;
633 if (fds[i].fd == sock4)
634 do_accept(sock4, ctx, fds, clients);
635 else if (fds[i].fd == sock6)
636 do_accept(sock6, ctx, fds, clients);
637 else
638 handle(&fds[i], &clients[i]);