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 #define SAFE_SETENV(var, val) do { \
60 const char *_tmp = (val); \
61 if (_tmp == NULL) \
62 _tmp = ""; \
63 setenv((var), _tmp, 1); \
64 } while(0)
66 enum {
67 S_OPEN,
68 S_INITIALIZING,
69 S_SENDING,
70 S_CLOSING,
71 };
73 struct client {
74 struct tls *ctx;
75 int state;
76 int code;
77 const char *meta;
78 int fd, waiting_on_child;
79 pid_t child;
80 char sbuf[1024]; /* static buffer */
81 void *buf, *i; /* mmap buffer */
82 ssize_t len, off; /* mmap/static buffer */
83 int af;
84 struct in_addr addr;
85 };
87 enum {
88 FILE_EXISTS,
89 FILE_EXECUTABLE,
90 FILE_DIRECTORY,
91 FILE_MISSING,
92 };
94 struct etm { /* file extension to mime */
95 const char *mime;
96 const char *ext;
97 } filetypes[] = {
98 {"application/pdf", "pdf"},
100 {"image/gif", "gif"},
101 {"image/jpeg", "jpg"},
102 {"image/jpeg", "jpeg"},
103 {"image/png", "png"},
104 {"image/svg+xml", "svg"},
106 {"text/gemini", "gemini"},
107 {"text/gemini", "gmi"},
108 {"text/markdown", "markdown"},
109 {"text/markdown", "md"},
110 {"text/plain", "txt"},
111 {"text/xml", "xml"},
113 {NULL, NULL}
114 };
116 #define LOG(c, fmt, ...) \
117 do { \
118 char buf[INET_ADDRSTRLEN]; \
119 if (inet_ntop((c)->af, &(c)->addr, buf, sizeof(buf)) == NULL) \
120 err(1, "inet_ntop"); \
121 dprintf(logfd, "[%s] " fmt "\n", buf, __VA_ARGS__); \
122 } while (0)
124 const char *dir, *cgi;
125 int dirfd, logfd;
126 int port;
127 int connected_clients;
129 void siginfo_handler(int);
130 int starts_with(const char*, const char*);
132 char *url_after_proto(char*);
133 char *url_start_of_request(char*);
134 int url_trim(struct client*, char*);
135 char *adjust_path(char*);
136 ssize_t filesize(int);
138 int start_reply(struct pollfd*, struct client*, int, const char*);
139 const char *path_ext(const char*);
140 const char *mime(const char*);
141 int check_path(const char*, int*);
142 int check_for_cgi(char *, char*, struct pollfd*, struct client*);
143 int open_file(char*, char*, struct pollfd*, struct client*);
144 int start_cgi(const char*, const char*, const char*, struct pollfd*, struct client*);
145 void cgi_setpoll_on_child(struct pollfd*, struct client*);
146 void cgi_setpoll_on_client(struct pollfd*, struct client*);
147 void handle_cgi(struct pollfd*, struct client*);
148 void send_file(char*, char*, struct pollfd*, struct client*);
149 void send_dir(char*, struct pollfd*, struct client*);
150 void handle(struct pollfd*, struct client*);
152 void mark_nonblock(int);
153 int make_soket(int);
154 void do_accept(int, struct tls*, struct pollfd*, struct client*);
155 void goodbye(struct pollfd*, struct client*);
156 void loop(struct tls*, int);
158 void usage(const char*);
160 void
161 siginfo_handler(int sig)
163 (void)sig;
166 int
167 starts_with(const char *str, const char *prefix)
169 size_t i;
171 for (i = 0; prefix[i] != '\0'; ++i)
172 if (str[i] != prefix[i])
173 return 0;
174 return 1;
177 char *
178 url_after_proto(char *url)
180 char *s;
181 const char *proto = "gemini:";
182 const char *marker = "//";
184 /* a relative URL */
185 if ((s = strstr(url, marker)) == NULL)
186 return url;
188 /*
189 * if a protocol is not specified, gemini should be implied:
190 * this handles the case of //example.com
191 */
192 if (s == url)
193 return s + strlen(marker);
195 if (s - strlen(proto) != url)
196 return NULL;
198 if (!starts_with(url, proto))
199 return NULL;
201 return s + strlen(marker);
204 char *
205 url_start_of_request(char *url)
207 char *s, *t;
209 if ((s = url_after_proto(url)) == NULL)
210 return NULL;
212 /* non-absolute URL */
213 if (s == url)
214 return s;
216 if ((t = strstr(s, "/")) == NULL)
217 return s + strlen(s);
218 return t;
221 int
222 url_trim(struct client *c, char *url)
224 const char *e = "\r\n";
225 char *s;
227 if ((s = strstr(url, e)) == NULL)
228 return 0;
229 s[0] = '\0';
230 s[1] = '\0';
232 if (s[2] != '\0') {
233 LOG(c, "%s", "request longer than 1024 bytes\n");
234 return 0;
237 return 1;
240 char *
241 adjust_path(char *path)
243 char *s, *query;
244 size_t len;
246 if ((query = strchr(path, '?')) != NULL) {
247 *query = '\0';
248 query++;
251 /* /.. -> / */
252 len = strlen(path);
253 if (len >= 3) {
254 if (!strcmp(&path[len-3], "/..")) {
255 path[len-2] = '\0';
259 /* if the path is only `..` trim out and exit */
260 if (!strcmp(path, "..")) {
261 path[0] = '\0';
262 return query;
265 /* remove every ../ in the path */
266 while (1) {
267 if ((s = strstr(path, "../")) == NULL)
268 return query;
269 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
273 int
274 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
276 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
277 int len;
278 int ret;
280 client->code = code;
281 client->meta = reason;
282 client->state = S_INITIALIZING;
284 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
285 assert(len < (int)sizeof(buf));
286 ret = tls_write(client->ctx, buf, len);
287 if (ret == TLS_WANT_POLLIN) {
288 pfd->events = POLLIN;
289 return 0;
292 if (ret == TLS_WANT_POLLOUT) {
293 pfd->events = POLLOUT;
294 return 0;
297 return 1;
300 ssize_t
301 filesize(int fd)
303 ssize_t len;
305 if ((len = lseek(fd, 0, SEEK_END)) == -1)
306 return -1;
307 if (lseek(fd, 0, SEEK_SET) == -1)
308 return -1;
309 return len;
312 const char *
313 path_ext(const char *path)
315 const char *end;
317 end = path + strlen(path)-1; /* the last byte before the NUL */
318 for (; end != path; --end) {
319 if (*end == '.')
320 return end+1;
321 if (*end == '/')
322 break;
325 return NULL;
328 const char *
329 mime(const char *path)
331 const char *ext, *def = "application/octet-stream";
332 struct etm *t;
334 if ((ext = path_ext(path)) == NULL)
335 return def;
337 for (t = filetypes; t->mime != NULL; ++t)
338 if (!strcmp(ext, t->ext))
339 return t->mime;
341 return def;
344 int
345 check_path(const char *path, int *fd)
347 struct stat sb;
349 assert(path != NULL);
350 if ((*fd = openat(dirfd, path,
351 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
352 return FILE_MISSING;
355 if (fstat(*fd, &sb) == -1) {
356 dprintf(logfd, "failed stat for %s\n", path);
357 return FILE_MISSING;
360 if (S_ISDIR(sb.st_mode))
361 return FILE_DIRECTORY;
363 if (sb.st_mode & S_IXUSR)
364 return FILE_EXECUTABLE;
366 return FILE_EXISTS;
369 /*
370 * the inverse of this algorithm, i.e. starting from the start of the
371 * path + strlen(cgi), and checking if each component, should be
372 * faster. But it's tedious to write. This does the opposite: starts
373 * from the end and strip one component at a time, until either an
374 * executable is found or we emptied the path.
375 */
376 int
377 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
379 char *end;
380 end = strchr(path, '\0');
382 /* NB: assume CGI is enabled and path matches cgi */
384 while (end > path) {
385 /* go up one level. UNIX paths are simple and POSIX
386 * dirname, with its ambiguities on if the given path
387 * is changed or not, gives me headaches. */
388 while (*end != '/')
389 end--;
390 *end = '\0';
392 switch (check_path(path, &c->fd)) {
393 case FILE_EXECUTABLE:
394 return start_cgi(path, end+1, query, fds,c);
395 case FILE_MISSING:
396 break;
397 default:
398 goto err;
401 *end = '/';
402 end--;
405 err:
406 if (!start_reply(fds, c, NOT_FOUND, "not found"))
407 return 0;
408 goodbye(fds, c);
409 return 0;
413 int
414 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
416 char fpath[PATHBUF];
418 bzero(fpath, sizeof(fpath));
420 if (*path != '.')
421 fpath[0] = '.';
422 strlcat(fpath, path, PATHBUF);
424 switch (check_path(fpath, &c->fd)) {
425 case FILE_EXECUTABLE:
426 /* +2 to skip the ./ */
427 if (cgi != NULL && starts_with(fpath+2, cgi))
428 return start_cgi(fpath, "", query, fds, c);
430 /* fallthrough */
432 case FILE_EXISTS:
433 if ((c->len = filesize(c->fd)) == -1) {
434 LOG(c, "failed to get file size for %s", fpath);
435 goodbye(fds, c);
436 return 0;
439 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
440 c->fd, 0)) == MAP_FAILED) {
441 warn("mmap: %s", fpath);
442 goodbye(fds, c);
443 return 0;
445 c->i = c->buf;
446 return start_reply(fds, c, SUCCESS, mime(fpath));
448 case FILE_DIRECTORY:
449 LOG(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
450 close(c->fd);
451 c->fd = -1;
452 send_dir(fpath, fds, c);
453 return 0;
455 case FILE_MISSING:
456 if (cgi != NULL && starts_with(fpath+2, cgi))
457 return check_for_cgi(fpath, query, fds, c);
459 if (!start_reply(fds, c, NOT_FOUND, "not found"))
460 return 0;
461 goodbye(fds, c);
462 return 0;
464 default:
465 /* unreachable */
466 abort();
470 int
471 start_cgi(const char *spath, const char *relpath, const char *query,
472 struct pollfd *fds, struct client *c)
474 pid_t pid;
475 int p[2]; /* read end, write end */
477 if (pipe(p) == -1)
478 goto err;
480 switch (pid = fork()) {
481 case -1:
482 goto err;
484 case 0: { /* child */
485 char *ex, *requri, *portno;
486 char addr[INET_ADDRSTRLEN];
487 char *argv[] = { NULL, NULL, NULL };
489 spath++;
491 close(p[0]);
492 if (dup2(p[1], 1) == -1)
493 goto childerr;
495 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
496 goto childerr;
498 if (asprintf(&portno, "%d", port) == -1)
499 goto childerr;
501 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
502 goto childerr;
504 if (asprintf(&requri, "%s%s%s", spath,
505 *relpath == '\0' ? "" : "/",
506 relpath) == -1)
507 goto childerr;
509 argv[0] = argv[1] = ex;
511 /* fix the env */
512 SAFE_SETENV("GATEWAY_INTERFACE", "CGI/1.1");
513 SAFE_SETENV("SERVER_SOFTWARE", "gmid");
514 SAFE_SETENV("SERVER_PORT", portno);
515 /* setenv("SERVER_NAME", "", 1); */
516 SAFE_SETENV("SCRIPT_NAME", spath);
517 SAFE_SETENV("SCRIPT_EXECUTABLE", ex);
518 SAFE_SETENV("REQUEST_URI", requri);
519 SAFE_SETENV("REQUEST_RELATIVE", relpath);
520 SAFE_SETENV("QUERY_STRING", query);
521 SAFE_SETENV("REMOTE_HOST", addr);
522 SAFE_SETENV("REMOTE_ADDR", addr);
523 SAFE_SETENV("DOCUMENT_ROOT", dir);
525 if (tls_peer_cert_provided(c->ctx)) {
526 SAFE_SETENV("AUTH_TYPE", "Certificate");
527 SAFE_SETENV("REMOTE_USER", tls_peer_cert_subject(c->ctx));
528 SAFE_SETENV("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
529 SAFE_SETENV("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
532 execvp(ex, argv);
533 goto childerr;
536 default: /* parent */
537 close(p[1]);
538 close(c->fd);
539 c->fd = p[0];
540 c->child = pid;
541 mark_nonblock(c->fd);
542 c->state = S_SENDING;
543 handle_cgi(fds, c);
544 return 0;
547 err:
548 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
549 return 0;
550 goodbye(fds, c);
551 return 0;
553 childerr:
554 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
555 close(p[1]);
556 _exit(1);
559 void
560 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
562 int fd;
564 if (c->waiting_on_child)
565 return;
566 c->waiting_on_child = 1;
568 fds->events = POLLIN;
570 fd = fds->fd;
571 fds->fd = c->fd;
572 c->fd = fd;
575 void
576 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
578 int fd;
580 if (!c->waiting_on_child)
581 return;
582 c->waiting_on_child = 0;
584 fd = fds->fd;
585 fds->fd = c->fd;
586 c->fd = fd;
589 void
590 handle_cgi(struct pollfd *fds, struct client *c)
592 ssize_t r;
594 /* ensure c->fd is the child and fds->fd the client */
595 cgi_setpoll_on_client(fds, c);
597 while (1) {
598 if (c->len == 0) {
599 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
600 goto end;
601 if (r == -1) {
602 if (errno == EAGAIN || errno == EWOULDBLOCK) {
603 cgi_setpoll_on_child(fds, c);
604 return;
606 goto end;
608 c->len = r;
609 c->off = 0;
612 while (c->len > 0) {
613 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
614 case -1:
615 goto end;
617 case TLS_WANT_POLLOUT:
618 fds->events = POLLOUT;
619 return;
621 case TLS_WANT_POLLIN:
622 fds->events = POLLIN;
623 return;
625 default:
626 c->off += r;
627 c->len -= r;
628 break;
633 end:
634 goodbye(fds, c);
637 void
638 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
640 ssize_t ret, len;
642 if (c->fd == -1) {
643 if (!open_file(path, query, fds, c))
644 return;
645 c->state = S_SENDING;
648 len = (c->buf + c->len) - c->i;
650 while (len > 0) {
651 switch (ret = tls_write(c->ctx, c->i, len)) {
652 case -1:
653 LOG(c, "tls_write: %s", tls_error(c->ctx));
654 goodbye(fds, c);
655 return;
657 case TLS_WANT_POLLIN:
658 fds->events = POLLIN;
659 return;
661 case TLS_WANT_POLLOUT:
662 fds->events = POLLOUT;
663 return;
665 default:
666 c->i += ret;
667 len -= ret;
668 break;
672 goodbye(fds, c);
675 void
676 send_dir(char *path, struct pollfd *fds, struct client *client)
678 char fpath[PATHBUF];
679 size_t len;
681 bzero(fpath, PATHBUF);
683 if (path[0] != '.')
684 fpath[0] = '.';
686 /* this cannot fail since sizeof(fpath) > maxlen of path */
687 strlcat(fpath, path, PATHBUF);
688 len = strlen(fpath);
690 /* add a trailing / in case. */
691 if (fpath[len-1] != '/') {
692 fpath[len] = '/';
695 strlcat(fpath, "index.gmi", sizeof(fpath));
697 send_file(fpath, NULL, fds, client);
700 void
701 handle(struct pollfd *fds, struct client *client)
703 char buf[GEMINI_URL_LEN];
704 char *path;
705 char *query;
707 switch (client->state) {
708 case S_OPEN:
709 bzero(buf, GEMINI_URL_LEN);
710 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
711 case -1:
712 LOG(client, "tls_read: %s", tls_error(client->ctx));
713 goodbye(fds, client);
714 return;
716 case TLS_WANT_POLLIN:
717 fds->events = POLLIN;
718 return;
720 case TLS_WANT_POLLOUT:
721 fds->events = POLLOUT;
722 return;
725 if (!url_trim(client, buf)) {
726 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
727 return;
728 goodbye(fds, client);
729 return;
732 if ((path = url_start_of_request(buf)) == NULL) {
733 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
734 return;
735 goodbye(fds, client);
736 return;
739 query = adjust_path(path);
740 LOG(client, "get %s%s%s", path,
741 query ? "?" : "",
742 query ? query : "");
744 send_file(path, query, fds, client);
745 break;
747 case S_INITIALIZING:
748 if (!start_reply(fds, client, client->code, client->meta))
749 return;
751 if (client->code != SUCCESS) {
752 /* we don't need a body */
753 goodbye(fds, client);
754 return;
757 client->state = S_SENDING;
759 /* fallthrough */
761 case S_SENDING:
762 if (client->child != -1)
763 handle_cgi(fds, client);
764 else
765 send_file(NULL, NULL, fds, client);
766 break;
768 case S_CLOSING:
769 goodbye(fds, client);
770 break;
772 default:
773 /* unreachable */
774 abort();
778 void
779 mark_nonblock(int fd)
781 int flags;
783 if ((flags = fcntl(fd, F_GETFL)) == -1)
784 err(1, "fcntl(F_GETFL)");
785 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
786 err(1, "fcntl(F_SETFL)");
789 int
790 make_socket(int port, int family)
792 int sock, v;
793 struct sockaddr_in addr4;
794 struct sockaddr_in6 addr6;
795 struct sockaddr *addr;
796 socklen_t len;
798 switch (family) {
799 case AF_INET:
800 bzero(&addr4, sizeof(addr4));
801 addr4.sin_family = family;
802 addr4.sin_port = htons(port);
803 addr4.sin_addr.s_addr = INADDR_ANY;
804 addr = (struct sockaddr*)&addr4;
805 len = sizeof(addr4);
806 break;
808 case AF_INET6:
809 bzero(&addr6, sizeof(addr6));
810 addr6.sin6_family = AF_INET6;
811 addr6.sin6_port = htons(port);
812 addr6.sin6_addr = in6addr_any;
813 addr = (struct sockaddr*)&addr6;
814 len = sizeof(addr6);
815 break;
817 default:
818 /* unreachable */
819 abort();
822 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
823 err(1, "socket");
825 v = 1;
826 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
827 err(1, "setsockopt(SO_REUSEADDR)");
829 v = 1;
830 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
831 err(1, "setsockopt(SO_REUSEPORT)");
833 mark_nonblock(sock);
835 if (bind(sock, addr, len) == -1)
836 err(1, "bind");
838 if (listen(sock, 16) == -1)
839 err(1, "listen");
841 return sock;
844 void
845 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
847 int i, fd;
848 struct sockaddr_in addr;
849 socklen_t len;
851 len = sizeof(addr);
852 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
853 if (errno == EWOULDBLOCK)
854 return;
855 err(1, "accept");
858 mark_nonblock(fd);
860 for (i = 0; i < MAX_USERS; ++i) {
861 if (fds[i].fd == -1) {
862 bzero(&clients[i], sizeof(struct client));
863 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
864 break; /* goodbye fd! */
866 fds[i].fd = fd;
867 fds[i].events = POLLIN;
869 clients[i].state = S_OPEN;
870 clients[i].fd = -1;
871 clients[i].child = -1;
872 clients[i].buf = MAP_FAILED;
873 clients[i].af = AF_INET;
874 clients[i].addr = addr.sin_addr;
876 connected_clients++;
877 return;
881 close(fd);
884 void
885 goodbye(struct pollfd *pfd, struct client *c)
887 ssize_t ret;
889 c->state = S_CLOSING;
891 ret = tls_close(c->ctx);
892 if (ret == TLS_WANT_POLLIN) {
893 pfd->events = POLLIN;
894 return;
896 if (ret == TLS_WANT_POLLOUT) {
897 pfd->events = POLLOUT;
898 return;
901 connected_clients--;
903 tls_free(c->ctx);
904 c->ctx = NULL;
906 if (c->buf != MAP_FAILED)
907 munmap(c->buf, c->len);
909 if (c->fd != -1)
910 close(c->fd);
912 close(pfd->fd);
913 pfd->fd = -1;
916 void
917 loop(struct tls *ctx, int sock)
919 int i, todo;
920 struct client clients[MAX_USERS];
921 struct pollfd fds[MAX_USERS];
923 for (i = 0; i < MAX_USERS; ++i) {
924 fds[i].fd = -1;
925 fds[i].events = POLLIN;
926 bzero(&clients[i], sizeof(struct client));
929 fds[0].fd = sock;
931 for (;;) {
932 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
933 if (errno == EINTR) {
934 warnx("connected clients: %d", connected_clients);
935 continue;
937 err(1, "poll");
940 for (i = 0; i < MAX_USERS; i++) {
941 assert(i < MAX_USERS);
943 if (fds[i].revents == 0)
944 continue;
946 if (fds[i].revents & (POLLERR|POLLNVAL))
947 err(1, "bad fd %d", fds[i].fd);
949 if (fds[i].revents & POLLHUP) {
950 /* fds[i] may be the fd of the stdin
951 * of a cgi script that has exited. */
952 if (!clients[i].waiting_on_child) {
953 goodbye(&fds[i], &clients[i]);
954 continue;
958 todo--;
960 if (i == 0) { /* new client */
961 do_accept(sock, ctx, fds, clients);
962 continue;
965 handle(&fds[i], &clients[i]);
970 void
971 usage(const char *me)
973 fprintf(stderr,
974 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
975 "[-l logfile] [-p port] [-x cgi-bin]\n",
976 me);
979 int
980 main(int argc, char **argv)
982 const char *cert = "cert.pem", *key = "key.pem";
983 struct tls *ctx = NULL;
984 struct tls_config *conf;
985 int sock, ch;
987 signal(SIGPIPE, SIG_IGN);
988 signal(SIGCHLD, SIG_IGN);
990 #ifdef SIGINFO
991 signal(SIGINFO, siginfo_handler);
992 #endif
993 signal(SIGUSR2, siginfo_handler);
995 connected_clients = 0;
997 dir = "docs/";
998 logfd = 2; /* stderr */
999 cgi = NULL;
1000 port = 1965;
1002 while ((ch = getopt(argc, argv, "c:d:hk:l:p:x:")) != -1) {
1003 switch (ch) {
1004 case 'c':
1005 cert = optarg;
1006 break;
1008 case 'd':
1009 dir = optarg;
1010 break;
1012 case 'h':
1013 usage(*argv);
1014 return 0;
1016 case 'k':
1017 key = optarg;
1018 break;
1020 case 'l':
1021 /* open log file or create it with 644 */
1022 if ((logfd = open(optarg, O_WRONLY | O_CREAT | O_CLOEXEC,
1023 S_IRUSR | S_IWUSR | S_IRGRP | S_IWOTH)) == -1)
1024 err(1, "%s", optarg);
1025 break;
1027 case 'p': {
1028 char *ep;
1029 long lval;
1031 errno = 0;
1032 lval = strtol(optarg, &ep, 10);
1033 if (optarg[0] == '\0' || *ep != '\0')
1034 err(1, "not a number: %s", optarg);
1035 if (lval < 0 || lval > UINT16_MAX)
1036 err(1, "port number out of range: %s", optarg);
1037 port = lval;
1038 break;
1041 case 'x':
1042 cgi = optarg;
1043 break;
1045 default:
1046 usage(*argv);
1047 return 1;
1051 if ((conf = tls_config_new()) == NULL)
1052 err(1, "tls_config_new");
1054 /* optionally accept client certs, but don't try to verify them */
1055 tls_config_verify_client_optional(conf);
1056 tls_config_insecure_noverifycert(conf);
1058 if (tls_config_set_protocols(conf,
1059 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1060 err(1, "tls_config_set_protocols");
1062 if (tls_config_set_cert_file(conf, cert) == -1)
1063 err(1, "tls_config_set_cert_file: %s", cert);
1065 if (tls_config_set_key_file(conf, key) == -1)
1066 err(1, "tls_config_set_key_file: %s", key);
1068 if ((ctx = tls_server()) == NULL)
1069 err(1, "tls_server");
1071 if (tls_configure(ctx, conf) == -1)
1072 errx(1, "tls_configure: %s", tls_error(ctx));
1074 sock = make_socket(port, AF_INET);
1076 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
1077 err(1, "open: %s", dir);
1079 if (cgi != NULL) {
1080 if (unveil(dir, "rx") == -1)
1081 err(1, "unveil");
1082 if (pledge("stdio rpath inet proc exec", NULL) == -1)
1083 err(1, "pledge");
1084 } else {
1085 if (unveil(dir, "r") == -1)
1086 err(1, "unveil");
1087 if (pledge("stdio rpath inet", NULL) == -1)
1088 err(1, "pledge");
1091 loop(ctx, sock);
1093 close(sock);
1094 tls_free(ctx);
1095 tls_config_free(conf);