Blob


1 /*
2 * Copyright (c) 2020, 2021, 2022 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: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 = "/etc/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 /* used by the server process, defined here so gg can provide its own impl. */
84 void
85 log_request(struct client *c, int code, const char *meta)
86 {
87 struct conf *conf = c->conf;
88 char tstamp[64], rfc3339[32];
89 char cntmp[64], cn[64] = "-";
90 char b[GEMINI_URL_LEN];
91 char *fmted;
92 const char *t;
93 struct tm *tm;
94 time_t now;
95 int ec;
97 if ((now = time(NULL)) == -1)
98 fatal("time");
99 if ((tm = localtime(&now)) == NULL)
100 fatal("localtime");
101 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
102 fatal("strftime");
103 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
104 fatal("strftime");
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));
115 else
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));
125 } else {
126 if ((t = c->req) == NULL)
127 t = "";
128 strlcpy(b, t, sizeof(b));
131 if (tls_peer_cert_provided(c->ctx)) {
132 const char *subj;
133 char *n;
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)
139 *n = '\0';
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);
148 break;
150 case LOG_FORMAT_CONDENSED:
151 /*
152 * XXX it should log the size of the request and
153 * response.
154 */
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,
157 b, code, meta);
158 break;
160 /*
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>
164 */
165 case LOG_FORMAT_COMMON:
166 /*
167 * XXX it should log the size of the response.
168 */
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);
172 break;
174 /*
175 * Attempt to be compatible with the default nginx' log_format
176 * combined:
177 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
178 */
179 case LOG_FORMAT_COMBINED:
180 default:
181 /*
182 * XXX it should log the size of the response.
183 */
184 ec = asprintf(&fmted, "%s - %s [%s] \"%s\" %d 0 \"-\" \"\"",
185 c->rhost, cn, tstamp, b, code);
186 break;
189 if (ec == -1)
190 fatal("asprintf");
192 if (debug)
193 fprintf(stderr, "%s\n", fmted);
195 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
196 fmted, ec + 1);
198 free(fmted);
201 static int
202 write_pidfile(const char *pidfile)
204 struct flock lock;
205 int fd;
207 if (pidfile == NULL)
208 return -1;
210 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
211 fatal("can't open pidfile %s", pidfile);
213 lock.l_start = 0;
214 lock.l_len = 0;
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());
226 return fd;
229 int
230 main(int argc, char **argv)
232 struct conf *conf;
233 struct privsep *ps;
234 const char *errstr, *title = NULL;
235 const char *user = NULL, *chroot = NULL;
236 size_t i;
237 int ch, conftest = 0;
238 int proc_instance = 0;
239 int proc_id = PROC_PARENT;
240 int argc0 = argc;
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) {
248 switch (ch) {
249 case 'c':
250 config_path = absolutify_path(optarg);
251 break;
252 case 'D':
253 if (cmdline_symset(optarg) == -1)
254 fatalx("could not parse macro definition: %s",
255 optarg);
256 break;
257 case 'f':
258 debug = 1;
259 break;
260 case 'h':
261 usage();
262 return 0;
263 case 'I':
264 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
265 &errstr);
266 if (errstr != NULL)
267 fatalx("invalid process instance");
268 break;
269 case 'n':
270 conftest++;
271 break;
272 case 'P':
273 pidfile = absolutify_path(optarg);
274 break;
275 case 'T':
276 title = optarg;
277 proc_id = proc_getid(procs, nitems(procs), title);
278 if (proc_id == PROC_MAX)
279 fatalx("invalid process name");
280 break;
281 case 'U':
282 user = optarg;
283 break;
284 case 'V':
285 puts("Version: " GMID_STRING);
286 return 0;
287 case 'v':
288 verbose = 1;
289 break;
290 case 'X':
291 chroot = optarg;
292 break;
293 default:
294 usage();
295 return 1;
299 if (argc - optind != 0)
300 usage();
302 conf = config_new();
304 /*
305 * Only the parent loads the config, the others get user and
306 * chroot via flags and the rest via imsg.
307 */
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.");
313 } else {
314 if (user)
315 strlcpy(conf->user, user, sizeof(conf->user));
316 if (chroot)
317 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
320 if (conftest) {
321 if (config_test(conf) == -1)
322 fatalx("failed to load the configuration");
323 fprintf(stderr, "config OK\n");
324 if (conftest > 1)
325 main_print_conf(conf);
326 return 0;
329 if ((ps = calloc(1, sizeof(*ps))) == NULL)
330 fatal("calloc");
331 ps->ps_env = conf;
332 conf->ps = ps;
333 if (*conf->user) {
334 if (geteuid())
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;
345 if (title != NULL)
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);
355 if (title != NULL)
356 log_procinit(title);
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)
363 fatal("daemon");
365 pidfd = write_pidfile(pidfile);
367 sandbox_main_process();
369 event_init();
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);
385 proc_connect(ps);
387 if (main_configure(conf) == -1)
388 fatal("configuration failed");
390 event_dispatch();
391 main_shutdown(conf);
392 /* NOTREACHED */
393 return 0;
396 static int
397 main_send_logfd(struct conf *conf)
399 struct privsep *ps = conf->ps;
400 char path[PATH_MAX];
401 int r, fd = -1;
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);
408 goto done;
411 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
412 if (fd == -1)
413 log_warn("can't open %s", conf->log_access);
416 done:
417 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
418 NULL, 0) == -1)
419 return -1;
420 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
421 &conf->log_facility, sizeof(conf->log_facility)) == -1)
422 return -1;
423 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
424 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
425 return -1;
426 return 0;
429 static int
430 main_configure(struct conf *conf)
432 struct privsep *ps = conf->ps;
434 if (main_send_logfd(conf) == -1)
435 return -1;
437 conf->reload = conf->prefork + 1; /* servers, crypto */
439 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
440 return -1;
441 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
442 return -1;
444 if (config_send(conf) == -1)
445 return -1;
447 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
448 return -1;
449 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
450 return -1;
452 return 0;
455 static void
456 main_configure_done(struct conf *conf)
458 if (conf->reload == 0) {
459 log_warnx("configuration already done");
460 return;
463 conf->reload--;
464 /* send IMSG_CTL_START? */
467 static void
468 main_reload(struct conf *conf)
470 if (conf->reload) {
471 log_debug("%s: already in progress: %d pending",
472 __func__, conf->reload);
473 return;
476 log_debug("%s: config file %s", __func__, config_path);
477 config_purge(conf);
479 if (parse_conf(conf, config_path) == -1) {
480 log_warnx("failed to parse the config");
481 return;
484 main_configure(conf);
487 static void
488 main_sig_handler(int sig, short ev, void *arg)
490 struct privsep *ps = arg;
492 /*
493 * Normal signal handler rules don't apply here because libevent
494 * decouples for us.
495 */
497 switch (sig) {
498 case SIGHUP:
499 if (privsep_process != PROC_PARENT)
500 return;
501 log_info("reload requested with SIGHUP");
502 main_reload(ps->ps_env);
503 break;
504 case SIGCHLD:
505 log_warnx("one child died, quitting");
506 /* fallthrough */
507 case SIGTERM:
508 case SIGINT:
509 main_shutdown(ps->ps_env);
510 break;
511 case SIGUSR1:
512 main_send_logfd(ps->ps_env);
513 break;
514 default:
515 fatalx("unexpected signal %d", sig);
519 static int
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);
528 break;
529 default:
530 return -1;
533 return 0;
536 static int
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);
545 break;
546 default:
547 return -1;
550 return 0;
553 static int
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);
562 break;
563 default:
564 return -1;
567 return 0;
570 static void __dead
571 main_shutdown(struct conf *conf)
573 proc_kill(conf->ps);
574 config_purge(conf);
575 free(conf->ps);
576 /* free(conf); */
578 log_info("parent terminating, pid %d", getpid());
580 if (pidfd != -1)
581 close(pidfd);
583 exit(0);
586 static void
587 main_print_conf(struct conf *conf)
589 struct vhost *h;
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... */
607 printf("}\n");