Blob


1 /*
2 * Copyright (c) 2020, 2021, 2022, 2023 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 /*
84 * Used by the server process, defined here so gemexp can provide
85 * its own implementation.
86 */
87 void
88 log_request(struct client *c, int code, const char *meta)
89 {
90 struct conf *conf = c->conf;
91 char tstamp[64], rfc3339[32];
92 char cntmp[64], cn[64] = "-";
93 char b[GEMINI_URL_LEN];
94 char *fmted;
95 const char *t;
96 struct tm *tm;
97 time_t now;
98 int ec;
100 if ((now = time(NULL)) == -1)
101 fatal("time");
102 if ((tm = localtime(&now)) == NULL)
103 fatal("localtime");
104 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
105 fatal("strftime");
106 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
107 fatal("strftime");
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));
118 else
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));
128 } else {
129 if ((t = c->req) == NULL)
130 t = "";
131 strlcpy(b, t, sizeof(b));
134 if (tls_peer_cert_provided(c->ctx)) {
135 const char *subj;
136 char *n;
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)
142 *n = '\0';
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);
151 break;
153 case LOG_FORMAT_CONDENSED:
154 /*
155 * XXX it should log the size of the request and
156 * response.
157 */
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,
160 b, code, meta);
161 break;
163 /*
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>
167 */
168 case LOG_FORMAT_COMMON:
169 /*
170 * XXX it should log the size of the response.
171 */
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);
175 break;
177 /*
178 * Attempt to be compatible with the default nginx' log_format
179 * combined:
180 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
181 */
182 case LOG_FORMAT_COMBINED:
183 default:
184 /*
185 * XXX it should log the size of the response.
186 */
187 ec = asprintf(&fmted, "%s - %s [%s] \"%s\" %d 0 \"-\" \"\"",
188 c->rhost, cn, tstamp, b, code);
189 break;
192 if (ec == -1)
193 fatal("asprintf");
195 if (debug)
196 fprintf(stderr, "%s\n", fmted);
198 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
199 fmted, ec + 1);
201 free(fmted);
204 static int
205 write_pidfile(const char *pidfile)
207 struct flock lock;
208 int fd;
210 if (pidfile == NULL)
211 return -1;
213 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
214 fatal("can't open pidfile %s", pidfile);
216 lock.l_start = 0;
217 lock.l_len = 0;
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());
229 return fd;
232 int
233 main(int argc, char **argv)
235 struct conf *conf;
236 struct privsep *ps;
237 const char *errstr, *title = NULL;
238 const char *user = NULL, *chroot = NULL;
239 size_t i;
240 int ch, conftest = 0;
241 int proc_instance = 0;
242 int proc_id = PROC_PARENT;
243 int argc0 = argc;
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) {
251 switch (ch) {
252 case 'c':
253 config_path = absolutify_path(optarg);
254 break;
255 case 'D':
256 if (cmdline_symset(optarg) == -1)
257 fatalx("could not parse macro definition: %s",
258 optarg);
259 break;
260 case 'f':
261 debug = 1;
262 break;
263 case 'h':
264 usage();
265 return 0;
266 case 'I':
267 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
268 &errstr);
269 if (errstr != NULL)
270 fatalx("invalid process instance");
271 break;
272 case 'n':
273 conftest++;
274 break;
275 case 'P':
276 pidfile = absolutify_path(optarg);
277 break;
278 case 'T':
279 title = optarg;
280 proc_id = proc_getid(procs, nitems(procs), title);
281 if (proc_id == PROC_MAX)
282 fatalx("invalid process name");
283 break;
284 case 'U':
285 user = optarg;
286 break;
287 case 'V':
288 puts("Version: " GMID_STRING);
289 return 0;
290 case 'v':
291 verbose = 1;
292 break;
293 case 'X':
294 chroot = optarg;
295 break;
296 default:
297 usage();
298 return 1;
302 if (argc - optind != 0)
303 usage();
305 conf = config_new();
307 /*
308 * Only the parent loads the config, the others get user and
309 * chroot via flags and the rest via imsg.
310 */
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.");
316 } else {
317 if (user)
318 strlcpy(conf->user, user, sizeof(conf->user));
319 if (chroot)
320 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
323 if (conftest) {
324 if (config_test(conf) == -1)
325 fatalx("failed to load the configuration");
326 fprintf(stderr, "config OK\n");
327 if (conftest > 1)
328 main_print_conf(conf);
329 return 0;
332 if ((ps = calloc(1, sizeof(*ps))) == NULL)
333 fatal("calloc");
334 ps->ps_env = conf;
335 conf->ps = ps;
336 if (*conf->user) {
337 if (geteuid())
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;
348 if (title != NULL)
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);
358 if (title != NULL)
359 log_procinit(title);
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)
366 fatal("daemon");
368 pidfd = write_pidfile(pidfile);
370 sandbox_main_process();
372 event_init();
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);
388 proc_connect(ps);
390 if (main_configure(conf) == -1)
391 fatal("configuration failed");
393 event_dispatch();
394 main_shutdown(conf);
395 /* NOTREACHED */
396 return 0;
399 static int
400 main_send_logfd(struct conf *conf)
402 struct privsep *ps = conf->ps;
403 char path[PATH_MAX];
404 int r, fd = -1;
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);
411 goto done;
414 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
415 if (fd == -1)
416 log_warn("can't open %s", conf->log_access);
419 done:
420 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
421 NULL, 0) == -1)
422 return -1;
423 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
424 &conf->log_facility, sizeof(conf->log_facility)) == -1)
425 return -1;
426 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
427 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
428 return -1;
429 return 0;
432 static int
433 main_configure(struct conf *conf)
435 struct privsep *ps = conf->ps;
437 if (main_send_logfd(conf) == -1)
438 return -1;
440 conf->reload = conf->prefork + 1; /* servers, crypto */
442 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
443 return -1;
444 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
445 return -1;
447 if (config_send(conf) == -1)
448 return -1;
450 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
451 return -1;
452 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
453 return -1;
455 return 0;
458 static void
459 main_configure_done(struct conf *conf)
461 if (conf->reload == 0) {
462 log_warnx("configuration already done");
463 return;
466 conf->reload--;
467 /* send IMSG_CTL_START? */
470 static void
471 main_reload(struct conf *conf)
473 if (conf->reload) {
474 log_debug("%s: already in progress: %d pending",
475 __func__, conf->reload);
476 return;
479 log_debug("%s: config file %s", __func__, config_path);
480 config_purge(conf);
482 if (parse_conf(conf, config_path) == -1) {
483 log_warnx("failed to parse the config");
484 return;
487 main_configure(conf);
490 static void
491 main_sig_handler(int sig, short ev, void *arg)
493 struct privsep *ps = arg;
495 /*
496 * Normal signal handler rules don't apply here because libevent
497 * decouples for us.
498 */
500 switch (sig) {
501 case SIGHUP:
502 if (privsep_process != PROC_PARENT)
503 return;
504 log_info("reload requested with SIGHUP");
505 main_reload(ps->ps_env);
506 break;
507 case SIGCHLD:
508 log_warnx("one child died, quitting");
509 /* fallthrough */
510 case SIGTERM:
511 case SIGINT:
512 main_shutdown(ps->ps_env);
513 break;
514 case SIGUSR1:
515 main_send_logfd(ps->ps_env);
516 break;
517 default:
518 fatalx("unexpected signal %d", sig);
522 static int
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);
531 break;
532 default:
533 return -1;
536 return 0;
539 static int
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);
548 break;
549 default:
550 return -1;
553 return 0;
556 static int
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);
565 break;
566 default:
567 return -1;
570 return 0;
573 static void __dead
574 main_shutdown(struct conf *conf)
576 proc_kill(conf->ps);
577 config_purge(conf);
578 free(conf->ps);
579 /* free(conf); */
581 log_info("parent terminating, pid %d", getpid());
583 if (pidfd != -1)
584 close(pidfd);
586 exit(0);
589 static void
590 main_print_conf(struct conf *conf)
592 struct vhost *h;
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... */
610 printf("}\n");