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>
33 #include "log.h"
34 #include "proc.h"
36 #ifndef nitems
37 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
38 #endif
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 },
54 };
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'},
61 {NULL, 0, NULL, 0},
62 };
64 int sock4, sock6;
65 int privsep_process;
66 int pidfd = -1;
68 int debug, verbose;
70 const char *config_path = "/etc/gmid.conf";
71 const char *pidfile;
73 static void
74 usage(void)
75 {
76 fprintf(stderr,
77 "Version: " GMID_STRING "\n"
78 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n",
79 getprogname());
80 }
82 /* used by the server process, defined here so gg can provide its own impl. */
83 void
84 log_request(struct client *c, int code, const char *meta)
85 {
86 struct conf *conf = c->conf;
87 char tstamp[64], rfc3339[32];
88 char b[GEMINI_URL_LEN];
89 char *fmted;
90 const char *t;
91 struct tm *tm;
92 time_t now;
93 int ec;
95 if ((now = time(NULL)) == -1)
96 fatal("time");
97 if ((tm = localtime(&now)) == NULL)
98 fatal("localtime");
99 if (strftime(tstamp, sizeof(tstamp), "%d/%b%Y:%H:%M:%S %z", tm) == 0)
100 fatal("strftime");
101 if (strftime(rfc3339, sizeof(rfc3339), "%FT%T%z", tm) == 0)
102 fatal("strftime");
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));
113 else
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));
123 } else {
124 if ((t = c->req) == NULL)
125 t = "";
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);
133 break;
135 case LOG_FORMAT_CONDENSED:
136 /*
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
141 */
142 ec = asprintf(&fmted, "%s %s - %s %s 0 %d %s", rfc3339,
143 c->rhost, *c->domain == '\0' ? c->iri.host : c->domain,
144 b, code, meta);
145 break;
147 /*
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>
151 */
152 case LOG_FORMAT_COMMON:
153 /*
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.
158 */
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);
162 break;
164 /*
165 * Attempt to be compatible with the default nginx' log_format
166 * combined:
167 * '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
168 */
169 case LOG_FORMAT_COMBINED:
170 default:
171 /*
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.
176 */
177 ec = asprintf(&fmted, "%s - - [%s] \"%s\" %d 0 \"-\" \"\"",
178 c->rhost, tstamp, b, code);
179 break;
182 if (ec == -1)
183 fatal("asprintf");
185 if (debug)
186 fprintf(stderr, "%s\n", fmted);
188 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
189 fmted, ec + 1);
191 free(fmted);
194 static int
195 write_pidfile(const char *pidfile)
197 struct flock lock;
198 int fd;
200 if (pidfile == NULL)
201 return -1;
203 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
204 fatal("can't open pidfile %s", pidfile);
206 lock.l_start = 0;
207 lock.l_len = 0;
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());
219 return fd;
222 int
223 main(int argc, char **argv)
225 struct conf *conf;
226 struct privsep *ps;
227 const char *errstr, *title = NULL;
228 const char *user = NULL, *chroot = NULL;
229 size_t i;
230 int ch, conftest = 0;
231 int proc_instance = 0;
232 int proc_id = PROC_PARENT;
233 int argc0 = argc;
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) {
241 switch (ch) {
242 case 'c':
243 config_path = absolutify_path(optarg);
244 break;
245 case 'D':
246 if (cmdline_symset(optarg) == -1)
247 fatalx("could not parse macro definition: %s",
248 optarg);
249 break;
250 case 'f':
251 debug = 1;
252 break;
253 case 'h':
254 usage();
255 return 0;
256 case 'I':
257 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
258 &errstr);
259 if (errstr != NULL)
260 fatalx("invalid process instance");
261 break;
262 case 'n':
263 conftest++;
264 break;
265 case 'P':
266 pidfile = absolutify_path(optarg);
267 break;
268 case 'T':
269 title = optarg;
270 proc_id = proc_getid(procs, nitems(procs), title);
271 if (proc_id == PROC_MAX)
272 fatalx("invalid process name");
273 break;
274 case 'U':
275 user = optarg;
276 break;
277 case 'V':
278 puts("Version: " GMID_STRING);
279 return 0;
280 case 'v':
281 verbose = 1;
282 break;
283 case 'X':
284 chroot = optarg;
285 break;
286 default:
287 usage();
288 return 1;
292 if (argc - optind != 0)
293 usage();
295 conf = config_new();
297 /*
298 * Only the parent loads the config, the others get user and
299 * chroot via flags and the rest via imsg.
300 */
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.");
306 } else {
307 if (user)
308 strlcpy(conf->user, user, sizeof(conf->user));
309 if (chroot)
310 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
313 if (conftest) {
314 fprintf(stderr, "config OK\n");
315 if (conftest > 1)
316 main_print_conf(conf);
317 return 0;
320 if ((ps = calloc(1, sizeof(*ps))) == NULL)
321 fatal("calloc");
322 ps->ps_env = conf;
323 conf->ps = ps;
324 if (*conf->user) {
325 if (geteuid())
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;
336 if (title != NULL)
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);
346 if (title != NULL)
347 log_procinit(title);
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)
354 fatal("daemon");
356 pidfd = write_pidfile(pidfile);
358 sandbox_main_process();
360 event_init();
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);
376 proc_connect(ps);
378 if (main_configure(conf) == -1)
379 fatal("configuration failed");
381 event_dispatch();
382 main_shutdown(conf);
383 /* NOTREACHED */
384 return 0;
387 static int
388 main_send_logfd(struct conf *conf)
390 struct privsep *ps = conf->ps;
391 char path[PATH_MAX];
392 int r, fd = -1;
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);
399 goto done;
402 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
403 if (fd == -1)
404 log_warn("can't open %s", conf->log_access);
407 done:
408 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_TYPE, -1, fd,
409 NULL, 0) == -1)
410 return -1;
411 return 0;
414 static int
415 main_configure(struct conf *conf)
417 struct privsep *ps = conf->ps;
419 if (main_send_logfd(conf) == -1)
420 return -1;
422 conf->reload = conf->prefork + 1; /* servers, crypto */
424 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
425 return -1;
426 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
427 return -1;
429 if (config_send(conf) == -1)
430 return -1;
432 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
433 return -1;
434 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
435 return -1;
437 return 0;
440 static void
441 main_configure_done(struct conf *conf)
443 if (conf->reload == 0) {
444 log_warnx("configuration already done");
445 return;
448 conf->reload--;
449 /* send IMSG_CTL_START? */
452 static void
453 main_reload(struct conf *conf)
455 if (conf->reload) {
456 log_debug("%s: already in progress: %d pending",
457 __func__, conf->reload);
458 return;
461 log_debug("%s: config file %s", __func__, config_path);
462 config_purge(conf);
464 if (parse_conf(conf, config_path) == -1) {
465 log_warnx("failed to parse the config");
466 return;
469 main_configure(conf);
472 static void
473 main_sig_handler(int sig, short ev, void *arg)
475 struct privsep *ps = arg;
477 /*
478 * Normal signal handler rules don't apply here because libevent
479 * decouples for us.
480 */
482 switch (sig) {
483 case SIGHUP:
484 if (privsep_process != PROC_PARENT)
485 return;
486 log_info("reload requested with SIGHUP");
487 main_reload(ps->ps_env);
488 break;
489 case SIGCHLD:
490 log_warnx("one child died, quitting");
491 /* fallthrough */
492 case SIGTERM:
493 case SIGINT:
494 main_shutdown(ps->ps_env);
495 break;
496 case SIGUSR1:
497 main_send_logfd(ps->ps_env);
498 break;
499 default:
500 fatalx("unexpected signal %d", sig);
504 static int
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);
513 break;
514 default:
515 return -1;
518 return 0;
521 static int
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);
530 break;
531 default:
532 return -1;
535 return 0;
538 static int
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);
547 break;
548 default:
549 return -1;
552 return 0;
555 static void __dead
556 main_shutdown(struct conf *conf)
558 proc_kill(conf->ps);
559 config_purge(conf);
560 free(conf->ps);
561 /* free(conf); */
563 log_info("parent terminating, pid %d", getpid());
565 if (pidfd != -1)
566 close(pidfd);
568 exit(0);
571 static void
572 main_print_conf(struct conf *conf)
574 struct vhost *h;
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... */
592 printf("}\n");