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 };
384 char *envp[] = {
385 /* inherited */
386 "PATH=",
388 /* CGI */
389 "SERVER_SOFTWARE=gmid",
390 /* "SERVER_NAME=example.com", */
391 /* "GATEWAY_INTERFACE=CGI/version" */
392 "SERVER_PROTOCOL=gemini",
393 "SERVER_PORT=1965",
394 /* "PATH_INFO=" */
395 /* "PATH_TRANSLATED=" */
396 /* "SCRIPT_NAME=" */
397 /* "QUERY_STRING=" */
398 "REMOTE_ADDR=",
399 NULL,
400 };
401 size_t i;
403 close(p[0]); /* close the read end */
404 if (dup2(p[1], 1) == -1)
405 goto childerr;
407 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
408 goto childerr;
410 /* skip the ./ at the start of path*/
411 if (asprintf(&expath, "%s%s", dir, path+2) == -1)
412 goto childerr;
413 argv[0] = argv[1] = expath;
415 /* fix the envp */
416 for (i = 0; envp[i] != NULL; ++i) {
417 if (!strcmp(envp[i], "PATH="))
418 envp[i] = getenv("PATH");
419 else if (!strcmp(envp[i], "REMOTE_ADDR="))
420 envp[i] = addr;
421 /* else if (!strcmp(envp[i], "PATH_INFO")) */
422 /* ... */
425 execvpe(expath, argv, envp);
426 goto childerr;
429 default: /* parent */
430 close(p[1]); /* close the write end */
431 close(c->fd);
432 c->fd = p[0];
433 c->child = pid;
434 handle_cgi(fds, c);
435 return;
438 err:
439 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
440 return;
441 goodbye(fds, c);
442 return;
444 childerr:
445 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
446 close(p[1]);
447 _exit(1);
450 void
451 handle_cgi(struct pollfd *fds, struct client *c)
453 char buf[1024];
454 ssize_t r, todo;
456 while (1) {
457 r = read(c->fd, buf, sizeof(buf));
458 if (r == -1 || r == 0)
459 break;
460 todo = r;
461 while (todo > 0) {
462 switch (r = tls_write(c->ctx, buf, todo)) {
463 case -1:
464 goto end;
466 case TLS_WANT_POLLOUT:
467 case TLS_WANT_POLLIN:
468 /* evil! */
469 continue;
471 default:
472 todo -= r;
477 end:
478 goodbye(fds, c);
481 void
482 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
484 ssize_t ret, len;
486 if (c->fd == -1) {
487 if (!open_file(path, query, fds, c))
488 return;
489 c->state = S_SENDING;
492 len = (c->buf + c->len) - c->i;
494 while (len > 0) {
495 switch (ret = tls_write(c->ctx, c->i, len)) {
496 case -1:
497 LOG(c, "tls_write: %s", tls_error(c->ctx));
498 goodbye(fds, c);
499 return;
501 case TLS_WANT_POLLIN:
502 fds->events = POLLIN;
503 return;
505 case TLS_WANT_POLLOUT:
506 fds->events = POLLOUT;
507 return;
509 default:
510 c->i += ret;
511 len -= ret;
512 break;
516 goodbye(fds, c);
519 void
520 send_dir(char *path, struct pollfd *fds, struct client *client)
522 char fpath[PATHBUF];
523 size_t len;
525 bzero(fpath, PATHBUF);
527 if (path[0] != '.')
528 fpath[0] = '.';
530 /* this cannot fail since sizeof(fpath) > maxlen of path */
531 strlcat(fpath, path, PATHBUF);
532 len = strlen(fpath);
534 /* add a trailing / in case. */
535 if (fpath[len-1] != '/') {
536 fpath[len] = '/';
539 strlcat(fpath, "index.gmi", sizeof(fpath));
541 send_file(fpath, NULL, fds, client);
544 void
545 handle(struct pollfd *fds, struct client *client)
547 char buf[GEMINI_URL_LEN];
548 char *path;
549 char *query;
551 switch (client->state) {
552 case S_OPEN:
553 bzero(buf, GEMINI_URL_LEN);
554 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
555 case -1:
556 LOG(client, "tls_read: %s", tls_error(client->ctx));
557 goodbye(fds, client);
558 return;
560 case TLS_WANT_POLLIN:
561 fds->events = POLLIN;
562 return;
564 case TLS_WANT_POLLOUT:
565 fds->events = POLLOUT;
566 return;
569 if (!url_trim(client, buf)) {
570 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
571 return;
572 goodbye(fds, client);
573 return;
576 if ((path = url_start_of_request(buf)) == NULL) {
577 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
578 return;
579 goodbye(fds, client);
580 return;
583 query = adjust_path(path);
584 LOG(client, "get %s%s%s", path,
585 query ? "?" : "",
586 query ? query : "");
588 if (path_isdir(path))
589 send_dir(path, fds, client);
590 else
591 send_file(path, query, fds, client);
592 break;
594 case S_INITIALIZING:
595 if (!start_reply(fds, client, client->code, client->meta))
596 return;
598 if (client->code != SUCCESS) {
599 /* we don't need a body */
600 goodbye(fds, client);
601 return;
604 client->state = S_SENDING;
606 /* fallthrough */
608 case S_SENDING:
609 send_file(NULL, NULL, fds, client);
610 break;
612 case S_CLOSING:
613 goodbye(fds, client);
614 break;
616 default:
617 /* unreachable */
618 abort();
622 void
623 mark_nonblock(int fd)
625 int flags;
627 if ((flags = fcntl(fd, F_GETFL)) == -1)
628 err(1, "fcntl(F_GETFL)");
629 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
630 err(1, "fcntl(F_SETFL)");
633 int
634 make_socket(int port, int family)
636 int sock, v;
637 struct sockaddr_in addr4;
638 struct sockaddr_in6 addr6;
639 struct sockaddr *addr;
640 socklen_t len;
642 switch (family) {
643 case AF_INET:
644 bzero(&addr4, sizeof(addr4));
645 addr4.sin_family = family;
646 addr4.sin_port = htons(port);
647 addr4.sin_addr.s_addr = INADDR_ANY;
648 addr = (struct sockaddr*)&addr4;
649 len = sizeof(addr4);
650 break;
652 case AF_INET6:
653 bzero(&addr6, sizeof(addr6));
654 addr6.sin6_family = AF_INET6;
655 addr6.sin6_port = htons(port);
656 addr6.sin6_addr = in6addr_any;
657 addr = (struct sockaddr*)&addr6;
658 len = sizeof(addr6);
659 break;
661 default:
662 /* unreachable */
663 abort();
666 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
667 err(1, "socket");
669 v = 1;
670 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
671 err(1, "setsockopt(SO_REUSEADDR)");
673 v = 1;
674 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
675 err(1, "setsockopt(SO_REUSEPORT)");
677 mark_nonblock(sock);
679 if (bind(sock, addr, len) == -1)
680 err(1, "bind");
682 if (listen(sock, 16) == -1)
683 err(1, "listen");
685 return sock;
688 void
689 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
691 int i, fd;
692 struct sockaddr_in addr;
693 socklen_t len;
695 len = sizeof(addr);
696 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
697 if (errno == EWOULDBLOCK)
698 return;
699 err(1, "accept");
702 mark_nonblock(fd);
704 for (i = 0; i < MAX_USERS; ++i) {
705 if (fds[i].fd == -1) {
706 bzero(&clients[i], sizeof(struct client));
707 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
708 break; /* goodbye fd! */
710 fds[i].fd = fd;
711 fds[i].events = POLLIN;
713 clients[i].state = S_OPEN;
714 clients[i].fd = -1;
715 clients[i].child = -1;
716 clients[i].buf = MAP_FAILED;
717 clients[i].af = AF_INET;
718 clients[i].addr = addr.sin_addr;
720 return;
724 close(fd);
727 void
728 goodbye(struct pollfd *pfd, struct client *c)
730 ssize_t ret;
732 c->state = S_CLOSING;
734 ret = tls_close(c->ctx);
735 if (ret == TLS_WANT_POLLIN) {
736 pfd->events = POLLIN;
737 return;
739 if (ret == TLS_WANT_POLLOUT) {
740 pfd->events = POLLOUT;
741 return;
744 tls_free(c->ctx);
745 c->ctx = NULL;
747 if (c->buf != MAP_FAILED)
748 munmap(c->buf, c->len);
750 if (c->fd != -1)
751 close(c->fd);
753 close(pfd->fd);
754 pfd->fd = -1;
757 void
758 loop(struct tls *ctx, int sock)
760 int i, todo;
761 struct client clients[MAX_USERS];
762 struct pollfd fds[MAX_USERS];
764 for (i = 0; i < MAX_USERS; ++i) {
765 fds[i].fd = -1;
766 fds[i].events = POLLIN;
767 bzero(&clients[i], sizeof(struct client));
770 fds[0].fd = sock;
772 for (;;) {
773 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1)
774 err(1, "poll");
776 for (i = 0; i < MAX_USERS; i++) {
777 assert(i < MAX_USERS);
779 if (fds[i].revents == 0)
780 continue;
782 if (fds[i].revents & (POLLERR|POLLNVAL))
783 err(1, "bad fd %d", fds[i].fd);
785 if (fds[i].revents & POLLHUP) {
786 goodbye(&fds[i], &clients[i]);
787 continue;
790 todo--;
792 if (i == 0) { /* new client */
793 do_accept(sock, ctx, fds, clients);
794 continue;
797 handle(&fds[i], &clients[i]);
802 void
803 usage(const char *me)
805 fprintf(stderr,
806 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem]\n",
807 me);
810 int
811 main(int argc, char **argv)
813 const char *cert = "cert.pem", *key = "key.pem";
814 struct tls *ctx = NULL;
815 struct tls_config *conf;
816 int sock, ch;
818 signal(SIGPIPE, SIG_IGN);
819 signal(SIGCHLD, SIG_IGN);
821 dir = "docs/";
822 logfd = 2; /* stderr */
823 cgi = 0;
825 while ((ch = getopt(argc, argv, "c:d:hk:l:x")) != -1) {
826 switch (ch) {
827 case 'c':
828 cert = optarg;
829 break;
831 case 'd':
832 dir = optarg;
833 break;
835 case 'h':
836 usage(*argv);
837 return 0;
839 case 'k':
840 key = optarg;
841 break;
843 case 'l':
844 /* open log file or create it with 644 */
845 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
846 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
847 err(1, "%s", optarg);
848 break;
850 case 'x':
851 cgi = 1;
852 break;
854 default:
855 usage(*argv);
856 return 1;
860 if ((conf = tls_config_new()) == NULL)
861 err(1, "tls_config_new");
863 if (tls_config_set_protocols(conf,
864 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
865 err(1, "tls_config_set_protocols");
867 if (tls_config_set_cert_file(conf, cert) == -1)
868 err(1, "tls_config_set_cert_file: %s", cert);
870 if (tls_config_set_key_file(conf, key) == -1)
871 err(1, "tls_config_set_key_file: %s", key);
873 if ((ctx = tls_server()) == NULL)
874 err(1, "tls_server");
876 if (tls_configure(ctx, conf) == -1)
877 errx(1, "tls_configure: %s", tls_error(ctx));
879 sock = make_socket(1965, AF_INET);
881 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
882 err(1, "open: %s", dir);
884 if (unveil(dir, cgi ? "rx" : "r") == -1)
885 err(1, "unveil");
887 if (pledge(cgi ? "stdio rpath inet proc exec" : "stdio rpath inet", NULL) == -1)
888 err(1, "pledge");
890 loop(ctx, sock);
892 close(sock);
893 tls_free(ctx);
894 tls_config_free(conf);