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 siginfo_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 /* +2 to skip the ./ */
222 if (cgi != NULL && starts_with(fpath+2, cgi))
223 return start_cgi(fpath, "", query, fds, c);
225 /* fallthrough */
227 case FILE_EXISTS:
228 if ((c->len = filesize(c->fd)) == -1) {
229 LOGE(c, "failed to get file size for %s", fpath);
230 goodbye(fds, c);
231 return 0;
234 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
235 c->fd, 0)) == MAP_FAILED) {
236 warn("mmap: %s", fpath);
237 goodbye(fds, c);
238 return 0;
240 c->i = c->buf;
241 return start_reply(fds, c, SUCCESS, mime(fpath));
243 case FILE_DIRECTORY:
244 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
245 close(c->fd);
246 c->fd = -1;
247 send_dir(fpath, fds, c);
248 return 0;
250 case FILE_MISSING:
251 if (cgi != NULL && starts_with(fpath+2, cgi))
252 return check_for_cgi(fpath, query, fds, c);
254 if (!start_reply(fds, c, NOT_FOUND, "not found"))
255 return 0;
256 goodbye(fds, c);
257 return 0;
259 default:
260 /* unreachable */
261 abort();
265 int
266 start_cgi(const char *spath, const char *relpath, const char *query,
267 struct pollfd *fds, struct client *c)
269 pid_t pid;
270 int p[2]; /* read end, write end */
272 if (pipe(p) == -1)
273 goto err;
275 switch (pid = fork()) {
276 case -1:
277 goto err;
279 case 0: { /* child */
280 char *ex, *requri, *portno;
281 char addr[INET_ADDRSTRLEN];
282 char *argv[] = { NULL, NULL, NULL };
284 spath++;
286 close(p[0]);
287 if (dup2(p[1], 1) == -1)
288 goto childerr;
290 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
291 goto childerr;
293 if (asprintf(&portno, "%d", port) == -1)
294 goto childerr;
296 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
297 goto childerr;
299 if (asprintf(&requri, "%s%s%s", spath,
300 *relpath == '\0' ? "" : "/",
301 relpath) == -1)
302 goto childerr;
304 argv[0] = argv[1] = ex;
306 /* fix the env */
307 SAFE_SETENV("GATEWAY_INTERFACE", "CGI/1.1");
308 SAFE_SETENV("SERVER_SOFTWARE", "gmid");
309 SAFE_SETENV("SERVER_PORT", portno);
310 /* setenv("SERVER_NAME", "", 1); */
311 SAFE_SETENV("SCRIPT_NAME", spath);
312 SAFE_SETENV("SCRIPT_EXECUTABLE", ex);
313 SAFE_SETENV("REQUEST_URI", requri);
314 SAFE_SETENV("REQUEST_RELATIVE", relpath);
315 SAFE_SETENV("QUERY_STRING", query);
316 SAFE_SETENV("REMOTE_HOST", addr);
317 SAFE_SETENV("REMOTE_ADDR", addr);
318 SAFE_SETENV("DOCUMENT_ROOT", dir);
320 if (tls_peer_cert_provided(c->ctx)) {
321 SAFE_SETENV("AUTH_TYPE", "Certificate");
322 SAFE_SETENV("REMOTE_USER", tls_peer_cert_subject(c->ctx));
323 SAFE_SETENV("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
324 SAFE_SETENV("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
327 execvp(ex, argv);
328 goto childerr;
331 default: /* parent */
332 close(p[1]);
333 close(c->fd);
334 c->fd = p[0];
335 c->child = pid;
336 mark_nonblock(c->fd);
337 c->state = S_SENDING;
338 handle_cgi(fds, c);
339 return 0;
342 err:
343 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
344 return 0;
345 goodbye(fds, c);
346 return 0;
348 childerr:
349 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
350 close(p[1]);
351 _exit(1);
354 void
355 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
357 int fd;
359 if (c->waiting_on_child)
360 return;
361 c->waiting_on_child = 1;
363 fds->events = POLLIN;
365 fd = fds->fd;
366 fds->fd = c->fd;
367 c->fd = fd;
370 void
371 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
373 int fd;
375 if (!c->waiting_on_child)
376 return;
377 c->waiting_on_child = 0;
379 fd = fds->fd;
380 fds->fd = c->fd;
381 c->fd = fd;
384 void
385 handle_cgi(struct pollfd *fds, struct client *c)
387 ssize_t r;
389 /* ensure c->fd is the child and fds->fd the client */
390 cgi_setpoll_on_client(fds, c);
392 while (1) {
393 if (c->len == 0) {
394 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
395 goto end;
396 if (r == -1) {
397 if (errno == EAGAIN || errno == EWOULDBLOCK) {
398 cgi_setpoll_on_child(fds, c);
399 return;
401 goto end;
403 c->len = r;
404 c->off = 0;
407 while (c->len > 0) {
408 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
409 case -1:
410 goto end;
412 case TLS_WANT_POLLOUT:
413 fds->events = POLLOUT;
414 return;
416 case TLS_WANT_POLLIN:
417 fds->events = POLLIN;
418 return;
420 default:
421 c->off += r;
422 c->len -= r;
423 break;
428 end:
429 goodbye(fds, c);
432 void
433 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
435 ssize_t ret, len;
437 if (c->fd == -1) {
438 if (!open_file(path, query, fds, c))
439 return;
440 c->state = S_SENDING;
443 len = (c->buf + c->len) - c->i;
445 while (len > 0) {
446 switch (ret = tls_write(c->ctx, c->i, len)) {
447 case -1:
448 LOGE(c, "tls_write: %s", tls_error(c->ctx));
449 goodbye(fds, c);
450 return;
452 case TLS_WANT_POLLIN:
453 fds->events = POLLIN;
454 return;
456 case TLS_WANT_POLLOUT:
457 fds->events = POLLOUT;
458 return;
460 default:
461 c->i += ret;
462 len -= ret;
463 break;
467 goodbye(fds, c);
470 void
471 send_dir(char *path, struct pollfd *fds, struct client *client)
473 char fpath[PATHBUF];
474 size_t len;
476 bzero(fpath, PATHBUF);
478 if (path[0] != '.')
479 fpath[0] = '.';
481 /* this cannot fail since sizeof(fpath) > maxlen of path */
482 strlcat(fpath, path, PATHBUF);
483 len = strlen(fpath);
485 /* add a trailing / in case. */
486 if (fpath[len-1] != '/') {
487 fpath[len] = '/';
490 strlcat(fpath, "index.gmi", sizeof(fpath));
492 send_file(fpath, NULL, fds, client);
495 void
496 handle(struct pollfd *fds, struct client *client)
498 char buf[GEMINI_URL_LEN];
499 const char *parse_err;
500 struct uri uri;
502 switch (client->state) {
503 case S_OPEN:
504 bzero(buf, GEMINI_URL_LEN);
505 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
506 case -1:
507 LOGE(client, "tls_read: %s", tls_error(client->ctx));
508 goodbye(fds, client);
509 return;
511 case TLS_WANT_POLLIN:
512 fds->events = POLLIN;
513 return;
515 case TLS_WANT_POLLOUT:
516 fds->events = POLLOUT;
517 return;
520 if (!trim_req_uri(buf) || !parse_uri(buf, &uri, &parse_err)) {
521 if (!start_reply(fds, client, BAD_REQUEST, parse_err))
522 return;
523 goodbye(fds, client);
524 return;
527 LOGI(client, "GET %s%s%s",
528 *uri.path ? uri.path : "/",
529 *uri.query ? "?" : "",
530 *uri.query ? uri.query : "");
532 send_file(uri.path, uri.query, fds, client);
533 break;
535 case S_INITIALIZING:
536 if (!start_reply(fds, client, client->code, client->meta))
537 return;
539 if (client->code != SUCCESS) {
540 /* we don't need a body */
541 goodbye(fds, client);
542 return;
545 client->state = S_SENDING;
547 /* fallthrough */
549 case S_SENDING:
550 if (client->child != -1)
551 handle_cgi(fds, client);
552 else
553 send_file(NULL, NULL, fds, client);
554 break;
556 case S_CLOSING:
557 goodbye(fds, client);
558 break;
560 default:
561 /* unreachable */
562 abort();
566 void
567 mark_nonblock(int fd)
569 int flags;
571 if ((flags = fcntl(fd, F_GETFL)) == -1)
572 FATAL("fcntl(F_GETFL): %s", strerror(errno));
573 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
574 FATAL("fcntl(F_SETFL): %s", strerror(errno));
577 int
578 make_socket(int port, int family)
580 int sock, v;
581 struct sockaddr_in addr4;
582 struct sockaddr_in6 addr6;
583 struct sockaddr *addr;
584 socklen_t len;
586 switch (family) {
587 case AF_INET:
588 bzero(&addr4, sizeof(addr4));
589 addr4.sin_family = family;
590 addr4.sin_port = htons(port);
591 addr4.sin_addr.s_addr = INADDR_ANY;
592 addr = (struct sockaddr*)&addr4;
593 len = sizeof(addr4);
594 break;
596 case AF_INET6:
597 bzero(&addr6, sizeof(addr6));
598 addr6.sin6_family = AF_INET6;
599 addr6.sin6_port = htons(port);
600 addr6.sin6_addr = in6addr_any;
601 addr = (struct sockaddr*)&addr6;
602 len = sizeof(addr6);
603 break;
605 default:
606 /* unreachable */
607 abort();
610 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
611 FATAL("socket: %s", strerror(errno));
613 v = 1;
614 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
615 FATAL("setsockopt(SO_REUSEADDR): %s", strerror(errno));
617 v = 1;
618 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
619 FATAL("setsockopt(SO_REUSEPORT): %s", strerror(errno));
621 mark_nonblock(sock);
623 if (bind(sock, addr, len) == -1)
624 FATAL("bind: %s", strerror(errno));
626 if (listen(sock, 16) == -1)
627 FATAL("listen: %s", strerror(errno));
629 return sock;
632 void
633 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
635 int i, fd;
636 struct sockaddr_in addr;
637 socklen_t len;
639 len = sizeof(addr);
640 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
641 if (errno == EWOULDBLOCK)
642 return;
643 FATAL("accept: %s", strerror(errno));
646 mark_nonblock(fd);
648 for (i = 0; i < MAX_USERS; ++i) {
649 if (fds[i].fd == -1) {
650 bzero(&clients[i], sizeof(struct client));
651 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
652 break; /* goodbye fd! */
654 fds[i].fd = fd;
655 fds[i].events = POLLIN;
657 clients[i].state = S_OPEN;
658 clients[i].fd = -1;
659 clients[i].child = -1;
660 clients[i].buf = MAP_FAILED;
661 clients[i].af = AF_INET;
662 clients[i].addr = addr.sin_addr;
664 connected_clients++;
665 return;
669 close(fd);
672 void
673 goodbye(struct pollfd *pfd, struct client *c)
675 ssize_t ret;
677 c->state = S_CLOSING;
679 ret = tls_close(c->ctx);
680 if (ret == TLS_WANT_POLLIN) {
681 pfd->events = POLLIN;
682 return;
684 if (ret == TLS_WANT_POLLOUT) {
685 pfd->events = POLLOUT;
686 return;
689 connected_clients--;
691 tls_free(c->ctx);
692 c->ctx = NULL;
694 if (c->buf != MAP_FAILED)
695 munmap(c->buf, c->len);
697 if (c->fd != -1)
698 close(c->fd);
700 close(pfd->fd);
701 pfd->fd = -1;
704 void
705 loop(struct tls *ctx, int sock)
707 int i, todo;
708 struct client clients[MAX_USERS];
709 struct pollfd fds[MAX_USERS];
711 for (i = 0; i < MAX_USERS; ++i) {
712 fds[i].fd = -1;
713 fds[i].events = POLLIN;
714 bzero(&clients[i], sizeof(struct client));
717 fds[0].fd = sock;
719 for (;;) {
720 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
721 if (errno == EINTR) {
722 warnx("connected clients: %d",
723 connected_clients);
724 continue;
726 FATAL("poll: %s", strerror(errno));
729 for (i = 0; i < MAX_USERS; i++) {
730 assert(i < MAX_USERS);
732 if (fds[i].revents == 0)
733 continue;
735 if (fds[i].revents & (POLLERR|POLLNVAL))
736 FATAL("bad fd %d: %s", fds[i].fd,
737 strerror(errno));
739 if (fds[i].revents & POLLHUP) {
740 /* fds[i] may be the fd of the stdin
741 * of a cgi script that has exited. */
742 if (!clients[i].waiting_on_child) {
743 goodbye(&fds[i], &clients[i]);
744 continue;
748 todo--;
750 if (i == 0) { /* new client */
751 do_accept(sock, ctx, fds, clients);
752 continue;
755 handle(&fds[i], &clients[i]);
760 char *
761 absolutify_path(const char *path)
763 char *wd, *r;
765 if (*path == '/')
766 return strdup(path);
768 wd = getwd(NULL);
769 if (asprintf(&r, "%s/%s", wd, path) == -1)
770 err(1, "asprintf");
771 free(wd);
772 return r;
775 void
776 usage(const char *me)
778 fprintf(stderr,
779 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
780 "[-l logfile] [-p port] [-x cgi-bin]\n",
781 me);
784 int
785 main(int argc, char **argv)
787 const char *cert = "cert.pem", *key = "key.pem";
788 struct tls *ctx = NULL;
789 struct tls_config *conf;
790 int sock, ch;
792 signal(SIGPIPE, SIG_IGN);
793 signal(SIGCHLD, SIG_IGN);
795 #ifdef SIGINFO
796 signal(SIGINFO, siginfo_handler);
797 #endif
798 signal(SIGUSR2, siginfo_handler);
800 connected_clients = 0;
802 if ((dir = absolutify_path("docs")) == NULL)
803 err(1, "absolutify_path");
805 cgi = NULL;
806 port = 1965;
807 foreground = 0;
809 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
810 switch (ch) {
811 case 'c':
812 cert = optarg;
813 break;
815 case 'd':
816 free((char*)dir);
817 if ((dir = absolutify_path(optarg)) == NULL)
818 err(1, "absolutify_path");
819 break;
821 case 'f':
822 foreground = 1;
823 break;
825 case 'h':
826 usage(*argv);
827 return 0;
829 case 'k':
830 key = optarg;
831 break;
833 case 'p': {
834 char *ep;
835 long lval;
837 errno = 0;
838 lval = strtol(optarg, &ep, 10);
839 if (optarg[0] == '\0' || *ep != '\0')
840 err(1, "not a number: %s", optarg);
841 if (lval < 0 || lval > UINT16_MAX)
842 err(1, "port number out of range: %s", optarg);
843 port = lval;
844 break;
847 case 'x':
848 cgi = optarg;
849 break;
851 default:
852 usage(*argv);
853 return 1;
857 if ((conf = tls_config_new()) == NULL)
858 err(1, "tls_config_new");
860 /* optionally accept client certs, but don't try to verify them */
861 tls_config_verify_client_optional(conf);
862 tls_config_insecure_noverifycert(conf);
864 if (tls_config_set_protocols(conf,
865 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
866 err(1, "tls_config_set_protocols");
868 if (tls_config_set_cert_file(conf, cert) == -1)
869 err(1, "tls_config_set_cert_file: %s", cert);
871 if (tls_config_set_key_file(conf, key) == -1)
872 err(1, "tls_config_set_key_file: %s", key);
874 if ((ctx = tls_server()) == NULL)
875 err(1, "tls_server");
877 if (tls_configure(ctx, conf) == -1)
878 errx(1, "tls_configure: %s", tls_error(ctx));
880 sock = make_socket(port, AF_INET);
882 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
883 err(1, "open: %s", dir);
885 if (!foreground && daemon(0, 1) == -1)
886 exit(1);
888 if (cgi != NULL) {
889 if (unveil(dir, "rx") == -1)
890 err(1, "unveil");
891 if (pledge("stdio rpath inet proc exec", NULL) == -1)
892 err(1, "pledge");
893 } else {
894 if (unveil(dir, "r") == -1)
895 err(1, "unveil");
896 if (pledge("stdio rpath inet", NULL) == -1)
897 err(1, "pledge");
900 loop(ctx, sock);
902 close(sock);
903 tls_free(ctx);
904 tls_config_free(conf);