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 hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
88 char *fmted;
89 const char *t;
90 size_t len;
91 int ec;
93 len = sizeof(c->addr);
94 ec = getnameinfo((struct sockaddr*)&c->addr, len,
95 hbuf, sizeof(hbuf),
96 sbuf, sizeof(sbuf),
97 NI_NUMERICHOST | NI_NUMERICSERV);
98 if (ec != 0)
99 fatalx("getnameinfo: %s", gai_strerror(ec));
101 if (c->iri.schema != NULL) {
102 /* serialize the IRI */
103 strlcpy(b, c->iri.schema, sizeof(b));
104 strlcat(b, "://", sizeof(b));
106 /* log the decoded host name, but if it was invalid
107 * use the raw one. */
108 if (*c->domain != '\0')
109 strlcat(b, c->domain, sizeof(b));
110 else
111 strlcat(b, c->iri.host, sizeof(b));
113 if (*c->iri.path != '/')
114 strlcat(b, "/", sizeof(b));
115 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
116 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
117 strlcat(b, "?", sizeof(b));
118 strlcat(b, c->iri.query, sizeof(b));
120 } else {
121 if ((t = c->req) == NULL)
122 t = "";
123 strlcpy(b, t, sizeof(b));
126 if ((t = memchr(meta, '\r', l)) == NULL)
127 t = meta + len;
129 ec = asprintf(&fmted, "%s:%s GET %s %.*s", hbuf, sbuf, b,
130 (int)(t-meta), meta);
131 if (ec == -1)
132 fatal("asprintf");
134 proc_compose(conf->ps, PROC_LOGGER, IMSG_LOG_REQUEST,
135 fmted, ec + 1);
137 free(fmted);
140 static int
141 write_pidfile(const char *pidfile)
143 struct flock lock;
144 int fd;
146 if (pidfile == NULL)
147 return -1;
149 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
150 fatal("can't open pidfile %s", pidfile);
152 lock.l_start = 0;
153 lock.l_len = 0;
154 lock.l_type = F_WRLCK;
155 lock.l_whence = SEEK_SET;
157 if (fcntl(fd, F_SETLK, &lock) == -1)
158 fatalx("can't lock %s, gmid is already running?", pidfile);
160 if (ftruncate(fd, 0) == -1)
161 fatal("ftruncate %s", pidfile);
163 dprintf(fd, "%d\n", getpid());
165 return fd;
168 int
169 main(int argc, char **argv)
171 struct conf *conf;
172 struct privsep *ps;
173 const char *errstr, *title = NULL;
174 const char *user = NULL, *chroot = NULL;
175 size_t i;
176 int ch, conftest = 0;
177 int proc_instance = 0;
178 int proc_id = PROC_PARENT;
179 int argc0 = argc;
181 setlocale(LC_CTYPE, "");
183 /* log to stderr until daemonized */
184 log_init(1, LOG_DAEMON);
186 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
187 switch (ch) {
188 case 'c':
189 config_path = absolutify_path(optarg);
190 break;
191 case 'D':
192 if (cmdline_symset(optarg) == -1)
193 fatalx("could not parse macro definition: %s",
194 optarg);
195 break;
196 case 'f':
197 debug = 1;
198 break;
199 case 'h':
200 usage();
201 return 0;
202 case 'I':
203 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
204 &errstr);
205 if (errstr != NULL)
206 fatalx("invalid process instance");
207 break;
208 case 'n':
209 conftest++;
210 break;
211 case 'P':
212 pidfile = absolutify_path(optarg);
213 break;
214 case 'T':
215 title = optarg;
216 proc_id = proc_getid(procs, nitems(procs), title);
217 if (proc_id == PROC_MAX)
218 fatalx("invalid process name");
219 break;
220 case 'U':
221 user = optarg;
222 break;
223 case 'V':
224 puts("Version: " GMID_STRING);
225 return 0;
226 case 'v':
227 verbose = 1;
228 break;
229 case 'X':
230 chroot = optarg;
231 break;
232 default:
233 usage();
234 return 1;
238 if (argc - optind != 0)
239 usage();
241 conf = config_new();
243 /*
244 * Only the parent loads the config, the others get user and
245 * chroot via flags and the rest via imsg.
246 */
247 if (proc_id == PROC_PARENT) {
248 if (parse_conf(conf, config_path) == -1)
249 fatalx("failed to load configuration file");
250 if (*conf->chroot != '\0' && *conf->user == '\0')
251 fatalx("can't chroot without a user to switch to.");
252 } else {
253 if (user)
254 strlcpy(conf->user, user, sizeof(conf->user));
255 if (chroot)
256 strlcpy(conf->chroot, chroot, sizeof(conf->chroot));
259 if (conftest) {
260 fprintf(stderr, "config OK\n");
261 if (conftest > 1)
262 main_print_conf(conf);
263 return 0;
266 if ((ps = calloc(1, sizeof(*ps))) == NULL)
267 fatal("calloc");
268 ps->ps_env = conf;
269 conf->ps = ps;
270 if (*conf->user) {
271 if (geteuid())
272 fatalx("need root privileges");
273 if ((ps->ps_pw = getpwnam(conf->user)) == NULL)
274 fatalx("unknown user %s", conf->user);
277 ps->ps_instances[PROC_SERVER] = conf->prefork;
278 ps->ps_instance = proc_instance;
279 if (title != NULL)
280 ps->ps_title[proc_id] = title;
282 if (*conf->chroot != '\0') {
283 for (i = 0; i < nitems(procs); ++i)
284 procs[i].p_chroot = conf->chroot;
287 log_init(debug, LOG_DAEMON);
288 log_setverbose(verbose);
289 if (title != NULL)
290 log_procinit(title);
292 /* only the parent returns */
293 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
295 log_procinit("main");
296 if (!debug && daemon(0, 0) == -1)
297 fatal("daemon");
299 pidfd = write_pidfile(pidfile);
301 sandbox_main_process();
303 event_init();
305 signal(SIGPIPE, SIG_IGN);
307 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
308 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
309 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
310 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
312 signal_add(&ps->ps_evsigint, NULL);
313 signal_add(&ps->ps_evsigterm, NULL);
314 signal_add(&ps->ps_evsigchld, NULL);
315 signal_add(&ps->ps_evsighup, NULL);
317 proc_connect(ps);
319 if (main_configure(conf) == -1)
320 fatal("configuration failed");
322 event_dispatch();
323 main_shutdown(conf);
324 /* NOTREACHED */
325 return 0;
328 static int
329 main_configure(struct conf *conf)
331 struct privsep *ps = conf->ps;
333 conf->reload = conf->prefork + 1; /* servers, crypto */
335 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
336 return -1;
337 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_START, NULL, 0) == -1)
338 return -1;
340 if (config_send(conf) == -1)
341 return -1;
343 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
344 return -1;
345 if (proc_compose(ps, PROC_CRYPTO, IMSG_RECONF_END, NULL, 0) == -1)
346 return -1;
348 return 0;
351 static void
352 main_configure_done(struct conf *conf)
354 if (conf->reload == 0) {
355 log_warnx("configuration already done");
356 return;
359 conf->reload--;
360 /* send IMSG_CTL_START? */
363 static void
364 main_reload(struct conf *conf)
366 if (conf->reload) {
367 log_debug("%s: already in progress: %d pending",
368 __func__, conf->reload);
369 return;
372 log_debug("%s: config file %s", __func__, config_path);
373 config_purge(conf);
375 if (parse_conf(conf, config_path) == -1) {
376 log_warnx("failed to parse the config");
377 return;
380 main_configure(conf);
383 static void
384 main_sig_handler(int sig, short ev, void *arg)
386 struct privsep *ps = arg;
388 /*
389 * Normal signal handler rules don't apply here because libevent
390 * decouples for us.
391 */
393 switch (sig) {
394 case SIGHUP:
395 if (privsep_process != PROC_PARENT)
396 return;
397 log_info("reload requested with SIGHUP");
398 main_reload(ps->ps_env);
399 break;
400 case SIGCHLD:
401 log_warnx("one child died, quitting");
402 /* fallthrough */
403 case SIGTERM:
404 case SIGINT:
405 main_shutdown(ps->ps_env);
406 break;
407 default:
408 fatalx("unexpected signal %d", sig);
412 static int
413 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
415 struct privsep *ps = p->p_ps;
416 struct conf *conf = ps->ps_env;
418 switch (imsg->hdr.type) {
419 case IMSG_RECONF_DONE:
420 main_configure_done(conf);
421 break;
422 default:
423 return -1;
426 return 0;
429 static int
430 main_dispatch_crypto(int fd, struct privsep_proc *p, struct imsg *imsg)
432 struct privsep *ps = p->p_ps;
433 struct conf *conf = ps->ps_env;
435 switch (imsg->hdr.type) {
436 case IMSG_RECONF_DONE:
437 main_configure_done(conf);
438 break;
439 default:
440 return -1;
443 return 0;
446 static int
447 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
449 struct privsep *ps = p->p_ps;
450 struct conf *conf = ps->ps_env;
452 switch (imsg->hdr.type) {
453 case IMSG_RECONF_DONE:
454 main_configure_done(conf);
455 break;
456 default:
457 return -1;
460 return 0;
463 static void __dead
464 main_shutdown(struct conf *conf)
466 proc_kill(conf->ps);
467 config_purge(conf);
468 free(conf->ps);
469 /* free(conf); */
471 log_info("parent terminating, pid %d", getpid());
473 if (pidfd != -1)
474 close(pidfd);
476 exit(0);
479 static void
480 main_print_conf(struct conf *conf)
482 struct vhost *h;
483 /* struct location *l; */
484 /* struct envlist *e; */
485 /* struct alist *a; */
487 if (*conf->chroot != '\0')
488 printf("chroot \"%s\"\n", conf->chroot);
489 printf("ipv6 %s\n", conf->ipv6 ? "on" : "off");
490 /* XXX: defined mimes? */
491 printf("port %d\n", conf->port);
492 printf("prefork %d\n", conf->prefork);
493 /* XXX: protocols? */
494 if (*conf->user != '\0')
495 printf("user \"%s\"\n", conf->user);
497 TAILQ_FOREACH(h, &conf->hosts, vhosts) {
498 printf("\nserver \"%s\" {\n", h->domain);
499 printf(" cert \"%s\"\n", h->cert);
500 printf(" key \"%s\"\n", h->key);
501 /* TODO: print locations... */
502 printf("}\n");