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, goterror;
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 va_start(ap, fmt);
70 if (c == NULL) {
71 strncpy(hbuf, "<internal>", sizeof(hbuf));
72 sbuf[0] = '\0';
73 } else {
74 len = sizeof(c->addr);
75 ec = getnameinfo((struct sockaddr*)&c->addr, len,
76 hbuf, sizeof(hbuf),
77 sbuf, sizeof(sbuf),
78 NI_NUMERICHOST | NI_NUMERICSERV);
79 if (ec != 0)
80 fatal("getnameinfo: %s", gai_strerror(ec));
81 }
83 if (vasprintf(&fmted, fmt, ap) == -1)
84 fatal("vasprintf: %s", strerror(errno));
86 if (foreground)
87 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
88 else {
89 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
90 fatal("asprintf: %s", strerror(errno));
91 syslog(priority | LOG_DAEMON, "%s", s);
92 free(s);
93 }
95 free(fmted);
97 va_end(ap);
98 }
100 /* strchr, but with a bound */
101 static char *
102 gmid_strnchr(char *s, int c, size_t len)
104 size_t i;
106 for (i = 0; i < len; ++i)
107 if (s[i] == c)
108 return &s[i];
109 return NULL;
112 void
113 log_request(struct client *c, char *meta, size_t l)
115 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
116 char *t;
117 size_t len;
118 int ec;
120 len = sizeof(c->addr);
121 ec = getnameinfo((struct sockaddr*)&c->addr, len,
122 hbuf, sizeof(hbuf),
123 sbuf, sizeof(sbuf),
124 NI_NUMERICHOST | NI_NUMERICSERV);
125 if (ec != 0)
126 fatal("getnameinfo: %s", gai_strerror(ec));
128 if (c->iri.schema != NULL) {
129 /* serialize the IRI */
130 strlcpy(b, c->iri.schema, sizeof(b));
131 strlcat(b, "://", sizeof(b));
133 /* log the decoded host name, but if it was invalid
134 * use the raw one. */
135 if (*c->domain != '\0')
136 strlcat(b, c->domain, sizeof(b));
137 else
138 strlcat(b, c->iri.host, sizeof(b));
140 strlcat(b, "/", sizeof(b));
141 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
142 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
143 strlcat(b, "?", sizeof(b));
144 strlcat(b, c->iri.query, sizeof(b));
146 } else {
147 strlcpy(b, c->req, sizeof(b));
150 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
151 t = meta + len;
153 if (foreground)
154 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
155 (int)(t - meta), meta);
156 else
157 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
158 hbuf, sbuf, b, (int)(t - meta), meta);
161 void
162 sig_handler(int sig)
164 (void)sig;
167 char *
168 absolutify_path(const char *path)
170 char *wd, *r;
172 if (*path == '/')
173 return strdup(path);
175 wd = getcwd(NULL, 0);
176 if (asprintf(&r, "%s/%s", wd, path) == -1)
177 fatal("asprintf: %s", strerror(errno));
178 free(wd);
179 return r;
182 void
183 gen_certificate(const char *host, const char *certpath, const char *keypath)
185 BIGNUM e;
186 EVP_PKEY *pkey;
187 RSA *rsa;
188 X509 *x509;
189 X509_NAME *name;
190 FILE *f;
191 const char *org = "gmid";
193 LOGN(NULL, "generating new certificate for %s (it could take a while)",
194 host);
196 if ((pkey = EVP_PKEY_new()) == NULL)
197 fatal("couldn't create a new private key");
199 if ((rsa = RSA_new()) == NULL)
200 fatal("could'nt generate rsa");
202 BN_init(&e);
203 BN_set_word(&e, 17);
204 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
205 fatal("couldn't generate a rsa key");
207 if (!EVP_PKEY_assign_RSA(pkey, rsa))
208 fatal("couldn't assign the key");
210 if ((x509 = X509_new()) == NULL)
211 fatal("couldn't generate the X509 certificate");
213 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
214 X509_gmtime_adj(X509_get_notBefore(x509), 0);
215 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
217 if (!X509_set_pubkey(x509, pkey))
218 fatal("couldn't set the public key");
220 name = X509_get_subject_name(x509);
221 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
222 fatal("couldn't add N to cert");
223 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
224 fatal("couldn't add CN to cert");
225 X509_set_issuer_name(x509, name);
227 if (!X509_sign(x509, pkey, EVP_sha256()))
228 fatal("couldn't sign the certificate");
230 if ((f = fopen(keypath, "w")) == NULL)
231 fatal("fopen(%s): %s", keypath, strerror(errno));
232 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
233 fatal("couldn't write private key");
234 fclose(f);
236 if ((f = fopen(certpath, "w")) == NULL)
237 fatal("fopen(%s): %s", certpath, strerror(errno));
238 if (!PEM_write_X509(f, x509))
239 fatal("couldn't write cert");
240 fclose(f);
242 X509_free(x509);
243 RSA_free(rsa);
246 /* XXX: create recursively */
247 void
248 mkdirs(const char *path)
250 if (mkdir(path, 0755) == -1 && errno != EEXIST)
251 fatal("can't mkdir %s: %s", path, strerror(errno));
254 /* $XDG_DATA_HOME/gmid */
255 char *
256 data_dir(void)
258 const char *home, *xdg;
259 char *t;
261 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
262 if ((home = getenv("HOME")) == NULL)
263 errx(1, "XDG_DATA_HOME and HOME both empty");
264 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
265 err(1, "asprintf");
266 mkdirs(t);
267 return t;
270 if (asprintf(&t, "%s/gmid", xdg) == -1)
271 err(1, "asprintf");
272 mkdirs(t);
273 return t;
276 void
277 load_local_cert(const char *hostname, const char *dir)
279 char *cert, *key;
281 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
282 errx(1, "asprintf");
283 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
284 errx(1, "asprintf");
286 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
287 gen_certificate(hostname, cert, key);
289 hosts[0].cert = cert;
290 hosts[0].key = key;
291 hosts[0].domain = hostname;
294 void
295 yyerror(const char *msg)
297 goterror = 1;
298 fprintf(stderr, "%d: %s\n", yylineno, msg);
301 int
302 parse_portno(const char *p)
304 const char *errstr;
305 int n;
307 n = strtonum(p, 0, UINT16_MAX, &errstr);
308 if (errstr != NULL)
309 errx(1, "port number is %s: %s", errstr, p);
310 return n;
313 void
314 parse_conf(const char *path)
316 if ((yyin = fopen(path, "r")) == NULL)
317 fatal("cannot open config %s", path);
318 yyparse();
319 fclose(yyin);
321 if (goterror)
322 exit(1);
325 void
326 load_vhosts(void)
328 struct vhost *h;
330 for (h = hosts; h->domain != NULL; ++h) {
331 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
332 fatal("open %s for domain %s", h->dir, h->domain);
336 int
337 make_socket(int port, int family)
339 int sock, v;
340 struct sockaddr_in addr4;
341 struct sockaddr_in6 addr6;
342 struct sockaddr *addr;
343 socklen_t len;
345 switch (family) {
346 case AF_INET:
347 bzero(&addr4, sizeof(addr4));
348 addr4.sin_family = family;
349 addr4.sin_port = htons(port);
350 addr4.sin_addr.s_addr = INADDR_ANY;
351 addr = (struct sockaddr*)&addr4;
352 len = sizeof(addr4);
353 break;
355 case AF_INET6:
356 bzero(&addr6, sizeof(addr6));
357 addr6.sin6_family = AF_INET6;
358 addr6.sin6_port = htons(port);
359 addr6.sin6_addr = in6addr_any;
360 addr = (struct sockaddr*)&addr6;
361 len = sizeof(addr6);
362 break;
364 default:
365 /* unreachable */
366 abort();
369 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
370 fatal("socket: %s", strerror(errno));
372 v = 1;
373 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
374 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
376 v = 1;
377 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
378 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
380 mark_nonblock(sock);
382 if (bind(sock, addr, len) == -1)
383 fatal("bind: %s", strerror(errno));
385 if (listen(sock, 16) == -1)
386 fatal("listen: %s", strerror(errno));
388 return sock;
391 void
392 setup_tls(void)
394 struct tls_config *tlsconf;
395 struct vhost *h;
397 if ((tlsconf = tls_config_new()) == NULL)
398 fatal("tls_config_new");
400 /* optionally accept client certs, but don't try to verify them */
401 tls_config_verify_client_optional(tlsconf);
402 tls_config_insecure_noverifycert(tlsconf);
404 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
405 fatal("tls_config_set_protocols");
407 if ((ctx = tls_server()) == NULL)
408 fatal("tls_server failure");
410 /* we need to set something, then we can add how many key we want */
411 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
412 fatal("tls_config_set_keypair_file failed");
414 for (h = &hosts[1]; h->domain != NULL; ++h) {
415 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
416 fatal("failed to load the keypair (%s, %s)",
417 h->cert, h->key);
420 if (tls_configure(ctx, tlsconf) == -1)
421 fatal("tls_configure: %s", tls_error(ctx));
424 int
425 listener_main(void)
427 int sock4, sock6;
429 load_default_mime(&conf.mime);
431 sock4 = make_socket(conf.port, AF_INET);
432 sock6 = -1;
433 if (conf.ipv6)
434 sock6 = make_socket(conf.port, AF_INET6);
436 load_vhosts();
438 sandbox();
439 loop(ctx, sock4, sock6);
441 return 0;
444 void
445 init_config(void)
447 size_t i;
449 bzero(hosts, sizeof(hosts));
450 for (i = 0; i < HOSTSLEN; ++i)
451 hosts[i].dirfd = -1;
453 conf.port = 1965;
454 conf.ipv6 = 0;
455 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
457 init_mime(&conf.mime);
459 conf.chroot = NULL;
460 conf.user = NULL;
463 void
464 drop_priv(void)
466 struct passwd *pw = NULL;
468 if (conf.chroot != NULL && conf.user == NULL)
469 fatal("can't chroot without an user to switch to after.");
471 if (conf.user != NULL) {
472 if ((pw = getpwnam(conf.user)) == NULL)
473 fatal("can't find user %s", conf.user);
476 if (conf.chroot != NULL) {
477 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
478 fatal("%s: %s", conf.chroot, strerror(errno));
481 if (pw != NULL) {
482 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
483 fatal("setresuid(%d): %s", pw->pw_uid,
484 strerror(errno));
487 if (getuid() == 0)
488 LOGW(NULL, "%s",
489 "not a good idea to run a network daemon as root");
492 void
493 usage(const char *me)
495 fprintf(stderr,
496 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
497 " [-p port] [-x cgi] [dir]",
498 me);
501 int
502 main(int argc, char **argv)
504 int ch, p[2];
505 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
506 int conftest = 0, configless = 0;
508 init_config();
510 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:x:")) != -1) {
511 switch (ch) {
512 case '6':
513 conf.ipv6 = 1;
514 configless = 1;
515 break;
517 case 'c':
518 config_path = optarg;
519 break;
521 case 'd':
522 certs_dir = optarg;
523 configless = 1;
524 break;
526 case 'f':
527 foreground = 1;
528 break;
530 case 'H':
531 hostname = optarg;
532 configless = 1;
533 break;
535 case 'h':
536 usage(*argv);
537 return 0;
539 case 'n':
540 conftest = 1;
541 break;
543 case 'p':
544 conf.port = parse_portno(optarg);
545 configless = 1;
546 break;
548 case 'x':
549 /* drop the starting / (if any) */
550 if (*optarg == '/')
551 optarg++;
552 hosts[0].cgi = optarg;
553 configless = 1;
554 break;
556 default:
557 usage(*argv);
558 return 1;
561 argc -= optind;
562 argv += optind;
564 if (config_path != NULL) {
565 if (argc > 0 || configless)
566 fatal("can't specify options is config mode.");
568 parse_conf(config_path);
569 } else {
570 configless = 1;
571 foreground = 1;
573 if (hostname == NULL)
574 hostname = "localhost";
575 if (certs_dir == NULL)
576 certs_dir = data_dir();
577 load_local_cert(hostname, certs_dir);
579 hosts[0].domain = "*";
580 hosts[0].locations[0].auto_index = 1;
581 hosts[0].locations[0].match = "*";
583 switch (argc) {
584 case 0:
585 hosts[0].dir = ".";
586 break;
587 case 1:
588 hosts[0].dir = argv[0];
589 break;
590 default:
591 usage(getprogname());
592 return 1;
595 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
598 if (conftest) {
599 puts("config OK");
600 return 0;
603 /* setup tls before dropping privileges: we don't want user
604 * to put private certs inside the chroot. */
605 setup_tls();
606 drop_priv();
608 signal(SIGPIPE, SIG_IGN);
609 signal(SIGCHLD, SIG_IGN);
611 #ifdef SIGINFO
612 signal(SIGINFO, sig_handler);
613 #endif
614 signal(SIGUSR2, sig_handler);
615 signal(SIGHUP, SIG_IGN);
617 if (!foreground && !configless) {
618 if (daemon(1, 1) == -1)
619 fatal("daemon: %s", strerror(errno));
622 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
623 fatal("socketpair: %s", strerror(errno));
625 switch (fork()) {
626 case -1:
627 fatal("fork: %s", strerror(errno));
629 case 0: /* child */
630 close(p[0]);
631 exfd = p[1];
632 listener_main();
633 _exit(0);
635 default: /* parent */
636 close(p[1]);
637 return executor_main(p[0]);