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(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 *client, int code, const char *reason)
252 char buf[1030]; /* status + ' ' + max reply len + \r\n\0 */
253 int len;
255 client->code = code;
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;
265 return 0;
266 case TLS_WANT_POLLOUT:
267 pfd->events = POLLOUT;
268 return 0;
269 default:
270 return 1;
274 int
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;
280 int e;
282 e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
283 addr, sizeof(addr),
284 NULL, 0,
285 NI_NUMERICHOST);
286 if (e != 0)
287 goto err;
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);
293 } else {
294 ruser = NULL;
295 cissuer = NULL;
296 chash = NULL;
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))
307 goto err;
309 close(c->fd);
310 if ((c->fd = recv_fd(exfd)) == -1) {
311 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
312 return 0;
313 goodbye(fds, c);
314 return 0;
316 c->child = 1;
317 c->state = S_SENDING;
318 cgi_poll_on_child(fds, c);
319 /* handle_cgi(fds, c); */
320 return 0;
322 err:
323 /* fatal("cannot talk to the executor process: %s", strerror(errno)); */
324 fatal("cannot talk to the executor process");
327 void
328 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
330 ssize_t ret, len;
332 if (c->fd == -1) {
333 if (!open_file(path, query, fds, c))
334 return;
335 c->state = S_SENDING;
338 len = (c->buf + c->len) - c->i;
340 while (len > 0) {
341 switch (ret = tls_write(c->ctx, c->i, len)) {
342 case -1:
343 LOGE(c, "tls_write: %s", tls_error(c->ctx));
344 goodbye(fds, c);
345 return;
347 case TLS_WANT_POLLIN:
348 fds->events = POLLIN;
349 return;
351 case TLS_WANT_POLLOUT:
352 fds->events = POLLOUT;
353 return;
355 default:
356 c->i += ret;
357 len -= ret;
358 break;
362 goodbye(fds, c);
365 void
366 send_dir(char *path, struct pollfd *fds, struct client *client)
368 char fpath[PATHBUF];
369 size_t len;
371 bzero(fpath, PATHBUF);
373 if (path[0] != '.')
374 fpath[0] = '.';
376 /* this cannot fail since sizeof(fpath) > maxlen of path */
377 strlcat(fpath, path, PATHBUF);
378 len = strlen(fpath);
380 /* add a trailing / in case. */
381 if (fpath[len-1] != '/') {
382 fpath[len] = '/';
385 strlcat(fpath, "index.gmi", sizeof(fpath));
387 send_file(fpath, NULL, fds, client);
390 void
391 cgi_poll_on_child(struct pollfd *fds, struct client *c)
393 int fd;
395 if (c->waiting_on_child)
396 return;
397 c->waiting_on_child = 1;
399 fds->events = POLLIN;
401 fd = fds->fd;
402 fds->fd = c->fd;
403 c->fd = fd;
406 void
407 cgi_poll_on_client(struct pollfd *fds, struct client *c)
409 int fd;
411 if (!c->waiting_on_child)
412 return;
413 c->waiting_on_child = 0;
415 fd = fds->fd;
416 fds->fd = c->fd;
417 c->fd = fd;
420 void
421 handle_cgi(struct pollfd *fds, struct client *c)
423 ssize_t r;
425 /* ensure c->fd is the child and fds->fd the client */
426 cgi_poll_on_client(fds, c);
428 while (1) {
429 if (c->len == 0) {
430 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
431 goto end;
432 if (r == -1) {
433 if (errno == EAGAIN || errno == EWOULDBLOCK) {
434 cgi_poll_on_child(fds, c);
435 return;
437 goto end;
439 c->len = r;
440 c->off = 0;
443 while (c->len > 0) {
444 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
445 case -1:
446 goto end;
448 case TLS_WANT_POLLOUT:
449 fds->events = POLLOUT;
450 return;
452 case TLS_WANT_POLLIN:
453 fds->events = POLLIN;
454 return;
456 default:
457 c->off += r;
458 c->len -= r;
459 break;
464 end:
465 goodbye(fds, c);
468 void
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;
476 return;
477 case TLS_WANT_POLLOUT:
478 pfd->events = POLLOUT;
479 return;
482 connected_clients--;
484 tls_free(c->ctx);
485 c->ctx = NULL;
487 if (c->buf != MAP_FAILED)
488 munmap(c->buf, c->len);
490 if (c->fd != -1)
491 close(c->fd);
493 close(pfd->fd);
494 pfd->fd = -1;
497 void
498 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
500 int i, fd;
501 struct sockaddr_storage addr;
502 socklen_t len;
504 len = sizeof(addr);
505 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
506 if (errno == EWOULDBLOCK)
507 return;
508 fatal("accept: %s", strerror(errno));
511 mark_nonblock(fd);
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! */
519 fds[i].fd = fd;
520 fds[i].events = POLLIN;
522 clients[i].state = S_HANDSHAKE;
523 clients[i].fd = -1;
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;
530 connected_clients++;
531 return;
535 close(fd);
538 void
539 handle(struct pollfd *fds, struct client *client)
541 switch (client->state) {
542 case S_HANDSHAKE:
543 handle_handshake(fds, client);
544 break;
546 case S_OPEN:
547 handle_open_conn(fds, client);
548 break;
550 case S_INITIALIZING:
551 if (!start_reply(fds, client, client->code, client->meta))
552 return;
554 if (client->code != SUCCESS) {
555 /* we don't need a body */
556 goodbye(fds, client);
557 return;
560 client->state = S_SENDING;
562 /* fallthrough */
564 case S_SENDING:
565 if (client->child)
566 handle_cgi(fds, client);
567 else
568 send_file(NULL, NULL, fds, client);
569 break;
571 case S_CLOSING:
572 goodbye(fds, client);
573 break;
575 default:
576 /* unreachable */
577 abort();
581 void
582 loop(struct tls *ctx, int sock4, int sock6)
584 int i;
585 struct client clients[MAX_USERS];
586 struct pollfd fds[MAX_USERS];
588 connected_clients = 0;
590 for (i = 0; i < MAX_USERS; ++i) {
591 fds[i].fd = -1;
592 fds[i].events = POLLIN;
593 bzero(&clients[i], sizeof(struct client));
596 fds[0].fd = sock4;
597 fds[1].fd = sock6;
599 for (;;) {
600 if (poll(fds, MAX_USERS, INFTIM) == -1) {
601 if (errno == EINTR) {
602 fprintf(stderr, "connected clients: %d\n",
603 connected_clients);
604 continue;
606 fatal("poll: %s", strerror(errno));
609 for (i = 0; i < MAX_USERS; i++) {
610 if (fds[i].revents == 0)
611 continue;
613 if (fds[i].revents & (POLLERR|POLLNVAL))
614 fatal("bad fd %d: %s", fds[i].fd,
615 strerror(errno));
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]);
622 continue;
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);
630 else
631 handle(&fds[i], &clients[i]);