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.
37 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
40 static int main_configure(struct conf *);
41 static void main_configure_done(struct conf *);
42 static void main_reload(struct conf *);
43 static void main_sig_handler(int, short, void *);
44 static int main_dispatch_server(int, struct privsep_proc *, struct imsg *);
45 static int main_dispatch_crypto(int, struct privsep_proc *, struct imsg *);
46 static int main_dispatch_logger(int, struct privsep_proc *, struct imsg *);
47 static void __dead main_shutdown(struct conf *);
48 static void main_print_conf(struct conf *);
50 static struct privsep_proc procs[] = {
51 { "server", PROC_SERVER, main_dispatch_server, server },
52 { "crypto", PROC_CRYPTO, main_dispatch_crypto, crypto },
53 { "logger", PROC_LOGGER, main_dispatch_logger, logger },
56 static const char *opts = "c:D:fI:hnP:T:U:VvX:";
58 static const struct option longopts[] = {
59 {"help", no_argument, NULL, 'h'},
60 {"version", no_argument, NULL, 'V'},
70 const char *config_path = "/etc/gmid.conf";
77 "Version: " GMID_STRING "\n"
78 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n",
82 /* used by the server process, defined here so gg can provide its own impl. */
84 log_request(struct client *c, int code, const char *meta)
86 struct conf *conf = c->conf;
87 char tstamp[64], rfc3339[32];
88 char b[GEMINI_URL_LEN];
95 if ((now = time(NULL)) == -1)
97 if ((tm = localtime(&now)) == NULL)
99 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
101 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
104 if (c->iri.schema != NULL) {
105 /* serialize the IRI */
106 strlcpy(b, c->iri.schema, sizeof(b));
107 strlcat(b, "://", sizeof(b));
109 /* log the decoded host name, but if it was invalid
110 * use the raw one. */
111 if (*c->domain != '\0')
112 strlcat(b, c->domain, sizeof(b));
114 strlcat(b, c->iri.host, sizeof(b));
116 if (*c->iri.path != '/')
117 strlcat(b, "/", sizeof(b));
118 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
119 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
120 strlcat(b, "?", sizeof(b));
121 strlcat(b, c->iri.query, sizeof(b));
124 if ((t = c->req) == NULL)
126 strlcpy(b, t, sizeof(b));
129 switch (conf->log_format) {
130 case LOG_FORMAT_LEGACY:
131 ec = asprintf(&fmted, "%s:%s GET %s %d %s", c->rhost,
132 c->rserv, b, code, meta);
135 case LOG_FORMAT_CONDENSED:
137 * XXX the first '-' is the remote user name, we
138 * could use the client cert for it.
140 * XXX it should log the size of the response
142 ec = asprintf(&fmted, "%s %s - %s %s 0 %d %s", rfc3339,
143 c->rhost, *c->domain == '\0' ? c->iri.host : c->domain,
148 * Attempt to be compatible with the default Apache httpd'
149 * LogFormat "%h %l %u %t \"%r\" %>s %b"
150 * see <https://httpd.apache.org/docs/current/mod/mod_log_config.html>
152 case LOG_FORMAT_COMMON:
154 * XXX the second '-' is the remote user name, we
155 * could use the client cert for it.
157 * XXX it should log the size of the response.
159 ec = asprintf(&fmted, "%s %s - - %s \"%s\" %d 0",
160 *c->domain == '\0' ? c->iri.host : c->domain,
161 c->rhost, tstamp, b, code);
165 * Attempt to be compatible with the default nginx' log_format
167 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
169 case LOG_FORMAT_COMBINED:
172 * XXX the second '-' is the remote user name, we
173 * could use the client cert for it.
175 * XXX it should log the size of the response.
177 ec = asprintf(&fmted, "%s - - [%s] \"%s\" %d 0 \"-\" \"\"",
178 c->rhost, tstamp, b, code);
186 fprintf(stderr, "%s\n", fmted);
188 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
195 write_pidfile(const char *pidfile)
203 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
204 fatal("can't open pidfile %s", pidfile);
208 lock.l_type = F_WRLCK;
209 lock.l_whence = SEEK_SET;
211 if (fcntl(fd, F_SETLK, &lock) == -1)
212 fatalx("can't lock %s, gmid is already running?", pidfile);
214 if (ftruncate(fd, 0) == -1)
215 fatal("ftruncate %s", pidfile);
217 dprintf(fd, "%d\n", getpid());
223 main(int argc, char **argv)
227 const char *errstr, *title = NULL;
228 const char *user = NULL, *chroot = NULL;
230 int ch, conftest = 0;
231 int proc_instance = 0;
232 int proc_id = PROC_PARENT;
235 setlocale(LC_CTYPE, "");
237 /* log to stderr until daemonized */
238 log_init(1, LOG_DAEMON);
240 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
243 config_path = absolutify_path(optarg);
246 if (cmdline_symset(optarg) == -1)
247 fatalx("could not parse macro definition: %s",
257 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
260 fatalx("invalid process instance");
266 pidfile = absolutify_path(optarg);
270 proc_id = proc_getid(procs, nitems(procs), title);
271 if (proc_id == PROC_MAX)
272 fatalx("invalid process name");
278 puts("Version: " GMID_STRING);
292 if (argc - optind != 0)
298 * Only the parent loads the config, the others get user and
299 * chroot via flags and the rest via imsg.
301 if (proc_id == PROC_PARENT) {
302 if (parse_conf(conf, config_path) == -1)
303 fatalx("failed to load configuration file");
304 if (*conf->chroot != '\0' && *conf->user == '\0')
305 fatalx("can't chroot without a user to switch to.");
308 strlcpy(conf->user, user, sizeof(conf->user));
310 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
314 fprintf(stderr, "config OK\n");
316 main_print_conf(conf);
320 if ((ps = calloc(1, sizeof(*ps))) == NULL)
326 fatalx("need root privileges");
327 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
328 fatalx("unknown user %s", conf->user);
329 if (*conf->chroot == '\0')
330 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
331 sizeof(conf->chroot));
334 ps->ps_instances[PROC_SERVER] = conf->prefork;
335 ps->ps_instance = proc_instance;
337 ps->ps_title[proc_id] = title;
339 if (*conf->chroot != '\0') {
340 for (i = 0; i < nitems(procs); ++i)
341 procs[i].p_chroot = conf->chroot;
344 log_init(debug, LOG_DAEMON);
345 log_setverbose(verbose);
349 /* only the parent returns */
350 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
352 log_procinit("main");
353 if (!debug && daemon(0, 0) == -1)
356 pidfd = write_pidfile(pidfile);
358 sandbox_main_process();
362 signal(SIGPIPE, SIG_IGN);
364 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
365 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
366 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
367 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
368 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
370 signal_add(&ps->ps_evsigint, NULL);
371 signal_add(&ps->ps_evsigterm, NULL);
372 signal_add(&ps->ps_evsigchld, NULL);
373 signal_add(&ps->ps_evsighup, NULL);
374 signal_add(&ps->ps_evsigusr1, NULL);
378 if (main_configure(conf) == -1)
379 fatal("configuration failed");
388 main_send_logfd(struct conf *conf)
390 struct privsep *ps = conf->ps;
394 if (conf->log_access) {
395 r = snprintf(path, sizeof(path), "%s%s%s", conf->chroot,
396 *conf->chroot == '\0' ? "" : "/", conf->log_access);
397 if (r < 0 || (size_t)r >= sizeof(path)) {
398 log_warnx("path too long: %s", conf->log_access);
402 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
404 log_warn("can't open %s", conf->log_access);
408 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_TYPE, -1, fd,
415 main_configure(struct conf *conf)
417 struct privsep *ps = conf->ps;
419 if (main_send_logfd(conf) == -1)
422 conf->reload = conf->prefork + 1; /* servers, crypto */
424 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
426 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
429 if (config_send(conf) == -1)
432 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
434 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
441 main_configure_done(struct conf *conf)
443 if (conf->reload == 0) {
444 log_warnx("configuration already done");
449 /* send IMSG_CTL_START? */
453 main_reload(struct conf *conf)
456 log_debug("%s: already in progress: %d pending",
457 __func__, conf->reload);
461 log_debug("%s: config file %s", __func__, config_path);
464 if (parse_conf(conf, config_path) == -1) {
465 log_warnx("failed to parse the config");
469 main_configure(conf);
473 main_sig_handler(int sig, short ev, void *arg)
475 struct privsep *ps = arg;
478 * Normal signal handler rules don't apply here because libevent
484 if (privsep_process != PROC_PARENT)
486 log_info("reload requested with SIGHUP");
487 main_reload(ps->ps_env);
490 log_warnx("one child died, quitting");
494 main_shutdown(ps->ps_env);
497 main_send_logfd(ps->ps_env);
500 fatalx("unexpected signal %d", sig);
505 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
507 struct privsep *ps = p->p_ps;
508 struct conf *conf = ps->ps_env;
510 switch (imsg->hdr.type) {
511 case IMSG_RECONF_DONE:
512 main_configure_done(conf);
522 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
524 struct privsep *ps = p->p_ps;
525 struct conf *conf = ps->ps_env;
527 switch (imsg->hdr.type) {
528 case IMSG_RECONF_DONE:
529 main_configure_done(conf);
539 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
541 struct privsep *ps = p->p_ps;
542 struct conf *conf = ps->ps_env;
544 switch (imsg->hdr.type) {
545 case IMSG_RECONF_DONE:
546 main_configure_done(conf);
556 main_shutdown(struct conf *conf)
563 log_info("parent terminating, pid %d", getpid());
572 main_print_conf(struct conf *conf)
575 /* struct location *l; */
576 /* struct envlist *e; */
577 /* struct alist *a; */
579 if (*conf->chroot != '\0')
580 printf("chroot \"%s\"\n", conf->chroot);
581 /* XXX: defined mimes? */
582 printf("prefork %d\n", conf->prefork);
583 /* XXX: protocols? */
584 if (*conf->user != '\0')
585 printf("user \"%s\"\n", conf->user);
587 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
588 printf("\nserver \"%s\" {\n", h->domain);
589 printf(" cert \"%s\"\n", h->cert);
590 printf(" key \"%s\"\n", h->key);
591 /* TODO: print locations... */