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.
29 #include <openssl/pem.h>
30 #include <openssl/x509.h>
34 struct vhost hosts[HOSTSLEN];
36 int exfd, foreground, verbose;
43 fatal(const char *fmt, ...)
50 vfprintf(stderr, fmt, ap);
51 fprintf(stderr, "\n");
53 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
60 logs(int priority, struct client *c,
63 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
69 if (foreground && !verbose) {
70 if (priority == LOG_DEBUG || priority == LOG_INFO)
77 strncpy(hbuf, "<internal>", sizeof(hbuf));
80 len = sizeof(c->addr);
81 ec = getnameinfo((struct sockaddr*)&c->addr, len,
84 NI_NUMERICHOST | NI_NUMERICSERV);
86 fatal("getnameinfo: %s", gai_strerror(ec));
89 if (vasprintf(&fmted, fmt, ap) == -1)
90 fatal("vasprintf: %s", strerror(errno));
93 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
95 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
96 fatal("asprintf: %s", strerror(errno));
97 syslog(priority | LOG_DAEMON, "%s", s);
106 /* strchr, but with a bound */
108 gmid_strnchr(char *s, int c, size_t len)
112 for (i = 0; i < len; ++i)
119 log_request(struct client *c, char *meta, size_t l)
121 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
126 len = sizeof(c->addr);
127 ec = getnameinfo((struct sockaddr*)&c->addr, len,
130 NI_NUMERICHOST | NI_NUMERICSERV);
132 fatal("getnameinfo: %s", gai_strerror(ec));
134 if (c->iri.schema != NULL) {
135 /* serialize the IRI */
136 strlcpy(b, c->iri.schema, sizeof(b));
137 strlcat(b, "://", sizeof(b));
139 /* log the decoded host name, but if it was invalid
140 * use the raw one. */
141 if (*c->domain != '\0')
142 strlcat(b, c->domain, sizeof(b));
144 strlcat(b, c->iri.host, sizeof(b));
146 strlcat(b, "/", sizeof(b));
147 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
148 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
149 strlcat(b, "?", sizeof(b));
150 strlcat(b, c->iri.query, sizeof(b));
153 strlcpy(b, c->req, sizeof(b));
156 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
160 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
161 (int)(t - meta), meta);
163 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
164 hbuf, sbuf, b, (int)(t - meta), meta);
174 gen_certificate(const char *host, const char *certpath, const char *keypath)
182 const char *org = "gmid";
184 LOGN(NULL, "generating new certificate for %s (it could take a while)",
187 if ((pkey = EVP_PKEY_new()) == NULL)
188 fatal("couldn't create a new private key");
190 if ((rsa = RSA_new()) == NULL)
191 fatal("could'nt generate rsa");
195 if (!RSA_generate_key_ex(rsa, 4096, &e, NULL))
196 fatal("couldn't generate a rsa key");
198 if (!EVP_PKEY_assign_RSA(pkey, rsa))
199 fatal("couldn't assign the key");
201 if ((x509 = X509_new()) == NULL)
202 fatal("couldn't generate the X509 certificate");
204 ASN1_INTEGER_set(X509_get_serialNumber(x509), 1);
205 X509_gmtime_adj(X509_get_notBefore(x509), 0);
206 X509_gmtime_adj(X509_get_notAfter(x509), 315360000L); /* 10 years */
208 if (!X509_set_pubkey(x509, pkey))
209 fatal("couldn't set the public key");
211 name = X509_get_subject_name(x509);
212 if (!X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, org, -1, -1, 0))
213 fatal("couldn't add N to cert");
214 if (!X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, host, -1, -1, 0))
215 fatal("couldn't add CN to cert");
216 X509_set_issuer_name(x509, name);
218 if (!X509_sign(x509, pkey, EVP_sha256()))
219 fatal("couldn't sign the certificate");
221 if ((f = fopen(keypath, "w")) == NULL)
222 fatal("fopen(%s): %s", keypath, strerror(errno));
223 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL))
224 fatal("couldn't write private key");
227 if ((f = fopen(certpath, "w")) == NULL)
228 fatal("fopen(%s): %s", certpath, strerror(errno));
229 if (!PEM_write_X509(f, x509))
230 fatal("couldn't write cert");
237 /* XXX: create recursively */
239 mkdirs(const char *path)
241 if (mkdir(path, 0755) == -1 && errno != EEXIST)
242 fatal("can't mkdir %s: %s", path, strerror(errno));
245 /* $XDG_DATA_HOME/gmid */
249 const char *home, *xdg;
252 if ((xdg = getenv("XDG_DATA_HOME")) == NULL) {
253 if ((home = getenv("HOME")) == NULL)
254 errx(1, "XDG_DATA_HOME and HOME both empty");
255 if (asprintf(&t, "%s/.local/share/gmid", home) == -1)
261 if (asprintf(&t, "%s/gmid", xdg) == -1)
268 load_local_cert(const char *hostname, const char *dir)
272 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
274 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
277 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
278 gen_certificate(hostname, cert, key);
280 hosts[0].cert = cert;
282 hosts[0].domain = hostname;
290 for (h = hosts; h->domain != NULL; ++h) {
291 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
292 fatal("open %s for domain %s", h->dir, h->domain);
297 make_socket(int port, int family)
300 struct sockaddr_in addr4;
301 struct sockaddr_in6 addr6;
302 struct sockaddr *addr;
307 bzero(&addr4, sizeof(addr4));
308 addr4.sin_family = family;
309 addr4.sin_port = htons(port);
310 addr4.sin_addr.s_addr = INADDR_ANY;
311 addr = (struct sockaddr*)&addr4;
316 bzero(&addr6, sizeof(addr6));
317 addr6.sin6_family = AF_INET6;
318 addr6.sin6_port = htons(port);
319 addr6.sin6_addr = in6addr_any;
320 addr = (struct sockaddr*)&addr6;
329 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
330 fatal("socket: %s", strerror(errno));
333 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
334 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
337 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
338 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
342 if (bind(sock, addr, len) == -1)
343 fatal("bind: %s", strerror(errno));
345 if (listen(sock, 16) == -1)
346 fatal("listen: %s", strerror(errno));
354 struct tls_config *tlsconf;
357 if ((tlsconf = tls_config_new()) == NULL)
358 fatal("tls_config_new");
360 /* optionally accept client certs, but don't try to verify them */
361 tls_config_verify_client_optional(tlsconf);
362 tls_config_insecure_noverifycert(tlsconf);
364 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
365 fatal("tls_config_set_protocols");
367 if ((ctx = tls_server()) == NULL)
368 fatal("tls_server failure");
370 /* we need to set something, then we can add how many key we want */
371 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
372 fatal("tls_config_set_keypair_file failed");
374 for (h = &hosts[1]; h->domain != NULL; ++h) {
375 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
376 fatal("failed to load the keypair (%s, %s)",
380 if (tls_configure(ctx, tlsconf) == -1)
381 fatal("tls_configure: %s", tls_error(ctx));
389 load_default_mime(&conf.mime);
391 sock4 = make_socket(conf.port, AF_INET);
394 sock6 = make_socket(conf.port, AF_INET6);
399 loop(ctx, sock4, sock6);
409 bzero(hosts, sizeof(hosts));
410 for (i = 0; i < HOSTSLEN; ++i)
415 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
417 init_mime(&conf.mime);
426 struct passwd *pw = NULL;
428 if (conf.chroot != NULL && conf.user == NULL)
429 fatal("can't chroot without an user to switch to after.");
431 if (conf.user != NULL) {
432 if ((pw = getpwnam(conf.user)) == NULL)
433 fatal("can't find user %s", conf.user);
436 if (conf.chroot != NULL) {
437 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
438 fatal("%s: %s", conf.chroot, strerror(errno));
442 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
443 fatal("setresuid(%d): %s", pw->pw_uid,
449 "not a good idea to run a network daemon as root");
453 usage(const char *me)
456 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
457 " [-p port] [-x cgi] [dir]",
462 main(int argc, char **argv)
466 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
467 int conftest = 0, configless = 0;
471 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
479 config_path = optarg;
505 conf.port = parse_portno(optarg);
514 /* drop the starting / (if any) */
517 hosts[0].cgi = optarg;
529 if (config_path != NULL) {
530 if (argc > 0 || configless)
531 fatal("can't specify options is config mode.");
533 parse_conf(config_path);
538 if (hostname == NULL)
539 hostname = "localhost";
540 if (certs_dir == NULL)
541 certs_dir = data_dir();
542 load_local_cert(hostname, certs_dir);
544 hosts[0].domain = "*";
545 hosts[0].locations[0].auto_index = 1;
546 hosts[0].locations[0].match = "*";
550 hosts[0].dir = getcwd(path, sizeof(path));
553 hosts[0].dir = absolutify_path(argv[0]);
556 usage(getprogname());
560 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
568 /* setup tls before dropping privileges: we don't want user
569 * to put private certs inside the chroot. */
573 signal(SIGPIPE, SIG_IGN);
574 signal(SIGCHLD, SIG_IGN);
577 signal(SIGINFO, sig_handler);
579 signal(SIGUSR2, sig_handler);
580 signal(SIGHUP, SIG_IGN);
582 if (!foreground && !configless) {
583 if (daemon(1, 1) == -1)
584 fatal("daemon: %s", strerror(errno));
587 if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC,
589 fatal("socketpair: %s", strerror(errno));
593 fatal("fork: %s", strerror(errno));
601 default: /* parent */
603 return executor_main(p[0]);