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, waiting_on_child;
72 pid_t child;
73 char sbuf[1024]; /* static buffer */
74 void *buf, *i; /* mmap buffer */
75 ssize_t len, off; /* mmap/static buffer */
76 int af;
77 struct in_addr addr;
78 };
80 enum {
81 FILE_EXISTS,
82 FILE_EXECUTABLE,
83 FILE_DIRECTORY,
84 FILE_MISSING,
85 };
87 struct etm { /* file extension to mime */
88 const char *mime;
89 const char *ext;
90 } filetypes[] = {
91 {"application/pdf", "pdf"},
93 {"image/gif", "gif"},
94 {"image/jpeg", "jpg"},
95 {"image/jpeg", "jpeg"},
96 {"image/png", "png"},
97 {"image/svg+xml", "svg"},
99 {"text/gemini", "gemini"},
100 {"text/gemini", "gmi"},
101 {"text/markdown", "markdown"},
102 {"text/markdown", "md"},
103 {"text/plain", "txt"},
104 {"text/xml", "xml"},
106 {NULL, NULL}
107 };
109 #define LOG(c, fmt, ...) \
110 do { \
111 char buf[INET_ADDRSTRLEN]; \
112 if (inet_ntop((c)->af, &(c)->addr, buf, sizeof(buf)) == NULL) \
113 err(1, "inet_ntop"); \
114 dprintf(logfd, "[%s] " fmt "\n", buf, __VA_ARGS__); \
115 } while (0)
117 const char *dir, *cgi;
118 int dirfd, logfd;
119 int port;
120 int connected_clients;
122 void siginfo_handler(int);
123 int starts_with(const char*, const char*);
125 char *url_after_proto(char*);
126 char *url_start_of_request(char*);
127 int url_trim(struct client*, char*);
128 char *adjust_path(char*);
129 ssize_t filesize(int);
131 int start_reply(struct pollfd*, struct client*, int, const char*);
132 const char *path_ext(const char*);
133 const char *mime(const char*);
134 int check_path(const char*, int*);
135 int check_for_cgi(char *, char*, struct pollfd*, struct client*);
136 int open_file(char*, char*, struct pollfd*, struct client*);
137 int start_cgi(const char*, const char*, const char*, struct pollfd*, struct client*);
138 void cgi_setpoll_on_child(struct pollfd*, struct client*);
139 void cgi_setpoll_on_client(struct pollfd*, struct client*);
140 void handle_cgi(struct pollfd*, struct client*);
141 void send_file(char*, char*, struct pollfd*, struct client*);
142 void send_dir(char*, struct pollfd*, struct client*);
143 void handle(struct pollfd*, struct client*);
145 void mark_nonblock(int);
146 int make_soket(int);
147 void do_accept(int, struct tls*, struct pollfd*, struct client*);
148 void goodbye(struct pollfd*, struct client*);
149 void loop(struct tls*, int);
151 void usage(const char*);
153 void
154 siginfo_handler(int sig)
156 (void)sig;
159 int
160 starts_with(const char *str, const char *prefix)
162 size_t i;
164 for (i = 0; prefix[i] != '\0'; ++i)
165 if (str[i] != prefix[i])
166 return 0;
167 return 1;
170 char *
171 url_after_proto(char *url)
173 char *s;
174 const char *proto = "gemini";
175 const char *marker = "//";
177 /* a relative URL */
178 if ((s = strstr(url, marker)) == NULL)
179 return url;
181 /*
182 * if a protocol is not specified, gemini should be implied:
183 * this handles the case of //example.com
184 */
185 if (s == url)
186 return s + strlen(marker);
188 if (s - strlen(proto) != url)
189 return NULL;
191 if (!starts_with(url, proto))
192 return NULL;
194 return s + strlen(marker);
197 char *
198 url_start_of_request(char *url)
200 char *s, *t;
202 if ((s = url_after_proto(url)) == NULL)
203 return NULL;
205 /* non-absolute URL */
206 if (s == url)
207 return s;
209 if ((t = strstr(s, "/")) == NULL)
210 return s + strlen(s);
211 return t;
214 int
215 url_trim(struct client *c, char *url)
217 const char *e = "\r\n";
218 char *s;
220 if ((s = strstr(url, e)) == NULL)
221 return 0;
222 s[0] = '\0';
223 s[1] = '\0';
225 if (s[2] != '\0') {
226 LOG(c, "%s", "request longer than 1024 bytes\n");
227 return 0;
230 return 1;
233 char *
234 adjust_path(char *path)
236 char *s, *query;
237 size_t len;
239 if ((query = strchr(path, '?')) != NULL) {
240 *query = '\0';
241 query++;
244 /* /.. -> / */
245 len = strlen(path);
246 if (len >= 3) {
247 if (!strcmp(&path[len-3], "/..")) {
248 path[len-2] = '\0';
252 /* if the path is only `..` trim out and exit */
253 if (!strcmp(path, "..")) {
254 path[0] = '\0';
255 return query;
258 /* remove every ../ in the path */
259 while (1) {
260 if ((s = strstr(path, "../")) == NULL)
261 return query;
262 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
266 int
267 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
269 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
270 int len;
271 int ret;
273 client->code = code;
274 client->meta = reason;
275 client->state = S_INITIALIZING;
277 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
278 assert(len < (int)sizeof(buf));
279 ret = tls_write(client->ctx, buf, len);
280 if (ret == TLS_WANT_POLLIN) {
281 pfd->events = POLLIN;
282 return 0;
285 if (ret == TLS_WANT_POLLOUT) {
286 pfd->events = POLLOUT;
287 return 0;
290 return 1;
293 ssize_t
294 filesize(int fd)
296 ssize_t len;
298 if ((len = lseek(fd, 0, SEEK_END)) == -1)
299 return -1;
300 if (lseek(fd, 0, SEEK_SET) == -1)
301 return -1;
302 return len;
305 const char *
306 path_ext(const char *path)
308 const char *end;
310 end = path + strlen(path)-1; /* the last byte before the NUL */
311 for (; end != path; --end) {
312 if (*end == '.')
313 return end+1;
314 if (*end == '/')
315 break;
318 return NULL;
321 const char *
322 mime(const char *path)
324 const char *ext, *def = "application/octet-stream";
325 struct etm *t;
327 if ((ext = path_ext(path)) == NULL)
328 return def;
330 for (t = filetypes; t->mime != NULL; ++t)
331 if (!strcmp(ext, t->ext))
332 return t->mime;
334 return def;
337 int
338 check_path(const char *path, int *fd)
340 struct stat sb;
342 assert(path != NULL);
343 if ((*fd = openat(dirfd, path,
344 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
345 return FILE_MISSING;
348 if (fstat(*fd, &sb) == -1) {
349 dprintf(logfd, "failed stat for %s\n", path);
350 return FILE_MISSING;
353 if (S_ISDIR(sb.st_mode))
354 return FILE_DIRECTORY;
356 if (sb.st_mode & S_IXUSR)
357 return FILE_EXECUTABLE;
359 return FILE_EXISTS;
362 /*
363 * the inverse of this algorithm, i.e. starting from the start of the
364 * path + strlen(cgi), and checking if each component, should be
365 * faster. But it's tedious to write. This does the opposite: starts
366 * from the end and strip one component at a time, until either an
367 * executable is found or we emptied the path.
368 */
369 int
370 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
372 char *end;
373 end = strchr(path, '\0');
375 /* NB: assume CGI is enabled and path matches cgi */
377 while (end > path) {
378 /* go up one level. UNIX paths are simple and POSIX
379 * dirname, with its ambiguities on if the given path
380 * is changed or not, gives me headaches. */
381 while (*end != '/')
382 end--;
383 *end = '\0';
385 switch (check_path(path, &c->fd)) {
386 case FILE_EXECUTABLE:
387 return start_cgi(path, end+1, query, fds,c);
388 case FILE_MISSING:
389 break;
390 default:
391 goto err;
394 *end = '/';
395 end--;
398 err:
399 if (!start_reply(fds, c, NOT_FOUND, "not found"))
400 return 0;
401 goodbye(fds, c);
402 return 0;
406 int
407 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
409 char fpath[PATHBUF];
411 bzero(fpath, sizeof(fpath));
413 if (*path != '.')
414 fpath[0] = '.';
415 strlcat(fpath, path, PATHBUF);
417 switch (check_path(fpath, &c->fd)) {
418 case FILE_EXECUTABLE:
419 /* +2 to skip the ./ */
420 if (cgi != NULL && starts_with(fpath+2, cgi))
421 return start_cgi(fpath, "", query, fds, c);
423 /* fallthrough */
425 case FILE_EXISTS:
426 if ((c->len = filesize(c->fd)) == -1) {
427 LOG(c, "failed to get file size for %s", fpath);
428 goodbye(fds, c);
429 return 0;
432 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
433 c->fd, 0)) == MAP_FAILED) {
434 warn("mmap: %s", fpath);
435 goodbye(fds, c);
436 return 0;
438 c->i = c->buf;
439 return start_reply(fds, c, SUCCESS, mime(fpath));
441 case FILE_DIRECTORY:
442 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
443 close(c->fd);
444 c->fd = -1;
445 send_dir(fpath, fds, c);
446 return 0;
448 case FILE_MISSING:
449 if (cgi != NULL && starts_with(fpath+2, cgi))
450 return check_for_cgi(fpath, query, fds, c);
452 if (!start_reply(fds, c, NOT_FOUND, "not found"))
453 return 0;
454 goodbye(fds, c);
455 return 0;
457 default:
458 /* unreachable */
459 abort();
463 int
464 start_cgi(const char *spath, const char *relpath, const char *query,
465 struct pollfd *fds, struct client *c)
467 pid_t pid;
468 int p[2]; /* read end, write end */
470 if (pipe(p) == -1)
471 goto err;
473 switch (pid = fork()) {
474 case -1:
475 goto err;
477 case 0: { /* child */
478 char *ex, *requri, *portno;
479 char addr[INET_ADDRSTRLEN];
480 char *argv[] = { NULL, NULL, NULL };
482 spath++;
484 close(p[0]);
485 if (dup2(p[1], 1) == -1)
486 goto childerr;
488 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
489 goto childerr;
491 if (asprintf(&portno, "%d", port) == -1)
492 goto childerr;
494 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
495 goto childerr;
497 if (asprintf(&requri, "%s%s%s", spath,
498 *relpath == '\0' ? "" : "/",
499 relpath) == -1)
500 goto childerr;
502 argv[0] = argv[1] = ex;
504 /* fix the env */
505 setenv("SERVER_SOFTWARE", "gmid", 1);
506 setenv("SERVER_PORT", portno, 1);
507 /* setenv("SERVER_NAME", "", 1); */
508 setenv("SCRIPT_NAME", spath, 1);
509 setenv("SCRIPT_EXECUTABLE", ex, 1);
510 setenv("REQUEST_URI", requri, 1);
511 setenv("REQUEST_RELATIVE", relpath, 1);
512 if (query != NULL)
513 setenv("QUERY_STRING", query, 1);
514 setenv("REMOTE_HOST", addr, 1);
515 setenv("DOCUMENT_ROOT", dir, 1);
517 execvp(ex, argv);
518 goto childerr;
521 default: /* parent */
522 close(p[1]);
523 close(c->fd);
524 c->fd = p[0];
525 c->child = pid;
526 mark_nonblock(c->fd);
527 c->state = S_SENDING;
528 handle_cgi(fds, c);
529 return 0;
532 err:
533 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
534 return 0;
535 goodbye(fds, c);
536 return 0;
538 childerr:
539 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
540 close(p[1]);
541 _exit(1);
544 void
545 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
547 int fd;
549 if (c->waiting_on_child)
550 return;
551 c->waiting_on_child = 1;
553 fds->events = POLLIN;
555 fd = fds->fd;
556 fds->fd = c->fd;
557 c->fd = fd;
560 void
561 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
563 int fd;
565 if (!c->waiting_on_child)
566 return;
567 c->waiting_on_child = 0;
569 fd = fds->fd;
570 fds->fd = c->fd;
571 c->fd = fd;
574 void
575 handle_cgi(struct pollfd *fds, struct client *c)
577 ssize_t r;
579 /* ensure c->fd is the child and fds->fd the client */
580 cgi_setpoll_on_client(fds, c);
582 while (1) {
583 if (c->len == 0) {
584 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
585 goto end;
586 if (r == -1) {
587 if (errno == EAGAIN || errno == EWOULDBLOCK) {
588 cgi_setpoll_on_child(fds, c);
589 return;
591 goto end;
593 c->len = r;
594 c->off = 0;
597 while (c->len > 0) {
598 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
599 case -1:
600 goto end;
602 case TLS_WANT_POLLOUT:
603 fds->events = POLLOUT;
604 return;
606 case TLS_WANT_POLLIN:
607 fds->events = POLLIN;
608 return;
610 default:
611 c->off += r;
612 c->len -= r;
613 break;
618 end:
619 goodbye(fds, c);
622 void
623 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
625 ssize_t ret, len;
627 if (c->fd == -1) {
628 if (!open_file(path, query, fds, c))
629 return;
630 c->state = S_SENDING;
633 len = (c->buf + c->len) - c->i;
635 while (len > 0) {
636 switch (ret = tls_write(c->ctx, c->i, len)) {
637 case -1:
638 LOG(c, "tls_write: %s", tls_error(c->ctx));
639 goodbye(fds, c);
640 return;
642 case TLS_WANT_POLLIN:
643 fds->events = POLLIN;
644 return;
646 case TLS_WANT_POLLOUT:
647 fds->events = POLLOUT;
648 return;
650 default:
651 c->i += ret;
652 len -= ret;
653 break;
657 goodbye(fds, c);
660 void
661 send_dir(char *path, struct pollfd *fds, struct client *client)
663 char fpath[PATHBUF];
664 size_t len;
666 bzero(fpath, PATHBUF);
668 if (path[0] != '.')
669 fpath[0] = '.';
671 /* this cannot fail since sizeof(fpath) > maxlen of path */
672 strlcat(fpath, path, PATHBUF);
673 len = strlen(fpath);
675 /* add a trailing / in case. */
676 if (fpath[len-1] != '/') {
677 fpath[len] = '/';
680 strlcat(fpath, "index.gmi", sizeof(fpath));
682 send_file(fpath, NULL, fds, client);
685 void
686 handle(struct pollfd *fds, struct client *client)
688 char buf[GEMINI_URL_LEN];
689 char *path;
690 char *query;
692 switch (client->state) {
693 case S_OPEN:
694 bzero(buf, GEMINI_URL_LEN);
695 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
696 case -1:
697 LOG(client, "tls_read: %s", tls_error(client->ctx));
698 goodbye(fds, client);
699 return;
701 case TLS_WANT_POLLIN:
702 fds->events = POLLIN;
703 return;
705 case TLS_WANT_POLLOUT:
706 fds->events = POLLOUT;
707 return;
710 if (!url_trim(client, buf)) {
711 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
712 return;
713 goodbye(fds, client);
714 return;
717 if ((path = url_start_of_request(buf)) == NULL) {
718 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
719 return;
720 goodbye(fds, client);
721 return;
724 query = adjust_path(path);
725 LOG(client, "get %s%s%s", path,
726 query ? "?" : "",
727 query ? query : "");
729 send_file(path, query, fds, client);
730 break;
732 case S_INITIALIZING:
733 if (!start_reply(fds, client, client->code, client->meta))
734 return;
736 if (client->code != SUCCESS) {
737 /* we don't need a body */
738 goodbye(fds, client);
739 return;
742 client->state = S_SENDING;
744 /* fallthrough */
746 case S_SENDING:
747 if (client->child != -1)
748 handle_cgi(fds, client);
749 else
750 send_file(NULL, NULL, fds, client);
751 break;
753 case S_CLOSING:
754 goodbye(fds, client);
755 break;
757 default:
758 /* unreachable */
759 abort();
763 void
764 mark_nonblock(int fd)
766 int flags;
768 if ((flags = fcntl(fd, F_GETFL)) == -1)
769 err(1, "fcntl(F_GETFL)");
770 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
771 err(1, "fcntl(F_SETFL)");
774 int
775 make_socket(int port, int family)
777 int sock, v;
778 struct sockaddr_in addr4;
779 struct sockaddr_in6 addr6;
780 struct sockaddr *addr;
781 socklen_t len;
783 switch (family) {
784 case AF_INET:
785 bzero(&addr4, sizeof(addr4));
786 addr4.sin_family = family;
787 addr4.sin_port = htons(port);
788 addr4.sin_addr.s_addr = INADDR_ANY;
789 addr = (struct sockaddr*)&addr4;
790 len = sizeof(addr4);
791 break;
793 case AF_INET6:
794 bzero(&addr6, sizeof(addr6));
795 addr6.sin6_family = AF_INET6;
796 addr6.sin6_port = htons(port);
797 addr6.sin6_addr = in6addr_any;
798 addr = (struct sockaddr*)&addr6;
799 len = sizeof(addr6);
800 break;
802 default:
803 /* unreachable */
804 abort();
807 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
808 err(1, "socket");
810 v = 1;
811 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
812 err(1, "setsockopt(SO_REUSEADDR)");
814 v = 1;
815 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
816 err(1, "setsockopt(SO_REUSEPORT)");
818 mark_nonblock(sock);
820 if (bind(sock, addr, len) == -1)
821 err(1, "bind");
823 if (listen(sock, 16) == -1)
824 err(1, "listen");
826 return sock;
829 void
830 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
832 int i, fd;
833 struct sockaddr_in addr;
834 socklen_t len;
836 len = sizeof(addr);
837 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
838 if (errno == EWOULDBLOCK)
839 return;
840 err(1, "accept");
843 mark_nonblock(fd);
845 for (i = 0; i < MAX_USERS; ++i) {
846 if (fds[i].fd == -1) {
847 bzero(&clients[i], sizeof(struct client));
848 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
849 break; /* goodbye fd! */
851 fds[i].fd = fd;
852 fds[i].events = POLLIN;
854 clients[i].state = S_OPEN;
855 clients[i].fd = -1;
856 clients[i].child = -1;
857 clients[i].buf = MAP_FAILED;
858 clients[i].af = AF_INET;
859 clients[i].addr = addr.sin_addr;
861 connected_clients++;
862 return;
866 close(fd);
869 void
870 goodbye(struct pollfd *pfd, struct client *c)
872 ssize_t ret;
874 c->state = S_CLOSING;
876 ret = tls_close(c->ctx);
877 if (ret == TLS_WANT_POLLIN) {
878 pfd->events = POLLIN;
879 return;
881 if (ret == TLS_WANT_POLLOUT) {
882 pfd->events = POLLOUT;
883 return;
886 connected_clients--;
888 tls_free(c->ctx);
889 c->ctx = NULL;
891 if (c->buf != MAP_FAILED)
892 munmap(c->buf, c->len);
894 if (c->fd != -1)
895 close(c->fd);
897 close(pfd->fd);
898 pfd->fd = -1;
901 void
902 loop(struct tls *ctx, int sock)
904 int i, todo;
905 struct client clients[MAX_USERS];
906 struct pollfd fds[MAX_USERS];
908 for (i = 0; i < MAX_USERS; ++i) {
909 fds[i].fd = -1;
910 fds[i].events = POLLIN;
911 bzero(&clients[i], sizeof(struct client));
914 fds[0].fd = sock;
916 for (;;) {
917 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
918 if (errno == EINTR) {
919 warnx("connected clients: %d", connected_clients);
920 continue;
922 err(1, "poll");
925 for (i = 0; i < MAX_USERS; i++) {
926 assert(i < MAX_USERS);
928 if (fds[i].revents == 0)
929 continue;
931 if (fds[i].revents & (POLLERR|POLLNVAL))
932 err(1, "bad fd %d", fds[i].fd);
934 if (fds[i].revents & POLLHUP) {
935 /* fds[i] may be the fd of the stdin
936 * of a cgi script that has exited. */
937 if (!clients[i].waiting_on_child) {
938 goodbye(&fds[i], &clients[i]);
939 continue;
943 todo--;
945 if (i == 0) { /* new client */
946 do_accept(sock, ctx, fds, clients);
947 continue;
950 handle(&fds[i], &clients[i]);
955 void
956 usage(const char *me)
958 fprintf(stderr,
959 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
960 "[-l logfile] [-p port] [-x cgi-bin]\n",
961 me);
964 int
965 main(int argc, char **argv)
967 const char *cert = "cert.pem", *key = "key.pem";
968 struct tls *ctx = NULL;
969 struct tls_config *conf;
970 int sock, ch;
972 signal(SIGPIPE, SIG_IGN);
973 signal(SIGCHLD, SIG_IGN);
975 #ifdef SIGINFO
976 signal(SIGINFO, siginfo_handler);
977 #endif
978 signal(SIGUSR2, siginfo_handler);
980 connected_clients = 0;
982 dir = "docs/";
983 logfd = 2; /* stderr */
984 cgi = NULL;
985 port = 1965;
987 while ((ch = getopt(argc, argv, "c:d:hk:l:p:x:")) != -1) {
988 switch (ch) {
989 case 'c':
990 cert = optarg;
991 break;
993 case 'd':
994 dir = optarg;
995 break;
997 case 'h':
998 usage(*argv);
999 return 0;
1001 case 'k':
1002 key = optarg;
1003 break;
1005 case 'l':
1006 /* open log file or create it with 644 */
1007 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
1008 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
1009 err(1, "%s", optarg);
1010 break;
1012 case 'p': {
1013 char *ep;
1014 long lval;
1016 errno = 0;
1017 lval = strtol(optarg, &ep, 10);
1018 if (optarg[0] == '\0' || *ep != '\0')
1019 err(1, "not a number: %s", optarg);
1020 if (lval < 0 || lval > UINT16_MAX)
1021 err(1, "port number out of range: %s", optarg);
1022 port = lval;
1023 break;
1026 case 'x':
1027 cgi = optarg;
1028 break;
1030 default:
1031 usage(*argv);
1032 return 1;
1036 if ((conf = tls_config_new()) == NULL)
1037 err(1, "tls_config_new");
1039 if (tls_config_set_protocols(conf,
1040 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1041 err(1, "tls_config_set_protocols");
1043 if (tls_config_set_cert_file(conf, cert) == -1)
1044 err(1, "tls_config_set_cert_file: %s", cert);
1046 if (tls_config_set_key_file(conf, key) == -1)
1047 err(1, "tls_config_set_key_file: %s", key);
1049 if ((ctx = tls_server()) == NULL)
1050 err(1, "tls_server");
1052 if (tls_configure(ctx, conf) == -1)
1053 errx(1, "tls_configure: %s", tls_error(ctx));
1055 sock = make_socket(port, AF_INET);
1057 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
1058 err(1, "open: %s", dir);
1060 if (cgi != NULL) {
1061 if (unveil(dir, "rx") == -1)
1062 err(1, "unveil");
1063 if (pledge("stdio rpath inet proc exec", NULL) == -1)
1064 err(1, "pledge");
1065 } else {
1066 if (unveil(dir, "r") == -1)
1067 err(1, "unveil");
1068 if (pledge("stdio rpath inet", NULL) == -1)
1069 err(1, "pledge");
1072 loop(ctx, sock);
1074 close(sock);
1075 tls_free(ctx);
1076 tls_config_free(conf);