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 b[GEMINI_URL_LEN];
88 char *fmted;
89 const char *t;
90 int ec;
92 if (c->iri.schema != NULL) {
93 /* serialize the IRI */
94 strlcpy(b, c->iri.schema, sizeof(b));
95 strlcat(b, "://", sizeof(b));
97 /* log the decoded host name, but if it was invalid
98 * use the raw one. */
99 if (*c->domain != '\0')
100 strlcat(b, c->domain, sizeof(b));
101 else
102 strlcat(b, c->iri.host, sizeof(b));
104 if (*c->iri.path != '/')
105 strlcat(b, "/", sizeof(b));
106 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
107 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
108 strlcat(b, "?", sizeof(b));
109 strlcat(b, c->iri.query, sizeof(b));
111 } else {
112 if ((t = c->req) == NULL)
113 t = "";
114 strlcpy(b, t, sizeof(b));
117 ec = asprintf(&fmted, "%s:%s GET %s %d %s", c->rhost, c->rserv, b,
118 code, meta);
119 if (ec == -1)
120 fatal("asprintf");
122 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
123 fmted, ec + 1);
125 free(fmted);
128 static int
129 write_pidfile(const char *pidfile)
131 struct flock lock;
132 int fd;
134 if (pidfile == NULL)
135 return -1;
137 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
138 fatal("can't open pidfile %s", pidfile);
140 lock.l_start = 0;
141 lock.l_len = 0;
142 lock.l_type = F_WRLCK;
143 lock.l_whence = SEEK_SET;
145 if (fcntl(fd, F_SETLK, &lock) == -1)
146 fatalx("can't lock %s, gmid is already running?", pidfile);
148 if (ftruncate(fd, 0) == -1)
149 fatal("ftruncate %s", pidfile);
151 dprintf(fd, "%d\n", getpid());
153 return fd;
156 int
157 main(int argc, char **argv)
159 struct conf *conf;
160 struct privsep *ps;
161 const char *errstr, *title = NULL;
162 const char *user = NULL, *chroot = NULL;
163 size_t i;
164 int ch, conftest = 0;
165 int proc_instance = 0;
166 int proc_id = PROC_PARENT;
167 int argc0 = argc;
169 setlocale(LC_CTYPE, "");
171 /* log to stderr until daemonized */
172 log_init(1, LOG_DAEMON);
174 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
175 switch (ch) {
176 case 'c':
177 config_path = absolutify_path(optarg);
178 break;
179 case 'D':
180 if (cmdline_symset(optarg) == -1)
181 fatalx("could not parse macro definition: %s",
182 optarg);
183 break;
184 case 'f':
185 debug = 1;
186 break;
187 case 'h':
188 usage();
189 return 0;
190 case 'I':
191 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
192 &errstr);
193 if (errstr != NULL)
194 fatalx("invalid process instance");
195 break;
196 case 'n':
197 conftest++;
198 break;
199 case 'P':
200 pidfile = absolutify_path(optarg);
201 break;
202 case 'T':
203 title = optarg;
204 proc_id = proc_getid(procs, nitems(procs), title);
205 if (proc_id == PROC_MAX)
206 fatalx("invalid process name");
207 break;
208 case 'U':
209 user = optarg;
210 break;
211 case 'V':
212 puts("Version: " GMID_STRING);
213 return 0;
214 case 'v':
215 verbose = 1;
216 break;
217 case 'X':
218 chroot = optarg;
219 break;
220 default:
221 usage();
222 return 1;
226 if (argc - optind != 0)
227 usage();
229 conf = config_new();
231 /*
232 * Only the parent loads the config, the others get user and
233 * chroot via flags and the rest via imsg.
234 */
235 if (proc_id == PROC_PARENT) {
236 if (parse_conf(conf, config_path) == -1)
237 fatalx("failed to load configuration file");
238 if (*conf->chroot != '\0' && *conf->user == '\0')
239 fatalx("can't chroot without a user to switch to.");
240 } else {
241 if (user)
242 strlcpy(conf->user, user, sizeof(conf->user));
243 if (chroot)
244 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
247 if (conftest) {
248 fprintf(stderr, "config OK\n");
249 if (conftest > 1)
250 main_print_conf(conf);
251 return 0;
254 if ((ps = calloc(1, sizeof(*ps))) == NULL)
255 fatal("calloc");
256 ps->ps_env = conf;
257 conf->ps = ps;
258 if (*conf->user) {
259 if (geteuid())
260 fatalx("need root privileges");
261 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
262 fatalx("unknown user %s", conf->user);
263 if (*conf->chroot == '\0')
264 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
265 sizeof(conf->chroot));
268 ps->ps_instances[PROC_SERVER] = conf->prefork;
269 ps->ps_instance = proc_instance;
270 if (title != NULL)
271 ps->ps_title[proc_id] = title;
273 if (*conf->chroot != '\0') {
274 for (i = 0; i < nitems(procs); ++i)
275 procs[i].p_chroot = conf->chroot;
278 log_init(debug, LOG_DAEMON);
279 log_setverbose(verbose);
280 if (title != NULL)
281 log_procinit(title);
283 /* only the parent returns */
284 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
286 log_procinit("main");
287 if (!debug && daemon(0, 0) == -1)
288 fatal("daemon");
290 pidfd = write_pidfile(pidfile);
292 sandbox_main_process();
294 event_init();
296 signal(SIGPIPE, SIG_IGN);
298 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
299 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
300 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
301 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
302 signal_set(&ps->ps_evsigusr1, SIGUSR1, main_sig_handler, ps);
304 signal_add(&ps->ps_evsigint, NULL);
305 signal_add(&ps->ps_evsigterm, NULL);
306 signal_add(&ps->ps_evsigchld, NULL);
307 signal_add(&ps->ps_evsighup, NULL);
308 signal_add(&ps->ps_evsigusr1, NULL);
310 proc_connect(ps);
312 if (main_configure(conf) == -1)
313 fatal("configuration failed");
315 event_dispatch();
316 main_shutdown(conf);
317 /* NOTREACHED */
318 return 0;
321 static int
322 main_send_logfd(struct conf *conf)
324 struct privsep *ps = conf->ps;
325 int fd = -1;
327 if (debug)
328 return 0;
330 if (conf->log_access) {
331 fd = open(conf->log_access, O_WRONLY|O_CREAT|O_APPEND, 0600);
332 if (fd == -1)
333 log_warn("can't open %s", conf->log_access);
335 if (proc_compose_imsg(ps, PROC_LOGGER, -1, IMSG_LOG_TYPE, -1, fd,
336 NULL, 0) == -1)
337 return -1;
338 return 0;
341 static int
342 main_configure(struct conf *conf)
344 struct privsep *ps = conf->ps;
346 if (main_send_logfd(conf) == -1)
347 return -1;
349 conf->reload = conf->prefork + 1; /* servers, crypto */
351 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
352 return -1;
353 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
354 return -1;
356 if (config_send(conf) == -1)
357 return -1;
359 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
360 return -1;
361 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
362 return -1;
364 return 0;
367 static void
368 main_configure_done(struct conf *conf)
370 if (conf->reload == 0) {
371 log_warnx("configuration already done");
372 return;
375 conf->reload--;
376 /* send IMSG_CTL_START? */
379 static void
380 main_reload(struct conf *conf)
382 if (conf->reload) {
383 log_debug("%s: already in progress: %d pending",
384 __func__, conf->reload);
385 return;
388 log_debug("%s: config file %s", __func__, config_path);
389 config_purge(conf);
391 if (parse_conf(conf, config_path) == -1) {
392 log_warnx("failed to parse the config");
393 return;
396 main_configure(conf);
399 static void
400 main_sig_handler(int sig, short ev, void *arg)
402 struct privsep *ps = arg;
404 /*
405 * Normal signal handler rules don't apply here because libevent
406 * decouples for us.
407 */
409 switch (sig) {
410 case SIGHUP:
411 if (privsep_process != PROC_PARENT)
412 return;
413 log_info("reload requested with SIGHUP");
414 main_reload(ps->ps_env);
415 break;
416 case SIGCHLD:
417 log_warnx("one child died, quitting");
418 /* fallthrough */
419 case SIGTERM:
420 case SIGINT:
421 main_shutdown(ps->ps_env);
422 break;
423 case SIGUSR1:
424 main_send_logfd(ps->ps_env);
425 break;
426 default:
427 fatalx("unexpected signal %d", sig);
431 static int
432 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
434 struct privsep *ps = p->p_ps;
435 struct conf *conf = ps->ps_env;
437 switch (imsg->hdr.type) {
438 case IMSG_RECONF_DONE:
439 main_configure_done(conf);
440 break;
441 default:
442 return -1;
445 return 0;
448 static int
449 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
451 struct privsep *ps = p->p_ps;
452 struct conf *conf = ps->ps_env;
454 switch (imsg->hdr.type) {
455 case IMSG_RECONF_DONE:
456 main_configure_done(conf);
457 break;
458 default:
459 return -1;
462 return 0;
465 static int
466 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
468 struct privsep *ps = p->p_ps;
469 struct conf *conf = ps->ps_env;
471 switch (imsg->hdr.type) {
472 case IMSG_RECONF_DONE:
473 main_configure_done(conf);
474 break;
475 default:
476 return -1;
479 return 0;
482 static void __dead
483 main_shutdown(struct conf *conf)
485 proc_kill(conf->ps);
486 config_purge(conf);
487 free(conf->ps);
488 /* free(conf); */
490 log_info("parent terminating, pid %d", getpid());
492 if (pidfd != -1)
493 close(pidfd);
495 exit(0);
498 static void
499 main_print_conf(struct conf *conf)
501 struct vhost *h;
502 /* struct location *l; */
503 /* struct envlist *e; */
504 /* struct alist *a; */
506 if (*conf->chroot != '\0')
507 printf("chroot \"%s\"\n", conf->chroot);
508 /* XXX: defined mimes? */
509 printf("prefork %d\n", conf->prefork);
510 /* XXX: protocols? */
511 if (*conf->user != '\0')
512 printf("user \"%s\"\n", conf->user);
514 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
515 printf("\nserver \"%s\" {\n", h->domain);
516 printf(" cert \"%s\"\n", h->cert);
517 printf(" key \"%s\"\n", h->key);
518 /* TODO: print locations... */
519 printf("}\n");