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 <errno.h>
18 #include <fcntl.h>
19 #include <limits.h>
20 #include <netdb.h>
21 #include <pwd.h>
22 #include <signal.h>
23 #include <stdarg.h>
24 #include <string.h>
26 #include "gmid.h"
28 struct vhost hosts[HOSTSLEN];
30 int goterror;
32 int exfd;
34 struct conf conf;
36 struct tls *ctx;
38 void
39 fatal(const char *fmt, ...)
40 {
41 va_list ap;
43 va_start(ap, fmt);
45 if (conf.foreground) {
46 vfprintf(stderr, fmt, ap);
47 fprintf(stderr, "\n");
48 } else
49 vsyslog(LOG_DAEMON | LOG_CRIT, fmt, ap);
51 va_end(ap);
52 exit(1);
53 }
55 void
56 logs(int priority, struct client *c,
57 const char *fmt, ...)
58 {
59 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
60 char *fmted, *s;
61 size_t len;
62 int ec;
63 va_list ap;
65 va_start(ap, fmt);
67 if (c == NULL) {
68 strncpy(hbuf, "<internal>", sizeof(hbuf));
69 sbuf[0] = '\0';
70 } else {
71 len = sizeof(c->addr);
72 ec = getnameinfo((struct sockaddr*)&c->addr, len,
73 hbuf, sizeof(hbuf),
74 sbuf, sizeof(sbuf),
75 NI_NUMERICHOST | NI_NUMERICSERV);
76 if (ec != 0)
77 fatal("getnameinfo: %s", gai_strerror(ec));
78 }
80 if (vasprintf(&fmted, fmt, ap) == -1)
81 fatal("vasprintf: %s", strerror(errno));
83 if (conf.foreground)
84 fprintf(stderr, "%s:%s %s\n", hbuf, sbuf, fmted);
85 else {
86 if (asprintf(&s, "%s:%s %s", hbuf, sbuf, fmted) == -1)
87 fatal("asprintf: %s", strerror(errno));
88 syslog(priority | LOG_DAEMON, "%s", s);
89 free(s);
90 }
92 free(fmted);
94 va_end(ap);
95 }
97 /* strchr, but with a bound */
98 static char *
99 gmid_strnchr(char *s, int c, size_t len)
101 size_t i;
103 for (i = 0; i < len; ++i)
104 if (s[i] == c)
105 return &s[i];
106 return NULL;
109 void
110 log_request(struct client *c, char *meta, size_t l)
112 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
113 char *t;
114 size_t len;
115 int ec;
117 len = sizeof(c->addr);
118 ec = getnameinfo((struct sockaddr*)&c->addr, len,
119 hbuf, sizeof(hbuf),
120 sbuf, sizeof(sbuf),
121 NI_NUMERICHOST | NI_NUMERICSERV);
122 if (ec != 0)
123 fatal("getnameinfo: %s", gai_strerror(ec));
125 if (c->iri.schema != NULL) {
126 /* serialize the IRI */
127 strlcpy(b, c->iri.schema, sizeof(b));
128 strlcat(b, "://", sizeof(b));
129 strlcat(b, c->iri.host, sizeof(b));
130 strlcat(b, "/", sizeof(b));
131 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
132 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
133 strlcat(b, "?", sizeof(b));
134 strlcat(b, c->iri.query, sizeof(b));
136 } else {
137 strlcpy(b, c->req, sizeof(b));
140 if ((t = gmid_strnchr(meta, '\r', l)) == NULL)
141 t = meta + len;
143 if (conf.foreground)
144 fprintf(stderr, "%s:%s GET %s %.*s\n", hbuf, sbuf, b,
145 (int)(t - meta), meta);
146 else
147 syslog(LOG_INFO | LOG_DAEMON, "%s:%s GET %s %.*s",
148 hbuf, sbuf, b, (int)(t - meta), meta);
151 void
152 sig_handler(int sig)
154 (void)sig;
157 int
158 starts_with(const char *str, const char *prefix)
160 size_t i;
162 if (prefix == NULL)
163 return 0;
165 for (i = 0; prefix[i] != '\0'; ++i)
166 if (str[i] != prefix[i])
167 return 0;
168 return 1;
171 int
172 ends_with(const char *str, const char *sufx)
174 size_t i, j;
176 i = strlen(str);
177 j = strlen(sufx);
179 if (j > i)
180 return 0;
182 i -= j;
183 for (j = 0; str[i] != '\0'; i++, j++)
184 if (str[i] != sufx[j])
185 return 0;
186 return 1;
189 ssize_t
190 filesize(int fd)
192 ssize_t len;
194 if ((len = lseek(fd, 0, SEEK_END)) == -1)
195 return -1;
196 if (lseek(fd, 0, SEEK_SET) == -1)
197 return -1;
198 return len;
201 char *
202 absolutify_path(const char *path)
204 char *wd, *r;
206 if (*path == '/')
207 return strdup(path);
209 wd = getcwd(NULL, 0);
210 if (asprintf(&r, "%s/%s", wd, path) == -1)
211 fatal("asprintf: %s", strerror(errno));
212 free(wd);
213 return r;
216 void
217 yyerror(const char *msg)
219 goterror = 1;
220 fprintf(stderr, "%d: %s\n", yylineno, msg);
223 int
224 parse_portno(const char *p)
226 const char *errstr;
227 int n;
229 n = strtonum(p, 0, UINT16_MAX, &errstr);
230 if (errstr != NULL)
231 errx(1, "port number is %s: %s", errstr, p);
232 return n;
235 void
236 parse_conf(const char *path)
238 if ((yyin = fopen(path, "r")) == NULL)
239 fatal("cannot open config %s", path);
240 yyparse();
241 fclose(yyin);
243 if (goterror)
244 exit(1);
247 void
248 load_vhosts(void)
250 struct vhost *h;
252 for (h = hosts; h->domain != NULL; ++h) {
253 if ((h->dirfd = open(h->dir, O_RDONLY | O_DIRECTORY)) == -1)
254 fatal("open %s for domain %s", h->dir, h->domain);
258 int
259 make_socket(int port, int family)
261 int sock, v;
262 struct sockaddr_in addr4;
263 struct sockaddr_in6 addr6;
264 struct sockaddr *addr;
265 socklen_t len;
267 switch (family) {
268 case AF_INET:
269 bzero(&addr4, sizeof(addr4));
270 addr4.sin_family = family;
271 addr4.sin_port = htons(port);
272 addr4.sin_addr.s_addr = INADDR_ANY;
273 addr = (struct sockaddr*)&addr4;
274 len = sizeof(addr4);
275 break;
277 case AF_INET6:
278 bzero(&addr6, sizeof(addr6));
279 addr6.sin6_family = AF_INET6;
280 addr6.sin6_port = htons(port);
281 addr6.sin6_addr = in6addr_any;
282 addr = (struct sockaddr*)&addr6;
283 len = sizeof(addr6);
284 break;
286 default:
287 /* unreachable */
288 abort();
291 if ((sock = socket(family, SOCK_STREAM, 0)) == -1)
292 fatal("socket: %s", strerror(errno));
294 v = 1;
295 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) == -1)
296 fatal("setsockopt(SO_REUSEADDR): %s", strerror(errno));
298 v = 1;
299 if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &v, sizeof(v)) == -1)
300 fatal("setsockopt(SO_REUSEPORT): %s", strerror(errno));
302 mark_nonblock(sock);
304 if (bind(sock, addr, len) == -1)
305 fatal("bind: %s", strerror(errno));
307 if (listen(sock, 16) == -1)
308 fatal("listen: %s", strerror(errno));
310 return sock;
313 void
314 setup_tls(void)
316 struct tls_config *tlsconf;
317 struct vhost *h;
319 if ((tlsconf = tls_config_new()) == NULL)
320 fatal("tls_config_new");
322 /* optionally accept client certs, but don't try to verify them */
323 tls_config_verify_client_optional(tlsconf);
324 tls_config_insecure_noverifycert(tlsconf);
326 if (tls_config_set_protocols(tlsconf, conf.protos) == -1)
327 fatal("tls_config_set_protocols");
329 if ((ctx = tls_server()) == NULL)
330 fatal("tls_server failure");
332 /* we need to set something, then we can add how many key we want */
333 if (tls_config_set_keypair_file(tlsconf, hosts->cert, hosts->key))
334 fatal("tls_config_set_keypair_file failed");
336 for (h = hosts; h->domain != NULL; ++h) {
337 if (tls_config_add_keypair_file(tlsconf, h->cert, h->key) == -1)
338 fatal("failed to load the keypair (%s, %s)",
339 h->cert, h->key);
342 if (tls_configure(ctx, tlsconf) == -1)
343 fatal("tls_configure: %s", tls_error(ctx));
346 int
347 listener_main(void)
349 int sock4, sock6;
351 load_default_mime(&conf.mime);
353 if (!conf.foreground && daemon(0, 1) == -1)
354 exit(1);
356 sock4 = make_socket(conf.port, AF_INET);
357 sock6 = -1;
358 if (conf.ipv6)
359 sock6 = make_socket(conf.port, AF_INET6);
361 load_vhosts();
363 sandbox();
364 loop(ctx, sock4, sock6);
366 return 0;
369 void
370 init_config(void)
372 size_t i;
374 bzero(hosts, sizeof(hosts));
375 for (i = 0; i < HOSTSLEN; ++i)
376 hosts[i].dirfd = -1;
378 conf.foreground = 1;
379 conf.port = 1965;
380 conf.ipv6 = 0;
381 conf.protos = TLS_PROTOCOL_TLSv1_2 | TLS_PROTOCOL_TLSv1_3;
383 init_mime(&conf.mime);
385 conf.chroot = NULL;
386 conf.user = NULL;
389 void
390 drop_priv(void)
392 struct passwd *pw = NULL;
394 if (conf.chroot != NULL && conf.user == NULL)
395 fatal("can't chroot without an user to switch to after.");
397 if (conf.user != NULL) {
398 if ((pw = getpwnam(conf.user)) == NULL)
399 fatal("can't find user %s", conf.user);
402 if (conf.chroot != NULL) {
403 if (chroot(conf.chroot) != 0 || chdir("/") != 0)
404 fatal("%s: %s", conf.chroot, strerror(errno));
407 if (pw != NULL) {
408 if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1)
409 fatal("setresuid(%d): %s", pw->pw_uid,
410 strerror(errno));
413 if (getuid() == 0)
414 LOGW(NULL, "%s",
415 "not a good idea to run a network daemon as root");
418 void
419 usage(const char *me)
421 fprintf(stderr,
422 "USAGE: %s [-n] [-c config] | [-6fh] [-C cert] [-d root] [-K key] "
423 "[-p port] [-x cgi-bin]\n",
424 me);
427 int
428 main(int argc, char **argv)
430 int ch, p[2];
431 const char *config_path = NULL;
432 int conftest = 0;
434 init_config();
436 while ((ch = getopt(argc, argv, "6C:c:d:fhK:np:x:")) != -1) {
437 switch (ch) {
438 case '6':
439 conf.ipv6 = 1;
440 break;
442 case 'C':
443 hosts[0].cert = optarg;
444 break;
446 case 'c':
447 config_path = optarg;
448 break;
450 case 'd':
451 free((char*)hosts[0].dir);
452 if ((hosts[0].dir = absolutify_path(optarg)) == NULL)
453 fatal("absolutify_path");
454 break;
456 case 'f':
457 conf.foreground = 1;
458 break;
460 case 'h':
461 usage(*argv);
462 return 0;
464 case 'K':
465 hosts[0].key = optarg;
466 break;
468 case 'n':
469 conftest = 1;
470 break;
472 case 'p':
473 conf.port = parse_portno(optarg);
474 break;
476 case 'x':
477 /* drop the starting / (if any) */
478 if (*optarg == '/')
479 optarg++;
480 hosts[0].cgi = optarg;
481 break;
483 default:
484 usage(*argv);
485 return 1;
489 if (config_path != NULL) {
490 if (hosts[0].cert != NULL || hosts[0].key != NULL ||
491 hosts[0].dir != NULL)
492 fatal("can't specify options in conf mode");
493 parse_conf(config_path);
494 } else {
495 if (hosts[0].cert == NULL || hosts[0].key == NULL ||
496 hosts[0].dir == NULL)
497 fatal("missing cert, key or root directory to serve");
498 hosts[0].domain = "*";
501 if (conftest) {
502 puts("config OK");
503 return 0;
506 /* setup tls before dropping privileges: we don't want user
507 * to put private certs inside the chroot. */
508 setup_tls();
509 drop_priv();
511 signal(SIGPIPE, SIG_IGN);
512 signal(SIGCHLD, SIG_IGN);
514 #ifdef SIGINFO
515 signal(SIGINFO, sig_handler);
516 #endif
517 signal(SIGUSR2, sig_handler);
519 if (!conf.foreground) {
520 signal(SIGHUP, SIG_IGN);
521 if (daemon(1, 1) == -1)
522 fatal("daemon: %s", strerror(errno));
525 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
526 fatal("socketpair: %s", strerror(errno));
528 switch (fork()) {
529 case -1:
530 fatal("fork: %s", strerror(errno));
532 case 0: /* child */
533 close(p[0]);
534 exfd = p[1];
535 listener_main();
536 _exit(0);
538 default: /* parent */
539 close(p[1]);
540 return executor_main(p[0]);