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 <limits.h>
29 #include <poll.h>
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <syslog.h>
35 #include <tls.h>
36 #include <unistd.h>
38 #ifndef __OpenBSD__
39 # define pledge(a, b) 0
40 # define unveil(a, b) 0
41 #endif
43 #ifndef INFTIM
44 # define INFTIM -1
45 #endif
47 #define GEMINI_URL_LEN (1024+3) /* URL max len + \r\n + \0 */
49 /* large enough to hold a copy of a gemini URL and still have extra room */
50 #define PATHBUF 2048
52 #define SUCCESS 20
53 #define TEMP_FAILURE 40
54 #define NOT_FOUND 51
55 #define BAD_REQUEST 59
57 #ifndef MAX_USERS
58 #define MAX_USERS 64
59 #endif
61 #define SAFE_SETENV(var, val) do { \
62 const char *_tmp = (val); \
63 if (_tmp == NULL) \
64 _tmp = ""; \
65 setenv((var), _tmp, 1); \
66 } while(0)
68 #define LOG(priority, c, fmt, ...) \
69 do { \
70 char buf[INET_ADDRSTRLEN]; \
71 if (inet_ntop((c)->af, &(c)->addr, \
72 buf, sizeof(buf)) == NULL) \
73 FATAL("inet_ntop: %s", strerror(errno)); \
74 if (foreground) \
75 fprintf(stderr, \
76 "%s " fmt "\n", buf, __VA_ARGS__); \
77 else \
78 syslog((priority) | LOG_DAEMON, \
79 "%s " fmt, buf, __VA_ARGS__); \
80 } while (0)
82 #define LOGE(c, fmt, ...) LOG(LOG_ERR, c, fmt, __VA_ARGS__)
83 #define LOGN(c, fmt, ...) LOG(LOG_NOTICE, c, fmt, __VA_ARGS__)
84 #define LOGI(c, fmt, ...) LOG(LOG_INFO, c, fmt, __VA_ARGS__)
85 #define LOGD(c, fmt, ...) LOG(LOG_DEBUG, c, fmt, __VA_ARGS__)
87 #define FATAL(fmt, ...) \
88 do { \
89 if (foreground) \
90 fprintf(stderr, fmt "\n", __VA_ARGS__); \
91 else \
92 syslog(LOG_DAEMON | LOG_CRIT, \
93 fmt, __VA_ARGS__); \
94 exit(1); \
95 } while (0)
97 enum {
98 S_OPEN,
99 S_INITIALIZING,
100 S_SENDING,
101 S_CLOSING,
102 };
104 struct client {
105 struct tls *ctx;
106 int state;
107 int code;
108 const char *meta;
109 int fd, waiting_on_child;
110 pid_t child;
111 char sbuf[1024]; /* static buffer */
112 void *buf, *i; /* mmap buffer */
113 ssize_t len, off; /* mmap/static buffer */
114 int af;
115 struct in_addr addr;
116 };
118 enum {
119 FILE_EXISTS,
120 FILE_EXECUTABLE,
121 FILE_DIRECTORY,
122 FILE_MISSING,
123 };
125 struct etm { /* file extension to mime */
126 const char *mime;
127 const char *ext;
128 } filetypes[] = {
129 {"application/pdf", "pdf"},
131 {"image/gif", "gif"},
132 {"image/jpeg", "jpg"},
133 {"image/jpeg", "jpeg"},
134 {"image/png", "png"},
135 {"image/svg+xml", "svg"},
137 {"text/gemini", "gemini"},
138 {"text/gemini", "gmi"},
139 {"text/markdown", "markdown"},
140 {"text/markdown", "md"},
141 {"text/plain", "txt"},
142 {"text/xml", "xml"},
144 {NULL, NULL}
145 };
147 const char *dir, *cgi;
148 int dirfd;
149 int port;
150 int foreground;
151 int connected_clients;
153 void siginfo_handler(int);
154 int starts_with(const char*, const char*);
156 char *url_after_proto(char*);
157 char *url_start_of_request(char*);
158 int url_trim(struct client*, char*);
159 char *adjust_path(char*);
160 ssize_t filesize(int);
162 int start_reply(struct pollfd*, struct client*, int, const char*);
163 const char *path_ext(const char*);
164 const char *mime(const char*);
165 int check_path(struct client*, const char*, int*);
166 int check_for_cgi(char *, char*, struct pollfd*, struct client*);
167 int open_file(char*, char*, struct pollfd*, struct client*);
168 int start_cgi(const char*, const char*, const char*, struct pollfd*, struct client*);
169 void cgi_setpoll_on_child(struct pollfd*, struct client*);
170 void cgi_setpoll_on_client(struct pollfd*, struct client*);
171 void handle_cgi(struct pollfd*, struct client*);
172 void send_file(char*, char*, struct pollfd*, struct client*);
173 void send_dir(char*, struct pollfd*, struct client*);
174 void handle(struct pollfd*, struct client*);
176 void mark_nonblock(int);
177 int make_soket(int);
178 void do_accept(int, struct tls*, struct pollfd*, struct client*);
179 void goodbye(struct pollfd*, struct client*);
180 void loop(struct tls*, int);
182 void usage(const char*);
184 void
185 siginfo_handler(int sig)
187 (void)sig;
190 int
191 starts_with(const char *str, const char *prefix)
193 size_t i;
195 for (i = 0; prefix[i] != '\0'; ++i)
196 if (str[i] != prefix[i])
197 return 0;
198 return 1;
201 char *
202 url_after_proto(char *url)
204 char *s;
205 const char *proto = "gemini:";
206 const char *marker = "//";
208 /* a relative URL */
209 if ((s = strstr(url, marker)) == NULL)
210 return url;
212 /*
213 * if a protocol is not specified, gemini should be implied:
214 * this handles the case of //example.com
215 */
216 if (s == url)
217 return s + strlen(marker);
219 if (s - strlen(proto) != url)
220 return NULL;
222 if (!starts_with(url, proto))
223 return NULL;
225 return s + strlen(marker);
228 char *
229 url_start_of_request(char *url)
231 char *s, *t;
233 if ((s = url_after_proto(url)) == NULL)
234 return NULL;
236 /* non-absolute URL */
237 if (s == url)
238 return s;
240 if ((t = strstr(s, "/")) == NULL)
241 return s + strlen(s);
242 return t;
245 int
246 url_trim(struct client *c, char *url)
248 const char *e = "\r\n";
249 char *s;
251 if ((s = strstr(url, e)) == NULL)
252 return 0;
253 s[0] = '\0';
254 s[1] = '\0';
256 if (s[2] != '\0') {
257 LOGE(c, "%s", "request longer than 1024 bytes");
258 return 0;
261 return 1;
264 char *
265 adjust_path(char *path)
267 char *s, *query;
268 size_t len;
270 if ((query = strchr(path, '?')) != NULL) {
271 *query = '\0';
272 query++;
275 /* /.. -> / */
276 len = strlen(path);
277 if (len >= 3) {
278 if (!strcmp(&path[len-3], "/..")) {
279 path[len-2] = '\0';
283 /* if the path is only `..` trim out and exit */
284 if (!strcmp(path, "..")) {
285 path[0] = '\0';
286 return query;
289 /* remove every ../ in the path */
290 while (1) {
291 if ((s = strstr(path, "../")) == NULL)
292 return query;
293 memmove(s, s+3, strlen(s)+1); /* copy also the \0 */
297 int
298 start_reply(struct pollfd *pfd, struct client *client, int code, const char *reason)
300 char buf[1030] = {0}; /* status + ' ' + max reply len + \r\n\0 */
301 int len;
302 int ret;
304 client->code = code;
305 client->meta = reason;
306 client->state = S_INITIALIZING;
308 len = snprintf(buf, sizeof(buf), "%d %s\r\n", code, reason);
309 assert(len < (int)sizeof(buf));
310 ret = tls_write(client->ctx, buf, len);
311 if (ret == TLS_WANT_POLLIN) {
312 pfd->events = POLLIN;
313 return 0;
316 if (ret == TLS_WANT_POLLOUT) {
317 pfd->events = POLLOUT;
318 return 0;
321 return 1;
324 ssize_t
325 filesize(int fd)
327 ssize_t len;
329 if ((len = lseek(fd, 0, SEEK_END)) == -1)
330 return -1;
331 if (lseek(fd, 0, SEEK_SET) == -1)
332 return -1;
333 return len;
336 const char *
337 path_ext(const char *path)
339 const char *end;
341 end = path + strlen(path)-1; /* the last byte before the NUL */
342 for (; end != path; --end) {
343 if (*end == '.')
344 return end+1;
345 if (*end == '/')
346 break;
349 return NULL;
352 const char *
353 mime(const char *path)
355 const char *ext, *def = "application/octet-stream";
356 struct etm *t;
358 if ((ext = path_ext(path)) == NULL)
359 return def;
361 for (t = filetypes; t->mime != NULL; ++t)
362 if (!strcmp(ext, t->ext))
363 return t->mime;
365 return def;
368 int
369 check_path(struct client *c, const char *path, int *fd)
371 struct stat sb;
373 assert(path != NULL);
374 if ((*fd = openat(dirfd, path,
375 O_RDONLY | O_NOFOLLOW | O_CLOEXEC)) == -1) {
376 return FILE_MISSING;
379 if (fstat(*fd, &sb) == -1) {
380 LOGN(c, "failed stat for %s: %s", path, strerror(errno));
381 return FILE_MISSING;
384 if (S_ISDIR(sb.st_mode))
385 return FILE_DIRECTORY;
387 if (sb.st_mode & S_IXUSR)
388 return FILE_EXECUTABLE;
390 return FILE_EXISTS;
393 /*
394 * the inverse of this algorithm, i.e. starting from the start of the
395 * path + strlen(cgi), and checking if each component, should be
396 * faster. But it's tedious to write. This does the opposite: starts
397 * from the end and strip one component at a time, until either an
398 * executable is found or we emptied the path.
399 */
400 int
401 check_for_cgi(char *path, char *query, struct pollfd *fds, struct client *c)
403 char *end;
404 end = strchr(path, '\0');
406 /* NB: assume CGI is enabled and path matches cgi */
408 while (end > path) {
409 /* go up one level. UNIX paths are simple and POSIX
410 * dirname, with its ambiguities on if the given path
411 * is changed or not, gives me headaches. */
412 while (*end != '/')
413 end--;
414 *end = '\0';
416 switch (check_path(c, path, &c->fd)) {
417 case FILE_EXECUTABLE:
418 return start_cgi(path, end+1, query, fds,c);
419 case FILE_MISSING:
420 break;
421 default:
422 goto err;
425 *end = '/';
426 end--;
429 err:
430 if (!start_reply(fds, c, NOT_FOUND, "not found"))
431 return 0;
432 goodbye(fds, c);
433 return 0;
437 int
438 open_file(char *path, char *query, struct pollfd *fds, struct client *c)
440 char fpath[PATHBUF];
442 bzero(fpath, sizeof(fpath));
444 if (*path != '.')
445 fpath[0] = '.';
446 strlcat(fpath, path, PATHBUF);
448 switch (check_path(c, fpath, &c->fd)) {
449 case FILE_EXECUTABLE:
450 /* +2 to skip the ./ */
451 if (cgi != NULL && starts_with(fpath+2, cgi))
452 return start_cgi(fpath, "", query, fds, c);
454 /* fallthrough */
456 case FILE_EXISTS:
457 if ((c->len = filesize(c->fd)) == -1) {
458 LOGE(c, "failed to get file size for %s", fpath);
459 goodbye(fds, c);
460 return 0;
463 if ((c->buf = mmap(NULL, c->len, PROT_READ, MAP_PRIVATE,
464 c->fd, 0)) == MAP_FAILED) {
465 warn("mmap: %s", fpath);
466 goodbye(fds, c);
467 return 0;
469 c->i = c->buf;
470 return start_reply(fds, c, SUCCESS, mime(fpath));
472 case FILE_DIRECTORY:
473 LOGD(c, "%s is a directory, trying %s/index.gmi", fpath, fpath);
474 close(c->fd);
475 c->fd = -1;
476 send_dir(fpath, fds, c);
477 return 0;
479 case FILE_MISSING:
480 if (cgi != NULL && starts_with(fpath+2, cgi))
481 return check_for_cgi(fpath, query, fds, c);
483 if (!start_reply(fds, c, NOT_FOUND, "not found"))
484 return 0;
485 goodbye(fds, c);
486 return 0;
488 default:
489 /* unreachable */
490 abort();
494 int
495 start_cgi(const char *spath, const char *relpath, const char *query,
496 struct pollfd *fds, struct client *c)
498 pid_t pid;
499 int p[2]; /* read end, write end */
501 if (pipe(p) == -1)
502 goto err;
504 switch (pid = fork()) {
505 case -1:
506 goto err;
508 case 0: { /* child */
509 char *ex, *requri, *portno;
510 char addr[INET_ADDRSTRLEN];
511 char *argv[] = { NULL, NULL, NULL };
513 spath++;
515 close(p[0]);
516 if (dup2(p[1], 1) == -1)
517 goto childerr;
519 if (inet_ntop(c->af, &c->addr, addr, sizeof(addr)) == NULL)
520 goto childerr;
522 if (asprintf(&portno, "%d", port) == -1)
523 goto childerr;
525 if (asprintf(&ex, "%s%s", dir, spath+1) == -1)
526 goto childerr;
528 if (asprintf(&requri, "%s%s%s", spath,
529 *relpath == '\0' ? "" : "/",
530 relpath) == -1)
531 goto childerr;
533 argv[0] = argv[1] = ex;
535 /* fix the env */
536 SAFE_SETENV("GATEWAY_INTERFACE", "CGI/1.1");
537 SAFE_SETENV("SERVER_SOFTWARE", "gmid");
538 SAFE_SETENV("SERVER_PORT", portno);
539 /* setenv("SERVER_NAME", "", 1); */
540 SAFE_SETENV("SCRIPT_NAME", spath);
541 SAFE_SETENV("SCRIPT_EXECUTABLE", ex);
542 SAFE_SETENV("REQUEST_URI", requri);
543 SAFE_SETENV("REQUEST_RELATIVE", relpath);
544 SAFE_SETENV("QUERY_STRING", query);
545 SAFE_SETENV("REMOTE_HOST", addr);
546 SAFE_SETENV("REMOTE_ADDR", addr);
547 SAFE_SETENV("DOCUMENT_ROOT", dir);
549 if (tls_peer_cert_provided(c->ctx)) {
550 SAFE_SETENV("AUTH_TYPE", "Certificate");
551 SAFE_SETENV("REMOTE_USER", tls_peer_cert_subject(c->ctx));
552 SAFE_SETENV("TLS_CLIENT_ISSUER", tls_peer_cert_issuer(c->ctx));
553 SAFE_SETENV("TLS_CLIENT_HASH", tls_peer_cert_hash(c->ctx));
556 execvp(ex, argv);
557 goto childerr;
560 default: /* parent */
561 close(p[1]);
562 close(c->fd);
563 c->fd = p[0];
564 c->child = pid;
565 mark_nonblock(c->fd);
566 c->state = S_SENDING;
567 handle_cgi(fds, c);
568 return 0;
571 err:
572 if (!start_reply(fds, c, TEMP_FAILURE, "internal server error"))
573 return 0;
574 goodbye(fds, c);
575 return 0;
577 childerr:
578 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
579 close(p[1]);
580 _exit(1);
583 void
584 cgi_setpoll_on_child(struct pollfd *fds, struct client *c)
586 int fd;
588 if (c->waiting_on_child)
589 return;
590 c->waiting_on_child = 1;
592 fds->events = POLLIN;
594 fd = fds->fd;
595 fds->fd = c->fd;
596 c->fd = fd;
599 void
600 cgi_setpoll_on_client(struct pollfd *fds, struct client *c)
602 int fd;
604 if (!c->waiting_on_child)
605 return;
606 c->waiting_on_child = 0;
608 fd = fds->fd;
609 fds->fd = c->fd;
610 c->fd = fd;
613 void
614 handle_cgi(struct pollfd *fds, struct client *c)
616 ssize_t r;
618 /* ensure c->fd is the child and fds->fd the client */
619 cgi_setpoll_on_client(fds, c);
621 while (1) {
622 if (c->len == 0) {
623 if ((r = read(c->fd, c->sbuf, sizeof(c->sbuf))) == 0)
624 goto end;
625 if (r == -1) {
626 if (errno == EAGAIN || errno == EWOULDBLOCK) {
627 cgi_setpoll_on_child(fds, c);
628 return;
630 goto end;
632 c->len = r;
633 c->off = 0;
636 while (c->len > 0) {
637 switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
638 case -1:
639 goto end;
641 case TLS_WANT_POLLOUT:
642 fds->events = POLLOUT;
643 return;
645 case TLS_WANT_POLLIN:
646 fds->events = POLLIN;
647 return;
649 default:
650 c->off += r;
651 c->len -= r;
652 break;
657 end:
658 goodbye(fds, c);
661 void
662 send_file(char *path, char *query, struct pollfd *fds, struct client *c)
664 ssize_t ret, len;
666 if (c->fd == -1) {
667 if (!open_file(path, query, fds, c))
668 return;
669 c->state = S_SENDING;
672 len = (c->buf + c->len) - c->i;
674 while (len > 0) {
675 switch (ret = tls_write(c->ctx, c->i, len)) {
676 case -1:
677 LOGE(c, "tls_write: %s", tls_error(c->ctx));
678 goodbye(fds, c);
679 return;
681 case TLS_WANT_POLLIN:
682 fds->events = POLLIN;
683 return;
685 case TLS_WANT_POLLOUT:
686 fds->events = POLLOUT;
687 return;
689 default:
690 c->i += ret;
691 len -= ret;
692 break;
696 goodbye(fds, c);
699 void
700 send_dir(char *path, struct pollfd *fds, struct client *client)
702 char fpath[PATHBUF];
703 size_t len;
705 bzero(fpath, PATHBUF);
707 if (path[0] != '.')
708 fpath[0] = '.';
710 /* this cannot fail since sizeof(fpath) > maxlen of path */
711 strlcat(fpath, path, PATHBUF);
712 len = strlen(fpath);
714 /* add a trailing / in case. */
715 if (fpath[len-1] != '/') {
716 fpath[len] = '/';
719 strlcat(fpath, "index.gmi", sizeof(fpath));
721 send_file(fpath, NULL, fds, client);
724 void
725 handle(struct pollfd *fds, struct client *client)
727 char buf[GEMINI_URL_LEN];
728 char *path;
729 char *query;
731 switch (client->state) {
732 case S_OPEN:
733 bzero(buf, GEMINI_URL_LEN);
734 switch (tls_read(client->ctx, buf, sizeof(buf)-1)) {
735 case -1:
736 LOGE(client, "tls_read: %s", tls_error(client->ctx));
737 goodbye(fds, client);
738 return;
740 case TLS_WANT_POLLIN:
741 fds->events = POLLIN;
742 return;
744 case TLS_WANT_POLLOUT:
745 fds->events = POLLOUT;
746 return;
749 if (!url_trim(client, buf)) {
750 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
751 return;
752 goodbye(fds, client);
753 return;
756 if ((path = url_start_of_request(buf)) == NULL) {
757 if (!start_reply(fds, client, BAD_REQUEST, "bad request"))
758 return;
759 goodbye(fds, client);
760 return;
763 query = adjust_path(path);
764 LOGI(client, "GET %s%s%s", path,
765 query ? "?" : "",
766 query ? query : "");
768 send_file(path, query, fds, client);
769 break;
771 case S_INITIALIZING:
772 if (!start_reply(fds, client, client->code, client->meta))
773 return;
775 if (client->code != SUCCESS) {
776 /* we don't need a body */
777 goodbye(fds, client);
778 return;
781 client->state = S_SENDING;
783 /* fallthrough */
785 case S_SENDING:
786 if (client->child != -1)
787 handle_cgi(fds, client);
788 else
789 send_file(NULL, NULL, fds, client);
790 break;
792 case S_CLOSING:
793 goodbye(fds, client);
794 break;
796 default:
797 /* unreachable */
798 abort();
802 void
803 mark_nonblock(int fd)
805 int flags;
807 if ((flags = fcntl(fd, F_GETFL)) == -1)
808 FATAL("fcntl(F_GETFL): %s", strerror(errno));
809 if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
810 FATAL("fcntl(F_SETFL): %s", strerror(errno));
813 int
814 make_socket(int port, int family)
816 int sock, v;
817 struct sockaddr_in addr4;
818 struct sockaddr_in6 addr6;
819 struct sockaddr *addr;
820 socklen_t len;
822 switch (family) {
823 case AF_INET:
824 bzero(&addr4, sizeof(addr4));
825 addr4.sin_family = family;
826 addr4.sin_port = htons(port);
827 addr4.sin_addr.s_addr = INADDR_ANY;
828 addr = (struct sockaddr*)&addr4;
829 len = sizeof(addr4);
830 break;
832 case AF_INET6:
833 bzero(&addr6, sizeof(addr6));
834 addr6.sin6_family = AF_INET6;
835 addr6.sin6_port = htons(port);
836 addr6.sin6_addr = in6addr_any;
837 addr = (struct sockaddr*)&addr6;
838 len = sizeof(addr6);
839 break;
841 default:
842 /* unreachable */
843 abort();
846 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
847 FATAL("socket: %s", strerror(errno));
849 v = 1;
850 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
851 FATAL("setsockopt(SO_REUSEADDR): %s", strerror(errno));
853 v = 1;
854 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
855 FATAL("setsockopt(SO_REUSEPORT): %s", strerror(errno));
857 mark_nonblock(sock);
859 if (bind(sock, addr, len) == -1)
860 FATAL("bind: %s", strerror(errno));
862 if (listen(sock, 16) == -1)
863 FATAL("listen: %s", strerror(errno));
865 return sock;
868 void
869 do_accept(int sock, struct tls *ctx, struct pollfd *fds, struct client *clients)
871 int i, fd;
872 struct sockaddr_in addr;
873 socklen_t len;
875 len = sizeof(addr);
876 if ((fd = accept(sock, (struct sockaddr*)&addr, &len)) == -1) {
877 if (errno == EWOULDBLOCK)
878 return;
879 FATAL("accept: %s", strerror(errno));
882 mark_nonblock(fd);
884 for (i = 0; i < MAX_USERS; ++i) {
885 if (fds[i].fd == -1) {
886 bzero(&clients[i], sizeof(struct client));
887 if (tls_accept_socket(ctx, &clients[i].ctx, fd) == -1)
888 break; /* goodbye fd! */
890 fds[i].fd = fd;
891 fds[i].events = POLLIN;
893 clients[i].state = S_OPEN;
894 clients[i].fd = -1;
895 clients[i].child = -1;
896 clients[i].buf = MAP_FAILED;
897 clients[i].af = AF_INET;
898 clients[i].addr = addr.sin_addr;
900 connected_clients++;
901 return;
905 close(fd);
908 void
909 goodbye(struct pollfd *pfd, struct client *c)
911 ssize_t ret;
913 c->state = S_CLOSING;
915 ret = tls_close(c->ctx);
916 if (ret == TLS_WANT_POLLIN) {
917 pfd->events = POLLIN;
918 return;
920 if (ret == TLS_WANT_POLLOUT) {
921 pfd->events = POLLOUT;
922 return;
925 connected_clients--;
927 tls_free(c->ctx);
928 c->ctx = NULL;
930 if (c->buf != MAP_FAILED)
931 munmap(c->buf, c->len);
933 if (c->fd != -1)
934 close(c->fd);
936 close(pfd->fd);
937 pfd->fd = -1;
940 void
941 loop(struct tls *ctx, int sock)
943 int i, todo;
944 struct client clients[MAX_USERS];
945 struct pollfd fds[MAX_USERS];
947 for (i = 0; i < MAX_USERS; ++i) {
948 fds[i].fd = -1;
949 fds[i].events = POLLIN;
950 bzero(&clients[i], sizeof(struct client));
953 fds[0].fd = sock;
955 for (;;) {
956 if ((todo = poll(fds, MAX_USERS, INFTIM)) == -1) {
957 if (errno == EINTR) {
958 warnx("connected clients: %d",
959 connected_clients);
960 continue;
962 FATAL("poll: %s", strerror(errno));
965 for (i = 0; i < MAX_USERS; i++) {
966 assert(i < MAX_USERS);
968 if (fds[i].revents == 0)
969 continue;
971 if (fds[i].revents & (POLLERR|POLLNVAL))
972 FATAL("bad fd %d: %s", fds[i].fd,
973 strerror(errno));
975 if (fds[i].revents & POLLHUP) {
976 /* fds[i] may be the fd of the stdin
977 * of a cgi script that has exited. */
978 if (!clients[i].waiting_on_child) {
979 goodbye(&fds[i], &clients[i]);
980 continue;
984 todo--;
986 if (i == 0) { /* new client */
987 do_accept(sock, ctx, fds, clients);
988 continue;
991 handle(&fds[i], &clients[i]);
996 char *
997 absolutify_path(const char *path)
999 char *wd, *r;
1001 if (*path == '/')
1002 return strdup(path);
1004 wd = getwd(NULL);
1005 if (asprintf(&r, "%s/%s", wd, path) == -1)
1006 err(1, "asprintf");
1007 free(wd);
1008 return r;
1011 void
1012 usage(const char *me)
1014 fprintf(stderr,
1015 "USAGE: %s [-h] [-c cert.pem] [-d docs] [-k key.pem] "
1016 "[-l logfile] [-p port] [-x cgi-bin]\n",
1017 me);
1020 int
1021 main(int argc, char **argv)
1023 const char *cert = "cert.pem", *key = "key.pem";
1024 struct tls *ctx = NULL;
1025 struct tls_config *conf;
1026 int sock, ch;
1028 signal(SIGPIPE, SIG_IGN);
1029 signal(SIGCHLD, SIG_IGN);
1031 #ifdef SIGINFO
1032 signal(SIGINFO, siginfo_handler);
1033 #endif
1034 signal(SIGUSR2, siginfo_handler);
1036 connected_clients = 0;
1038 if ((dir = absolutify_path("docs")) == NULL)
1039 err(1, "absolutify_path");
1041 cgi = NULL;
1042 port = 1965;
1043 foreground = 0;
1045 while ((ch = getopt(argc, argv, "c:d:fhk:p:x:")) != -1) {
1046 switch (ch) {
1047 case 'c':
1048 cert = optarg;
1049 break;
1051 case 'd':
1052 free((char*)dir);
1053 if ((dir = absolutify_path(optarg)) == NULL)
1054 err(1, "absolutify_path");
1055 break;
1057 case 'f':
1058 foreground = 1;
1059 break;
1061 case 'h':
1062 usage(*argv);
1063 return 0;
1065 case 'k':
1066 key = optarg;
1067 break;
1069 case 'p': {
1070 char *ep;
1071 long lval;
1073 errno = 0;
1074 lval = strtol(optarg, &ep, 10);
1075 if (optarg[0] == '\0' || *ep != '\0')
1076 err(1, "not a number: %s", optarg);
1077 if (lval < 0 || lval > UINT16_MAX)
1078 err(1, "port number out of range: %s", optarg);
1079 port = lval;
1080 break;
1083 case 'x':
1084 cgi = optarg;
1085 break;
1087 default:
1088 usage(*argv);
1089 return 1;
1093 if ((conf = tls_config_new()) == NULL)
1094 err(1, "tls_config_new");
1096 /* optionally accept client certs, but don't try to verify them */
1097 tls_config_verify_client_optional(conf);
1098 tls_config_insecure_noverifycert(conf);
1100 if (tls_config_set_protocols(conf,
1101 TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3) == -1)
1102 err(1, "tls_config_set_protocols");
1104 if (tls_config_set_cert_file(conf, cert) == -1)
1105 err(1, "tls_config_set_cert_file: %s", cert);
1107 if (tls_config_set_key_file(conf, key) == -1)
1108 err(1, "tls_config_set_key_file: %s", key);
1110 if ((ctx = tls_server()) == NULL)
1111 err(1, "tls_server");
1113 if (tls_configure(ctx, conf) == -1)
1114 errx(1, "tls_configure: %s", tls_error(ctx));
1116 sock = make_socket(port, AF_INET);
1118 if ((dirfd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
1119 err(1, "open: %s", dir);
1121 if (!foreground && daemon(0, 1) == -1)
1122 exit(1);
1124 if (cgi != NULL) {
1125 if (unveil(dir, "rx") == -1)
1126 err(1, "unveil");
1127 if (pledge("stdio rpath inet proc exec", NULL) == -1)
1128 err(1, "pledge");
1129 } else {
1130 if (unveil(dir, "r") == -1)
1131 err(1, "unveil");
1132 if (pledge("stdio rpath inet", NULL) == -1)
1133 err(1, "pledge");
1136 loop(ctx, sock);
1138 close(sock);
1139 tls_free(ctx);
1140 tls_config_free(conf);