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, char *meta, size_t l)
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 if ((t = memchr(meta, '\r', l)) == NULL)
118 t = meta + l;
120 ec = asprintf(&fmted, "%s:%s GET %s %.*s", c->rhost, c->rserv, b,
121 (int)(t-meta), meta);
122 if (ec == -1)
123 fatal("asprintf");
125 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
126 fmted, ec + 1);
128 free(fmted);
131 static int
132 write_pidfile(const char *pidfile)
134 struct flock lock;
135 int fd;
137 if (pidfile == NULL)
138 return -1;
140 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
141 fatal("can't open pidfile %s", pidfile);
143 lock.l_start = 0;
144 lock.l_len = 0;
145 lock.l_type = F_WRLCK;
146 lock.l_whence = SEEK_SET;
148 if (fcntl(fd, F_SETLK, &lock) == -1)
149 fatalx("can't lock %s, gmid is already running?", pidfile);
151 if (ftruncate(fd, 0) == -1)
152 fatal("ftruncate %s", pidfile);
154 dprintf(fd, "%d\n", getpid());
156 return fd;
159 int
160 main(int argc, char **argv)
162 struct conf *conf;
163 struct privsep *ps;
164 const char *errstr, *title = NULL;
165 const char *user = NULL, *chroot = NULL;
166 size_t i;
167 int ch, conftest = 0;
168 int proc_instance = 0;
169 int proc_id = PROC_PARENT;
170 int argc0 = argc;
172 setlocale(LC_CTYPE, "");
174 /* log to stderr until daemonized */
175 log_init(1, LOG_DAEMON);
177 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
178 switch (ch) {
179 case 'c':
180 config_path = absolutify_path(optarg);
181 break;
182 case 'D':
183 if (cmdline_symset(optarg) == -1)
184 fatalx("could not parse macro definition: %s",
185 optarg);
186 break;
187 case 'f':
188 debug = 1;
189 break;
190 case 'h':
191 usage();
192 return 0;
193 case 'I':
194 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
195 &errstr);
196 if (errstr != NULL)
197 fatalx("invalid process instance");
198 break;
199 case 'n':
200 conftest++;
201 break;
202 case 'P':
203 pidfile = absolutify_path(optarg);
204 break;
205 case 'T':
206 title = optarg;
207 proc_id = proc_getid(procs, nitems(procs), title);
208 if (proc_id == PROC_MAX)
209 fatalx("invalid process name");
210 break;
211 case 'U':
212 user = optarg;
213 break;
214 case 'V':
215 puts("Version: " GMID_STRING);
216 return 0;
217 case 'v':
218 verbose = 1;
219 break;
220 case 'X':
221 chroot = optarg;
222 break;
223 default:
224 usage();
225 return 1;
229 if (argc - optind != 0)
230 usage();
232 conf = config_new();
234 /*
235 * Only the parent loads the config, the others get user and
236 * chroot via flags and the rest via imsg.
237 */
238 if (proc_id == PROC_PARENT) {
239 if (parse_conf(conf, config_path) == -1)
240 fatalx("failed to load configuration file");
241 if (*conf->chroot != '\0' && *conf->user == '\0')
242 fatalx("can't chroot without a user to switch to.");
243 } else {
244 if (user)
245 strlcpy(conf->user, user, sizeof(conf->user));
246 if (chroot)
247 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
250 if (conftest) {
251 fprintf(stderr, "config OK\n");
252 if (conftest > 1)
253 main_print_conf(conf);
254 return 0;
257 if ((ps = calloc(1, sizeof(*ps))) == NULL)
258 fatal("calloc");
259 ps->ps_env = conf;
260 conf->ps = ps;
261 if (*conf->user) {
262 if (geteuid())
263 fatalx("need root privileges");
264 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
265 fatalx("unknown user %s", conf->user);
266 if (*conf->chroot == '\0')
267 strlcpy(conf->chroot, ps->ps_pw->pw_dir,
268 sizeof(conf->chroot));
271 ps->ps_instances[PROC_SERVER] = conf->prefork;
272 ps->ps_instance = proc_instance;
273 if (title != NULL)
274 ps->ps_title[proc_id] = title;
276 if (*conf->chroot != '\0') {
277 for (i = 0; i < nitems(procs); ++i)
278 procs[i].p_chroot = conf->chroot;
281 log_init(debug, LOG_DAEMON);
282 log_setverbose(verbose);
283 if (title != NULL)
284 log_procinit(title);
286 /* only the parent returns */
287 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
289 log_procinit("main");
290 if (!debug && daemon(0, 0) == -1)
291 fatal("daemon");
293 pidfd = write_pidfile(pidfile);
295 sandbox_main_process();
297 event_init();
299 signal(SIGPIPE, SIG_IGN);
301 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
302 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
303 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
304 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
306 signal_add(&ps->ps_evsigint, NULL);
307 signal_add(&ps->ps_evsigterm, NULL);
308 signal_add(&ps->ps_evsigchld, NULL);
309 signal_add(&ps->ps_evsighup, NULL);
311 proc_connect(ps);
313 if (main_configure(conf) == -1)
314 fatal("configuration failed");
316 event_dispatch();
317 main_shutdown(conf);
318 /* NOTREACHED */
319 return 0;
322 static int
323 main_configure(struct conf *conf)
325 struct privsep *ps = conf->ps;
327 conf->reload = conf->prefork + 1; /* servers, crypto */
329 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
330 return -1;
331 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
332 return -1;
334 if (config_send(conf) == -1)
335 return -1;
337 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
338 return -1;
339 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
340 return -1;
342 return 0;
345 static void
346 main_configure_done(struct conf *conf)
348 if (conf->reload == 0) {
349 log_warnx("configuration already done");
350 return;
353 conf->reload--;
354 /* send IMSG_CTL_START? */
357 static void
358 main_reload(struct conf *conf)
360 if (conf->reload) {
361 log_debug("%s: already in progress: %d pending",
362 __func__, conf->reload);
363 return;
366 log_debug("%s: config file %s", __func__, config_path);
367 config_purge(conf);
369 if (parse_conf(conf, config_path) == -1) {
370 log_warnx("failed to parse the config");
371 return;
374 main_configure(conf);
377 static void
378 main_sig_handler(int sig, short ev, void *arg)
380 struct privsep *ps = arg;
382 /*
383 * Normal signal handler rules don't apply here because libevent
384 * decouples for us.
385 */
387 switch (sig) {
388 case SIGHUP:
389 if (privsep_process != PROC_PARENT)
390 return;
391 log_info("reload requested with SIGHUP");
392 main_reload(ps->ps_env);
393 break;
394 case SIGCHLD:
395 log_warnx("one child died, quitting");
396 /* fallthrough */
397 case SIGTERM:
398 case SIGINT:
399 main_shutdown(ps->ps_env);
400 break;
401 default:
402 fatalx("unexpected signal %d", sig);
406 static int
407 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
409 struct privsep *ps = p->p_ps;
410 struct conf *conf = ps->ps_env;
412 switch (imsg->hdr.type) {
413 case IMSG_RECONF_DONE:
414 main_configure_done(conf);
415 break;
416 default:
417 return -1;
420 return 0;
423 static int
424 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
426 struct privsep *ps = p->p_ps;
427 struct conf *conf = ps->ps_env;
429 switch (imsg->hdr.type) {
430 case IMSG_RECONF_DONE:
431 main_configure_done(conf);
432 break;
433 default:
434 return -1;
437 return 0;
440 static int
441 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
443 struct privsep *ps = p->p_ps;
444 struct conf *conf = ps->ps_env;
446 switch (imsg->hdr.type) {
447 case IMSG_RECONF_DONE:
448 main_configure_done(conf);
449 break;
450 default:
451 return -1;
454 return 0;
457 static void __dead
458 main_shutdown(struct conf *conf)
460 proc_kill(conf->ps);
461 config_purge(conf);
462 free(conf->ps);
463 /* free(conf); */
465 log_info("parent terminating, pid %d", getpid());
467 if (pidfd != -1)
468 close(pidfd);
470 exit(0);
473 static void
474 main_print_conf(struct conf *conf)
476 struct vhost *h;
477 /* struct location *l; */
478 /* struct envlist *e; */
479 /* struct alist *a; */
481 if (*conf->chroot != '\0')
482 printf("chroot \"%s\"\n", conf->chroot);
483 /* XXX: defined mimes? */
484 printf("prefork %d\n", conf->prefork);
485 /* XXX: protocols? */
486 if (*conf->user != '\0')
487 printf("user \"%s\"\n", conf->user);
489 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
490 printf("\nserver \"%s\" {\n", h->domain);
491 printf(" cert \"%s\"\n", h->cert);
492 printf(" key \"%s\"\n", h->key);
493 /* TODO: print locations... */
494 printf("}\n");