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 <limits.h>
23 #include <netdb.h>
24 #include <pwd.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <string.h>
29 #include <openssl/pem.h>
30 #include <openssl/x509.h>
32 #include "gmid.h"
34 struct vhost hosts[HOSTSLEN];
36 int exfd, foreground, verbose;
38 struct conf conf;
40 struct tls *ctx;
42 void
43 fatal(const char *fmt, ...)
44 {
45 va_list ap;
47 va_start(ap, fmt);
49 if (foreground) {
50 vfprintf(stderr, fmt, ap);
51 fprintf(stderr, "\n");
52 } else
53 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
55 va_end(ap);
56 exit(1);
57 }
59 void
60 logs(int priority, struct client *c,
61 const char *fmt, ...)
62 {
63 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
64 char *fmted, *s;
65 size_t len;
66 int ec;
67 va_list ap;
69 if (foreground && !verbose) {
70 if (priority == LOG_DEBUG || priority == LOG_INFO)
71 return;
72 }
74 va_start(ap, fmt);
76 if (c == NULL) {
77 strncpy(hbuf, "<internal>", sizeof(hbuf));
78 sbuf[0] = '\0';
79 } else {
80 len = sizeof(c->addr);
81 ec = getnameinfo((struct sockaddr*)&c->addr, len,
82 hbuf, sizeof(hbuf),
83 sbuf, sizeof(sbuf),
84 NI_NUMERICHOST | NI_NUMERICSERV);
85 if (ec != 0)
86 fatal("getnameinfo: %s", gai_strerror(ec));
87 }
89 if (vasprintf(&fmted, fmt, ap) == -1)
90 fatal("vasprintf: %s", strerror(errno));
92 if (foreground)
93 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
94 else {
95 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
96 fatal("asprintf: %s", strerror(errno));
97 syslog(priority | LOG_DAEMON, "%s", s);
98 free(s);
99 }
101 free(fmted);
103 va_end(ap);
106 /* strchr, but with a bound */
107 static char *
108 gmid_strnchr(char *s, int c, size_t len)
110 size_t i;
112 for (i = 0; i < len; ++i)
113 if (s[i] == c)
114 return &s[i];
115 return NULL;
118 void
119 log_request(struct client *c, char *meta, size_t l)
121 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
122 char *t;
123 size_t len;
124 int ec;
126 len = sizeof(c->addr);
127 ec = getnameinfo((struct sockaddr*)&c->addr, len,
128 hbuf, sizeof(hbuf),
129 sbuf, sizeof(sbuf),
130 NI_NUMERICHOST | NI_NUMERICSERV);
131 if (ec != 0)
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));
143 else
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));
152 } else {
153 strlcpy(b, c->req, sizeof(b));
156 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
157 t = meta + len;
159 if (foreground)
160 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
161 (int)(t - meta), meta);
162 else
163 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
164 hbuf, sbuf, b, (int)(t - meta), meta);
167 void
168 sig_handler(int sig)
170 (void)sig;
173 void
174 gen_certificate(const char *host, const char *certpath, const char *keypath)
176 BIGNUM e;
177 EVP_PKEY *pkey;
178 RSA *rsa;
179 X509 *x509;
180 X509_NAME *name;
181 FILE *f;
182 const char *org = "gmid";
184 LOGN(NULL, "generating new certificate for %s (it could take a while)",
185 host);
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");
193 BN_init(&e);
194 BN_set_word(&e, 17);
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");
225 fclose(f);
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");
231 fclose(f);
233 X509_free(x509);
234 RSA_free(rsa);
237 /* XXX: create recursively */
238 void
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 */
246 char *
247 data_dir(void)
249 const char *home, *xdg;
250 char *t;
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)
256 err(1, "asprintf");
257 mkdirs(t);
258 return t;
261 if (asprintf(&t, "%s/gmid", xdg) == -1)
262 err(1, "asprintf");
263 mkdirs(t);
264 return t;
267 void
268 load_local_cert(const char *hostname, const char *dir)
270 char *cert, *key;
272 if (asprintf(&cert, "%s/%s.cert.pem", dir, hostname) == -1)
273 errx(1, "asprintf");
274 if (asprintf(&key, "%s/%s.key.pem", dir, hostname) == -1)
275 errx(1, "asprintf");
277 if (access(cert, R_OK) == -1 || access(key, R_OK) == -1)
278 gen_certificate(hostname, cert, key);
280 hosts[0].cert = cert;
281 hosts[0].key = key;
282 hosts[0].domain = hostname;
285 void
286 load_vhosts(void)
288 struct vhost *h;
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);
296 int
297 make_socket(int port, int family)
299 int sock, v;
300 struct sockaddr_in addr4;
301 struct sockaddr_in6 addr6;
302 struct sockaddr *addr;
303 socklen_t len;
305 switch (family) {
306 case AF_INET:
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;
312 len = sizeof(addr4);
313 break;
315 case AF_INET6:
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;
321 len = sizeof(addr6);
322 break;
324 default:
325 /* unreachable */
326 abort();
329 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
330 fatal("socket: %s", strerror(errno));
332 v = 1;
333 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
334 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
336 v = 1;
337 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
338 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
340 mark_nonblock(sock);
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));
348 return sock;
351 void
352 setup_tls(void)
354 struct tls_config *tlsconf;
355 struct vhost *h;
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)",
377 h->cert, h->key);
380 if (tls_configure(ctx, tlsconf) == -1)
381 fatal("tls_configure: %s", tls_error(ctx));
384 int
385 listener_main(void)
387 int sock4, sock6;
389 load_default_mime(&conf.mime);
391 sock4 = make_socket(conf.port, AF_INET);
392 sock6 = -1;
393 if (conf.ipv6)
394 sock6 = make_socket(conf.port, AF_INET6);
396 load_vhosts();
398 sandbox();
399 loop(ctx, sock4, sock6);
401 return 0;
404 void
405 init_config(void)
407 size_t i;
409 bzero(hosts, sizeof(hosts));
410 for (i = 0; i < HOSTSLEN; ++i)
411 hosts[i].dirfd = -1;
413 conf.port = 1965;
414 conf.ipv6 = 0;
415 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
417 init_mime(&conf.mime);
419 conf.chroot = NULL;
420 conf.user = NULL;
423 void
424 drop_priv(void)
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));
441 if (pw != NULL) {
442 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
443 fatal("setresuid(%d): %s", pw->pw_uid,
444 strerror(errno));
447 if (getuid() == 0)
448 LOGW(NULL, "%s",
449 "not a good idea to run a network daemon as root");
452 void
453 usage(const char *me)
455 fprintf(stderr,
456 "USAGE: %s [-fn] [-c config] | [-6h] [-d certs-dir] [-H host]"
457 " [-p port] [-x cgi] [dir]",
458 me);
461 int
462 main(int argc, char **argv)
464 int ch, p[2];
465 char path[PATH_MAX];
466 const char *config_path = NULL, *certs_dir = NULL, *hostname = NULL;
467 int conftest = 0, configless = 0;
469 init_config();
471 while ((ch = getopt(argc, argv, "6c:d:fH:hnp:vx:")) != -1) {
472 switch (ch) {
473 case '6':
474 conf.ipv6 = 1;
475 configless = 1;
476 break;
478 case 'c':
479 config_path = optarg;
480 break;
482 case 'd':
483 certs_dir = optarg;
484 configless = 1;
485 break;
487 case 'f':
488 foreground = 1;
489 break;
491 case 'H':
492 hostname = optarg;
493 configless = 1;
494 break;
496 case 'h':
497 usage(*argv);
498 return 0;
500 case 'n':
501 conftest = 1;
502 break;
504 case 'p':
505 conf.port = parse_portno(optarg);
506 configless = 1;
507 break;
509 case 'v':
510 verbose = 1;
511 break;
513 case 'x':
514 /* drop the starting / (if any) */
515 if (*optarg == '/')
516 optarg++;
517 hosts[0].cgi = optarg;
518 configless = 1;
519 break;
521 default:
522 usage(*argv);
523 return 1;
526 argc -= optind;
527 argv += optind;
529 if (config_path != NULL) {
530 if (argc > 0 || configless)
531 fatal("can't specify options is config mode.");
533 parse_conf(config_path);
534 } else {
535 configless = 1;
536 foreground = 1;
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 = "*";
548 switch (argc) {
549 case 0:
550 hosts[0].dir = getcwd(path, sizeof(path));
551 break;
552 case 1:
553 hosts[0].dir = absolutify_path(argv[0]);
554 break;
555 default:
556 usage(getprogname());
557 return 1;
560 LOGN(NULL, "serving %s on port %d", hosts[0].dir, conf.port);
563 if (conftest) {
564 puts("config OK");
565 return 0;
568 /* setup tls before dropping privileges: we don't want user
569 * to put private certs inside the chroot. */
570 setup_tls();
571 drop_priv();
573 signal(SIGPIPE, SIG_IGN);
574 signal(SIGCHLD, SIG_IGN);
576 #ifdef SIGINFO
577 signal(SIGINFO, sig_handler);
578 #endif
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,
588 PF_UNSPEC, p) == -1)
589 fatal("socketpair: %s", strerror(errno));
591 switch (fork()) {
592 case -1:
593 fatal("fork: %s", strerror(errno));
595 case 0: /* child */
596 close(p[0]);
597 exfd = p[1];
598 listener_main();
599 _exit(0);
601 default: /* parent */
602 close(p[1]);
603 return executor_main(p[0]);