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 if ((t = strstr(s, "/")) == NULL)
206 return s + strlen(s);
207 return t;
210 int
211 url_trim(struct client *c, char *url)
213 const char *e = "\r\n";
214 char *s;
216 if ((s = strstr(url, e)) == NULL)
217 return 0;
218 s[0] = '\0';
219 s[1] = '\0';
221 if (s[2] != '\0') {
222 LOG(c, "%s", "request longer than 1024 bytes\n");
223 return 0;
226 return 1;
229 char *
230 adjust_path(char *path)
232 char *s, *query;
233 size_t len;
235 if ((query = strchr(path, '?')) != NULL) {
236 *query = '\0';
237 query++;
240 /* /.. -> / */
241 len = strlen(path);
242 if (len >= 3) {
243 if (!strcmp(&path[len-3], "/..")) {
244 path[len-2] = '\0';
248 /* if the path is only `..` trim out and exit */
249 if (!strcmp(path, "..")) {
250 path[0] = '\0';
251 return query;
254 /* remove every ../ in the path */
255 while (1) {
256 if ((s = strstr(path, "../")) == NULL)
257 return query;
258 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
262 int
263 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
265 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
266 int len;
267 int ret;
269 client->code = code;
270 client->meta = reason;
271 client->state = S_INITIALIZING;
273 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
274 assert(len < (int)sizeof(buf));
275 ret = tls_write(client->ctx, buf, len);
276 if (ret == TLS_WANT_POLLIN) {
277 pfd->events = POLLIN;
278 return 0;
281 if (ret == TLS_WANT_POLLOUT) {
282 pfd->events = POLLOUT;
283 return 0;
286 return 1;
289 ssize_t
290 filesize(int fd)
292 ssize_t len;
294 if ((len = lseek(fd, 0, SEEK_END)) == -1)
295 return -1;
296 if (lseek(fd, 0, SEEK_SET) == -1)
297 return -1;
298 return len;
301 const char *
302 path_ext(const char *path)
304 const char *end;
306 end = path + strlen(path)-1; /* the last byte before the NUL */
307 for (; end != path; --end) {
308 if (*end == '.')
309 return end+1;
310 if (*end == '/')
311 break;
314 return NULL;
317 const char *
318 mime(const char *path)
320 const char *ext, *def = "application/octet-stream";
321 struct etm *t;
323 if ((ext = path_ext(path)) == NULL)
324 return def;
326 for (t = filetypes; t->mime != NULL; ++t)
327 if (!strcmp(ext, t->ext))
328 return t->mime;
330 return def;
333 int
334 check_path(const char *path, int *fd)
336 struct stat sb;
338 assert(path != NULL);
339 if ((*fd = openat(dirfd, path,
340 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
341 return FILE_MISSING;
344 if (fstat(*fd, &sb) == -1) {
345 dprintf(logfd, "failed stat for %s\n", path);
346 return FILE_MISSING;
349 if (S_ISDIR(sb.st_mode))
350 return FILE_DIRECTORY;
352 if (sb.st_mode & S_IXUSR)
353 return FILE_EXECUTABLE;
355 return FILE_EXISTS;
358 /*
359 * the inverse of this algorithm, i.e. starting from the start of the
360 * path + strlen(cgi), and checking if each component, should be
361 * faster. But it's tedious to write. This does the opposite: starts
362 * from the end and strip one component at a time, until either an
363 * executable is found or we emptied the path.
364 */
365 int
366 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
368 char *end;
369 end = strchr(path, '\0');
371 /* NB: assume CGI is enabled and path matches cgi */
373 while (end > path) {
374 /* go up one level. UNIX paths are simple and POSIX
375 * dirname, with its ambiguities on if the given path
376 * is changed or not, gives me headaches. */
377 while (*end != '/')
378 end--;
379 *end = '\0';
381 switch (check_path(path, &c->fd)) {
382 case FILE_EXECUTABLE:
383 return start_cgi(path, end+1, query, fds,c);
384 case FILE_MISSING:
385 break;
386 default:
387 goto err;
390 *end = '/';
391 end--;
394 err:
395 if (!start_reply(fds, c, NOT_FOUND, "not found"))
396 return 0;
397 goodbye(fds, c);
398 return 0;
402 int
403 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
405 char fpath[PATHBUF];
407 bzero(fpath, sizeof(fpath));
409 if (*path != '.')
410 fpath[0] = '.';
411 strlcat(fpath, path, PATHBUF);
413 switch (check_path(fpath, &c->fd)) {
414 case FILE_EXECUTABLE:
415 /* +2 to skip the ./ */
416 if (cgi != NULL && starts_with(fpath+2, cgi))
417 return start_cgi(fpath, "", query, fds, c);
419 /* fallthrough */
421 case FILE_EXISTS:
422 if ((c->len = filesize(c->fd)) == -1) {
423 LOG(c, "failed to get file size for %s", fpath);
424 goodbye(fds, c);
425 return 0;
428 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
429 c->fd, 0)) == MAP_FAILED) {
430 warn("mmap: %s", fpath);
431 goodbye(fds, c);
432 return 0;
434 c->i = c->buf;
435 return start_reply(fds, c, SUCCESS, mime(fpath));
437 case FILE_DIRECTORY:
438 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
439 close(c->fd);
440 c->fd = -1;
441 send_dir(fpath, fds, c);
442 return 0;
444 case FILE_MISSING:
445 if (cgi != NULL && starts_with(fpath+2, cgi))
446 return check_for_cgi(fpath, query, fds, c);
448 if (!start_reply(fds, c, NOT_FOUND, "not found"))
449 return 0;
450 goodbye(fds, c);
451 return 0;
453 default:
454 /* unreachable */
455 abort();
459 int
460 start_cgi(const char *spath, const char *relpath, const char *query,
461 struct pollfd *fds, struct client *c)
463 pid_t pid;
464 int p[2]; /* read end, write end */
466 if (pipe(p) == -1)
467 goto err;
469 switch (pid = fork()) {
470 case -1:
471 goto err;
473 case 0: { /* child */
474 char *ex, *requri, *portno;
475 char addr[INET_ADDRSTRLEN];
476 char *argv[] = { NULL, NULL, NULL };
478 spath++;
480 close(p[0]);
481 if (dup2(p[1], 1) == -1)
482 goto childerr;
484 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
485 goto childerr;
487 if (asprintf(&portno, "%d", port) == -1)
488 goto childerr;
490 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
491 goto childerr;
493 if (asprintf(&requri, "%s%s%s", spath,
494 *relpath == '\0' ? "" : "/",
495 relpath) == -1)
496 goto childerr;
498 argv[0] = argv[1] = ex;
500 /* fix the env */
501 setenv("SERVER_SOFTWARE", "gmid", 1);
502 setenv("SERVER_PORT", portno, 1);
503 /* setenv("SERVER_NAME", "", 1); */
504 setenv("SCRIPT_NAME", spath, 1);
505 setenv("SCRIPT_EXECUTABLE", ex, 1);
506 setenv("REQUEST_URI", requri, 1);
507 setenv("REQUEST_RELATIVE", relpath, 1);
508 if (query != NULL)
509 setenv("QUERY_STRING", query, 1);
510 setenv("REMOTE_HOST", addr, 1);
511 setenv("DOCUMENT_ROOT", dir, 1);
513 execvp(ex, argv);
514 goto childerr;
517 default: /* parent */
518 close(p[1]);
519 close(c->fd);
520 c->fd = p[0];
521 c->child = pid;
522 mark_nonblock(c->fd);
523 c->state = S_SENDING;
524 handle_cgi(fds, c);
525 return 0;
528 err:
529 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
530 return 0;
531 goodbye(fds, c);
532 return 0;
534 childerr:
535 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
536 close(p[1]);
537 _exit(1);
540 void
541 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
543 int fd;
545 if (c->waiting_on_child)
546 return;
547 c->waiting_on_child = 1;
549 fds->events = POLLIN;
551 fd = fds->fd;
552 fds->fd = c->fd;
553 c->fd = fd;
556 void
557 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
559 int fd;
561 if (!c->waiting_on_child)
562 return;
563 c->waiting_on_child = 0;
565 fd = fds->fd;
566 fds->fd = c->fd;
567 c->fd = fd;
570 void
571 handle_cgi(struct pollfd *fds, struct client *c)
573 ssize_t r;
575 /* ensure c->fd is the child and fds->fd the client */
576 cgi_setpoll_on_client(fds, c);
578 while (1) {
579 if (c->len == 0) {
580 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
581 goto end;
582 if (r == -1) {
583 if (errno == EAGAIN || errno == EWOULDBLOCK) {
584 cgi_setpoll_on_child(fds, c);
585 return;
587 goto end;
589 c->len = r;
590 c->off = 0;
593 while (c->len > 0) {
594 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
595 case -1:
596 goto end;
598 case TLS_WANT_POLLOUT:
599 fds->events = POLLOUT;
600 return;
602 case TLS_WANT_POLLIN:
603 fds->events = POLLIN;
604 return;
606 default:
607 c->off += r;
608 c->len -= r;
609 break;
614 end:
615 goodbye(fds, c);
618 void
619 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
621 ssize_t ret, len;
623 if (c->fd == -1) {
624 if (!open_file(path, query, fds, c))
625 return;
626 c->state = S_SENDING;
629 len = (c->buf + c->len) - c->i;
631 while (len > 0) {
632 switch (ret = tls_write(c->ctx, c->i, len)) {
633 case -1:
634 LOG(c, "tls_write: %s", tls_error(c->ctx));
635 goodbye(fds, c);
636 return;
638 case TLS_WANT_POLLIN:
639 fds->events = POLLIN;
640 return;
642 case TLS_WANT_POLLOUT:
643 fds->events = POLLOUT;
644 return;
646 default:
647 c->i += ret;
648 len -= ret;
649 break;
653 goodbye(fds, c);
656 void
657 send_dir(char *path, struct pollfd *fds, struct client *client)
659 char fpath[PATHBUF];
660 size_t len;
662 bzero(fpath, PATHBUF);
664 if (path[0] != '.')
665 fpath[0] = '.';
667 /* this cannot fail since sizeof(fpath) > maxlen of path */
668 strlcat(fpath, path, PATHBUF);
669 len = strlen(fpath);
671 /* add a trailing / in case. */
672 if (fpath[len-1] != '/') {
673 fpath[len] = '/';
676 strlcat(fpath, "index.gmi", sizeof(fpath));
678 send_file(fpath, NULL, fds, client);
681 void
682 handle(struct pollfd *fds, struct client *client)
684 char buf[GEMINI_URL_LEN];
685 char *path;
686 char *query;
688 switch (client->state) {
689 case S_OPEN:
690 bzero(buf, GEMINI_URL_LEN);
691 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
692 case -1:
693 LOG(client, "tls_read: %s", tls_error(client->ctx));
694 goodbye(fds, client);
695 return;
697 case TLS_WANT_POLLIN:
698 fds->events = POLLIN;
699 return;
701 case TLS_WANT_POLLOUT:
702 fds->events = POLLOUT;
703 return;
706 if (!url_trim(client, buf)) {
707 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
708 return;
709 goodbye(fds, client);
710 return;
713 if ((path = url_start_of_request(buf)) == NULL) {
714 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
715 return;
716 goodbye(fds, client);
717 return;
720 query = adjust_path(path);
721 LOG(client, "get %s%s%s", path,
722 query ? "?" : "",
723 query ? query : "");
725 send_file(path, query, fds, client);
726 break;
728 case S_INITIALIZING:
729 if (!start_reply(fds, client, client->code, client->meta))
730 return;
732 if (client->code != SUCCESS) {
733 /* we don't need a body */
734 goodbye(fds, client);
735 return;
738 client->state = S_SENDING;
740 /* fallthrough */
742 case S_SENDING:
743 if (client->child != -1)
744 handle_cgi(fds, client);
745 else
746 send_file(NULL, NULL, fds, client);
747 break;
749 case S_CLOSING:
750 goodbye(fds, client);
751 break;
753 default:
754 /* unreachable */
755 abort();
759 void
760 mark_nonblock(int fd)
762 int flags;
764 if ((flags = fcntl(fd, F_GETFL)) == -1)
765 err(1, "fcntl(F_GETFL)");
766 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
767 err(1, "fcntl(F_SETFL)");
770 int
771 make_socket(int port, int family)
773 int sock, v;
774 struct sockaddr_in addr4;
775 struct sockaddr_in6 addr6;
776 struct sockaddr *addr;
777 socklen_t len;
779 switch (family) {
780 case AF_INET:
781 bzero(&addr4, sizeof(addr4));
782 addr4.sin_family = family;
783 addr4.sin_port = htons(port);
784 addr4.sin_addr.s_addr = INADDR_ANY;
785 addr = (struct sockaddr*)&addr4;
786 len = sizeof(addr4);
787 break;
789 case AF_INET6:
790 bzero(&addr6, sizeof(addr6));
791 addr6.sin6_family = AF_INET6;
792 addr6.sin6_port = htons(port);
793 addr6.sin6_addr = in6addr_any;
794 addr = (struct sockaddr*)&addr6;
795 len = sizeof(addr6);
796 break;
798 default:
799 /* unreachable */
800 abort();
803 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
804 err(1, "socket");
806 v = 1;
807 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
808 err(1, "setsockopt(SO_REUSEADDR)");
810 v = 1;
811 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
812 err(1, "setsockopt(SO_REUSEPORT)");
814 mark_nonblock(sock);
816 if (bind(sock, addr, len) == -1)
817 err(1, "bind");
819 if (listen(sock, 16) == -1)
820 err(1, "listen");
822 return sock;
825 void
826 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
828 int i, fd;
829 struct sockaddr_in addr;
830 socklen_t len;
832 len = sizeof(addr);
833 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
834 if (errno == EWOULDBLOCK)
835 return;
836 err(1, "accept");
839 mark_nonblock(fd);
841 for (i = 0; i < MAX_USERS; ++i) {
842 if (fds[i].fd == -1) {
843 bzero(&clients[i], sizeof(struct client));
844 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
845 break; /* goodbye fd! */
847 fds[i].fd = fd;
848 fds[i].events = POLLIN;
850 clients[i].state = S_OPEN;
851 clients[i].fd = -1;
852 clients[i].child = -1;
853 clients[i].buf = MAP_FAILED;
854 clients[i].af = AF_INET;
855 clients[i].addr = addr.sin_addr;
857 connected_clients++;
858 return;
862 close(fd);
865 void
866 goodbye(struct pollfd *pfd, struct client *c)
868 ssize_t ret;
870 c->state = S_CLOSING;
872 ret = tls_close(c->ctx);
873 if (ret == TLS_WANT_POLLIN) {
874 pfd->events = POLLIN;
875 return;
877 if (ret == TLS_WANT_POLLOUT) {
878 pfd->events = POLLOUT;
879 return;
882 connected_clients--;
884 tls_free(c->ctx);
885 c->ctx = NULL;
887 if (c->buf != MAP_FAILED)
888 munmap(c->buf, c->len);
890 if (c->fd != -1)
891 close(c->fd);
893 close(pfd->fd);
894 pfd->fd = -1;
897 void
898 loop(struct tls *ctx, int sock)
900 int i, todo;
901 struct client clients[MAX_USERS];
902 struct pollfd fds[MAX_USERS];
904 for (i = 0; i < MAX_USERS; ++i) {
905 fds[i].fd = -1;
906 fds[i].events = POLLIN;
907 bzero(&clients[i], sizeof(struct client));
910 fds[0].fd = sock;
912 for (;;) {
913 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
914 if (errno == EINTR) {
915 warnx("connected clients: %d", connected_clients);
916 continue;
918 err(1, "poll");
921 for (i = 0; i < MAX_USERS; i++) {
922 assert(i < MAX_USERS);
924 if (fds[i].revents == 0)
925 continue;
927 if (fds[i].revents & (POLLERR|POLLNVAL))
928 err(1, "bad fd %d", fds[i].fd);
930 if (fds[i].revents & POLLHUP) {
931 /* fds[i] may be the fd of the stdin
932 * of a cgi script that has exited. */
933 if (!clients[i].waiting_on_child) {
934 goodbye(&fds[i], &clients[i]);
935 continue;
939 todo--;
941 if (i == 0) { /* new client */
942 do_accept(sock, ctx, fds, clients);
943 continue;
946 handle(&fds[i], &clients[i]);
951 void
952 usage(const char *me)
954 fprintf(stderr,
955 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
956 "[-l logfile] [-p port] [-x cgi-bin]\n",
957 me);
960 int
961 main(int argc, char **argv)
963 const char *cert = "cert.pem", *key = "key.pem";
964 struct tls *ctx = NULL;
965 struct tls_config *conf;
966 int sock, ch;
968 signal(SIGPIPE, SIG_IGN);
969 signal(SIGCHLD, SIG_IGN);
971 #ifdef SIGINFO
972 signal(SIGINFO, siginfo_handler);
973 #endif
974 signal(SIGUSR2, siginfo_handler);
976 connected_clients = 0;
978 dir = "docs/";
979 logfd = 2; /* stderr */
980 cgi = NULL;
981 port = 1965;
983 while ((ch = getopt(argc, argv, "c:d:hk:l:p:x:")) != -1) {
984 switch (ch) {
985 case 'c':
986 cert = optarg;
987 break;
989 case 'd':
990 dir = optarg;
991 break;
993 case 'h':
994 usage(*argv);
995 return 0;
997 case 'k':
998 key = optarg;
999 break;
1001 case 'l':
1002 /* open log file or create it with 644 */
1003 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
1004 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
1005 err(1, "%s", optarg);
1006 break;
1008 case 'p': {
1009 char *ep;
1010 long lval;
1012 errno = 0;
1013 lval = strtol(optarg, &ep, 10);
1014 if (optarg[0] == '\0' || *ep != '\0')
1015 err(1, "not a number: %s", optarg);
1016 if (lval < 0 || lval > UINT16_MAX)
1017 err(1, "port number out of range: %s", optarg);
1018 port = lval;
1019 break;
1022 case 'x':
1023 cgi = optarg;
1024 break;
1026 default:
1027 usage(*argv);
1028 return 1;
1032 if ((conf = tls_config_new()) == NULL)
1033 err(1, "tls_config_new");
1035 if (tls_config_set_protocols(conf,
1036 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1037 err(1, "tls_config_set_protocols");
1039 if (tls_config_set_cert_file(conf, cert) == -1)
1040 err(1, "tls_config_set_cert_file: %s", cert);
1042 if (tls_config_set_key_file(conf, key) == -1)
1043 err(1, "tls_config_set_key_file: %s", key);
1045 if ((ctx = tls_server()) == NULL)
1046 err(1, "tls_server");
1048 if (tls_configure(ctx, conf) == -1)
1049 errx(1, "tls_configure: %s", tls_error(ctx));
1051 sock = make_socket(port, AF_INET);
1053 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
1054 err(1, "open: %s", dir);
1056 if (cgi != NULL) {
1057 if (unveil(dir, "rx") == -1)
1058 err(1, "unveil");
1059 if (pledge("stdio rpath inet proc exec", NULL) == -1)
1060 err(1, "pledge");
1061 } else {
1062 if (unveil(dir, "r") == -1)
1063 err(1, "unveil");
1064 if (pledge("stdio rpath inet", NULL) == -1)
1065 err(1, "pledge");
1068 loop(ctx, sock);
1070 close(sock);
1071 tls_free(ctx);
1072 tls_config_free(conf);