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);
303 signal_add(&ps->ps_evsigint, NULL);
304 signal_add(&ps->ps_evsigterm, NULL);
305 signal_add(&ps->ps_evsigchld, NULL);
306 signal_add(&ps->ps_evsighup, NULL);
308 proc_connect(ps);
310 if (main_configure(conf) == -1)
311 fatal("configuration failed");
313 event_dispatch();
314 main_shutdown(conf);
315 /* NOTREACHED */
316 return 0;
319 static int
320 main_configure(struct conf *conf)
322 struct privsep *ps = conf->ps;
324 conf->reload = conf->prefork + 1; /* servers, crypto */
326 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
327 return -1;
328 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
329 return -1;
331 if (config_send(conf) == -1)
332 return -1;
334 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
335 return -1;
336 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
337 return -1;
339 return 0;
342 static void
343 main_configure_done(struct conf *conf)
345 if (conf->reload == 0) {
346 log_warnx("configuration already done");
347 return;
350 conf->reload--;
351 /* send IMSG_CTL_START? */
354 static void
355 main_reload(struct conf *conf)
357 if (conf->reload) {
358 log_debug("%s: already in progress: %d pending",
359 __func__, conf->reload);
360 return;
363 log_debug("%s: config file %s", __func__, config_path);
364 config_purge(conf);
366 if (parse_conf(conf, config_path) == -1) {
367 log_warnx("failed to parse the config");
368 return;
371 main_configure(conf);
374 static void
375 main_sig_handler(int sig, short ev, void *arg)
377 struct privsep *ps = arg;
379 /*
380 * Normal signal handler rules don't apply here because libevent
381 * decouples for us.
382 */
384 switch (sig) {
385 case SIGHUP:
386 if (privsep_process != PROC_PARENT)
387 return;
388 log_info("reload requested with SIGHUP");
389 main_reload(ps->ps_env);
390 break;
391 case SIGCHLD:
392 log_warnx("one child died, quitting");
393 /* fallthrough */
394 case SIGTERM:
395 case SIGINT:
396 main_shutdown(ps->ps_env);
397 break;
398 default:
399 fatalx("unexpected signal %d", sig);
403 static int
404 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
406 struct privsep *ps = p->p_ps;
407 struct conf *conf = ps->ps_env;
409 switch (imsg->hdr.type) {
410 case IMSG_RECONF_DONE:
411 main_configure_done(conf);
412 break;
413 default:
414 return -1;
417 return 0;
420 static int
421 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
423 struct privsep *ps = p->p_ps;
424 struct conf *conf = ps->ps_env;
426 switch (imsg->hdr.type) {
427 case IMSG_RECONF_DONE:
428 main_configure_done(conf);
429 break;
430 default:
431 return -1;
434 return 0;
437 static int
438 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
440 struct privsep *ps = p->p_ps;
441 struct conf *conf = ps->ps_env;
443 switch (imsg->hdr.type) {
444 case IMSG_RECONF_DONE:
445 main_configure_done(conf);
446 break;
447 default:
448 return -1;
451 return 0;
454 static void __dead
455 main_shutdown(struct conf *conf)
457 proc_kill(conf->ps);
458 config_purge(conf);
459 free(conf->ps);
460 /* free(conf); */
462 log_info("parent terminating, pid %d", getpid());
464 if (pidfd != -1)
465 close(pidfd);
467 exit(0);
470 static void
471 main_print_conf(struct conf *conf)
473 struct vhost *h;
474 /* struct location *l; */
475 /* struct envlist *e; */
476 /* struct alist *a; */
478 if (*conf->chroot != '\0')
479 printf("chroot \"%s\"\n", conf->chroot);
480 /* XXX: defined mimes? */
481 printf("prefork %d\n", conf->prefork);
482 /* XXX: protocols? */
483 if (*conf->user != '\0')
484 printf("user \"%s\"\n", conf->user);
486 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
487 printf("\nserver \"%s\" {\n", h->domain);
488 printf(" cert \"%s\"\n", h->cert);
489 printf(" key \"%s\"\n", h->key);
490 /* TODO: print locations... */
491 printf("}\n");