2 * Copyright (c) 2020 Omar Polo <op@omarpolo.com>
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.
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.
28 #include <openssl/pem.h>
29 #include <openssl/x509.h>
33 struct vhost hosts[HOSTSLEN];
44 fatal(const char *fmt, ...)
50 if (conf.foreground) {
51 vfprintf(stderr, fmt, ap);
52 fprintf(stderr, "\n");
54 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
61 logs(int priority, struct client *c,
64 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
73 strncpy(hbuf, "<internal>", sizeof(hbuf));
76 len = sizeof(c->addr);
77 ec = getnameinfo((struct sockaddr*)&c->addr, len,
80 NI_NUMERICHOST | NI_NUMERICSERV);
82 fatal("getnameinfo: %s", gai_strerror(ec));
85 if (vasprintf(&fmted, fmt, ap) == -1)
86 fatal("vasprintf: %s", strerror(errno));
89 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
91 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
92 fatal("asprintf: %s", strerror(errno));
93 syslog(priority | LOG_DAEMON, "%s", s);
102 /* strchr, but with a bound */
104 gmid_strnchr(char *s, int c, size_t len)
108 for (i = 0; i < len; ++i)
115 log_request(struct client *c, char *meta, size_t l)
117 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
122 len = sizeof(c->addr);
123 ec = getnameinfo((struct sockaddr*)&c->addr, len,
126 NI_NUMERICHOST | NI_NUMERICSERV);
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));
134 strlcat(b, c->iri.host, sizeof(b));
135 strlcat(b, "/", sizeof(b));
136 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
137 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
138 strlcat(b, "?", sizeof(b));
139 strlcat(b, c->iri.query, sizeof(b));
142 strlcpy(b, c->req, sizeof(b));
145 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
149 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
150 (int)(t - meta), meta);
152 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
153 hbuf, sbuf, b, (int)(t - meta), meta);
163 starts_with(const char *str, const char *prefix)
170 for (i = 0; prefix[i] != '\0'; ++i)
171 if (str[i] != prefix[i])
177 ends_with(const char *str, const char *sufx)
188 for (j = 0; str[i] != '\0'; i++, j++)
189 if (str[i] != sufx[j])
199 if ((len = lseek(fd, 0, SEEK_END)) == -1)
201 if (lseek(fd, 0, SEEK_SET) == -1)
207 absolutify_path(const char *path)
214 wd = getcwd(NULL, 0);
215 if (asprintf(&r, "%s/%s", wd, path) == -1)
216 fatal("asprintf: %s", strerror(errno));
222 gen_certificate(const char *host, const char *certpath, const char *keypath)
230 const char *org = "gmid";
232 LOGN(NULL, "generating a new certificate for %s in %s (it could take a while)",
235 if ((pkey = EVP_PKEY_new()) == NULL)
236 fatal("couldn't create a new private key");
238 if ((rsa = RSA_new()) == NULL)
239 fatal("could'nt generate rsa");
243 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
244 fatal("couldn't generate a rsa key");
246 if (!EVP_PKEY_assign_RSA(pkey, rsa))
247 fatal("couldn't assign the key");
249 if ((x509 = X509_new()) == NULL)
250 fatal("couldn't generate the X509 certificate");
252 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
253 X509_gmtime_adj(X509_get_notBefore(x509), 0);
254 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
256 if (!X509_set_pubkey(x509, pkey))
257 fatal("couldn't set the public key");
259 name = X509_get_subject_name(x509);
260 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
261 fatal("couldn't add N to cert");
262 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
263 fatal("couldn't add CN to cert");
264 X509_set_issuer_name(x509, name);
266 if (!X509_sign(x509, pkey, EVP_sha256()))
267 fatal("couldn't sign the certificate");
269 if ((f = fopen(keypath, "w")) == NULL)
270 fatal("fopen(%s): %s", keypath, strerror(errno));
271 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
272 fatal("couldn't write private key");
275 if ((f = fopen(certpath, "w")) == NULL)
276 fatal("fopen(%s): %s", certpath, strerror(errno));
277 if (!PEM_write_X509(f, x509))
278 fatal("couldn't write cert");
285 /* XXX: create recursively */
287 mkdirs(const char *path)
289 if (mkdir(path, 0755) == -1 && errno != EEXIST)
290 fatal("can't mkdir %s: %s", path, strerror(errno));
293 /* $XDG_DATA_HOME/gmid */
297 const char *home, *xdg;
301 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
302 if ((home = getenv("HOME")) == NULL)
303 errx(1, "XDG_DATA_HOME and HOME both empty");
304 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
310 if (asprintf(&t, "%s/gmid", xdg) == -1)
317 load_local_cert(const char *hostname, const char *dir)
321 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
323 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
326 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
327 gen_certificate(hostname, cert, key);
329 hosts[0].cert = cert;
331 hosts[0].domain = hostname;
335 yyerror(const char *msg)
338 fprintf(stderr, "%d: %s\n", yylineno, msg);
342 parse_portno(const char *p)
347 n = strtonum(p, 0, UINT16_MAX, &errstr);
349 errx(1, "port number is %s: %s", errstr, p);
354 parse_conf(const char *path)
356 if ((yyin = fopen(path, "r")) == NULL)
357 fatal("cannot open config %s", path);
370 for (h = hosts; h->domain != NULL; ++h) {
371 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
372 fatal("open %s for domain %s", h->dir, h->domain);
377 make_socket(int port, int family)
380 struct sockaddr_in addr4;
381 struct sockaddr_in6 addr6;
382 struct sockaddr *addr;
387 bzero(&addr4, sizeof(addr4));
388 addr4.sin_family = family;
389 addr4.sin_port = htons(port);
390 addr4.sin_addr.s_addr = INADDR_ANY;
391 addr = (struct sockaddr*)&addr4;
396 bzero(&addr6, sizeof(addr6));
397 addr6.sin6_family = AF_INET6;
398 addr6.sin6_port = htons(port);
399 addr6.sin6_addr = in6addr_any;
400 addr = (struct sockaddr*)&addr6;
409 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
410 fatal("socket: %s", strerror(errno));
413 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
414 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
417 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
418 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
422 if (bind(sock, addr, len) == -1)
423 fatal("bind: %s", strerror(errno));
425 if (listen(sock, 16) == -1)
426 fatal("listen: %s", strerror(errno));
434 struct tls_config *tlsconf;
437 if ((tlsconf = tls_config_new()) == NULL)
438 fatal("tls_config_new");
440 /* optionally accept client certs, but don't try to verify them */
441 tls_config_verify_client_optional(tlsconf);
442 tls_config_insecure_noverifycert(tlsconf);
444 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
445 fatal("tls_config_set_protocols");
447 if ((ctx = tls_server()) == NULL)
448 fatal("tls_server failure");
450 /* we need to set something, then we can add how many key we want */
451 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
452 fatal("tls_config_set_keypair_file failed");
454 for (h = &hosts[1]; h->domain != NULL; ++h) {
455 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
456 fatal("failed to load the keypair (%s, %s)",
460 if (tls_configure(ctx, tlsconf) == -1)
461 fatal("tls_configure: %s", tls_error(ctx));
469 load_default_mime(&conf.mime);
471 if (!conf.foreground && daemon(0, 1) == -1)
474 sock4 = make_socket(conf.port, AF_INET);
477 sock6 = make_socket(conf.port, AF_INET6);
482 loop(ctx, sock4, sock6);
492 bzero(hosts, sizeof(hosts));
493 for (i = 0; i < HOSTSLEN; ++i)
499 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
501 init_mime(&conf.mime);
510 struct passwd *pw = NULL;
512 if (conf.chroot != NULL && conf.user == NULL)
513 fatal("can't chroot without an user to switch to after.");
515 if (conf.user != NULL) {
516 if ((pw = getpwnam(conf.user)) == NULL)
517 fatal("can't find user %s", conf.user);
520 if (conf.chroot != NULL) {
521 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
522 fatal("%s: %s", conf.chroot, strerror(errno));
526 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
527 fatal("setresuid(%d): %s", pw->pw_uid,
533 "not a good idea to run a network daemon as root");
537 usage(const char *me)
540 "USAGE: %s [-n] [-c config] | [-6h] [-d certs-dir] [-H host]"
541 " [-p port] [-x cgi] [dir]",
546 main(int argc, char **argv)
549 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
550 int conftest = 0, configless = 0;
554 while ((ch = getopt(argc, argv, "6c:d:H:hnp:x:")) != -1) {
562 config_path = optarg;
584 conf.port = parse_portno(optarg);
589 /* drop the starting / (if any) */
592 hosts[0].cgi = optarg;
604 if (config_path != NULL) {
605 if (argc > 0 || configless)
606 fatal("can't specify options is config mode.");
608 parse_conf(config_path);
612 if (hostname == NULL)
613 hostname = "localhost";
614 if (certs_dir == NULL)
615 certs_dir = data_dir();
616 load_local_cert(hostname, certs_dir);
623 hosts[0].dir = argv[0];
626 usage(getprogname());
630 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
638 /* setup tls before dropping privileges: we don't want user
639 * to put private certs inside the chroot. */
643 signal(SIGPIPE, SIG_IGN);
644 signal(SIGCHLD, SIG_IGN);
647 signal(SIGINFO, sig_handler);
649 signal(SIGUSR2, sig_handler);
651 if (!conf.foreground) {
652 signal(SIGHUP, SIG_IGN);
653 if (daemon(1, 1) == -1)
654 fatal("daemon: %s", strerror(errno));
657 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
658 fatal("socketpair: %s", strerror(errno));
662 fatal("fork: %s", strerror(errno));
670 default: /* parent */
672 return executor_main(p[0]);