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 <arpa/inet.h>
22 #include <netinet/in.h>
24 #include <assert.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <poll.h>
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <tls.h>
34 #include <unistd.h>
36 #ifndef __OpenBSD__
37 # define pledge(a, b) 0
38 # define unveil(a, b) 0
39 #endif /* __OpenBSD__ */
41 #ifndef INFTIM
42 # define INFTIM -1
43 #endif /* INFTIM */
45 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
47 /* large enough to hold a copy of a gemini URL and still have extra room */
48 #define PATHBUF 2048
50 #define SUCCESS 20
51 #define TEMP_FAILURE 40
52 #define NOT_FOUND 51
53 #define BAD_REQUEST 59
55 #ifndef MAX_USERS
56 #define MAX_USERS 64
57 #endif
59 enum {
60 S_OPEN,
61 S_INITIALIZING,
62 S_SENDING,
63 S_CLOSING,
64 };
66 struct client {
67 struct tls *ctx;
68 int state;
69 int code;
70 const char *meta;
71 int fd;
72 pid_t child;
73 void *buf, *i;
74 ssize_t len, off;
75 int af;
76 struct in_addr addr;
77 };
79 struct etm { /* file extension to mime */
80 const char *mime;
81 const char *ext;
82 } filetypes[] = {
83 {"application/pdf", "pdf"},
85 {"image/gif", "gif"},
86 {"image/jpeg", "jpg"},
87 {"image/jpeg", "jpeg"},
88 {"image/png", "png"},
89 {"image/svg+xml", "svg"},
91 {"text/gemini", "gemini"},
92 {"text/gemini", "gmi"},
93 {"text/markdown", "markdown"},
94 {"text/markdown", "md"},
95 {"text/plain", "txt"},
96 {"text/xml", "xml"},
98 {NULL, NULL}
99 };
101 #define LOG(c, fmt, ...) \
102 do { \
103 char buf[INET_ADDRSTRLEN]; \
104 if (inet_ntop((c)->af, &(c)->addr, buf, sizeof(buf)) == NULL) \
105 err(1, "inet_ntop"); \
106 dprintf(logfd, "[%s] " fmt "\n", buf, __VA_ARGS__); \
107 } while (0)
109 const char *dir;
110 int dirfd, logfd;
111 int cgi;
113 char *url_after_proto(char*);
114 char *url_start_of_request(char*);
115 int url_trim(struct client*, char*);
116 char *adjust_path(char*);
117 int path_isdir(char*);
118 ssize_t filesize(int);
120 int start_reply(struct pollfd*, struct client*, int, const char*);
121 const char *path_ext(const char*);
122 const char *mime(const char*);
123 int open_file(char*, char*, struct pollfd*, struct client*);
124 void start_cgi(const char*, const char*, struct pollfd*, struct client*);
125 void handle_cgi(struct pollfd*, struct client*);
126 void send_file(char*, char*, struct pollfd*, struct client*);
127 void send_dir(char*, struct pollfd*, struct client*);
128 void handle(struct pollfd*, struct client*);
130 void mark_nonblock(int);
131 int make_soket(int);
132 void do_accept(int, struct tls*, struct pollfd*, struct client*);
133 void goodbye(struct pollfd*, struct client*);
134 void loop(struct tls*, int);
136 void usage(const char*);
138 char *
139 url_after_proto(char *url)
141 char *s;
142 const char *proto = "gemini";
143 const char *marker = "://";
144 size_t i;
146 /* a relative URL */
147 if ((s = strstr(url, marker)) == NULL)
148 return url;
150 if (s - strlen(proto) != url)
151 return NULL;
153 for (i = 0; proto[i] != '\0'; ++i)
154 if (url[i] != proto[i])
155 return NULL;
157 /* a valid gemini:// URL */
158 return s + strlen(marker);
161 char *
162 url_start_of_request(char *url)
164 char *s, *t;
166 if ((s = url_after_proto(url)) == NULL)
167 return NULL;
169 if ((t = strstr(s, "/")) == NULL)
170 return s + strlen(s);
171 return t;
174 int
175 url_trim(struct client *c, char *url)
177 const char *e = "\r\n";
178 char *s;
180 if ((s = strstr(url, e)) == NULL)
181 return 0;
182 s[0] = '\0';
183 s[1] = '\0';
185 if (s[2] != '\0') {
186 LOG(c, "%s", "request longer than 1024 bytes\n");
187 return 0;
190 return 1;
193 char *
194 adjust_path(char *path)
196 char *s, *query;
197 size_t len;
199 if ((query = strchr(path, '?')) != NULL) {
200 *query = '\0';
201 query++;
204 /* /.. -> / */
205 len = strlen(path);
206 if (len >= 3) {
207 if (!strcmp(&path[len-3], "/..")) {
208 path[len-2] = '\0';
212 /* if the path is only `..` trim out and exit */
213 if (!strcmp(path, "..")) {
214 path[0] = '\0';
215 return query;
218 /* remove every ../ in the path */
219 while (1) {
220 if ((s = strstr(path, "../")) == NULL)
221 return query;
222 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
226 int
227 path_isdir(char *path)
229 if (*path == '\0')
230 return 1;
231 return path[strlen(path)-1] == '/';
234 int
235 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
237 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
238 int len;
239 int ret;
241 client->code = code;
242 client->meta = reason;
243 client->state = S_INITIALIZING;
245 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
246 assert(len < (int)sizeof(buf));
247 ret = tls_write(client->ctx, buf, len);
248 if (ret == TLS_WANT_POLLIN) {
249 pfd->events = POLLIN;
250 return 0;
253 if (ret == TLS_WANT_POLLOUT) {
254 pfd->events = POLLOUT;
255 return 0;
258 return 1;
261 ssize_t
262 filesize(int fd)
264 ssize_t len;
266 if ((len = lseek(fd, 0, SEEK_END)) == -1)
267 return -1;
268 if (lseek(fd, 0, SEEK_SET) == -1)
269 return -1;
270 return len;
273 const char *
274 path_ext(const char *path)
276 const char *end;
278 end = path + strlen(path)-1; /* the last byte before the NUL */
279 for (; end != path; --end) {
280 if (*end == '.')
281 return end+1;
282 if (*end == '/')
283 break;
286 return NULL;
289 const char *
290 mime(const char *path)
292 const char *ext, *def = "application/octet-stream";
293 struct etm *t;
295 if ((ext = path_ext(path)) == NULL)
296 return def;
298 for (t = filetypes; t->mime != NULL; ++t)
299 if (!strcmp(ext, t->ext))
300 return t->mime;
302 return def;
305 int
306 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
308 char fpath[PATHBUF];
309 struct stat sb;
311 assert(path != NULL);
313 bzero(fpath, sizeof(fpath));
315 if (*path != '.')
316 fpath[0] = '.';
317 strlcat(fpath, path, PATHBUF);
319 if ((c->fd = openat(dirfd, fpath,
320 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
321 LOG(c, "open failed: %s", fpath);
322 if (!start_reply(fds, c, NOT_FOUND, "not found"))
323 return 0;
324 goodbye(fds, c);
325 return 0;
328 if (fstat(c->fd, &sb) == -1) {
329 LOG(c, "fstat failed for %s", fpath);
330 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
331 return 0;
332 goodbye(fds, c);
333 return 0;
336 if (S_ISDIR(sb.st_mode)) {
337 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
338 close(c->fd);
339 c->fd = -1;
340 send_dir(fpath, fds, c);
341 return 0;
344 if (cgi && (sb.st_mode & S_IXUSR)) {
345 start_cgi(fpath, query, fds, c);
346 return 0;
349 if ((c->len = filesize(c->fd)) == -1) {
350 LOG(c, "failed to get file size for %s", fpath);
351 goodbye(fds, c);
352 return 0;
355 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
356 c->fd, 0)) == MAP_FAILED) {
357 warn("mmap: %s", fpath);
358 goodbye(fds, c);
359 return 0;
361 c->i = c->buf;
363 return start_reply(fds, c, SUCCESS, mime(fpath));
366 void
367 start_cgi(const char *path, const char *query,
368 struct pollfd *fds, struct client *c)
370 pid_t pid;
371 int p[2];
373 if (pipe(p) == -1)
374 goto err;
376 switch (pid = fork()) {
377 case -1:
378 goto err;
380 case 0: { /* child */
381 char *expath;
382 char addr[INET_ADDRSTRLEN];
383 char *argv[] = { NULL, NULL, NULL };
385 /* skip the initial ./ */
386 path += 2;
388 close(p[0]); /* close the read end */
389 if (dup2(p[1], 1) == -1)
390 goto childerr;
392 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
393 goto childerr;
395 /* skip the ./ at the start of path*/
396 if (asprintf(&expath, "%s%s", dir, path) == -1)
397 goto childerr;
398 argv[0] = argv[1] = expath;
400 /* fix the env */
401 setenv("SERVER_SOFTWARE", "gmid", 1);
402 /* setenv("SERVER_NAME", "", 1); */
403 /* setenv("GATEWAY_INTERFACE", "CGI/version", 1); */
404 setenv("SERVER_PROTOCOL", "gemini", 1);
405 setenv("SERVER_PORT", "1965", 1);
406 setenv("PATH_INFO", path, 1);
407 setenv("PATH_TRANSLATED", expath, 1);
408 setenv("QUERY_STRING", query ? query : "", 1);
409 setenv("REMOTE_ADDR", addr, 1);
411 execvp(expath, argv);
412 goto childerr;
415 default: /* parent */
416 close(p[1]); /* close the write end */
417 close(c->fd);
418 c->fd = p[0];
419 c->child = pid;
420 handle_cgi(fds, c);
421 return;
424 err:
425 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
426 return;
427 goodbye(fds, c);
428 return;
430 childerr:
431 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
432 close(p[1]);
433 _exit(1);
436 void
437 handle_cgi(struct pollfd *fds, struct client *c)
439 char buf[1024];
440 ssize_t r, todo;
442 while (1) {
443 r = read(c->fd, buf, sizeof(buf));
444 if (r == -1 || r == 0)
445 break;
446 todo = r;
447 while (todo > 0) {
448 switch (r = tls_write(c->ctx, buf, todo)) {
449 case -1:
450 goto end;
452 case TLS_WANT_POLLOUT:
453 case TLS_WANT_POLLIN:
454 /* evil! */
455 continue;
457 default:
458 todo -= r;
463 end:
464 goodbye(fds, c);
467 void
468 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
470 ssize_t ret, len;
472 if (c->fd == -1) {
473 if (!open_file(path, query, fds, c))
474 return;
475 c->state = S_SENDING;
478 len = (c->buf + c->len) - c->i;
480 while (len > 0) {
481 switch (ret = tls_write(c->ctx, c->i, len)) {
482 case -1:
483 LOG(c, "tls_write: %s", tls_error(c->ctx));
484 goodbye(fds, c);
485 return;
487 case TLS_WANT_POLLIN:
488 fds->events = POLLIN;
489 return;
491 case TLS_WANT_POLLOUT:
492 fds->events = POLLOUT;
493 return;
495 default:
496 c->i += ret;
497 len -= ret;
498 break;
502 goodbye(fds, c);
505 void
506 send_dir(char *path, struct pollfd *fds, struct client *client)
508 char fpath[PATHBUF];
509 size_t len;
511 bzero(fpath, PATHBUF);
513 if (path[0] != '.')
514 fpath[0] = '.';
516 /* this cannot fail since sizeof(fpath) > maxlen of path */
517 strlcat(fpath, path, PATHBUF);
518 len = strlen(fpath);
520 /* add a trailing / in case. */
521 if (fpath[len-1] != '/') {
522 fpath[len] = '/';
525 strlcat(fpath, "index.gmi", sizeof(fpath));
527 send_file(fpath, NULL, fds, client);
530 void
531 handle(struct pollfd *fds, struct client *client)
533 char buf[GEMINI_URL_LEN];
534 char *path;
535 char *query;
537 switch (client->state) {
538 case S_OPEN:
539 bzero(buf, GEMINI_URL_LEN);
540 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
541 case -1:
542 LOG(client, "tls_read: %s", tls_error(client->ctx));
543 goodbye(fds, client);
544 return;
546 case TLS_WANT_POLLIN:
547 fds->events = POLLIN;
548 return;
550 case TLS_WANT_POLLOUT:
551 fds->events = POLLOUT;
552 return;
555 if (!url_trim(client, buf)) {
556 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
557 return;
558 goodbye(fds, client);
559 return;
562 if ((path = url_start_of_request(buf)) == NULL) {
563 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
564 return;
565 goodbye(fds, client);
566 return;
569 query = adjust_path(path);
570 LOG(client, "get %s%s%s", path,
571 query ? "?" : "",
572 query ? query : "");
574 if (path_isdir(path))
575 send_dir(path, fds, client);
576 else
577 send_file(path, query, fds, client);
578 break;
580 case S_INITIALIZING:
581 if (!start_reply(fds, client, client->code, client->meta))
582 return;
584 if (client->code != SUCCESS) {
585 /* we don't need a body */
586 goodbye(fds, client);
587 return;
590 client->state = S_SENDING;
592 /* fallthrough */
594 case S_SENDING:
595 send_file(NULL, NULL, fds, client);
596 break;
598 case S_CLOSING:
599 goodbye(fds, client);
600 break;
602 default:
603 /* unreachable */
604 abort();
608 void
609 mark_nonblock(int fd)
611 int flags;
613 if ((flags = fcntl(fd, F_GETFL)) == -1)
614 err(1, "fcntl(F_GETFL)");
615 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
616 err(1, "fcntl(F_SETFL)");
619 int
620 make_socket(int port, int family)
622 int sock, v;
623 struct sockaddr_in addr4;
624 struct sockaddr_in6 addr6;
625 struct sockaddr *addr;
626 socklen_t len;
628 switch (family) {
629 case AF_INET:
630 bzero(&addr4, sizeof(addr4));
631 addr4.sin_family = family;
632 addr4.sin_port = htons(port);
633 addr4.sin_addr.s_addr = INADDR_ANY;
634 addr = (struct sockaddr*)&addr4;
635 len = sizeof(addr4);
636 break;
638 case AF_INET6:
639 bzero(&addr6, sizeof(addr6));
640 addr6.sin6_family = AF_INET6;
641 addr6.sin6_port = htons(port);
642 addr6.sin6_addr = in6addr_any;
643 addr = (struct sockaddr*)&addr6;
644 len = sizeof(addr6);
645 break;
647 default:
648 /* unreachable */
649 abort();
652 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
653 err(1, "socket");
655 v = 1;
656 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
657 err(1, "setsockopt(SO_REUSEADDR)");
659 v = 1;
660 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
661 err(1, "setsockopt(SO_REUSEPORT)");
663 mark_nonblock(sock);
665 if (bind(sock, addr, len) == -1)
666 err(1, "bind");
668 if (listen(sock, 16) == -1)
669 err(1, "listen");
671 return sock;
674 void
675 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
677 int i, fd;
678 struct sockaddr_in addr;
679 socklen_t len;
681 len = sizeof(addr);
682 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
683 if (errno == EWOULDBLOCK)
684 return;
685 err(1, "accept");
688 mark_nonblock(fd);
690 for (i = 0; i < MAX_USERS; ++i) {
691 if (fds[i].fd == -1) {
692 bzero(&clients[i], sizeof(struct client));
693 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
694 break; /* goodbye fd! */
696 fds[i].fd = fd;
697 fds[i].events = POLLIN;
699 clients[i].state = S_OPEN;
700 clients[i].fd = -1;
701 clients[i].child = -1;
702 clients[i].buf = MAP_FAILED;
703 clients[i].af = AF_INET;
704 clients[i].addr = addr.sin_addr;
706 return;
710 close(fd);
713 void
714 goodbye(struct pollfd *pfd, struct client *c)
716 ssize_t ret;
718 c->state = S_CLOSING;
720 ret = tls_close(c->ctx);
721 if (ret == TLS_WANT_POLLIN) {
722 pfd->events = POLLIN;
723 return;
725 if (ret == TLS_WANT_POLLOUT) {
726 pfd->events = POLLOUT;
727 return;
730 tls_free(c->ctx);
731 c->ctx = NULL;
733 if (c->buf != MAP_FAILED)
734 munmap(c->buf, c->len);
736 if (c->fd != -1)
737 close(c->fd);
739 close(pfd->fd);
740 pfd->fd = -1;
743 void
744 loop(struct tls *ctx, int sock)
746 int i, todo;
747 struct client clients[MAX_USERS];
748 struct pollfd fds[MAX_USERS];
750 for (i = 0; i < MAX_USERS; ++i) {
751 fds[i].fd = -1;
752 fds[i].events = POLLIN;
753 bzero(&clients[i], sizeof(struct client));
756 fds[0].fd = sock;
758 for (;;) {
759 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
760 err(1, "poll");
762 for (i = 0; i < MAX_USERS; i++) {
763 assert(i < MAX_USERS);
765 if (fds[i].revents == 0)
766 continue;
768 if (fds[i].revents & (POLLERR|POLLNVAL))
769 err(1, "bad fd %d", fds[i].fd);
771 if (fds[i].revents & POLLHUP) {
772 goodbye(&fds[i], &clients[i]);
773 continue;
776 todo--;
778 if (i == 0) { /* new client */
779 do_accept(sock, ctx, fds, clients);
780 continue;
783 handle(&fds[i], &clients[i]);
788 void
789 usage(const char *me)
791 fprintf(stderr,
792 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
793 me);
796 int
797 main(int argc, char **argv)
799 const char *cert = "cert.pem", *key = "key.pem";
800 struct tls *ctx = NULL;
801 struct tls_config *conf;
802 int sock, ch;
804 signal(SIGPIPE, SIG_IGN);
805 signal(SIGCHLD, SIG_IGN);
807 dir = "docs/";
808 logfd = 2; /* stderr */
809 cgi = 0;
811 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
812 switch (ch) {
813 case 'c':
814 cert = optarg;
815 break;
817 case 'd':
818 dir = optarg;
819 break;
821 case 'h':
822 usage(*argv);
823 return 0;
825 case 'k':
826 key = optarg;
827 break;
829 case 'l':
830 /* open log file or create it with 644 */
831 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
832 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
833 err(1, "%s", optarg);
834 break;
836 case 'x':
837 cgi = 1;
838 break;
840 default:
841 usage(*argv);
842 return 1;
846 if ((conf = tls_config_new()) == NULL)
847 err(1, "tls_config_new");
849 if (tls_config_set_protocols(conf,
850 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
851 err(1, "tls_config_set_protocols");
853 if (tls_config_set_cert_file(conf, cert) == -1)
854 err(1, "tls_config_set_cert_file: %s", cert);
856 if (tls_config_set_key_file(conf, key) == -1)
857 err(1, "tls_config_set_key_file: %s", key);
859 if ((ctx = tls_server()) == NULL)
860 err(1, "tls_server");
862 if (tls_configure(ctx, conf) == -1)
863 errx(1, "tls_configure: %s", tls_error(ctx));
865 sock = make_socket(1965, AF_INET);
867 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
868 err(1, "open: %s", dir);
870 if (unveil(dir, cgi ? "rx" : "r") == -1)
871 err(1, "unveil");
873 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
874 err(1, "pledge");
876 loop(ctx, sock);
878 close(sock);
879 tls_free(ctx);
880 tls_config_free(conf);