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 goterror;
37 int exfd;
39 struct conf conf;
41 struct tls *ctx;
43 void
44 fatal(const char *fmt, ...)
45 {
46 va_list ap;
48 va_start(ap, fmt);
50 if (conf.foreground) {
51 vfprintf(stderr, fmt, ap);
52 fprintf(stderr, "\n");
53 } else
54 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
56 va_end(ap);
57 exit(1);
58 }
60 void
61 logs(int priority, struct client *c,
62 const char *fmt, ...)
63 {
64 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
65 char *fmted, *s;
66 size_t len;
67 int ec;
68 va_list ap;
70 va_start(ap, fmt);
72 if (c == NULL) {
73 strncpy(hbuf, "<internal>", sizeof(hbuf));
74 sbuf[0] = '\0';
75 } else {
76 len = sizeof(c->addr);
77 ec = getnameinfo((struct sockaddr*)&c->addr, len,
78 hbuf, sizeof(hbuf),
79 sbuf, sizeof(sbuf),
80 NI_NUMERICHOST | NI_NUMERICSERV);
81 if (ec != 0)
82 fatal("getnameinfo: %s", gai_strerror(ec));
83 }
85 if (vasprintf(&fmted, fmt, ap) == -1)
86 fatal("vasprintf: %s", strerror(errno));
88 if (conf.foreground)
89 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
90 else {
91 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
92 fatal("asprintf: %s", strerror(errno));
93 syslog(priority | LOG_DAEMON, "%s", s);
94 free(s);
95 }
97 free(fmted);
99 va_end(ap);
102 /* strchr, but with a bound */
103 static char *
104 gmid_strnchr(char *s, int c, size_t len)
106 size_t i;
108 for (i = 0; i < len; ++i)
109 if (s[i] == c)
110 return &s[i];
111 return NULL;
114 void
115 log_request(struct client *c, char *meta, size_t l)
117 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
118 char *t;
119 size_t len;
120 int ec;
122 len = sizeof(c->addr);
123 ec = getnameinfo((struct sockaddr*)&c->addr, len,
124 hbuf, sizeof(hbuf),
125 sbuf, sizeof(sbuf),
126 NI_NUMERICHOST | NI_NUMERICSERV);
127 if (ec != 0)
128 fatal("getnameinfo: %s", gai_strerror(ec));
130 if (c->iri.schema != NULL) {
131 /* serialize the IRI */
132 strlcpy(b, c->iri.schema, sizeof(b));
133 strlcat(b, "://", sizeof(b));
135 /* log the decoded host name, but if it was invalid
136 * use the raw one. */
137 if (*c->domain != '\0')
138 strlcat(b, c->domain, sizeof(b));
139 else
140 strlcat(b, c->iri.host, sizeof(b));
142 strlcat(b, "/", sizeof(b));
143 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
144 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
145 strlcat(b, "?", sizeof(b));
146 strlcat(b, c->iri.query, sizeof(b));
148 } else {
149 strlcpy(b, c->req, sizeof(b));
152 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
153 t = meta + len;
155 if (conf.foreground)
156 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
157 (int)(t - meta), meta);
158 else
159 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
160 hbuf, sbuf, b, (int)(t - meta), meta);
163 void
164 sig_handler(int sig)
166 (void)sig;
169 int
170 starts_with(const char *str, const char *prefix)
172 size_t i;
174 if (prefix == NULL)
175 return 0;
177 for (i = 0; prefix[i] != '\0'; ++i)
178 if (str[i] != prefix[i])
179 return 0;
180 return 1;
183 int
184 ends_with(const char *str, const char *sufx)
186 size_t i, j;
188 i = strlen(str);
189 j = strlen(sufx);
191 if (j > i)
192 return 0;
194 i -= j;
195 for (j = 0; str[i] != '\0'; i++, j++)
196 if (str[i] != sufx[j])
197 return 0;
198 return 1;
201 ssize_t
202 filesize(int fd)
204 ssize_t len;
206 if ((len = lseek(fd, 0, SEEK_END)) == -1)
207 return -1;
208 if (lseek(fd, 0, SEEK_SET) == -1)
209 return -1;
210 return len;
213 char *
214 absolutify_path(const char *path)
216 char *wd, *r;
218 if (*path == '/')
219 return strdup(path);
221 wd = getcwd(NULL, 0);
222 if (asprintf(&r, "%s/%s", wd, path) == -1)
223 fatal("asprintf: %s", strerror(errno));
224 free(wd);
225 return r;
228 void
229 gen_certificate(const char *host, const char *certpath, const char *keypath)
231 BIGNUM e;
232 EVP_PKEY *pkey;
233 RSA *rsa;
234 X509 *x509;
235 X509_NAME *name;
236 FILE *f;
237 const char *org = "gmid";
239 LOGN(NULL, "generating a new certificate for %s in %s (it could take a while)",
240 host, certpath);
242 if ((pkey = EVP_PKEY_new()) == NULL)
243 fatal("couldn't create a new private key");
245 if ((rsa = RSA_new()) == NULL)
246 fatal("could'nt generate rsa");
248 BN_init(&e);
249 BN_set_word(&e, 17);
250 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
251 fatal("couldn't generate a rsa key");
253 if (!EVP_PKEY_assign_RSA(pkey, rsa))
254 fatal("couldn't assign the key");
256 if ((x509 = X509_new()) == NULL)
257 fatal("couldn't generate the X509 certificate");
259 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
260 X509_gmtime_adj(X509_get_notBefore(x509), 0);
261 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
263 if (!X509_set_pubkey(x509, pkey))
264 fatal("couldn't set the public key");
266 name = X509_get_subject_name(x509);
267 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
268 fatal("couldn't add N to cert");
269 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
270 fatal("couldn't add CN to cert");
271 X509_set_issuer_name(x509, name);
273 if (!X509_sign(x509, pkey, EVP_sha256()))
274 fatal("couldn't sign the certificate");
276 if ((f = fopen(keypath, "w")) == NULL)
277 fatal("fopen(%s): %s", keypath, strerror(errno));
278 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
279 fatal("couldn't write private key");
280 fclose(f);
282 if ((f = fopen(certpath, "w")) == NULL)
283 fatal("fopen(%s): %s", certpath, strerror(errno));
284 if (!PEM_write_X509(f, x509))
285 fatal("couldn't write cert");
286 fclose(f);
288 X509_free(x509);
289 RSA_free(rsa);
292 /* XXX: create recursively */
293 void
294 mkdirs(const char *path)
296 if (mkdir(path, 0755) == -1 && errno != EEXIST)
297 fatal("can't mkdir %s: %s", path, strerror(errno));
300 /* $XDG_DATA_HOME/gmid */
301 char *
302 data_dir(void)
304 const char *home, *xdg;
305 char dir[PATH_MAX];
306 char *t;
308 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
309 if ((home = getenv("HOME")) == NULL)
310 errx(1, "XDG_DATA_HOME and HOME both empty");
311 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
312 err(1, "asprintf");
313 mkdirs(t);
314 return t;
317 if (asprintf(&t, "%s/gmid", xdg) == -1)
318 err(1, "asprintf");
319 mkdirs(t);
320 return t;
323 void
324 load_local_cert(const char *hostname, const char *dir)
326 char *cert, *key;
328 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
329 errx(1, "asprintf");
330 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
331 errx(1, "asprintf");
333 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
334 gen_certificate(hostname, cert, key);
336 hosts[0].cert = cert;
337 hosts[0].key = key;
338 hosts[0].domain = hostname;
341 void
342 yyerror(const char *msg)
344 goterror = 1;
345 fprintf(stderr, "%d: %s\n", yylineno, msg);
348 int
349 parse_portno(const char *p)
351 const char *errstr;
352 int n;
354 n = strtonum(p, 0, UINT16_MAX, &errstr);
355 if (errstr != NULL)
356 errx(1, "port number is %s: %s", errstr, p);
357 return n;
360 void
361 parse_conf(const char *path)
363 if ((yyin = fopen(path, "r")) == NULL)
364 fatal("cannot open config %s", path);
365 yyparse();
366 fclose(yyin);
368 if (goterror)
369 exit(1);
372 void
373 load_vhosts(void)
375 struct vhost *h;
377 for (h = hosts; h->domain != NULL; ++h) {
378 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
379 fatal("open %s for domain %s", h->dir, h->domain);
383 int
384 make_socket(int port, int family)
386 int sock, v;
387 struct sockaddr_in addr4;
388 struct sockaddr_in6 addr6;
389 struct sockaddr *addr;
390 socklen_t len;
392 switch (family) {
393 case AF_INET:
394 bzero(&addr4, sizeof(addr4));
395 addr4.sin_family = family;
396 addr4.sin_port = htons(port);
397 addr4.sin_addr.s_addr = INADDR_ANY;
398 addr = (struct sockaddr*)&addr4;
399 len = sizeof(addr4);
400 break;
402 case AF_INET6:
403 bzero(&addr6, sizeof(addr6));
404 addr6.sin6_family = AF_INET6;
405 addr6.sin6_port = htons(port);
406 addr6.sin6_addr = in6addr_any;
407 addr = (struct sockaddr*)&addr6;
408 len = sizeof(addr6);
409 break;
411 default:
412 /* unreachable */
413 abort();
416 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
417 fatal("socket: %s", strerror(errno));
419 v = 1;
420 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
421 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
423 v = 1;
424 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
425 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
427 mark_nonblock(sock);
429 if (bind(sock, addr, len) == -1)
430 fatal("bind: %s", strerror(errno));
432 if (listen(sock, 16) == -1)
433 fatal("listen: %s", strerror(errno));
435 return sock;
438 void
439 setup_tls(void)
441 struct tls_config *tlsconf;
442 struct vhost *h;
444 if ((tlsconf = tls_config_new()) == NULL)
445 fatal("tls_config_new");
447 /* optionally accept client certs, but don't try to verify them */
448 tls_config_verify_client_optional(tlsconf);
449 tls_config_insecure_noverifycert(tlsconf);
451 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
452 fatal("tls_config_set_protocols");
454 if ((ctx = tls_server()) == NULL)
455 fatal("tls_server failure");
457 /* we need to set something, then we can add how many key we want */
458 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
459 fatal("tls_config_set_keypair_file failed");
461 for (h = &hosts[1]; h->domain != NULL; ++h) {
462 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
463 fatal("failed to load the keypair (%s, %s)",
464 h->cert, h->key);
467 if (tls_configure(ctx, tlsconf) == -1)
468 fatal("tls_configure: %s", tls_error(ctx));
471 int
472 listener_main(void)
474 int sock4, sock6;
476 load_default_mime(&conf.mime);
478 if (!conf.foreground && daemon(0, 1) == -1)
479 exit(1);
481 sock4 = make_socket(conf.port, AF_INET);
482 sock6 = -1;
483 if (conf.ipv6)
484 sock6 = make_socket(conf.port, AF_INET6);
486 load_vhosts();
488 sandbox();
489 loop(ctx, sock4, sock6);
491 return 0;
494 void
495 init_config(void)
497 size_t i;
499 bzero(hosts, sizeof(hosts));
500 for (i = 0; i < HOSTSLEN; ++i)
501 hosts[i].dirfd = -1;
503 conf.foreground = 0;
504 conf.port = 1965;
505 conf.ipv6 = 0;
506 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
508 init_mime(&conf.mime);
510 conf.chroot = NULL;
511 conf.user = NULL;
514 void
515 drop_priv(void)
517 struct passwd *pw = NULL;
519 if (conf.chroot != NULL && conf.user == NULL)
520 fatal("can't chroot without an user to switch to after.");
522 if (conf.user != NULL) {
523 if ((pw = getpwnam(conf.user)) == NULL)
524 fatal("can't find user %s", conf.user);
527 if (conf.chroot != NULL) {
528 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
529 fatal("%s: %s", conf.chroot, strerror(errno));
532 if (pw != NULL) {
533 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
534 fatal("setresuid(%d): %s", pw->pw_uid,
535 strerror(errno));
538 if (getuid() == 0)
539 LOGW(NULL, "%s",
540 "not a good idea to run a network daemon as root");
543 void
544 usage(const char *me)
546 fprintf(stderr,
547 "USAGE: %s [-n] [-c config] | [-6h] [-d certs-dir] [-H host]"
548 " [-p port] [-x cgi] [dir]",
549 me);
552 int
553 main(int argc, char **argv)
555 int ch, p[2];
556 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
557 int conftest = 0, configless = 0;
559 init_config();
561 while ((ch = getopt(argc, argv, "6c:d:H:hnp:x:")) != -1) {
562 switch (ch) {
563 case '6':
564 conf.ipv6 = 1;
565 configless = 1;
566 break;
568 case 'c':
569 config_path = optarg;
570 break;
572 case 'd':
573 certs_dir = optarg;
574 configless = 1;
575 break;
577 case 'H':
578 hostname = optarg;
579 configless = 1;
580 break;
582 case 'h':
583 usage(*argv);
584 return 0;
586 case 'n':
587 conftest = 1;
588 break;
590 case 'p':
591 conf.port = parse_portno(optarg);
592 configless = 1;
593 break;
595 case 'x':
596 /* drop the starting / (if any) */
597 if (*optarg == '/')
598 optarg++;
599 hosts[0].cgi = optarg;
600 configless = 1;
601 break;
603 default:
604 usage(*argv);
605 return 1;
608 argc -= optind;
609 argv += optind;
611 if (config_path != NULL) {
612 if (argc > 0 || configless)
613 fatal("can't specify options is config mode.");
615 parse_conf(config_path);
616 } else {
617 conf.foreground = 1;
619 if (hostname == NULL)
620 hostname = "localhost";
621 if (certs_dir == NULL)
622 certs_dir = data_dir();
623 load_local_cert(hostname, certs_dir);
625 hosts[0].locations[0].auto_index = 1;
626 hosts[0].locations[0].match = "*";
628 switch (argc) {
629 case 0:
630 hosts[0].dir = ".";
631 break;
632 case 1:
633 hosts[0].dir = argv[0];
634 break;
635 default:
636 usage(getprogname());
637 return 1;
640 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
643 if (conftest) {
644 puts("config OK");
645 return 0;
648 /* setup tls before dropping privileges: we don't want user
649 * to put private certs inside the chroot. */
650 setup_tls();
651 drop_priv();
653 signal(SIGPIPE, SIG_IGN);
654 signal(SIGCHLD, SIG_IGN);
656 #ifdef SIGINFO
657 signal(SIGINFO, sig_handler);
658 #endif
659 signal(SIGUSR2, sig_handler);
661 if (!conf.foreground) {
662 signal(SIGHUP, SIG_IGN);
663 if (daemon(1, 1) == -1)
664 fatal("daemon: %s", strerror(errno));
667 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
668 fatal("socketpair: %s", strerror(errno));
670 switch (fork()) {
671 case -1:
672 fatal("fork: %s", strerror(errno));
674 case 0: /* child */
675 close(p[0]);
676 exfd = p[1];
677 listener_main();
678 _exit(0);
680 default: /* parent */
681 close(p[1]);
682 return executor_main(p[0]);