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);
444 memset(hosts, 0, sizeof(hosts));
446 tls_free(ctx);
447 tls_config_free(tlsconf);
450 static void
451 wait_sighup(void)
453 sigset_t mask;
454 int signo;
456 sigemptyset(&mask);
457 sigaddset(&mask, SIGHUP);
458 sigwait(&mask, &signo);
461 void
462 drop_priv(void)
464 struct passwd *pw = NULL;
466 if (conf.chroot != NULL && conf.user == NULL)
467 fatal("can't chroot without an user to switch to after.");
469 if (conf.user != NULL) {
470 if ((pw = getpwnam(conf.user)) == NULL)
471 fatal("can't find user %s", conf.user);
474 if (conf.chroot != NULL) {
475 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
476 fatal("%s: %s", conf.chroot, strerror(errno));
479 if (pw != NULL) {
480 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
481 fatal("setresuid(%d): %s", pw->pw_uid,
482 strerror(errno));
485 if (getuid() == 0)
486 LOGW(NULL, "%s",
487 "not a good idea to run a network daemon as root");
490 void
491 usage(const char *me)
493 fprintf(stderr,
494 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
495 " [-p port] [-x cgi] [dir]",
496 me);
499 static int
500 serve(int argc, char **argv, int *p)
502 char path[PATH_MAX];
504 if (config_path == NULL) {
505 if (hostname == NULL)
506 hostname = "localhost";
507 if (certs_dir == NULL)
508 certs_dir = data_dir();
509 load_local_cert(hostname, certs_dir);
511 hosts[0].domain = "*";
512 hosts[0].locations[0].auto_index = 1;
513 hosts[0].locations[0].match = "*";
515 switch (argc) {
516 case 0:
517 hosts[0].dir = getcwd(path, sizeof(path));
518 break;
519 case 1:
520 hosts[0].dir = absolutify_path(argv[0]);
521 break;
522 default:
523 usage(getprogname());
524 return 1;
527 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
530 /* setup tls before dropping privileges: we don't want user
531 * to put private certs inside the chroot. */
532 setup_tls();
534 switch (fork()) {
535 case -1:
536 fatal("fork: %s", strerror(errno));
538 case 0: /* child */
539 setproctitle("listener");
540 close(p[0]);
541 exfd = p[1];
542 drop_priv();
543 unblock_signals();
544 listener_main();
545 _exit(0);
547 default: /* parent */
548 setproctitle("executor");
549 close(p[1]);
550 exfd = p[0];
551 drop_priv();
552 unblock_signals();
553 return executor_main();
557 int
558 main(int argc, char **argv)
560 int ch, p[2];
561 int conftest = 0, configless = 0;
562 int old_ipv6, old_port;
564 init_config();
566 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
567 switch (ch) {
568 case '6':
569 conf.ipv6 = 1;
570 configless = 1;
571 break;
573 case 'c':
574 config_path = absolutify_path(optarg);
575 break;
577 case 'd':
578 certs_dir = optarg;
579 configless = 1;
580 break;
582 case 'f':
583 foreground = 1;
584 break;
586 case 'H':
587 hostname = optarg;
588 configless = 1;
589 break;
591 case 'h':
592 usage(*argv);
593 return 0;
595 case 'n':
596 conftest = 1;
597 break;
599 case 'p':
600 conf.port = parse_portno(optarg);
601 configless = 1;
602 break;
604 case 'v':
605 verbose = 1;
606 break;
608 case 'x':
609 /* drop the starting / (if any) */
610 if (*optarg == '/')
611 optarg++;
612 hosts[0].cgi = optarg;
613 configless = 1;
614 break;
616 default:
617 usage(*argv);
618 return 1;
621 argc -= optind;
622 argv += optind;
624 if (config_path == NULL) {
625 configless = 1;
626 foreground = 1;
629 if (config_path != NULL && (argc > 0 || configless))
630 err(1, "can't specify options in config mode.");
632 if (conftest) {
633 parse_conf(config_path);
634 puts("config OK");
635 return 0;
638 signal(SIGPIPE, SIG_IGN);
639 signal(SIGCHLD, SIG_IGN);
641 #ifdef SIGINFO
642 signal(SIGINFO, sig_handler);
643 #endif
644 signal(SIGUSR2, sig_handler);
645 signal(SIGHUP, sig_handler);
647 if (!foreground && !configless) {
648 if (daemon(1, 1) == -1)
649 fatal("daemon: %s", strerror(errno));
652 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
653 PF_UNSPEC, p) == -1)
654 fatal("socketpair: %s", strerror(errno));
656 if (config_path != NULL)
657 parse_conf(config_path);
659 sock4 = make_socket(conf.port, AF_INET);
660 sock6 = -1;
661 if (conf.ipv6)
662 sock6 = make_socket(conf.port, AF_INET6);
664 if (configless)
665 return serve(argc, argv, p);
667 /* wait a sighup and reload the daemon */
668 for (;;) {
669 block_signals();
671 hupped = 0;
672 switch (fork()) {
673 case -1:
674 fatal("fork: %s", strerror(errno));
675 case 0:
676 return serve(argc, argv, p);
679 close(p[0]);
680 close(p[1]);
682 wait_sighup();
683 unblock_signals();
684 LOGI(NULL, "reloading configuration %s", config_path);
686 old_ipv6 = conf.ipv6;
687 old_port = conf.port;
689 free_config();
690 init_config();
691 parse_conf(config_path);
693 if (old_port != conf.port) {
694 close(sock4);
695 close(sock6);
696 sock4 = -1;
697 sock6 = -1;
700 if (sock6 != -1 && old_ipv6 != conf.ipv6) {
701 close(sock6);
702 sock6 = -1;
705 if (sock4 == -1)
706 sock4 = make_socket(conf.port, AF_INET);
707 if (sock6 == -1 && conf.ipv6)
708 sock6 = make_socket(conf.port, AF_INET6);
710 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
711 PF_UNSPEC, p) == -1)
712 fatal("socketpair: %s", strerror(errno));