Blob


1 /*
2 * Copyright (c) 2020 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/socket.h>
19 #include <sys/stat.h>
21 #include <assert.h>
22 #include <err.h>
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <limits.h>
26 #include <signal.h>
27 #include <string.h>
29 #include "gmid.h"
31 const char *dir, *cgi;
32 int dirfd;
33 int port;
34 int foreground;
35 int connected_clients;
37 struct etm { /* file extension to mime */
38 const char *mime;
39 const char *ext;
40 } filetypes[] = {
41 {"application/pdf", "pdf"},
43 {"image/gif", "gif"},
44 {"image/jpeg", "jpg"},
45 {"image/jpeg", "jpeg"},
46 {"image/png", "png"},
47 {"image/svg+xml", "svg"},
49 {"text/gemini", "gemini"},
50 {"text/gemini", "gmi"},
51 {"text/markdown", "markdown"},
52 {"text/markdown", "md"},
53 {"text/plain", "txt"},
54 {"text/xml", "xml"},
56 {NULL, NULL}
57 };
59 void
60 sig_handler(int sig)
61 {
62 (void)sig;
63 }
65 int
66 starts_with(const char *str, const char *prefix)
67 {
68 size_t i;
70 for (i = 0; prefix[i] != '\0'; ++i)
71 if (str[i] != prefix[i])
72 return 0;
73 return 1;
74 }
76 int
77 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
78 {
79 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
80 int len;
81 int ret;
83 client->code = code;
84 client->meta = reason;
85 client->state = S_INITIALIZING;
87 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
88 assert(len < (int)sizeof(buf));
89 ret = tls_write(client->ctx, buf, len);
90 if (ret == TLS_WANT_POLLIN) {
91 pfd->events = POLLIN;
92 return 0;
93 }
95 if (ret == TLS_WANT_POLLOUT) {
96 pfd->events = POLLOUT;
97 return 0;
98 }
100 return 1;
103 ssize_t
104 filesize(int fd)
106 ssize_t len;
108 if ((len = lseek(fd, 0, SEEK_END)) == -1)
109 return -1;
110 if (lseek(fd, 0, SEEK_SET) == -1)
111 return -1;
112 return len;
115 const char *
116 path_ext(const char *path)
118 const char *end;
120 end = path + strlen(path)-1; /* the last byte before the NUL */
121 for (; end != path; --end) {
122 if (*end == '.')
123 return end+1;
124 if (*end == '/')
125 break;
128 return NULL;
131 const char *
132 mime(const char *path)
134 const char *ext, *def = "application/octet-stream";
135 struct etm *t;
137 if ((ext = path_ext(path)) == NULL)
138 return def;
140 for (t = filetypes; t->mime != NULL; ++t)
141 if (!strcmp(ext, t->ext))
142 return t->mime;
144 return def;
147 int
148 check_path(struct client *c, const char *path, int *fd)
150 struct stat sb;
152 assert(path != NULL);
153 if ((*fd = openat(dirfd, *path ? path : ".",
154 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
155 return FILE_MISSING;
158 if (fstat(*fd, &sb) == -1) {
159 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
160 return FILE_MISSING;
163 if (S_ISDIR(sb.st_mode))
164 return FILE_DIRECTORY;
166 if (sb.st_mode & S_IXUSR)
167 return FILE_EXECUTABLE;
169 return FILE_EXISTS;
172 /*
173 * the inverse of this algorithm, i.e. starting from the start of the
174 * path + strlen(cgi), and checking if each component, should be
175 * faster. But it's tedious to write. This does the opposite: starts
176 * from the end and strip one component at a time, until either an
177 * executable is found or we emptied the path.
178 */
179 int
180 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
182 char *end;
183 end = strchr(path, '\0');
185 /* NB: assume CGI is enabled and path matches cgi */
187 while (end > path) {
188 /* go up one level. UNIX paths are simple and POSIX
189 * dirname, with its ambiguities on if the given path
190 * is changed or not, gives me headaches. */
191 while (*end != '/')
192 end--;
193 *end = '\0';
195 switch (check_path(c, path, &c->fd)) {
196 case FILE_EXECUTABLE:
197 return start_cgi(path, end+1, query, fds,c);
198 case FILE_MISSING:
199 break;
200 default:
201 goto err;
204 *end = '/';
205 end--;
208 err:
209 if (!start_reply(fds, c, NOT_FOUND, "not found"))
210 return 0;
211 goodbye(fds, c);
212 return 0;
216 int
217 open_file(char *fpath, char *query, struct pollfd *fds, struct client *c)
219 switch (check_path(c, fpath, &c->fd)) {
220 case FILE_EXECUTABLE:
221 if (cgi != NULL && starts_with(fpath, cgi))
222 return start_cgi(fpath, "", query, fds, c);
224 /* fallthrough */
226 case FILE_EXISTS:
227 if ((c->len = filesize(c->fd)) == -1) {
228 LOGE(c, "failed to get file size for %s", fpath);
229 goodbye(fds, c);
230 return 0;
233 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
234 c->fd, 0)) == MAP_FAILED) {
235 warn("mmap: %s", fpath);
236 goodbye(fds, c);
237 return 0;
239 c->i = c->buf;
240 return start_reply(fds, c, SUCCESS, mime(fpath));
242 case FILE_DIRECTORY:
243 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
244 close(c->fd);
245 c->fd = -1;
246 send_dir(fpath, fds, c);
247 return 0;
249 case FILE_MISSING:
250 if (cgi != NULL && starts_with(fpath, cgi))
251 return check_for_cgi(fpath, query, fds, c);
253 if (!start_reply(fds, c, NOT_FOUND, "not found"))
254 return 0;
255 goodbye(fds, c);
256 return 0;
258 default:
259 /* unreachable */
260 abort();
264 int
265 start_cgi(const char *spath, const char *relpath, const char *query,
266 struct pollfd *fds, struct client *c)
268 pid_t pid;
269 int p[2]; /* read end, write end */
271 if (pipe(p) == -1)
272 goto err;
274 switch (pid = fork()) {
275 case -1:
276 goto err;
278 case 0: { /* child */
279 char *ex, *requri, *portno;
280 char addr[INET_ADDRSTRLEN];
281 char *argv[] = { NULL, NULL, NULL };
283 close(p[0]);
284 if (dup2(p[1], 1) == -1)
285 goto childerr;
287 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
288 goto childerr;
290 if (asprintf(&portno, "%d", port) == -1)
291 goto childerr;
293 if (asprintf(&ex, "%s/%s", dir, spath) == -1)
294 goto childerr;
296 if (asprintf(&requri, "%s%s%s", spath,
297 *relpath == '\0' ? "" : "/",
298 relpath) == -1)
299 goto childerr;
301 argv[0] = argv[1] = ex;
303 /* fix the env */
304 SAFE_SETENV("GATEWAY_INTERFACE", "CGI/1.1");
305 SAFE_SETENV("SERVER_SOFTWARE", "gmid");
306 SAFE_SETENV("SERVER_PORT", portno);
307 /* setenv("SERVER_NAME", "", 1); */
308 SAFE_SETENV("SCRIPT_NAME", spath);
309 SAFE_SETENV("SCRIPT_EXECUTABLE", ex);
310 SAFE_SETENV("REQUEST_URI", requri);
311 SAFE_SETENV("REQUEST_RELATIVE", relpath);
312 SAFE_SETENV("QUERY_STRING", query);
313 SAFE_SETENV("REMOTE_HOST", addr);
314 SAFE_SETENV("REMOTE_ADDR", addr);
315 SAFE_SETENV("DOCUMENT_ROOT", dir);
317 if (tls_peer_cert_provided(c->ctx)) {
318 SAFE_SETENV("AUTH_TYPE", "Certificate");
319 SAFE_SETENV("REMOTE_USER", tls_peer_cert_subject(c->ctx));
320 SAFE_SETENV("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
321 SAFE_SETENV("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
324 execvp(ex, argv);
325 goto childerr;
328 default: /* parent */
329 close(p[1]);
330 close(c->fd);
331 c->fd = p[0];
332 c->child = pid;
333 mark_nonblock(c->fd);
334 c->state = S_SENDING;
335 handle_cgi(fds, c);
336 return 0;
339 err:
340 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
341 return 0;
342 goodbye(fds, c);
343 return 0;
345 childerr:
346 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
347 close(p[1]);
348 _exit(1);
351 void
352 cgi_poll_on_child(struct pollfd *fds, struct client *c)
354 int fd;
356 if (c->waiting_on_child)
357 return;
358 c->waiting_on_child = 1;
360 fds->events = POLLIN;
362 fd = fds->fd;
363 fds->fd = c->fd;
364 c->fd = fd;
367 void
368 cgi_poll_on_client(struct pollfd *fds, struct client *c)
370 int fd;
372 if (!c->waiting_on_child)
373 return;
374 c->waiting_on_child = 0;
376 fd = fds->fd;
377 fds->fd = c->fd;
378 c->fd = fd;
381 void
382 handle_cgi(struct pollfd *fds, struct client *c)
384 ssize_t r;
386 /* ensure c->fd is the child and fds->fd the client */
387 cgi_poll_on_client(fds, c);
389 while (1) {
390 if (c->len == 0) {
391 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
392 goto end;
393 if (r == -1) {
394 if (errno == EAGAIN || errno == EWOULDBLOCK) {
395 cgi_poll_on_child(fds, c);
396 return;
398 goto end;
400 c->len = r;
401 c->off = 0;
404 while (c->len > 0) {
405 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
406 case -1:
407 goto end;
409 case TLS_WANT_POLLOUT:
410 fds->events = POLLOUT;
411 return;
413 case TLS_WANT_POLLIN:
414 fds->events = POLLIN;
415 return;
417 default:
418 c->off += r;
419 c->len -= r;
420 break;
425 end:
426 goodbye(fds, c);
429 void
430 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
432 ssize_t ret, len;
434 if (c->fd == -1) {
435 if (!open_file(path, query, fds, c))
436 return;
437 c->state = S_SENDING;
440 len = (c->buf + c->len) - c->i;
442 while (len > 0) {
443 switch (ret = tls_write(c->ctx, c->i, len)) {
444 case -1:
445 LOGE(c, "tls_write: %s", tls_error(c->ctx));
446 goodbye(fds, c);
447 return;
449 case TLS_WANT_POLLIN:
450 fds->events = POLLIN;
451 return;
453 case TLS_WANT_POLLOUT:
454 fds->events = POLLOUT;
455 return;
457 default:
458 c->i += ret;
459 len -= ret;
460 break;
464 goodbye(fds, c);
467 void
468 send_dir(char *path, struct pollfd *fds, struct client *client)
470 char fpath[PATHBUF];
471 size_t len;
473 bzero(fpath, PATHBUF);
475 if (path[0] != '.')
476 fpath[0] = '.';
478 /* this cannot fail since sizeof(fpath) > maxlen of path */
479 strlcat(fpath, path, PATHBUF);
480 len = strlen(fpath);
482 /* add a trailing / in case. */
483 if (fpath[len-1] != '/') {
484 fpath[len] = '/';
487 strlcat(fpath, "index.gmi", sizeof(fpath));
489 send_file(fpath, NULL, fds, client);
492 void
493 handle(struct pollfd *fds, struct client *client)
495 char buf[GEMINI_URL_LEN];
496 const char *parse_err;
497 struct uri uri;
499 switch (client->state) {
500 case S_OPEN:
501 bzero(buf, GEMINI_URL_LEN);
502 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
503 case -1:
504 LOGE(client, "tls_read: %s", tls_error(client->ctx));
505 goodbye(fds, client);
506 return;
508 case TLS_WANT_POLLIN:
509 fds->events = POLLIN;
510 return;
512 case TLS_WANT_POLLOUT:
513 fds->events = POLLOUT;
514 return;
517 parse_err = "invalid request";
518 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
519 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
520 return;
521 goodbye(fds, client);
522 return;
525 LOGI(client, "GET %s%s%s",
526 *uri.path ? uri.path : "/",
527 *uri.query ? "?" : "",
528 *uri.query ? uri.query : "");
530 send_file(uri.path, uri.query, fds, client);
531 break;
533 case S_INITIALIZING:
534 if (!start_reply(fds, client, client->code, client->meta))
535 return;
537 if (client->code != SUCCESS) {
538 /* we don't need a body */
539 goodbye(fds, client);
540 return;
543 client->state = S_SENDING;
545 /* fallthrough */
547 case S_SENDING:
548 if (client->child != -1)
549 handle_cgi(fds, client);
550 else
551 send_file(NULL, NULL, fds, client);
552 break;
554 case S_CLOSING:
555 goodbye(fds, client);
556 break;
558 default:
559 /* unreachable */
560 abort();
564 void
565 mark_nonblock(int fd)
567 int flags;
569 if ((flags = fcntl(fd, F_GETFL)) == -1)
570 FATAL("fcntl(F_GETFL): %s", strerror(errno));
571 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
572 FATAL("fcntl(F_SETFL): %s", strerror(errno));
575 int
576 make_socket(int port, int family)
578 int sock, v;
579 struct sockaddr_in addr4;
580 struct sockaddr_in6 addr6;
581 struct sockaddr *addr;
582 socklen_t len;
584 switch (family) {
585 case AF_INET:
586 bzero(&addr4, sizeof(addr4));
587 addr4.sin_family = family;
588 addr4.sin_port = htons(port);
589 addr4.sin_addr.s_addr = INADDR_ANY;
590 addr = (struct sockaddr*)&addr4;
591 len = sizeof(addr4);
592 break;
594 case AF_INET6:
595 bzero(&addr6, sizeof(addr6));
596 addr6.sin6_family = AF_INET6;
597 addr6.sin6_port = htons(port);
598 addr6.sin6_addr = in6addr_any;
599 addr = (struct sockaddr*)&addr6;
600 len = sizeof(addr6);
601 break;
603 default:
604 /* unreachable */
605 abort();
608 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
609 FATAL("socket: %s", strerror(errno));
611 v = 1;
612 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
613 FATAL("setsockopt(SO_REUSEADDR): %s", strerror(errno));
615 v = 1;
616 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
617 FATAL("setsockopt(SO_REUSEPORT): %s", strerror(errno));
619 mark_nonblock(sock);
621 if (bind(sock, addr, len) == -1)
622 FATAL("bind: %s", strerror(errno));
624 if (listen(sock, 16) == -1)
625 FATAL("listen: %s", strerror(errno));
627 return sock;
630 void
631 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
633 int i, fd;
634 struct sockaddr_in addr;
635 socklen_t len;
637 len = sizeof(addr);
638 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
639 if (errno == EWOULDBLOCK)
640 return;
641 FATAL("accept: %s", strerror(errno));
644 mark_nonblock(fd);
646 for (i = 0; i < MAX_USERS; ++i) {
647 if (fds[i].fd == -1) {
648 bzero(&clients[i], sizeof(struct client));
649 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
650 break; /* goodbye fd! */
652 fds[i].fd = fd;
653 fds[i].events = POLLIN;
655 clients[i].state = S_OPEN;
656 clients[i].fd = -1;
657 clients[i].child = -1;
658 clients[i].buf = MAP_FAILED;
659 clients[i].af = AF_INET;
660 clients[i].addr = addr.sin_addr;
662 connected_clients++;
663 return;
667 close(fd);
670 void
671 goodbye(struct pollfd *pfd, struct client *c)
673 ssize_t ret;
675 c->state = S_CLOSING;
677 ret = tls_close(c->ctx);
678 if (ret == TLS_WANT_POLLIN) {
679 pfd->events = POLLIN;
680 return;
682 if (ret == TLS_WANT_POLLOUT) {
683 pfd->events = POLLOUT;
684 return;
687 connected_clients--;
689 tls_free(c->ctx);
690 c->ctx = NULL;
692 if (c->buf != MAP_FAILED)
693 munmap(c->buf, c->len);
695 if (c->fd != -1)
696 close(c->fd);
698 close(pfd->fd);
699 pfd->fd = -1;
702 void
703 loop(struct tls *ctx, int sock)
705 int i;
706 struct client clients[MAX_USERS];
707 struct pollfd fds[MAX_USERS];
709 for (i = 0; i < MAX_USERS; ++i) {
710 fds[i].fd = -1;
711 fds[i].events = POLLIN;
712 bzero(&clients[i], sizeof(struct client));
715 fds[0].fd = sock;
717 for (;;) {
718 if (poll(fds, MAX_USERS, INFTIM) == -1) {
719 if (errno == EINTR) {
720 warnx("connected clients: %d",
721 connected_clients);
722 continue;
724 FATAL("poll: %s", strerror(errno));
727 for (i = 0; i < MAX_USERS; i++) {
728 if (fds[i].revents == 0)
729 continue;
731 if (fds[i].revents & (POLLERR|POLLNVAL))
732 FATAL("bad fd %d: %s", fds[i].fd,
733 strerror(errno));
735 if (fds[i].revents & POLLHUP) {
736 /* fds[i] may be the fd of the stdin
737 * of a cgi script that has exited. */
738 if (!clients[i].waiting_on_child) {
739 goodbye(&fds[i], &clients[i]);
740 continue;
744 if (i == 0) { /* new client */
745 do_accept(sock, ctx, fds, clients);
746 continue;
749 handle(&fds[i], &clients[i]);
754 char *
755 absolutify_path(const char *path)
757 char *wd, *r;
759 if (*path == '/')
760 return strdup(path);
762 wd = getwd(NULL);
763 if (asprintf(&r, "%s/%s", wd, path) == -1)
764 err(1, "asprintf");
765 free(wd);
766 return r;
769 void
770 usage(const char *me)
772 fprintf(stderr,
773 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
774 "[-l logfile] [-p port] [-x cgi-bin]\n",
775 me);
778 int
779 main(int argc, char **argv)
781 const char *cert = "cert.pem", *key = "key.pem";
782 struct tls *ctx = NULL;
783 struct tls_config *conf;
784 int sock, ch;
785 connected_clients = 0;
787 if ((dir = absolutify_path("docs")) == NULL)
788 err(1, "absolutify_path");
790 cgi = NULL;
791 port = 1965;
792 foreground = 0;
794 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
795 switch (ch) {
796 case 'c':
797 cert = optarg;
798 break;
800 case 'd':
801 free((char*)dir);
802 if ((dir = absolutify_path(optarg)) == NULL)
803 err(1, "absolutify_path");
804 break;
806 case 'f':
807 foreground = 1;
808 break;
810 case 'h':
811 usage(*argv);
812 return 0;
814 case 'k':
815 key = optarg;
816 break;
818 case 'p': {
819 char *ep;
820 long lval;
822 errno = 0;
823 lval = strtol(optarg, &ep, 10);
824 if (optarg[0] == '\0' || *ep != '\0')
825 err(1, "not a number: %s", optarg);
826 if (lval < 0 || lval > UINT16_MAX)
827 err(1, "port number out of range: %s", optarg);
828 port = lval;
829 break;
832 case 'x':
833 cgi = optarg;
834 break;
836 default:
837 usage(*argv);
838 return 1;
842 signal(SIGPIPE, SIG_IGN);
843 signal(SIGCHLD, SIG_IGN);
845 #ifdef SIGINFO
846 signal(SIGINFO, sig_handler);
847 #endif
848 signal(SIGUSR2, sig_handler);
850 if (!foreground)
851 signal(SIGHUP, SIG_IGN);
853 if ((conf = tls_config_new()) == NULL)
854 err(1, "tls_config_new");
856 /* optionally accept client certs, but don't try to verify them */
857 tls_config_verify_client_optional(conf);
858 tls_config_insecure_noverifycert(conf);
860 if (tls_config_set_protocols(conf,
861 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
862 err(1, "tls_config_set_protocols");
864 if (tls_config_set_cert_file(conf, cert) == -1)
865 err(1, "tls_config_set_cert_file: %s", cert);
867 if (tls_config_set_key_file(conf, key) == -1)
868 err(1, "tls_config_set_key_file: %s", key);
870 if ((ctx = tls_server()) == NULL)
871 err(1, "tls_server");
873 if (tls_configure(ctx, conf) == -1)
874 errx(1, "tls_configure: %s", tls_error(ctx));
876 sock = make_socket(port, AF_INET);
878 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
879 err(1, "open: %s", dir);
881 if (!foreground && daemon(0, 1) == -1)
882 exit(1);
884 if (unveil(dir, "rx") == -1)
885 err(1, "unveil");
887 if (pledge("stdio rpath inet proc exec", NULL) == -1)
888 err(1, "pledge");
890 /* drop proc and exec if cgi isn't enabled */
891 if (cgi == NULL && pledge("stdio rpath inet", NULL) == -1)
892 err(1, "pledge");
894 loop(ctx, sock);
896 close(sock);
897 tls_free(ctx);
898 tls_config_free(conf);