2 * Copyright (c) 2020, 2021, 2022, 2023 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 = SYSCONFDIR "/gmid.conf";
78 "Version: " GMID_STRING "\n"
79 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n",
84 * Used by the server process, defined here so gemexp can provide
85 * its own implementation.
88 log_request(struct client *c, int code, const char *meta)
90 struct conf *conf = c->conf;
91 char tstamp[64], rfc3339[32];
92 char cntmp[64], cn[64] = "-";
93 char b[GEMINI_URL_LEN];
100 if ((now = time(NULL)) == -1)
102 if ((tm = localtime(&now)) == NULL)
104 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
106 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
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));
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));
129 if ((t = c->req) == NULL)
131 strlcpy(b, t, sizeof(b));
134 if (tls_peer_cert_provided(c->ctx)) {
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)
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);
153 case LOG_FORMAT_CONDENSED:
155 * XXX it should log the size of the request and
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,
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>
168 case LOG_FORMAT_COMMON:
170 * XXX it should log the size of the response.
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);
178 * Attempt to be compatible with the default nginx' log_format
180 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
182 case LOG_FORMAT_COMBINED:
185 * XXX it should log the size of the response.
187 ec = asprintf(&fmted, "%s - %s [%s] \"%s\" %d 0 \"-\" \"\"",
188 c->rhost, cn, tstamp, b, code);
196 fprintf(stderr, "%s\n", fmted);
198 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
205 write_pidfile(const char *pidfile)
213 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
214 fatal("can't open pidfile %s", pidfile);
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());
233 main(int argc, char **argv)
237 const char *errstr, *title = NULL;
238 const char *user = NULL, *chroot = NULL;
240 int ch, conftest = 0;
241 int proc_instance = 0;
242 int proc_id = PROC_PARENT;
245 setlocale(LC_CTYPE, "");
247 /* log to stderr until daemonized */
248 log_init(1, LOG_DAEMON);
250 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
253 config_path = absolutify_path(optarg);
256 if (cmdline_symset(optarg) == -1)
257 fatalx("could not parse macro definition: %s",
267 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
270 fatalx("invalid process instance");
276 pidfile = absolutify_path(optarg);
280 proc_id = proc_getid(procs, nitems(procs), title);
281 if (proc_id == PROC_MAX)
282 fatalx("invalid process name");
288 puts("Version: " GMID_STRING);
302 if (argc - optind != 0)
308 * Only the parent loads the config, the others get user and
309 * chroot via flags and the rest via imsg.
311 if (proc_id == PROC_PARENT) {
312 if (parse_conf(conf, config_path) == -1)
313 fatalx("failed to load configuration file");
314 if (*conf->chroot != '\0' && *conf->user == '\0')
315 fatalx("can't chroot without a user to switch to.");
318 strlcpy(conf->user, user, sizeof(conf->user));
320 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
323 if ((ps = calloc(1, sizeof(*ps))) == NULL)
329 fatalx("need root privileges");
330 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
331 fatalx("unknown user %s", conf->user);
332 if (*conf->chroot == '\0')
333 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
334 sizeof(conf->chroot));
339 if (config_test(conf) == -1)
340 fatalx("failed to load the configuration");
341 fprintf(stderr, "config OK\n");
343 main_print_conf(conf);
347 ps->ps_instances[PROC_SERVER] = conf->prefork;
348 ps->ps_instance = proc_instance;
350 ps->ps_title[proc_id] = title;
352 if (*conf->chroot != '\0') {
353 for (i = 0; i < nitems(procs); ++i)
354 procs[i].p_chroot = conf->chroot;
357 log_init(debug, LOG_DAEMON);
358 log_setverbose(verbose);
362 /* only the parent returns */
363 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
365 log_procinit("main");
366 if (!debug && daemon(0, 0) == -1)
369 pidfd = write_pidfile(pidfile);
371 sandbox_main_process();
375 signal(SIGPIPE, SIG_IGN);
377 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
378 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
379 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
380 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
381 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
383 signal_add(&ps->ps_evsigint, NULL);
384 signal_add(&ps->ps_evsigterm, NULL);
385 signal_add(&ps->ps_evsigchld, NULL);
386 signal_add(&ps->ps_evsighup, NULL);
387 signal_add(&ps->ps_evsigusr1, NULL);
391 if (main_configure(conf) == -1)
392 fatal("configuration failed");
401 main_send_logfd(struct conf *conf)
403 struct privsep *ps = conf->ps;
407 if (conf->log_access) {
408 r = snprintf(path, sizeof(path), "%s%s%s", conf->chroot,
409 *conf->chroot == '\0' ? "" : "/", conf->log_access);
410 if (r < 0 || (size_t)r >= sizeof(path)) {
411 log_warnx("path too long: %s", conf->log_access);
415 fd = open(path, O_WRONLY|O_CREAT|O_APPEND, 0600);
417 log_warn("can't open %s", conf->log_access);
421 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
424 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
425 &conf->log_facility, sizeof(conf->log_facility)) == -1)
427 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
428 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
434 main_configure(struct conf *conf)
436 struct privsep *ps = conf->ps;
438 if (main_send_logfd(conf) == -1)
441 conf->reload = conf->prefork + 1; /* servers, crypto */
443 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
445 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
448 if (config_send(conf) == -1)
451 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
453 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
460 main_configure_done(struct conf *conf)
462 if (conf->reload == 0) {
463 log_warnx("configuration already done");
468 /* send IMSG_CTL_START? */
472 main_reload(struct conf *conf)
475 log_debug("%s: already in progress: %d pending",
476 __func__, conf->reload);
480 log_debug("%s: config file %s", __func__, config_path);
483 if (parse_conf(conf, config_path) == -1) {
484 log_warnx("failed to parse the config");
488 main_configure(conf);
492 main_sig_handler(int sig, short ev, void *arg)
494 struct privsep *ps = arg;
497 * Normal signal handler rules don't apply here because libevent
503 if (privsep_process != PROC_PARENT)
505 log_info("reload requested with SIGHUP");
506 main_reload(ps->ps_env);
509 log_warnx("one child died, quitting");
513 main_shutdown(ps->ps_env);
516 main_send_logfd(ps->ps_env);
519 fatalx("unexpected signal %d", sig);
524 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
526 struct privsep *ps = p->p_ps;
527 struct conf *conf = ps->ps_env;
529 switch (imsg_get_type(imsg)) {
530 case IMSG_RECONF_DONE:
531 main_configure_done(conf);
541 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
543 struct privsep *ps = p->p_ps;
544 struct conf *conf = ps->ps_env;
546 switch (imsg_get_type(imsg)) {
547 case IMSG_RECONF_DONE:
548 main_configure_done(conf);
558 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
560 struct privsep *ps = p->p_ps;
561 struct conf *conf = ps->ps_env;
563 switch (imsg_get_type(imsg)) {
564 case IMSG_RECONF_DONE:
565 main_configure_done(conf);
575 main_shutdown(struct conf *conf)
582 log_info("parent terminating, pid %d", getpid());
591 main_print_conf(struct conf *conf)
594 /* struct location *l; */
595 /* struct envlist *e; */
596 /* struct alist *a; */
598 if (*conf->chroot != '\0')
599 printf("chroot \"%s\"\n", conf->chroot);
600 /* XXX: defined mimes? */
601 printf("prefork %d\n", conf->prefork);
602 /* XXX: protocols? */
603 if (*conf->user != '\0')
604 printf("user \"%s\"\n", conf->user);
606 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
607 printf("\nserver \"%s\" {\n", h->domain);
608 printf(" cert \"%s\"\n", h->cert);
609 printf(" key \"%s\"\n", h->key);
610 /* TODO: print locations... */