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 struct vhost hosts[HOSTSLEN];
36 int exfd, foreground, verbose, sock4, sock6;
38 const char *config_path, *certs_dir, *hostname;
40 struct conf conf;
42 struct tls *ctx;
44 void
45 fatal(const char *fmt, ...)
46 {
47 va_list ap;
49 va_start(ap, fmt);
51 if (foreground) {
52 vfprintf(stderr, fmt, ap);
53 fprintf(stderr, "\n");
54 } else
55 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
57 va_end(ap);
58 exit(1);
59 }
61 void
62 logs(int priority, struct client *c,
63 const char *fmt, ...)
64 {
65 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
66 char *fmted, *s;
67 size_t len;
68 int ec;
69 va_list ap;
71 if (foreground && !verbose) {
72 if (priority == LOG_DEBUG || priority == LOG_INFO)
73 return;
74 }
76 va_start(ap, fmt);
78 if (c == NULL) {
79 strncpy(hbuf, "<internal>", sizeof(hbuf));
80 sbuf[0] = '\0';
81 } else {
82 len = sizeof(c->addr);
83 ec = getnameinfo((struct sockaddr*)&c->addr, len,
84 hbuf, sizeof(hbuf),
85 sbuf, sizeof(sbuf),
86 NI_NUMERICHOST | NI_NUMERICSERV);
87 if (ec != 0)
88 fatal("getnameinfo: %s", gai_strerror(ec));
89 }
91 if (vasprintf(&fmted, fmt, ap) == -1)
92 fatal("vasprintf: %s", strerror(errno));
94 if (foreground)
95 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
96 else {
97 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
98 fatal("asprintf: %s", strerror(errno));
99 syslog(priority | LOG_DAEMON, "%s", s);
100 free(s);
103 free(fmted);
105 va_end(ap);
108 /* strchr, but with a bound */
109 static char *
110 gmid_strnchr(char *s, int c, size_t len)
112 size_t i;
114 for (i = 0; i < len; ++i)
115 if (s[i] == c)
116 return &s[i];
117 return NULL;
120 void
121 log_request(struct client *c, char *meta, size_t l)
123 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
124 char *t;
125 size_t len;
126 int ec;
128 len = sizeof(c->addr);
129 ec = getnameinfo((struct sockaddr*)&c->addr, len,
130 hbuf, sizeof(hbuf),
131 sbuf, sizeof(sbuf),
132 NI_NUMERICHOST | NI_NUMERICSERV);
133 if (ec != 0)
134 fatal("getnameinfo: %s", gai_strerror(ec));
136 if (c->iri.schema != NULL) {
137 /* serialize the IRI */
138 strlcpy(b, c->iri.schema, sizeof(b));
139 strlcat(b, "://", sizeof(b));
141 /* log the decoded host name, but if it was invalid
142 * use the raw one. */
143 if (*c->domain != '\0')
144 strlcat(b, c->domain, sizeof(b));
145 else
146 strlcat(b, c->iri.host, sizeof(b));
148 strlcat(b, "/", sizeof(b));
149 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
150 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
151 strlcat(b, "?", sizeof(b));
152 strlcat(b, c->iri.query, sizeof(b));
154 } else {
155 strlcpy(b, c->req, sizeof(b));
158 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
159 t = meta + len;
161 if (foreground)
162 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
163 (int)(t - meta), meta);
164 else
165 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
166 hbuf, sbuf, b, (int)(t - meta), meta);
169 void
170 sig_handler(int sig)
172 (void)sig;
175 void
176 gen_certificate(const char *host, const char *certpath, const char *keypath)
178 BIGNUM e;
179 EVP_PKEY *pkey;
180 RSA *rsa;
181 X509 *x509;
182 X509_NAME *name;
183 FILE *f;
184 const char *org = "gmid";
186 LOGN(NULL, "generating new certificate for %s (it could take a while)",
187 host);
189 if ((pkey = EVP_PKEY_new()) == NULL)
190 fatal("couldn't create a new private key");
192 if ((rsa = RSA_new()) == NULL)
193 fatal("could'nt generate rsa");
195 BN_init(&e);
196 BN_set_word(&e, 17);
197 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
198 fatal("couldn't generate a rsa key");
200 if (!EVP_PKEY_assign_RSA(pkey, rsa))
201 fatal("couldn't assign the key");
203 if ((x509 = X509_new()) == NULL)
204 fatal("couldn't generate the X509 certificate");
206 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
207 X509_gmtime_adj(X509_get_notBefore(x509), 0);
208 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
210 if (!X509_set_pubkey(x509, pkey))
211 fatal("couldn't set the public key");
213 name = X509_get_subject_name(x509);
214 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
215 fatal("couldn't add N to cert");
216 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
217 fatal("couldn't add CN to cert");
218 X509_set_issuer_name(x509, name);
220 if (!X509_sign(x509, pkey, EVP_sha256()))
221 fatal("couldn't sign the certificate");
223 if ((f = fopen(keypath, "w")) == NULL)
224 fatal("fopen(%s): %s", keypath, strerror(errno));
225 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
226 fatal("couldn't write private key");
227 fclose(f);
229 if ((f = fopen(certpath, "w")) == NULL)
230 fatal("fopen(%s): %s", certpath, strerror(errno));
231 if (!PEM_write_X509(f, x509))
232 fatal("couldn't write cert");
233 fclose(f);
235 X509_free(x509);
236 RSA_free(rsa);
239 /* XXX: create recursively */
240 void
241 mkdirs(const char *path)
243 if (mkdir(path, 0755) == -1 && errno != EEXIST)
244 fatal("can't mkdir %s: %s", path, strerror(errno));
247 /* $XDG_DATA_HOME/gmid */
248 char *
249 data_dir(void)
251 const char *home, *xdg;
252 char *t;
254 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
255 if ((home = getenv("HOME")) == NULL)
256 errx(1, "XDG_DATA_HOME and HOME both empty");
257 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
258 err(1, "asprintf");
259 mkdirs(t);
260 return t;
263 if (asprintf(&t, "%s/gmid", xdg) == -1)
264 err(1, "asprintf");
265 mkdirs(t);
266 return t;
269 void
270 load_local_cert(const char *hostname, const char *dir)
272 char *cert, *key;
274 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
275 errx(1, "asprintf");
276 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
277 errx(1, "asprintf");
279 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
280 gen_certificate(hostname, cert, key);
282 hosts[0].cert = cert;
283 hosts[0].key = key;
284 hosts[0].domain = hostname;
287 void
288 load_vhosts(void)
290 struct vhost *h;
292 for (h = hosts; h->domain != NULL; ++h) {
293 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
294 fatal("open %s for domain %s", h->dir, h->domain);
298 int
299 make_socket(int port, int family)
301 int sock, v;
302 struct sockaddr_in addr4;
303 struct sockaddr_in6 addr6;
304 struct sockaddr *addr;
305 socklen_t len;
307 switch (family) {
308 case AF_INET:
309 bzero(&addr4, sizeof(addr4));
310 addr4.sin_family = family;
311 addr4.sin_port = htons(port);
312 addr4.sin_addr.s_addr = INADDR_ANY;
313 addr = (struct sockaddr*)&addr4;
314 len = sizeof(addr4);
315 break;
317 case AF_INET6:
318 bzero(&addr6, sizeof(addr6));
319 addr6.sin6_family = AF_INET6;
320 addr6.sin6_port = htons(port);
321 addr6.sin6_addr = in6addr_any;
322 addr = (struct sockaddr*)&addr6;
323 len = sizeof(addr6);
324 break;
326 default:
327 /* unreachable */
328 abort();
331 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
332 fatal("socket: %s", strerror(errno));
334 v = 1;
335 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
336 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
338 v = 1;
339 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
340 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
342 mark_nonblock(sock);
344 if (bind(sock, addr, len) == -1)
345 fatal("bind: %s", strerror(errno));
347 if (listen(sock, 16) == -1)
348 fatal("listen: %s", strerror(errno));
350 return sock;
353 void
354 setup_tls(void)
356 struct tls_config *tlsconf;
357 struct vhost *h;
359 if ((tlsconf = tls_config_new()) == NULL)
360 fatal("tls_config_new");
362 /* optionally accept client certs, but don't try to verify them */
363 tls_config_verify_client_optional(tlsconf);
364 tls_config_insecure_noverifycert(tlsconf);
366 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
367 fatal("tls_config_set_protocols");
369 if ((ctx = tls_server()) == NULL)
370 fatal("tls_server failure");
372 /* we need to set something, then we can add how many key we want */
373 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
374 fatal("tls_config_set_keypair_file failed");
376 for (h = &hosts[1]; h->domain != NULL; ++h) {
377 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
378 fatal("failed to load the keypair (%s, %s)",
379 h->cert, h->key);
382 if (tls_configure(ctx, tlsconf) == -1)
383 fatal("tls_configure: %s", tls_error(ctx));
386 static int
387 listener_main(void)
389 load_default_mime(&conf.mime);
390 load_vhosts();
391 sandbox();
392 loop(ctx, sock4, sock6);
393 return 0;
396 void
397 init_config(void)
399 size_t i;
401 bzero(hosts, sizeof(hosts));
402 for (i = 0; i < HOSTSLEN; ++i)
403 hosts[i].dirfd = -1;
405 conf.port = 1965;
406 conf.ipv6 = 0;
407 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
409 init_mime(&conf.mime);
411 conf.chroot = NULL;
412 conf.user = NULL;
415 void
416 drop_priv(void)
418 struct passwd *pw = NULL;
420 if (conf.chroot != NULL && conf.user == NULL)
421 fatal("can't chroot without an user to switch to after.");
423 if (conf.user != NULL) {
424 if ((pw = getpwnam(conf.user)) == NULL)
425 fatal("can't find user %s", conf.user);
428 if (conf.chroot != NULL) {
429 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
430 fatal("%s: %s", conf.chroot, strerror(errno));
433 if (pw != NULL) {
434 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
435 fatal("setresuid(%d): %s", pw->pw_uid,
436 strerror(errno));
439 if (getuid() == 0)
440 LOGW(NULL, "%s",
441 "not a good idea to run a network daemon as root");
444 void
445 usage(const char *me)
447 fprintf(stderr,
448 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
449 " [-p port] [-x cgi] [dir]",
450 me);
453 static int
454 serve(int argc, char **argv, int *p)
456 char path[PATH_MAX];
458 if (config_path == NULL) {
459 if (hostname == NULL)
460 hostname = "localhost";
461 if (certs_dir == NULL)
462 certs_dir = data_dir();
463 load_local_cert(hostname, certs_dir);
465 hosts[0].domain = "*";
466 hosts[0].locations[0].auto_index = 1;
467 hosts[0].locations[0].match = "*";
469 switch (argc) {
470 case 0:
471 hosts[0].dir = getcwd(path, sizeof(path));
472 break;
473 case 1:
474 hosts[0].dir = absolutify_path(argv[0]);
475 break;
476 default:
477 usage(getprogname());
478 return 1;
481 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
484 /* setup tls before dropping privileges: we don't want user
485 * to put private certs inside the chroot. */
486 setup_tls();
488 switch (fork()) {
489 case -1:
490 fatal("fork: %s", strerror(errno));
492 case 0: /* child */
493 close(p[0]);
494 exfd = p[1];
495 drop_priv();
496 listener_main();
497 _exit(0);
499 default: /* parent */
500 close(p[1]);
501 exfd = p[0];
502 drop_priv();
503 return executor_main();
507 int
508 main(int argc, char **argv)
510 int ch, p[2];
511 int conftest = 0, configless = 0;
513 init_config();
515 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
516 switch (ch) {
517 case '6':
518 conf.ipv6 = 1;
519 configless = 1;
520 break;
522 case 'c':
523 config_path = optarg;
524 break;
526 case 'd':
527 certs_dir = optarg;
528 configless = 1;
529 break;
531 case 'f':
532 foreground = 1;
533 break;
535 case 'H':
536 hostname = optarg;
537 configless = 1;
538 break;
540 case 'h':
541 usage(*argv);
542 return 0;
544 case 'n':
545 conftest = 1;
546 break;
548 case 'p':
549 conf.port = parse_portno(optarg);
550 configless = 1;
551 break;
553 case 'v':
554 verbose = 1;
555 break;
557 case 'x':
558 /* drop the starting / (if any) */
559 if (*optarg == '/')
560 optarg++;
561 hosts[0].cgi = optarg;
562 configless = 1;
563 break;
565 default:
566 usage(*argv);
567 return 1;
570 argc -= optind;
571 argv += optind;
573 if (config_path == NULL) {
574 configless = 1;
575 foreground = 1;
578 if (config_path != NULL && (argc > 0 || configless))
579 err(1, "can't specify options in config mode.");
581 if (conftest) {
582 parse_conf(config_path);
583 puts("config OK");
584 return 0;
587 signal(SIGPIPE, SIG_IGN);
588 signal(SIGCHLD, SIG_IGN);
590 #ifdef SIGINFO
591 signal(SIGINFO, sig_handler);
592 #endif
593 signal(SIGUSR2, sig_handler);
594 signal(SIGHUP, SIG_IGN);
596 if (!foreground && !configless) {
597 if (daemon(1, 1) == -1)
598 fatal("daemon: %s", strerror(errno));
601 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
602 PF_UNSPEC, p) == -1)
603 fatal("socketpair: %s", strerror(errno));
605 if (config_path != NULL)
606 parse_conf(config_path);
608 sock4 = make_socket(conf.port, AF_INET);
609 sock6 = -1;
610 if (conf.ipv6)
611 sock6 = make_socket(conf.port, AF_INET6);
613 return serve(argc, argv, p);