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 = SYSCONFDIR "/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 ((ps = calloc(1, sizeof(*ps))) == NULL)
324 fatal("calloc");
325 ps->ps_env = conf;
326 conf->ps = ps;
327 if (*conf->user) {
328 if (geteuid())
329 fatalx("need root privileges");
330 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
331 fatalx("unknown user %s", conf->user);
332 if (*conf->chroot == '\0')
333 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
334 sizeof(conf->chroot));
337 if (conftest) {
338 conf->conftest = 1;
339 if (config_test(conf) == -1)
340 fatalx("failed to load the configuration");
341 fprintf(stderr, "config OK\n");
342 if (conftest > 1)
343 main_print_conf(conf);
344 return 0;
347 ps->ps_instances[PROC_SERVER] = conf->prefork;
348 ps->ps_instance = proc_instance;
349 if (title != NULL)
350 ps->ps_title[proc_id] = title;
352 if (*conf->chroot != '\0') {
353 for (i = 0; i < nitems(procs); ++i)
354 procs[i].p_chroot = conf->chroot;
357 log_init(debug, LOG_DAEMON);
358 log_setverbose(verbose);
359 if (title != NULL)
360 log_procinit(title);
362 /* only the parent returns */
363 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
365 log_procinit("main");
366 if (!debug && daemon(0, 0) == -1)
367 fatal("daemon");
369 pidfd = write_pidfile(pidfile);
371 sandbox_main_process();
373 event_init();
375 signal(SIGPIPE, SIG_IGN);
377 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
378 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
379 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
380 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
381 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
383 signal_add(&ps->ps_evsigint, NULL);
384 signal_add(&ps->ps_evsigterm, NULL);
385 signal_add(&ps->ps_evsigchld, NULL);
386 signal_add(&ps->ps_evsighup, NULL);
387 signal_add(&ps->ps_evsigusr1, NULL);
389 proc_connect(ps);
391 if (main_configure(conf) == -1)
392 fatal("configuration failed");
394 event_dispatch();
395 main_shutdown(conf);
396 /* NOTREACHED */
397 return 0;
400 static int
401 main_send_logfd(struct conf *conf)
403 struct privsep *ps = conf->ps;
404 char path[PATH_MAX];
405 int r, fd = -1;
407 if (conf->log_access) {
408 r = snprintf(path, sizeof(path), "%s%s%s", conf->chroot,
409 *conf->chroot == '\0' ? "" : "/", conf->log_access);
410 if (r < 0 || (size_t)r >= sizeof(path)) {
411 log_warnx("path too long: %s", conf->log_access);
412 goto done;
415 fd = open(path, O_WRONLY|O_CREAT|O_APPEND, 0600);
416 if (fd == -1)
417 log_warn("can't open %s", conf->log_access);
420 done:
421 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_ACCESS, -1, fd,
422 NULL, 0) == -1)
423 return -1;
424 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_FACILITY, -1, -1,
425 &conf->log_facility, sizeof(conf->log_facility)) == -1)
426 return -1;
427 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_SYSLOG, -1, -1,
428 &conf->log_syslog, sizeof(conf->log_syslog)) == -1)
429 return -1;
430 return 0;
433 static int
434 main_configure(struct conf *conf)
436 struct privsep *ps = conf->ps;
438 if (main_send_logfd(conf) == -1)
439 return -1;
441 conf->reload = conf->prefork + 1; /* servers, crypto */
443 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
444 return -1;
445 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
446 return -1;
448 if (config_send(conf) == -1)
449 return -1;
451 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
452 return -1;
453 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
454 return -1;
456 return 0;
459 static void
460 main_configure_done(struct conf *conf)
462 if (conf->reload == 0) {
463 log_warnx("configuration already done");
464 return;
467 conf->reload--;
468 /* send IMSG_CTL_START? */
471 static void
472 main_reload(struct conf *conf)
474 if (conf->reload) {
475 log_debug("%s: already in progress: %d pending",
476 __func__, conf->reload);
477 return;
480 log_debug("%s: config file %s", __func__, config_path);
481 config_purge(conf);
483 if (parse_conf(conf, config_path) == -1) {
484 log_warnx("failed to parse the config");
485 return;
488 main_configure(conf);
491 static void
492 main_sig_handler(int sig, short ev, void *arg)
494 struct privsep *ps = arg;
496 /*
497 * Normal signal handler rules don't apply here because libevent
498 * decouples for us.
499 */
501 switch (sig) {
502 case SIGHUP:
503 if (privsep_process != PROC_PARENT)
504 return;
505 log_info("reload requested with SIGHUP");
506 main_reload(ps->ps_env);
507 break;
508 case SIGCHLD:
509 log_warnx("one child died, quitting");
510 /* fallthrough */
511 case SIGTERM:
512 case SIGINT:
513 main_shutdown(ps->ps_env);
514 break;
515 case SIGUSR1:
516 main_send_logfd(ps->ps_env);
517 break;
518 default:
519 fatalx("unexpected signal %d", sig);
523 static int
524 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
526 struct privsep *ps = p->p_ps;
527 struct conf *conf = ps->ps_env;
529 switch (imsg_get_type(imsg)) {
530 case IMSG_RECONF_DONE:
531 main_configure_done(conf);
532 break;
533 default:
534 return -1;
537 return 0;
540 static int
541 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
543 struct privsep *ps = p->p_ps;
544 struct conf *conf = ps->ps_env;
546 switch (imsg_get_type(imsg)) {
547 case IMSG_RECONF_DONE:
548 main_configure_done(conf);
549 break;
550 default:
551 return -1;
554 return 0;
557 static int
558 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
560 struct privsep *ps = p->p_ps;
561 struct conf *conf = ps->ps_env;
563 switch (imsg_get_type(imsg)) {
564 case IMSG_RECONF_DONE:
565 main_configure_done(conf);
566 break;
567 default:
568 return -1;
571 return 0;
574 static void __dead
575 main_shutdown(struct conf *conf)
577 proc_kill(conf->ps);
578 config_purge(conf);
579 free(conf->ps);
580 /* free(conf); */
582 log_info("parent terminating, pid %d", getpid());
584 if (pidfd != -1)
585 close(pidfd);
587 exit(0);
590 static void
591 main_print_conf(struct conf *conf)
593 struct vhost *h;
594 /* struct location *l; */
595 /* struct envlist *e; */
596 /* struct alist *a; */
598 if (*conf->chroot != '\0')
599 printf("chroot \"%s\"\n", conf->chroot);
600 /* XXX: defined mimes? */
601 printf("prefork %d\n", conf->prefork);
602 /* XXX: protocols? */
603 if (*conf->user != '\0')
604 printf("user \"%s\"\n", conf->user);
606 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
607 printf("\nserver \"%s\" {\n", h->domain);
608 printf(" cert \"%s\"\n", h->cert);
609 printf(" key \"%s\"\n", h->key);
610 /* TODO: print locations... */
611 printf("}\n");