Blob


1 /*
2 * Copyright (c) 2020, 2021, 2022, 2023 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 "gmid.h"
19 #include <sys/stat.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <getopt.h>
24 #include <locale.h>
25 #include <libgen.h>
26 #include <limits.h>
27 #include <grp.h>
28 #include <pwd.h>
29 #include <signal.h>
30 #include <string.h>
31 #include <syslog.h>
32 #include <vis.h>
34 #include "log.h"
35 #include "proc.h"
37 #ifndef nitems
38 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
39 #endif
41 static int main_configure(struct conf *);
42 static void main_configure_done(struct conf *);
43 static void main_reload(struct conf *);
44 static void main_sig_handler(int, short, void *);
45 static int main_dispatch_server(int, struct privsep_proc *, struct imsg *);
46 static int main_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
47 static int main_dispatch_logger(int, struct privsep_proc *, struct imsg *);
48 static void __dead main_shutdown(struct conf *);
49 static void main_print_conf(struct conf *);
51 static struct privsep_proc procs[] = {
52 { "server", PROC_SERVER, main_dispatch_server, server },
53 { "crypto", PROC_CRYPTO, main_dispatch_crypto, crypto },
54 { "logger", PROC_LOGGER, main_dispatch_logger, logger },
55 };
57 static const char *opts = "c:D:fI:J:hnP:T:U:VvX:";
59 static const struct option longopts[] = {
60 {"help", no_argument, NULL, 'h'},
61 {"version", no_argument, NULL, 'V'},
62 {NULL, 0, NULL, 0},
63 };
65 int sock4, sock6;
66 int privsep_process;
67 int pidfd = -1;
69 int debug, verbose;
71 const char *config_path = SYSCONFDIR "/gmid.conf";
72 const char *pidfile;
74 static void
75 usage(void)
76 {
77 fprintf(stderr,
78 "Version: " GMID_STRING "\n"
79 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n",
80 getprogname());
81 }
83 /*
84 * Used by the server process, defined here so gemexp can provide
85 * its own implementation.
86 */
87 void
88 log_request(struct client *c, int code, const char *meta)
89 {
90 struct conf *conf = c->conf;
91 char tstamp[64], rfc3339[32];
92 char cntmp[64], cn[64] = "-";
93 char b[GEMINI_URL_LEN];
94 char *fmted;
95 const char *t;
96 struct tm *tm;
97 time_t now;
98 int ec;
100 if ((now = time(NULL)) == -1)
101 fatal("time");
102 if ((tm = localtime(&now)) == NULL)
103 fatal("localtime");
104 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
105 fatal("strftime");
106 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
107 fatal("strftime");
109 if (c->iri.schema != NULL) {
110 /* serialize the IRI */
111 strlcpy(b, c->iri.schema, sizeof(b));
112 strlcat(b, "://", sizeof(b));
114 /* log the decoded host name, but if it was invalid
115 * use the raw one. */
116 if (*c->domain != '\0')
117 strlcat(b, c->domain, sizeof(b));
118 else
119 strlcat(b, c->iri.host, sizeof(b));
121 if (*c->iri.path != '/')
122 strlcat(b, "/", sizeof(b));
123 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
124 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
125 strlcat(b, "?", sizeof(b));
126 strlcat(b, c->iri.query, sizeof(b));
128 } else {
129 if ((t = c->req) == NULL)
130 t = "";
131 strlcpy(b, t, sizeof(b));
134 if (tls_peer_cert_provided(c->ctx)) {
135 const char *subj;
136 char *n;
138 subj = tls_peer_cert_subject(c->ctx);
139 if ((n = strstr(subj, "/CN=")) != NULL) {
140 strlcpy(cntmp, subj + 4, sizeof(cntmp));
141 if ((n = strchr(cntmp, '/')) != NULL)
142 *n = '\0';
143 strnvis(cn, cntmp, sizeof(cn), VIS_WHITE|VIS_DQ);
147 switch (conf->log_format) {
148 case LOG_FORMAT_LEGACY:
149 ec = asprintf(&fmted, "%s:%s GET %s %d %s", c->rhost,
150 c->rserv, b, code, meta);
151 break;
153 case LOG_FORMAT_CONDENSED:
154 /*
155 * XXX it should log the size of the request and
156 * response.
157 */
158 ec = asprintf(&fmted, "%s %s %s %s %s 0 0 %d %s", rfc3339,
159 c->rhost, cn, *c->domain == '\0' ? c->iri.host : c->domain,
160 b, code, meta);
161 break;
163 /*
164 * Attempt to be compatible with the default Apache httpd'
165 * LogFormat "%h %l %u %t \"%r\" %>s %b"
166 * see <https://httpd.apache.org/docs/current/mod/mod_log_config.html>
167 */
168 case LOG_FORMAT_COMMON:
169 /*
170 * XXX it should log the size of the response.
171 */
172 ec = asprintf(&fmted, "%s %s - %s %s \"%s\" %d 0",
173 *c->domain == '\0' ? c->iri.host : c->domain,
174 c->rhost, cn, tstamp, b, code);
175 break;
177 /*
178 * Attempt to be compatible with the default nginx' log_format
179 * combined:
180 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
181 */
182 case LOG_FORMAT_COMBINED:
183 default:
184 /*
185 * XXX it should log the size of the response.
186 */
187 ec = asprintf(&fmted, "%s - %s [%s] \"%s\" %d 0 \"-\" \"\"",
188 c->rhost, cn, tstamp, b, code);
189 break;
192 if (ec == -1)
193 fatal("asprintf");
195 if (debug)
196 fprintf(stderr, "%s\n", fmted);
198 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
199 fmted, ec + 1);
201 free(fmted);
204 static int
205 write_pidfile(const char *pidfile)
207 struct flock lock;
208 int fd;
210 if (pidfile == NULL)
211 return -1;
213 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
214 fatal("can't open pidfile %s", pidfile);
216 lock.l_start = 0;
217 lock.l_len = 0;
218 lock.l_type = F_WRLCK;
219 lock.l_whence = SEEK_SET;
221 if (fcntl(fd, F_SETLK, &lock) == -1)
222 fatalx("can't lock %s, gmid is already running?", pidfile);
224 if (ftruncate(fd, 0) == -1)
225 fatal("ftruncate %s", pidfile);
227 dprintf(fd, "%d\n", getpid());
229 return fd;
232 int
233 main(int argc, char **argv)
235 struct conf *conf;
236 struct privsep *ps;
237 const char *errstr, *title = NULL;
238 const char *user = NULL, *chroot = NULL;
239 size_t i;
240 int ch, conftest = 0;
241 int proc_instance = 0;
242 int proc_id = PROC_PARENT;
243 int nprocs = 0;
244 int argc0 = argc;
246 setlocale(LC_CTYPE, "");
248 /* log to stderr until daemonized */
249 log_init(1, LOG_DAEMON);
251 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
252 switch (ch) {
253 case 'c':
254 config_path = absolutify_path(optarg);
255 break;
256 case 'D':
257 if (cmdline_symset(optarg) == -1)
258 fatalx("could not parse macro definition: %s",
259 optarg);
260 break;
261 case 'f':
262 debug = 1;
263 break;
264 case 'h':
265 usage();
266 return 0;
267 case 'I':
268 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
269 &errstr);
270 if (errstr != NULL)
271 fatalx("invalid process instance");
272 break;
273 case 'J':
274 nprocs = strtonum(optarg, 0, PROC_MAX_INSTANCES,
275 &errstr);
276 if (errstr != NULL)
277 fatalx("invalid process instance");
278 break;
279 case 'n':
280 conftest++;
281 break;
282 case 'P':
283 pidfile = absolutify_path(optarg);
284 break;
285 case 'T':
286 title = optarg;
287 proc_id = proc_getid(procs, nitems(procs), title);
288 if (proc_id == PROC_MAX)
289 fatalx("invalid process name");
290 break;
291 case 'U':
292 user = optarg;
293 break;
294 case 'V':
295 puts("Version: " GMID_STRING);
296 return 0;
297 case 'v':
298 verbose = 1;
299 break;
300 case 'X':
301 chroot = optarg;
302 break;
303 default:
304 usage();
305 return 1;
309 if (argc - optind != 0)
310 usage();
312 conf = config_new();
314 /*
315 * Only the parent loads the config, the others get user and
316 * chroot via flags and the rest via imsg.
317 */
318 if (proc_id == PROC_PARENT) {
319 if (parse_conf(conf, config_path) == -1)
320 fatalx("failed to load configuration file");
321 if (*conf->chroot != '\0' && *conf->user == '\0')
322 fatalx("can't chroot without a user to switch to.");
323 } else {
324 if (user && strlcpy(conf->user, user, sizeof(conf->user))
325 >= sizeof(conf->user))
326 fatalx("user name too long: %s", user);
327 if (chroot && strlcpy(conf->chroot, chroot, sizeof(conf->chroot))
328 >= sizeof(conf->chroot))
329 fatalx("chroot path too long: %s", chroot);
330 conf->prefork = nprocs;
333 if ((ps = calloc(1, sizeof(*ps))) == NULL)
334 fatal("calloc");
335 ps->ps_env = conf;
336 conf->ps = ps;
337 if (*conf->user) {
338 if (geteuid())
339 fatalx("need root privileges");
340 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
341 fatalx("unknown user %s", conf->user);
342 if (*conf->chroot == '\0')
343 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
344 sizeof(conf->chroot));
347 if (conftest) {
348 conf->conftest = 1;
349 if (config_test(conf) == -1)
350 fatalx("failed to load the configuration");
351 fprintf(stderr, "config OK\n");
352 if (conftest > 1)
353 main_print_conf(conf);
354 return 0;
357 ps->ps_instances[PROC_SERVER] = conf->prefork;
358 ps->ps_instance = proc_instance;
359 if (title != NULL)
360 ps->ps_title[proc_id] = title;
362 if (*conf->chroot != '\0') {
363 for (i = 0; i < nitems(procs); ++i)
364 procs[i].p_chroot = conf->chroot;
367 log_init(debug, LOG_DAEMON);
368 log_setverbose(verbose);
369 if (title != NULL)
370 log_procinit(title);
372 /* only the parent returns */
373 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
375 log_procinit("main");
376 if (!debug && daemon(0, 0) == -1)
377 fatal("daemon");
379 pidfd = write_pidfile(pidfile);
381 sandbox_main_process();
383 event_init();
385 signal(SIGPIPE, SIG_IGN);
387 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
388 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
389 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
390 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
391 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
393 signal_add(&ps->ps_evsigint, NULL);
394 signal_add(&ps->ps_evsigterm, NULL);
395 signal_add(&ps->ps_evsigchld, NULL);
396 signal_add(&ps->ps_evsighup, NULL);
397 signal_add(&ps->ps_evsigusr1, NULL);
399 proc_connect(ps);
401 if (main_configure(conf) == -1)
402 fatal("configuration failed");
404 event_dispatch();
405 main_shutdown(conf);
406 /* NOTREACHED */
407 return 0;
410 static int
411 main_send_logfd(struct conf *conf)
413 struct privsep *ps = conf->ps;
414 char path[PATH_MAX];
415 int r, fd = -1;
417 if (conf->log_access) {
418 r = snprintf(path, sizeof(path), "%s%s%s", conf->chroot,
419 *conf->chroot == '\0' ? "" : "/", conf->log_access);
420 if (r < 0 || (size_t)r >= sizeof(path)) {
421 log_warnx("path too long: %s", conf->log_access);
422 goto done;
425 fd = open(path, O_WRONLY|O_CREAT|O_APPEND, 0600);
426 if (fd == -1)
427 log_warn("can't open %s", conf->log_access);
430 done:
431 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
432 NULL, 0) == -1)
433 return -1;
434 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
435 &conf->log_facility, sizeof(conf->log_facility)) == -1)
436 return -1;
437 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
438 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
439 return -1;
440 return 0;
443 static int
444 main_configure(struct conf *conf)
446 struct privsep *ps = conf->ps;
448 if (main_send_logfd(conf) == -1)
449 return -1;
451 conf->reload = conf->prefork + 1; /* servers, crypto */
453 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
454 return -1;
455 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
456 return -1;
458 if (config_send(conf) == -1)
459 return -1;
461 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
462 return -1;
463 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
464 return -1;
466 return 0;
469 static void
470 main_configure_done(struct conf *conf)
472 if (conf->reload == 0) {
473 log_warnx("configuration already done");
474 return;
477 conf->reload--;
478 /* send IMSG_CTL_START? */
481 static void
482 main_reload(struct conf *conf)
484 if (conf->reload) {
485 log_debug("%s: already in progress: %d pending",
486 __func__, conf->reload);
487 return;
490 log_debug("%s: config file %s", __func__, config_path);
491 config_purge(conf);
493 if (parse_conf(conf, config_path) == -1) {
494 log_warnx("failed to parse the config");
495 return;
498 main_configure(conf);
501 static void
502 main_sig_handler(int sig, short ev, void *arg)
504 struct privsep *ps = arg;
506 /*
507 * Normal signal handler rules don't apply here because libevent
508 * decouples for us.
509 */
511 switch (sig) {
512 case SIGHUP:
513 if (privsep_process != PROC_PARENT)
514 return;
515 log_info("reload requested with SIGHUP");
516 main_reload(ps->ps_env);
517 break;
518 case SIGCHLD:
519 log_warnx("one child died, quitting");
520 /* fallthrough */
521 case SIGTERM:
522 case SIGINT:
523 main_shutdown(ps->ps_env);
524 break;
525 case SIGUSR1:
526 main_send_logfd(ps->ps_env);
527 break;
528 default:
529 fatalx("unexpected signal %d", sig);
533 static int
534 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
536 struct privsep *ps = p->p_ps;
537 struct conf *conf = ps->ps_env;
539 switch (imsg_get_type(imsg)) {
540 case IMSG_RECONF_DONE:
541 main_configure_done(conf);
542 break;
543 default:
544 return -1;
547 return 0;
550 static int
551 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
553 struct privsep *ps = p->p_ps;
554 struct conf *conf = ps->ps_env;
556 switch (imsg_get_type(imsg)) {
557 case IMSG_RECONF_DONE:
558 main_configure_done(conf);
559 break;
560 default:
561 return -1;
564 return 0;
567 static int
568 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
570 struct privsep *ps = p->p_ps;
571 struct conf *conf = ps->ps_env;
573 switch (imsg_get_type(imsg)) {
574 case IMSG_RECONF_DONE:
575 main_configure_done(conf);
576 break;
577 default:
578 return -1;
581 return 0;
584 static void __dead
585 main_shutdown(struct conf *conf)
587 proc_kill(conf->ps);
588 config_purge(conf);
589 free(conf->ps);
590 /* free(conf); */
592 log_info("parent terminating, pid %d", getpid());
594 if (pidfd != -1)
595 close(pidfd);
597 exit(0);
600 static void
601 main_print_conf(struct conf *conf)
603 struct vhost *h;
604 /* struct location *l; */
605 /* struct envlist *e; */
606 /* struct alist *a; */
608 if (*conf->chroot != '\0')
609 printf("chroot \"%s\"\n", conf->chroot);
610 /* XXX: defined mimes? */
611 printf("prefork %d\n", conf->prefork);
612 /* XXX: protocols? */
613 if (*conf->user != '\0')
614 printf("user \"%s\"\n", conf->user);
616 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
617 printf("\nserver \"%s\" {\n", h->domain);
618 printf(" cert \"%s\"\n", h->cert_path);
619 printf(" key \"%s\"\n", h->key_path);
620 /* TODO: print locations... */
621 printf("}\n");