2 * Copyright (c) 2020, 2021, 2022 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.
38 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
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 },
57 static const char *opts = "c:D:fI:hnP:T:U:VvX:";
59 static const struct option longopts[] = {
60 {"help", no_argument, NULL, 'h'},
61 {"version", no_argument, NULL, 'V'},
71 const char *config_path = "/etc/gmid.conf";
78 "Version: " GMID_STRING "\n"
79 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n",
83 /* used by the server process, defined here so gg can provide its own impl. */
85 log_request(struct client *c, int code, const char *meta)
87 struct conf *conf = c->conf;
88 char tstamp[64], rfc3339[32];
89 char cntmp[64], cn[64] = "-";
90 char b[GEMINI_URL_LEN];
97 if ((now = time(NULL)) == -1)
99 if ((tm = localtime(&now)) == NULL)
101 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
103 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
106 if (c->iri.schema != NULL) {
107 /* serialize the IRI */
108 strlcpy(b, c->iri.schema, sizeof(b));
109 strlcat(b, "://", sizeof(b));
111 /* log the decoded host name, but if it was invalid
112 * use the raw one. */
113 if (*c->domain != '\0')
114 strlcat(b, c->domain, sizeof(b));
116 strlcat(b, c->iri.host, sizeof(b));
118 if (*c->iri.path != '/')
119 strlcat(b, "/", sizeof(b));
120 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
121 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
122 strlcat(b, "?", sizeof(b));
123 strlcat(b, c->iri.query, sizeof(b));
126 if ((t = c->req) == NULL)
128 strlcpy(b, t, sizeof(b));
131 if (tls_peer_cert_provided(c->ctx)) {
135 subj = tls_peer_cert_subject(c->ctx);
136 if ((n = strstr(subj, "/CN=")) != NULL) {
137 strlcpy(cntmp, subj + 4, sizeof(cntmp));
138 if ((n = strchr(cntmp, '/')) != NULL)
140 strnvis(cn, cntmp, sizeof(cn), VIS_WHITE|VIS_DQ);
144 switch (conf->log_format) {
145 case LOG_FORMAT_LEGACY:
146 ec = asprintf(&fmted, "%s:%s GET %s %d %s", c->rhost,
147 c->rserv, b, code, meta);
150 case LOG_FORMAT_CONDENSED:
152 * XXX it should log the size of the request and
155 ec = asprintf(&fmted, "%s %s %s %s %s 0 0 %d %s", rfc3339,
156 c->rhost, cn, *c->domain == '\0' ? c->iri.host : c->domain,
161 * Attempt to be compatible with the default Apache httpd'
162 * LogFormat "%h %l %u %t \"%r\" %>s %b"
163 * see <https://httpd.apache.org/docs/current/mod/mod_log_config.html>
165 case LOG_FORMAT_COMMON:
167 * XXX it should log the size of the response.
169 ec = asprintf(&fmted, "%s %s - %s %s \"%s\" %d 0",
170 *c->domain == '\0' ? c->iri.host : c->domain,
171 c->rhost, cn, tstamp, b, code);
175 * Attempt to be compatible with the default nginx' log_format
177 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
179 case LOG_FORMAT_COMBINED:
182 * XXX it should log the size of the response.
184 ec = asprintf(&fmted, "%s - %s [%s] \"%s\" %d 0 \"-\" \"\"",
185 c->rhost, cn, tstamp, b, code);
193 fprintf(stderr, "%s\n", fmted);
195 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
202 write_pidfile(const char *pidfile)
210 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
211 fatal("can't open pidfile %s", pidfile);
215 lock.l_type = F_WRLCK;
216 lock.l_whence = SEEK_SET;
218 if (fcntl(fd, F_SETLK, &lock) == -1)
219 fatalx("can't lock %s, gmid is already running?", pidfile);
221 if (ftruncate(fd, 0) == -1)
222 fatal("ftruncate %s", pidfile);
224 dprintf(fd, "%d\n", getpid());
230 main(int argc, char **argv)
234 const char *errstr, *title = NULL;
235 const char *user = NULL, *chroot = NULL;
237 int ch, conftest = 0;
238 int proc_instance = 0;
239 int proc_id = PROC_PARENT;
242 setlocale(LC_CTYPE, "");
244 /* log to stderr until daemonized */
245 log_init(1, LOG_DAEMON);
247 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
250 config_path = absolutify_path(optarg);
253 if (cmdline_symset(optarg) == -1)
254 fatalx("could not parse macro definition: %s",
264 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
267 fatalx("invalid process instance");
273 pidfile = absolutify_path(optarg);
277 proc_id = proc_getid(procs, nitems(procs), title);
278 if (proc_id == PROC_MAX)
279 fatalx("invalid process name");
285 puts("Version: " GMID_STRING);
299 if (argc - optind != 0)
305 * Only the parent loads the config, the others get user and
306 * chroot via flags and the rest via imsg.
308 if (proc_id == PROC_PARENT) {
309 if (parse_conf(conf, config_path) == -1)
310 fatalx("failed to load configuration file");
311 if (*conf->chroot != '\0' && *conf->user == '\0')
312 fatalx("can't chroot without a user to switch to.");
315 strlcpy(conf->user, user, sizeof(conf->user));
317 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
321 if (config_test(conf) == -1)
322 fatalx("failed to load the configuration");
323 fprintf(stderr, "config OK\n");
325 main_print_conf(conf);
329 if ((ps = calloc(1, sizeof(*ps))) == NULL)
335 fatalx("need root privileges");
336 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
337 fatalx("unknown user %s", conf->user);
338 if (*conf->chroot == '\0')
339 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
340 sizeof(conf->chroot));
343 ps->ps_instances[PROC_SERVER] = conf->prefork;
344 ps->ps_instance = proc_instance;
346 ps->ps_title[proc_id] = title;
348 if (*conf->chroot != '\0') {
349 for (i = 0; i < nitems(procs); ++i)
350 procs[i].p_chroot = conf->chroot;
353 log_init(debug, LOG_DAEMON);
354 log_setverbose(verbose);
358 /* only the parent returns */
359 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
361 log_procinit("main");
362 if (!debug && daemon(0, 0) == -1)
365 pidfd = write_pidfile(pidfile);
367 sandbox_main_process();
371 signal(SIGPIPE, SIG_IGN);
373 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
374 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
375 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
376 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
377 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
379 signal_add(&ps->ps_evsigint, NULL);
380 signal_add(&ps->ps_evsigterm, NULL);
381 signal_add(&ps->ps_evsigchld, NULL);
382 signal_add(&ps->ps_evsighup, NULL);
383 signal_add(&ps->ps_evsigusr1, NULL);
387 if (main_configure(conf) == -1)
388 fatal("configuration failed");
397 main_send_logfd(struct conf *conf)
399 struct privsep *ps = conf->ps;
403 if (conf->log_access) {
404 r = snprintf(path, sizeof(path), "%s%s%s", conf->chroot,
405 *conf->chroot == '\0' ? "" : "/", conf->log_access);
406 if (r < 0 || (size_t)r >= sizeof(path)) {
407 log_warnx("path too long: %s", conf->log_access);
411 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
413 log_warn("can't open %s", conf->log_access);
417 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
420 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
421 &conf->log_facility, sizeof(conf->log_facility)) == -1)
423 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
424 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
430 main_configure(struct conf *conf)
432 struct privsep *ps = conf->ps;
434 if (main_send_logfd(conf) == -1)
437 conf->reload = conf->prefork + 1; /* servers, crypto */
439 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
441 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
444 if (config_send(conf) == -1)
447 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
449 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
456 main_configure_done(struct conf *conf)
458 if (conf->reload == 0) {
459 log_warnx("configuration already done");
464 /* send IMSG_CTL_START? */
468 main_reload(struct conf *conf)
471 log_debug("%s: already in progress: %d pending",
472 __func__, conf->reload);
476 log_debug("%s: config file %s", __func__, config_path);
479 if (parse_conf(conf, config_path) == -1) {
480 log_warnx("failed to parse the config");
484 main_configure(conf);
488 main_sig_handler(int sig, short ev, void *arg)
490 struct privsep *ps = arg;
493 * Normal signal handler rules don't apply here because libevent
499 if (privsep_process != PROC_PARENT)
501 log_info("reload requested with SIGHUP");
502 main_reload(ps->ps_env);
505 log_warnx("one child died, quitting");
509 main_shutdown(ps->ps_env);
512 main_send_logfd(ps->ps_env);
515 fatalx("unexpected signal %d", sig);
520 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
522 struct privsep *ps = p->p_ps;
523 struct conf *conf = ps->ps_env;
525 switch (imsg->hdr.type) {
526 case IMSG_RECONF_DONE:
527 main_configure_done(conf);
537 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
539 struct privsep *ps = p->p_ps;
540 struct conf *conf = ps->ps_env;
542 switch (imsg->hdr.type) {
543 case IMSG_RECONF_DONE:
544 main_configure_done(conf);
554 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
556 struct privsep *ps = p->p_ps;
557 struct conf *conf = ps->ps_env;
559 switch (imsg->hdr.type) {
560 case IMSG_RECONF_DONE:
561 main_configure_done(conf);
571 main_shutdown(struct conf *conf)
578 log_info("parent terminating, pid %d", getpid());
587 main_print_conf(struct conf *conf)
590 /* struct location *l; */
591 /* struct envlist *e; */
592 /* struct alist *a; */
594 if (*conf->chroot != '\0')
595 printf("chroot \"%s\"\n", conf->chroot);
596 /* XXX: defined mimes? */
597 printf("prefork %d\n", conf->prefork);
598 /* XXX: protocols? */
599 if (*conf->user != '\0')
600 printf("user \"%s\"\n", conf->user);
602 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
603 printf("\nserver \"%s\" {\n", h->domain);
604 printf(" cert \"%s\"\n", h->cert);
605 printf(" key \"%s\"\n", h->key);
606 /* TODO: print locations... */