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/stat.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include <limits.h>
23 #include <netdb.h>
24 #include <pwd.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <string.h>
29 #include <openssl/pem.h>
30 #include <openssl/x509.h>
32 #include "gmid.h"
34 volatile sig_atomic_t hupped;
36 struct vhost hosts[HOSTSLEN];
38 int exfd, foreground, verbose, sock4, sock6;
40 const char *config_path, *certs_dir, *hostname;
42 struct conf conf;
44 struct tls_config *tlsconf;
45 struct tls *ctx;
47 void
48 fatal(const char *fmt, ...)
49 {
50 va_list ap;
52 va_start(ap, fmt);
54 if (foreground) {
55 vfprintf(stderr, fmt, ap);
56 fprintf(stderr, "\n");
57 } else
58 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
60 va_end(ap);
61 exit(1);
62 }
64 void
65 logs(int priority, struct client *c,
66 const char *fmt, ...)
67 {
68 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
69 char *fmted, *s;
70 size_t len;
71 int ec;
72 va_list ap;
74 if (foreground && !verbose) {
75 if (priority == LOG_DEBUG || priority == LOG_INFO)
76 return;
77 }
79 va_start(ap, fmt);
81 if (c == NULL) {
82 strncpy(hbuf, "<internal>", sizeof(hbuf));
83 sbuf[0] = '\0';
84 } else {
85 len = sizeof(c->addr);
86 ec = getnameinfo((struct sockaddr*)&c->addr, len,
87 hbuf, sizeof(hbuf),
88 sbuf, sizeof(sbuf),
89 NI_NUMERICHOST | NI_NUMERICSERV);
90 if (ec != 0)
91 fatal("getnameinfo: %s", gai_strerror(ec));
92 }
94 if (vasprintf(&fmted, fmt, ap) == -1)
95 fatal("vasprintf: %s", strerror(errno));
97 if (foreground)
98 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
99 else {
100 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
101 fatal("asprintf: %s", strerror(errno));
102 syslog(priority | LOG_DAEMON, "%s", s);
103 free(s);
106 free(fmted);
108 va_end(ap);
111 /* strchr, but with a bound */
112 static char *
113 gmid_strnchr(char *s, int c, size_t len)
115 size_t i;
117 for (i = 0; i < len; ++i)
118 if (s[i] == c)
119 return &s[i];
120 return NULL;
123 void
124 log_request(struct client *c, char *meta, size_t l)
126 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
127 char *t;
128 size_t len;
129 int ec;
131 len = sizeof(c->addr);
132 ec = getnameinfo((struct sockaddr*)&c->addr, len,
133 hbuf, sizeof(hbuf),
134 sbuf, sizeof(sbuf),
135 NI_NUMERICHOST | NI_NUMERICSERV);
136 if (ec != 0)
137 fatal("getnameinfo: %s", gai_strerror(ec));
139 if (c->iri.schema != NULL) {
140 /* serialize the IRI */
141 strlcpy(b, c->iri.schema, sizeof(b));
142 strlcat(b, "://", sizeof(b));
144 /* log the decoded host name, but if it was invalid
145 * use the raw one. */
146 if (*c->domain != '\0')
147 strlcat(b, c->domain, sizeof(b));
148 else
149 strlcat(b, c->iri.host, sizeof(b));
151 strlcat(b, "/", sizeof(b));
152 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
153 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
154 strlcat(b, "?", sizeof(b));
155 strlcat(b, c->iri.query, sizeof(b));
157 } else {
158 strlcpy(b, c->req, sizeof(b));
161 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
162 t = meta + len;
164 if (foreground)
165 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
166 (int)(t - meta), meta);
167 else
168 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
169 hbuf, sbuf, b, (int)(t - meta), meta);
172 void
173 sig_handler(int sig)
175 (void)sig;
177 hupped = sig == SIGHUP;
180 void
181 gen_certificate(const char *host, const char *certpath, const char *keypath)
183 BIGNUM e;
184 EVP_PKEY *pkey;
185 RSA *rsa;
186 X509 *x509;
187 X509_NAME *name;
188 FILE *f;
189 const char *org = "gmid";
191 LOGN(NULL, "generating new certificate for %s (it could take a while)",
192 host);
194 if ((pkey = EVP_PKEY_new()) == NULL)
195 fatal("couldn't create a new private key");
197 if ((rsa = RSA_new()) == NULL)
198 fatal("could'nt generate rsa");
200 BN_init(&e);
201 BN_set_word(&e, 17);
202 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
203 fatal("couldn't generate a rsa key");
205 if (!EVP_PKEY_assign_RSA(pkey, rsa))
206 fatal("couldn't assign the key");
208 if ((x509 = X509_new()) == NULL)
209 fatal("couldn't generate the X509 certificate");
211 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
212 X509_gmtime_adj(X509_get_notBefore(x509), 0);
213 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
215 if (!X509_set_pubkey(x509, pkey))
216 fatal("couldn't set the public key");
218 name = X509_get_subject_name(x509);
219 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
220 fatal("couldn't add N to cert");
221 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
222 fatal("couldn't add CN to cert");
223 X509_set_issuer_name(x509, name);
225 if (!X509_sign(x509, pkey, EVP_sha256()))
226 fatal("couldn't sign the certificate");
228 if ((f = fopen(keypath, "w")) == NULL)
229 fatal("fopen(%s): %s", keypath, strerror(errno));
230 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
231 fatal("couldn't write private key");
232 fclose(f);
234 if ((f = fopen(certpath, "w")) == NULL)
235 fatal("fopen(%s): %s", certpath, strerror(errno));
236 if (!PEM_write_X509(f, x509))
237 fatal("couldn't write cert");
238 fclose(f);
240 X509_free(x509);
241 RSA_free(rsa);
244 /* XXX: create recursively */
245 void
246 mkdirs(const char *path)
248 if (mkdir(path, 0755) == -1 && errno != EEXIST)
249 fatal("can't mkdir %s: %s", path, strerror(errno));
252 /* $XDG_DATA_HOME/gmid */
253 char *
254 data_dir(void)
256 const char *home, *xdg;
257 char *t;
259 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
260 if ((home = getenv("HOME")) == NULL)
261 errx(1, "XDG_DATA_HOME and HOME both empty");
262 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
263 err(1, "asprintf");
264 mkdirs(t);
265 return t;
268 if (asprintf(&t, "%s/gmid", xdg) == -1)
269 err(1, "asprintf");
270 mkdirs(t);
271 return t;
274 void
275 load_local_cert(const char *hostname, const char *dir)
277 char *cert, *key;
279 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
280 errx(1, "asprintf");
281 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
282 errx(1, "asprintf");
284 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
285 gen_certificate(hostname, cert, key);
287 hosts[0].cert = cert;
288 hosts[0].key = key;
289 hosts[0].domain = hostname;
292 void
293 load_vhosts(void)
295 struct vhost *h;
297 for (h = hosts; h->domain != NULL; ++h) {
298 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
299 fatal("open %s for domain %s", h->dir, h->domain);
303 int
304 make_socket(int port, int family)
306 int sock, v;
307 struct sockaddr_in addr4;
308 struct sockaddr_in6 addr6;
309 struct sockaddr *addr;
310 socklen_t len;
312 switch (family) {
313 case AF_INET:
314 bzero(&addr4, sizeof(addr4));
315 addr4.sin_family = family;
316 addr4.sin_port = htons(port);
317 addr4.sin_addr.s_addr = INADDR_ANY;
318 addr = (struct sockaddr*)&addr4;
319 len = sizeof(addr4);
320 break;
322 case AF_INET6:
323 bzero(&addr6, sizeof(addr6));
324 addr6.sin6_family = AF_INET6;
325 addr6.sin6_port = htons(port);
326 addr6.sin6_addr = in6addr_any;
327 addr = (struct sockaddr*)&addr6;
328 len = sizeof(addr6);
329 break;
331 default:
332 /* unreachable */
333 abort();
336 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
337 fatal("socket: %s", strerror(errno));
339 v = 1;
340 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
341 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
343 v = 1;
344 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
345 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
347 mark_nonblock(sock);
349 if (bind(sock, addr, len) == -1)
350 fatal("bind: %s", strerror(errno));
352 if (listen(sock, 16) == -1)
353 fatal("listen: %s", strerror(errno));
355 return sock;
358 void
359 setup_tls(void)
361 struct vhost *h;
363 if ((tlsconf = tls_config_new()) == NULL)
364 fatal("tls_config_new");
366 /* optionally accept client certs, but don't try to verify them */
367 tls_config_verify_client_optional(tlsconf);
368 tls_config_insecure_noverifycert(tlsconf);
370 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
371 fatal("tls_config_set_protocols");
373 if ((ctx = tls_server()) == NULL)
374 fatal("tls_server failure");
376 /* we need to set something, then we can add how many key we want */
377 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
378 fatal("tls_config_set_keypair_file failed for (%s, %s)",
379 hosts->cert, hosts->key);
381 for (h = &hosts[1]; h->domain != NULL; ++h) {
382 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
383 fatal("failed to load the keypair (%s, %s)",
384 h->cert, h->key);
387 if (tls_configure(ctx, tlsconf) == -1)
388 fatal("tls_configure: %s", tls_error(ctx));
391 static int
392 listener_main(void)
394 load_default_mime(&conf.mime);
395 load_vhosts();
396 sandbox();
397 loop(ctx, sock4, sock6);
398 return 0;
401 void
402 init_config(void)
404 size_t i;
406 bzero(hosts, sizeof(hosts));
407 for (i = 0; i < HOSTSLEN; ++i)
408 hosts[i].dirfd = -1;
410 conf.port = 1965;
411 conf.ipv6 = 0;
412 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
414 init_mime(&conf.mime);
416 conf.chroot = NULL;
417 conf.user = NULL;
420 void
421 free_config(void)
423 struct vhost *h;
424 struct location *l;
426 free(conf.chroot);
427 free(conf.user);
428 memset(&conf, 0, sizeof(conf));
430 for (h = hosts; h->domain != NULL; ++h) {
431 free((char*)h->domain);
432 free((char*)h->cert);
433 free((char*)h->key);
434 free((char*)h->dir);
435 free((char*)h->cgi);
437 for (l = h->locations; l->match != NULL; ++l) {
438 free((char*)l->match);
439 free((char*)l->lang);
440 free((char*)l->default_mime);
441 free((char*)l->index);
442 free((char*)l->block_fmt);
445 memset(hosts, 0, sizeof(hosts));
447 tls_free(ctx);
448 tls_config_free(tlsconf);
451 static void
452 wait_sighup(void)
454 sigset_t mask;
455 int signo;
457 sigemptyset(&mask);
458 sigaddset(&mask, SIGHUP);
459 sigwait(&mask, &signo);
462 void
463 drop_priv(void)
465 struct passwd *pw = NULL;
467 if (conf.chroot != NULL && conf.user == NULL)
468 fatal("can't chroot without an user to switch to after.");
470 if (conf.user != NULL) {
471 if ((pw = getpwnam(conf.user)) == NULL)
472 fatal("can't find user %s", conf.user);
475 if (conf.chroot != NULL) {
476 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
477 fatal("%s: %s", conf.chroot, strerror(errno));
480 if (pw != NULL) {
481 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
482 fatal("setresuid(%d): %s", pw->pw_uid,
483 strerror(errno));
486 if (getuid() == 0)
487 LOGW(NULL, "%s",
488 "not a good idea to run a network daemon as root");
491 void
492 usage(const char *me)
494 fprintf(stderr,
495 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
496 " [-p port] [-x cgi] [dir]",
497 me);
500 static int
501 serve(int argc, char **argv, int *p)
503 char path[PATH_MAX];
505 if (config_path == NULL) {
506 if (hostname == NULL)
507 hostname = "localhost";
508 if (certs_dir == NULL)
509 certs_dir = data_dir();
510 load_local_cert(hostname, certs_dir);
512 hosts[0].domain = "*";
513 hosts[0].locations[0].auto_index = 1;
514 hosts[0].locations[0].match = "*";
516 switch (argc) {
517 case 0:
518 hosts[0].dir = getcwd(path, sizeof(path));
519 break;
520 case 1:
521 hosts[0].dir = absolutify_path(argv[0]);
522 break;
523 default:
524 usage(getprogname());
525 return 1;
528 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
531 /* setup tls before dropping privileges: we don't want user
532 * to put private certs inside the chroot. */
533 setup_tls();
535 switch (fork()) {
536 case -1:
537 fatal("fork: %s", strerror(errno));
539 case 0: /* child */
540 setproctitle("listener");
541 close(p[0]);
542 exfd = p[1];
543 drop_priv();
544 unblock_signals();
545 listener_main();
546 _exit(0);
548 default: /* parent */
549 setproctitle("executor");
550 close(p[1]);
551 exfd = p[0];
552 drop_priv();
553 unblock_signals();
554 return executor_main();
558 int
559 main(int argc, char **argv)
561 int ch, p[2];
562 int conftest = 0, configless = 0;
563 int old_ipv6, old_port;
565 init_config();
567 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
568 switch (ch) {
569 case '6':
570 conf.ipv6 = 1;
571 configless = 1;
572 break;
574 case 'c':
575 config_path = absolutify_path(optarg);
576 break;
578 case 'd':
579 certs_dir = optarg;
580 configless = 1;
581 break;
583 case 'f':
584 foreground = 1;
585 break;
587 case 'H':
588 hostname = optarg;
589 configless = 1;
590 break;
592 case 'h':
593 usage(*argv);
594 return 0;
596 case 'n':
597 conftest = 1;
598 break;
600 case 'p':
601 conf.port = parse_portno(optarg);
602 configless = 1;
603 break;
605 case 'v':
606 verbose = 1;
607 break;
609 case 'x':
610 /* drop the starting / (if any) */
611 if (*optarg == '/')
612 optarg++;
613 hosts[0].cgi = optarg;
614 configless = 1;
615 break;
617 default:
618 usage(*argv);
619 return 1;
622 argc -= optind;
623 argv += optind;
625 if (config_path == NULL) {
626 configless = 1;
627 foreground = 1;
630 if (config_path != NULL && (argc > 0 || configless))
631 err(1, "can't specify options in config mode.");
633 if (conftest) {
634 parse_conf(config_path);
635 puts("config OK");
636 return 0;
639 signal(SIGPIPE, SIG_IGN);
640 signal(SIGCHLD, SIG_IGN);
642 #ifdef SIGINFO
643 signal(SIGINFO, sig_handler);
644 #endif
645 signal(SIGUSR2, sig_handler);
646 signal(SIGHUP, sig_handler);
648 if (!foreground && !configless) {
649 if (daemon(1, 1) == -1)
650 fatal("daemon: %s", strerror(errno));
653 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
654 PF_UNSPEC, p) == -1)
655 fatal("socketpair: %s", strerror(errno));
657 if (config_path != NULL)
658 parse_conf(config_path);
660 sock4 = make_socket(conf.port, AF_INET);
661 sock6 = -1;
662 if (conf.ipv6)
663 sock6 = make_socket(conf.port, AF_INET6);
665 if (configless)
666 return serve(argc, argv, p);
668 /* wait a sighup and reload the daemon */
669 for (;;) {
670 block_signals();
672 hupped = 0;
673 switch (fork()) {
674 case -1:
675 fatal("fork: %s", strerror(errno));
676 case 0:
677 return serve(argc, argv, p);
680 close(p[0]);
681 close(p[1]);
683 wait_sighup();
684 unblock_signals();
685 LOGI(NULL, "reloading configuration %s", config_path);
687 old_ipv6 = conf.ipv6;
688 old_port = conf.port;
690 free_config();
691 init_config();
692 parse_conf(config_path);
694 if (old_port != conf.port) {
695 close(sock4);
696 close(sock6);
697 sock4 = -1;
698 sock6 = -1;
701 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
702 close(sock6);
703 sock6 = -1;
706 if (sock4 == -1)
707 sock4 = make_socket(conf.port, AF_INET);
708 if (sock6 == -1 && conf.ipv6)
709 sock6 = make_socket(conf.port, AF_INET6);
711 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
712 PF_UNSPEC, p) == -1)
713 fatal("socketpair: %s", strerror(errno));