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 = "/etc/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));
324 if (config_test(conf) == -1)
325 fatalx("failed to load the configuration");
326 fprintf(stderr, "config OK\n");
328 main_print_conf(conf);
332 if ((ps = calloc(1, sizeof(*ps))) == NULL)
338 fatalx("need root privileges");
339 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
340 fatalx("unknown user %s", conf->user);
341 if (*conf->chroot == '\0')
342 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
343 sizeof(conf->chroot));
346 ps->ps_instances[PROC_SERVER] = conf->prefork;
347 ps->ps_instance = proc_instance;
349 ps->ps_title[proc_id] = title;
351 if (*conf->chroot != '\0') {
352 for (i = 0; i < nitems(procs); ++i)
353 procs[i].p_chroot = conf->chroot;
356 log_init(debug, LOG_DAEMON);
357 log_setverbose(verbose);
361 /* only the parent returns */
362 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
364 log_procinit("main");
365 if (!debug && daemon(0, 0) == -1)
368 pidfd = write_pidfile(pidfile);
370 sandbox_main_process();
374 signal(SIGPIPE, SIG_IGN);
376 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
377 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
378 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
379 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
380 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
382 signal_add(&ps->ps_evsigint, NULL);
383 signal_add(&ps->ps_evsigterm, NULL);
384 signal_add(&ps->ps_evsigchld, NULL);
385 signal_add(&ps->ps_evsighup, NULL);
386 signal_add(&ps->ps_evsigusr1, NULL);
390 if (main_configure(conf) == -1)
391 fatal("configuration failed");
400 main_send_logfd(struct conf *conf)
402 struct privsep *ps = conf->ps;
406 if (conf->log_access) {
407 r = snprintf(path, sizeof(path), "%s%s%s", conf->chroot,
408 *conf->chroot == '\0' ? "" : "/", conf->log_access);
409 if (r < 0 || (size_t)r >= sizeof(path)) {
410 log_warnx("path too long: %s", conf->log_access);
414 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
416 log_warn("can't open %s", conf->log_access);
420 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
423 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
424 &conf->log_facility, sizeof(conf->log_facility)) == -1)
426 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
427 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
433 main_configure(struct conf *conf)
435 struct privsep *ps = conf->ps;
437 if (main_send_logfd(conf) == -1)
440 conf->reload = conf->prefork + 1; /* servers, crypto */
442 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
444 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
447 if (config_send(conf) == -1)
450 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
452 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
459 main_configure_done(struct conf *conf)
461 if (conf->reload == 0) {
462 log_warnx("configuration already done");
467 /* send IMSG_CTL_START? */
471 main_reload(struct conf *conf)
474 log_debug("%s: already in progress: %d pending",
475 __func__, conf->reload);
479 log_debug("%s: config file %s", __func__, config_path);
482 if (parse_conf(conf, config_path) == -1) {
483 log_warnx("failed to parse the config");
487 main_configure(conf);
491 main_sig_handler(int sig, short ev, void *arg)
493 struct privsep *ps = arg;
496 * Normal signal handler rules don't apply here because libevent
502 if (privsep_process != PROC_PARENT)
504 log_info("reload requested with SIGHUP");
505 main_reload(ps->ps_env);
508 log_warnx("one child died, quitting");
512 main_shutdown(ps->ps_env);
515 main_send_logfd(ps->ps_env);
518 fatalx("unexpected signal %d", sig);
523 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
525 struct privsep *ps = p->p_ps;
526 struct conf *conf = ps->ps_env;
528 switch (imsg->hdr.type) {
529 case IMSG_RECONF_DONE:
530 main_configure_done(conf);
540 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
542 struct privsep *ps = p->p_ps;
543 struct conf *conf = ps->ps_env;
545 switch (imsg->hdr.type) {
546 case IMSG_RECONF_DONE:
547 main_configure_done(conf);
557 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
559 struct privsep *ps = p->p_ps;
560 struct conf *conf = ps->ps_env;
562 switch (imsg->hdr.type) {
563 case IMSG_RECONF_DONE:
564 main_configure_done(conf);
574 main_shutdown(struct conf *conf)
581 log_info("parent terminating, pid %d", getpid());
590 main_print_conf(struct conf *conf)
593 /* struct location *l; */
594 /* struct envlist *e; */
595 /* struct alist *a; */
597 if (*conf->chroot != '\0')
598 printf("chroot \"%s\"\n", conf->chroot);
599 /* XXX: defined mimes? */
600 printf("prefork %d\n", conf->prefork);
601 /* XXX: protocols? */
602 if (*conf->user != '\0')
603 printf("user \"%s\"\n", conf->user);
605 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
606 printf("\nserver \"%s\" {\n", h->domain);
607 printf(" cert \"%s\"\n", h->cert);
608 printf(" key \"%s\"\n", h->key);
609 /* TODO: print locations... */