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];
35 int exfd, foreground, verbose;
42 fatal(const char *fmt, ...)
49 vfprintf(stderr, fmt, ap);
50 fprintf(stderr, "\n");
52 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
59 logs(int priority, struct client *c,
62 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
68 if (foreground && !verbose) {
69 if (priority == LOG_DEBUG || priority == LOG_INFO)
76 strncpy(hbuf, "<internal>", sizeof(hbuf));
79 len = sizeof(c->addr);
80 ec = getnameinfo((struct sockaddr*)&c->addr, len,
83 NI_NUMERICHOST | NI_NUMERICSERV);
85 fatal("getnameinfo: %s", gai_strerror(ec));
88 if (vasprintf(&fmted, fmt, ap) == -1)
89 fatal("vasprintf: %s", strerror(errno));
92 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
94 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
95 fatal("asprintf: %s", strerror(errno));
96 syslog(priority | LOG_DAEMON, "%s", s);
105 /* strchr, but with a bound */
107 gmid_strnchr(char *s, int c, size_t len)
111 for (i = 0; i < len; ++i)
118 log_request(struct client *c, char *meta, size_t l)
120 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
125 len = sizeof(c->addr);
126 ec = getnameinfo((struct sockaddr*)&c->addr, len,
129 NI_NUMERICHOST | NI_NUMERICSERV);
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));
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));
152 strlcpy(b, c->req, sizeof(b));
155 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
159 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
160 (int)(t - meta), meta);
162 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
163 hbuf, sbuf, b, (int)(t - meta), meta);
173 gen_certificate(const char *host, const char *certpath, const char *keypath)
181 const char *org = "gmid";
183 LOGN(NULL, "generating new certificate for %s (it could take a while)",
186 if ((pkey = EVP_PKEY_new()) == NULL)
187 fatal("couldn't create a new private key");
189 if ((rsa = RSA_new()) == NULL)
190 fatal("could'nt generate rsa");
194 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
195 fatal("couldn't generate a rsa key");
197 if (!EVP_PKEY_assign_RSA(pkey, rsa))
198 fatal("couldn't assign the key");
200 if ((x509 = X509_new()) == NULL)
201 fatal("couldn't generate the X509 certificate");
203 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
204 X509_gmtime_adj(X509_get_notBefore(x509), 0);
205 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
207 if (!X509_set_pubkey(x509, pkey))
208 fatal("couldn't set the public key");
210 name = X509_get_subject_name(x509);
211 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
212 fatal("couldn't add N to cert");
213 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
214 fatal("couldn't add CN to cert");
215 X509_set_issuer_name(x509, name);
217 if (!X509_sign(x509, pkey, EVP_sha256()))
218 fatal("couldn't sign the certificate");
220 if ((f = fopen(keypath, "w")) == NULL)
221 fatal("fopen(%s): %s", keypath, strerror(errno));
222 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
223 fatal("couldn't write private key");
226 if ((f = fopen(certpath, "w")) == NULL)
227 fatal("fopen(%s): %s", certpath, strerror(errno));
228 if (!PEM_write_X509(f, x509))
229 fatal("couldn't write cert");
236 /* XXX: create recursively */
238 mkdirs(const char *path)
240 if (mkdir(path, 0755) == -1 && errno != EEXIST)
241 fatal("can't mkdir %s: %s", path, strerror(errno));
244 /* $XDG_DATA_HOME/gmid */
248 const char *home, *xdg;
251 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
252 if ((home = getenv("HOME")) == NULL)
253 errx(1, "XDG_DATA_HOME and HOME both empty");
254 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
260 if (asprintf(&t, "%s/gmid", xdg) == -1)
267 load_local_cert(const char *hostname, const char *dir)
271 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
273 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
276 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
277 gen_certificate(hostname, cert, key);
279 hosts[0].cert = cert;
281 hosts[0].domain = hostname;
289 for (h = hosts; h->domain != NULL; ++h) {
290 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
291 fatal("open %s for domain %s", h->dir, h->domain);
296 make_socket(int port, int family)
299 struct sockaddr_in addr4;
300 struct sockaddr_in6 addr6;
301 struct sockaddr *addr;
306 bzero(&addr4, sizeof(addr4));
307 addr4.sin_family = family;
308 addr4.sin_port = htons(port);
309 addr4.sin_addr.s_addr = INADDR_ANY;
310 addr = (struct sockaddr*)&addr4;
315 bzero(&addr6, sizeof(addr6));
316 addr6.sin6_family = AF_INET6;
317 addr6.sin6_port = htons(port);
318 addr6.sin6_addr = in6addr_any;
319 addr = (struct sockaddr*)&addr6;
328 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
329 fatal("socket: %s", strerror(errno));
332 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
333 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
336 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
337 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
341 if (bind(sock, addr, len) == -1)
342 fatal("bind: %s", strerror(errno));
344 if (listen(sock, 16) == -1)
345 fatal("listen: %s", strerror(errno));
353 struct tls_config *tlsconf;
356 if ((tlsconf = tls_config_new()) == NULL)
357 fatal("tls_config_new");
359 /* optionally accept client certs, but don't try to verify them */
360 tls_config_verify_client_optional(tlsconf);
361 tls_config_insecure_noverifycert(tlsconf);
363 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
364 fatal("tls_config_set_protocols");
366 if ((ctx = tls_server()) == NULL)
367 fatal("tls_server failure");
369 /* we need to set something, then we can add how many key we want */
370 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
371 fatal("tls_config_set_keypair_file failed");
373 for (h = &hosts[1]; h->domain != NULL; ++h) {
374 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
375 fatal("failed to load the keypair (%s, %s)",
379 if (tls_configure(ctx, tlsconf) == -1)
380 fatal("tls_configure: %s", tls_error(ctx));
388 load_default_mime(&conf.mime);
390 sock4 = make_socket(conf.port, AF_INET);
393 sock6 = make_socket(conf.port, AF_INET6);
398 loop(ctx, sock4, sock6);
408 bzero(hosts, sizeof(hosts));
409 for (i = 0; i < HOSTSLEN; ++i)
414 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
416 init_mime(&conf.mime);
425 struct passwd *pw = NULL;
427 if (conf.chroot != NULL && conf.user == NULL)
428 fatal("can't chroot without an user to switch to after.");
430 if (conf.user != NULL) {
431 if ((pw = getpwnam(conf.user)) == NULL)
432 fatal("can't find user %s", conf.user);
435 if (conf.chroot != NULL) {
436 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
437 fatal("%s: %s", conf.chroot, strerror(errno));
441 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
442 fatal("setresuid(%d): %s", pw->pw_uid,
448 "not a good idea to run a network daemon as root");
452 usage(const char *me)
455 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
456 " [-p port] [-x cgi] [dir]",
461 main(int argc, char **argv)
464 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
465 int conftest = 0, configless = 0;
469 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
477 config_path = optarg;
503 conf.port = parse_portno(optarg);
512 /* drop the starting / (if any) */
515 hosts[0].cgi = optarg;
527 if (config_path != NULL) {
528 if (argc > 0 || configless)
529 fatal("can't specify options is config mode.");
531 parse_conf(config_path);
536 if (hostname == NULL)
537 hostname = "localhost";
538 if (certs_dir == NULL)
539 certs_dir = data_dir();
540 load_local_cert(hostname, certs_dir);
542 hosts[0].domain = "*";
543 hosts[0].locations[0].auto_index = 1;
544 hosts[0].locations[0].match = "*";
551 hosts[0].dir = argv[0];
554 usage(getprogname());
558 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
566 /* setup tls before dropping privileges: we don't want user
567 * to put private certs inside the chroot. */
571 signal(SIGPIPE, SIG_IGN);
572 signal(SIGCHLD, SIG_IGN);
575 signal(SIGINFO, sig_handler);
577 signal(SIGUSR2, sig_handler);
578 signal(SIGHUP, SIG_IGN);
580 if (!foreground && !configless) {
581 if (daemon(1, 1) == -1)
582 fatal("daemon: %s", strerror(errno));
585 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
587 fatal("socketpair: %s", strerror(errno));
591 fatal("fork: %s", strerror(errno));
599 default: /* parent */
601 return executor_main(p[0]);