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 <netdb.h>
23 #include <pwd.h>
24 #include <signal.h>
25 #include <stdarg.h>
26 #include <string.h>
28 #include <openssl/pem.h>
29 #include <openssl/x509.h>
31 #include "gmid.h"
33 struct vhost hosts[HOSTSLEN];
35 int exfd, foreground, verbose;
37 struct conf conf;
39 struct tls *ctx;
41 void
42 fatal(const char *fmt, ...)
43 {
44 va_list ap;
46 va_start(ap, fmt);
48 if (foreground) {
49 vfprintf(stderr, fmt, ap);
50 fprintf(stderr, "\n");
51 } else
52 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
54 va_end(ap);
55 exit(1);
56 }
58 void
59 logs(int priority, struct client *c,
60 const char *fmt, ...)
61 {
62 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
63 char *fmted, *s;
64 size_t len;
65 int ec;
66 va_list ap;
68 if (foreground && !verbose) {
69 if (priority == LOG_DEBUG || priority == LOG_INFO)
70 return;
71 }
73 va_start(ap, fmt);
75 if (c == NULL) {
76 strncpy(hbuf, "<internal>", sizeof(hbuf));
77 sbuf[0] = '\0';
78 } else {
79 len = sizeof(c->addr);
80 ec = getnameinfo((struct sockaddr*)&c->addr, len,
81 hbuf, sizeof(hbuf),
82 sbuf, sizeof(sbuf),
83 NI_NUMERICHOST | NI_NUMERICSERV);
84 if (ec != 0)
85 fatal("getnameinfo: %s", gai_strerror(ec));
86 }
88 if (vasprintf(&fmted, fmt, ap) == -1)
89 fatal("vasprintf: %s", strerror(errno));
91 if (foreground)
92 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
93 else {
94 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
95 fatal("asprintf: %s", strerror(errno));
96 syslog(priority | LOG_DAEMON, "%s", s);
97 free(s);
98 }
100 free(fmted);
102 va_end(ap);
105 /* strchr, but with a bound */
106 static char *
107 gmid_strnchr(char *s, int c, size_t len)
109 size_t i;
111 for (i = 0; i < len; ++i)
112 if (s[i] == c)
113 return &s[i];
114 return NULL;
117 void
118 log_request(struct client *c, char *meta, size_t l)
120 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
121 char *t;
122 size_t len;
123 int ec;
125 len = sizeof(c->addr);
126 ec = getnameinfo((struct sockaddr*)&c->addr, len,
127 hbuf, sizeof(hbuf),
128 sbuf, sizeof(sbuf),
129 NI_NUMERICHOST | NI_NUMERICSERV);
130 if (ec != 0)
131 fatal("getnameinfo: %s", gai_strerror(ec));
133 if (c->iri.schema != NULL) {
134 /* serialize the IRI */
135 strlcpy(b, c->iri.schema, sizeof(b));
136 strlcat(b, "://", sizeof(b));
138 /* log the decoded host name, but if it was invalid
139 * use the raw one. */
140 if (*c->domain != '\0')
141 strlcat(b, c->domain, sizeof(b));
142 else
143 strlcat(b, c->iri.host, sizeof(b));
145 strlcat(b, "/", sizeof(b));
146 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
147 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
148 strlcat(b, "?", sizeof(b));
149 strlcat(b, c->iri.query, sizeof(b));
151 } else {
152 strlcpy(b, c->req, sizeof(b));
155 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
156 t = meta + len;
158 if (foreground)
159 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
160 (int)(t - meta), meta);
161 else
162 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
163 hbuf, sbuf, b, (int)(t - meta), meta);
166 void
167 sig_handler(int sig)
169 (void)sig;
172 char *
173 absolutify_path(const char *path)
175 char *wd, *r;
177 if (*path == '/')
178 return strdup(path);
180 wd = getcwd(NULL, 0);
181 if (asprintf(&r, "%s/%s", wd, path) == -1)
182 fatal("asprintf: %s", strerror(errno));
183 free(wd);
184 return r;
187 void
188 gen_certificate(const char *host, const char *certpath, const char *keypath)
190 BIGNUM e;
191 EVP_PKEY *pkey;
192 RSA *rsa;
193 X509 *x509;
194 X509_NAME *name;
195 FILE *f;
196 const char *org = "gmid";
198 LOGN(NULL, "generating new certificate for %s (it could take a while)",
199 host);
201 if ((pkey = EVP_PKEY_new()) == NULL)
202 fatal("couldn't create a new private key");
204 if ((rsa = RSA_new()) == NULL)
205 fatal("could'nt generate rsa");
207 BN_init(&e);
208 BN_set_word(&e, 17);
209 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
210 fatal("couldn't generate a rsa key");
212 if (!EVP_PKEY_assign_RSA(pkey, rsa))
213 fatal("couldn't assign the key");
215 if ((x509 = X509_new()) == NULL)
216 fatal("couldn't generate the X509 certificate");
218 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
219 X509_gmtime_adj(X509_get_notBefore(x509), 0);
220 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
222 if (!X509_set_pubkey(x509, pkey))
223 fatal("couldn't set the public key");
225 name = X509_get_subject_name(x509);
226 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
227 fatal("couldn't add N to cert");
228 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
229 fatal("couldn't add CN to cert");
230 X509_set_issuer_name(x509, name);
232 if (!X509_sign(x509, pkey, EVP_sha256()))
233 fatal("couldn't sign the certificate");
235 if ((f = fopen(keypath, "w")) == NULL)
236 fatal("fopen(%s): %s", keypath, strerror(errno));
237 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
238 fatal("couldn't write private key");
239 fclose(f);
241 if ((f = fopen(certpath, "w")) == NULL)
242 fatal("fopen(%s): %s", certpath, strerror(errno));
243 if (!PEM_write_X509(f, x509))
244 fatal("couldn't write cert");
245 fclose(f);
247 X509_free(x509);
248 RSA_free(rsa);
251 /* XXX: create recursively */
252 void
253 mkdirs(const char *path)
255 if (mkdir(path, 0755) == -1 && errno != EEXIST)
256 fatal("can't mkdir %s: %s", path, strerror(errno));
259 /* $XDG_DATA_HOME/gmid */
260 char *
261 data_dir(void)
263 const char *home, *xdg;
264 char *t;
266 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
267 if ((home = getenv("HOME")) == NULL)
268 errx(1, "XDG_DATA_HOME and HOME both empty");
269 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
270 err(1, "asprintf");
271 mkdirs(t);
272 return t;
275 if (asprintf(&t, "%s/gmid", xdg) == -1)
276 err(1, "asprintf");
277 mkdirs(t);
278 return t;
281 void
282 load_local_cert(const char *hostname, const char *dir)
284 char *cert, *key;
286 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
287 errx(1, "asprintf");
288 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
289 errx(1, "asprintf");
291 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
292 gen_certificate(hostname, cert, key);
294 hosts[0].cert = cert;
295 hosts[0].key = key;
296 hosts[0].domain = hostname;
299 void
300 load_vhosts(void)
302 struct vhost *h;
304 for (h = hosts; h->domain != NULL; ++h) {
305 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
306 fatal("open %s for domain %s", h->dir, h->domain);
310 int
311 make_socket(int port, int family)
313 int sock, v;
314 struct sockaddr_in addr4;
315 struct sockaddr_in6 addr6;
316 struct sockaddr *addr;
317 socklen_t len;
319 switch (family) {
320 case AF_INET:
321 bzero(&addr4, sizeof(addr4));
322 addr4.sin_family = family;
323 addr4.sin_port = htons(port);
324 addr4.sin_addr.s_addr = INADDR_ANY;
325 addr = (struct sockaddr*)&addr4;
326 len = sizeof(addr4);
327 break;
329 case AF_INET6:
330 bzero(&addr6, sizeof(addr6));
331 addr6.sin6_family = AF_INET6;
332 addr6.sin6_port = htons(port);
333 addr6.sin6_addr = in6addr_any;
334 addr = (struct sockaddr*)&addr6;
335 len = sizeof(addr6);
336 break;
338 default:
339 /* unreachable */
340 abort();
343 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
344 fatal("socket: %s", strerror(errno));
346 v = 1;
347 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
348 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
350 v = 1;
351 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
352 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
354 mark_nonblock(sock);
356 if (bind(sock, addr, len) == -1)
357 fatal("bind: %s", strerror(errno));
359 if (listen(sock, 16) == -1)
360 fatal("listen: %s", strerror(errno));
362 return sock;
365 void
366 setup_tls(void)
368 struct tls_config *tlsconf;
369 struct vhost *h;
371 if ((tlsconf = tls_config_new()) == NULL)
372 fatal("tls_config_new");
374 /* optionally accept client certs, but don't try to verify them */
375 tls_config_verify_client_optional(tlsconf);
376 tls_config_insecure_noverifycert(tlsconf);
378 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
379 fatal("tls_config_set_protocols");
381 if ((ctx = tls_server()) == NULL)
382 fatal("tls_server failure");
384 /* we need to set something, then we can add how many key we want */
385 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
386 fatal("tls_config_set_keypair_file failed");
388 for (h = &hosts[1]; h->domain != NULL; ++h) {
389 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
390 fatal("failed to load the keypair (%s, %s)",
391 h->cert, h->key);
394 if (tls_configure(ctx, tlsconf) == -1)
395 fatal("tls_configure: %s", tls_error(ctx));
398 int
399 listener_main(void)
401 int sock4, sock6;
403 load_default_mime(&conf.mime);
405 sock4 = make_socket(conf.port, AF_INET);
406 sock6 = -1;
407 if (conf.ipv6)
408 sock6 = make_socket(conf.port, AF_INET6);
410 load_vhosts();
412 sandbox();
413 loop(ctx, sock4, sock6);
415 return 0;
418 void
419 init_config(void)
421 size_t i;
423 bzero(hosts, sizeof(hosts));
424 for (i = 0; i < HOSTSLEN; ++i)
425 hosts[i].dirfd = -1;
427 conf.port = 1965;
428 conf.ipv6 = 0;
429 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
431 init_mime(&conf.mime);
433 conf.chroot = NULL;
434 conf.user = NULL;
437 void
438 drop_priv(void)
440 struct passwd *pw = NULL;
442 if (conf.chroot != NULL && conf.user == NULL)
443 fatal("can't chroot without an user to switch to after.");
445 if (conf.user != NULL) {
446 if ((pw = getpwnam(conf.user)) == NULL)
447 fatal("can't find user %s", conf.user);
450 if (conf.chroot != NULL) {
451 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
452 fatal("%s: %s", conf.chroot, strerror(errno));
455 if (pw != NULL) {
456 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
457 fatal("setresuid(%d): %s", pw->pw_uid,
458 strerror(errno));
461 if (getuid() == 0)
462 LOGW(NULL, "%s",
463 "not a good idea to run a network daemon as root");
466 void
467 usage(const char *me)
469 fprintf(stderr,
470 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
471 " [-p port] [-x cgi] [dir]",
472 me);
475 int
476 main(int argc, char **argv)
478 int ch, p[2];
479 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
480 int conftest = 0, configless = 0;
482 init_config();
484 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
485 switch (ch) {
486 case '6':
487 conf.ipv6 = 1;
488 configless = 1;
489 break;
491 case 'c':
492 config_path = optarg;
493 break;
495 case 'd':
496 certs_dir = optarg;
497 configless = 1;
498 break;
500 case 'f':
501 foreground = 1;
502 break;
504 case 'H':
505 hostname = optarg;
506 configless = 1;
507 break;
509 case 'h':
510 usage(*argv);
511 return 0;
513 case 'n':
514 conftest = 1;
515 break;
517 case 'p':
518 conf.port = parse_portno(optarg);
519 configless = 1;
520 break;
522 case 'v':
523 verbose = 1;
524 break;
526 case 'x':
527 /* drop the starting / (if any) */
528 if (*optarg == '/')
529 optarg++;
530 hosts[0].cgi = optarg;
531 configless = 1;
532 break;
534 default:
535 usage(*argv);
536 return 1;
539 argc -= optind;
540 argv += optind;
542 if (config_path != NULL) {
543 if (argc > 0 || configless)
544 fatal("can't specify options is config mode.");
546 parse_conf(config_path);
547 } else {
548 configless = 1;
549 foreground = 1;
551 if (hostname == NULL)
552 hostname = "localhost";
553 if (certs_dir == NULL)
554 certs_dir = data_dir();
555 load_local_cert(hostname, certs_dir);
557 hosts[0].domain = "*";
558 hosts[0].locations[0].auto_index = 1;
559 hosts[0].locations[0].match = "*";
561 switch (argc) {
562 case 0:
563 hosts[0].dir = ".";
564 break;
565 case 1:
566 hosts[0].dir = argv[0];
567 break;
568 default:
569 usage(getprogname());
570 return 1;
573 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
576 if (conftest) {
577 puts("config OK");
578 return 0;
581 /* setup tls before dropping privileges: we don't want user
582 * to put private certs inside the chroot. */
583 setup_tls();
584 drop_priv();
586 signal(SIGPIPE, SIG_IGN);
587 signal(SIGCHLD, SIG_IGN);
589 #ifdef SIGINFO
590 signal(SIGINFO, sig_handler);
591 #endif
592 signal(SIGUSR2, sig_handler);
593 signal(SIGHUP, SIG_IGN);
595 if (!foreground && !configless) {
596 if (daemon(1, 1) == -1)
597 fatal("daemon: %s", strerror(errno));
600 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
601 fatal("socketpair: %s", strerror(errno));
603 switch (fork()) {
604 case -1:
605 fatal("fork: %s", strerror(errno));
607 case 0: /* child */
608 close(p[0]);
609 exfd = p[1];
610 listener_main();
611 _exit(0);
613 default: /* parent */
614 close(p[1]);
615 return executor_main(p[0]);