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_logger(int, struct privsep_proc *, struct imsg *);
46 static void __dead main_shutdown(struct conf *);
48 static struct privsep_proc procs[] = {
49 { "server", PROC_SERVER, main_dispatch_server, server },
50 { "logger", PROC_LOGGER, main_dispatch_logger, logger },
51 };
53 static const char *opts = "c:D:fI:hnP:T:Vv";
55 static const struct option longopts[] = {
56 {"help", no_argument, NULL, 'h'},
57 {"version", no_argument, NULL, 'V'},
58 {NULL, 0, NULL, 0},
59 };
61 struct fcgi fcgi[FCGI_MAX];
63 struct vhosthead hosts;
65 int sock4, sock6;
66 int privsep_process;
67 int pidfd = -1;
69 int debug, verbose;
71 const char *config_path = "/etc/gmid.conf";
72 const char *pidfile;
74 struct conf conf;
76 static void
77 usage(void)
78 {
79 fprintf(stderr,
80 "Version: " GMID_STRING "\n"
81 "Usage: %s [-fnv] [-c config] [-D macro=value] [-P pidfile]\n",
82 getprogname());
83 }
85 /* used by the server process, defined here so gg can provide its own impl. */
86 void
87 log_request(struct client *c, char *meta, size_t l)
88 {
89 char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV], b[GEMINI_URL_LEN];
90 char *fmted;
91 const char *t;
92 size_t len;
93 int ec;
95 len = sizeof(c->addr);
96 ec = getnameinfo((struct sockaddr*)&c->addr, len,
97 hbuf, sizeof(hbuf),
98 sbuf, sizeof(sbuf),
99 NI_NUMERICHOST | NI_NUMERICSERV);
100 if (ec != 0)
101 fatalx("getnameinfo: %s", gai_strerror(ec));
103 if (c->iri.schema != NULL) {
104 /* serialize the IRI */
105 strlcpy(b, c->iri.schema, sizeof(b));
106 strlcat(b, "://", sizeof(b));
108 /* log the decoded host name, but if it was invalid
109 * use the raw one. */
110 if (*c->domain != '\0')
111 strlcat(b, c->domain, sizeof(b));
112 else
113 strlcat(b, c->iri.host, sizeof(b));
115 if (*c->iri.path != '/')
116 strlcat(b, "/", sizeof(b));
117 strlcat(b, c->iri.path, sizeof(b)); /* TODO: sanitize UTF8 */
118 if (*c->iri.query != '\0') { /* TODO: sanitize UTF8 */
119 strlcat(b, "?", sizeof(b));
120 strlcat(b, c->iri.query, sizeof(b));
122 } else {
123 if ((t = c->req) == NULL)
124 t = "";
125 strlcpy(b, t, sizeof(b));
128 if ((t = memchr(meta, '\r', l)) == NULL)
129 t = meta + len;
131 ec = asprintf(&fmted, "%s:%s GET %s %.*s", hbuf, sbuf, b,
132 (int)(t-meta), meta);
133 if (ec == -1)
134 err(1, "asprintf");
136 proc_compose(conf.ps, PROC_LOGGER, IMSG_LOG_REQUEST,
137 fmted, ec + 1);
139 free(fmted);
142 static int
143 write_pidfile(const char *pidfile)
145 struct flock lock;
146 int fd;
148 if (pidfile == NULL)
149 return -1;
151 if ((fd = open(pidfile, O_WRONLY|O_CREAT|O_CLOEXEC, 0600)) == -1)
152 fatal("can't open pidfile %s", pidfile);
154 lock.l_start = 0;
155 lock.l_len = 0;
156 lock.l_type = F_WRLCK;
157 lock.l_whence = SEEK_SET;
159 if (fcntl(fd, F_SETLK, &lock) == -1)
160 fatalx("can't lock %s, gmid is already running?", pidfile);
162 if (ftruncate(fd, 0) == -1)
163 fatal("ftruncate %s", pidfile);
165 dprintf(fd, "%d\n", getpid());
167 return fd;
170 int
171 main(int argc, char **argv)
173 struct privsep *ps;
174 const char *errstr, *title = 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);
185 config_init();
187 while ((ch = getopt_long(argc, argv, opts, longopts, NULL)) != -1) {
188 switch (ch) {
189 case 'c':
190 config_path = absolutify_path(optarg);
191 break;
192 case 'D':
193 if (cmdline_symset(optarg) == -1)
194 fatalx("could not parse macro definition: %s",
195 optarg);
196 break;
197 case 'f':
198 debug = 1;
199 break;
200 case 'h':
201 usage();
202 return 0;
203 case 'I':
204 proc_instance = strtonum(optarg, 0, PROC_MAX_INSTANCES,
205 &errstr);
206 if (errstr != NULL)
207 fatalx("invalid process instance");
208 break;
209 case 'n':
210 conftest++;
211 break;
212 case 'P':
213 pidfile = absolutify_path(optarg);
214 break;
215 case 'T':
216 title = optarg;
217 proc_id = proc_getid(procs, nitems(procs), title);
218 if (proc_id == PROC_MAX)
219 fatalx("invalid process name");
220 break;
221 case 'V':
222 puts("Version: " GMID_STRING);
223 return 0;
224 case 'v':
225 verbose = 1;
226 break;
227 default:
228 usage();
229 return 1;
233 if (argc - optind != 0)
234 usage();
236 parse_conf(config_path);
237 if (*conf.chroot != '\0' && *conf.user == '\0')
238 fatalx("can't chroot without a user to switch to after.");
240 if (conftest) {
241 fprintf(stderr, "config OK\n");
242 if (conftest > 1)
243 print_conf();
244 return 0;
247 if ((ps = calloc(1, sizeof(*ps))) == NULL)
248 fatal("calloc");
249 ps->ps_env = &conf;
250 conf.ps = ps;
251 if (*conf.user) {
252 if (geteuid())
253 fatalx("need root privileges");
254 if ((ps->ps_pw = getpwnam(conf.user)) == NULL)
255 fatalx("unknown user %s", conf.user);
258 ps->ps_instances[PROC_SERVER] = conf.prefork;
259 ps->ps_instance = proc_instance;
260 if (title != NULL)
261 ps->ps_title[proc_id] = title;
263 if (*conf.chroot != '\0') {
264 for (i = 0; i < nitems(procs); ++i)
265 procs[i].p_chroot = conf.chroot;
268 log_init(debug, LOG_DAEMON);
269 log_setverbose(verbose);
270 if (title != NULL)
271 log_procinit(title);
273 /* only the parent returns */
274 proc_init(ps, procs, nitems(procs), debug, argc0, argv, proc_id);
276 log_procinit("main");
277 if (!debug && daemon(0, 0) == -1)
278 fatal("daemon");
280 pidfd = write_pidfile(pidfile);
282 sandbox_main_process();
284 event_init();
286 signal(SIGPIPE, SIG_IGN);
288 signal_set(&ps->ps_evsigint, SIGINT, main_sig_handler, ps);
289 signal_set(&ps->ps_evsigterm, SIGTERM, main_sig_handler, ps);
290 signal_set(&ps->ps_evsigchld, SIGCHLD, main_sig_handler, ps);
291 signal_set(&ps->ps_evsighup, SIGHUP, main_sig_handler, ps);
293 signal_add(&ps->ps_evsigint, NULL);
294 signal_add(&ps->ps_evsigterm, NULL);
295 signal_add(&ps->ps_evsigchld, NULL);
296 signal_add(&ps->ps_evsighup, NULL);
298 proc_connect(ps);
300 if (main_configure(&conf) == -1)
301 fatal("configuration failed");
303 event_dispatch();
304 main_shutdown(&conf);
305 /* NOTREACHED */
306 return 0;
309 static int
310 main_configure(struct conf *conf)
312 struct privsep *ps = conf->ps;
314 conf->reload = conf->prefork;
316 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_START, NULL, 0) == -1)
317 return -1;
319 if (config_send(conf, fcgi, &hosts) == -1)
320 return -1;
322 if (proc_compose(ps, PROC_SERVER, IMSG_RECONF_END, NULL, 0) == -1)
323 return -1;
325 return 0;
328 static void
329 main_configure_done(struct conf *conf)
331 if (conf->reload == 0) {
332 log_warnx("configuration already done");
333 return;
336 conf->reload--;
337 /* send IMSG_CTL_START? */
340 static void
341 main_reload(struct conf *conf)
343 if (conf->reload) {
344 log_debug("%s: already in progress: %d pending",
345 __func__, conf->reload);
346 return;
349 log_debug("%s: config file %s", __func__, config_path);
350 config_free();
351 parse_conf(config_path); /* XXX should handle error here */
353 main_configure(conf);
356 static void
357 main_sig_handler(int sig, short ev, void *arg)
359 struct privsep *ps = arg;
361 /*
362 * Normal signal handler rules don't apply here because libevent
363 * decouples for us.
364 */
366 switch (sig) {
367 case SIGHUP:
368 if (privsep_process != PROC_PARENT)
369 return;
370 log_info("reload requested with SIGHUP");
371 main_reload(ps->ps_env);
372 break;
373 case SIGCHLD:
374 log_warnx("one child died, quitting");
375 /* fallthrough */
376 case SIGTERM:
377 case SIGINT:
378 main_shutdown(ps->ps_env);
379 break;
380 default:
381 fatalx("unexpected signal %d", sig);
385 static int
386 main_dispatch_server(int fd, struct privsep_proc *p, struct imsg *imsg)
388 struct privsep *ps = p->p_ps;
389 struct conf *conf = ps->ps_env;
391 switch (imsg->hdr.type) {
392 case IMSG_RECONF_DONE:
393 main_configure_done(conf);
394 break;
395 default:
396 return -1;
399 return 0;
402 static int
403 main_dispatch_logger(int fd, struct privsep_proc *p, struct imsg *imsg)
405 struct privsep *ps = p->p_ps;
406 struct conf *conf = ps->ps_env;
408 switch (imsg->hdr.type) {
409 case IMSG_RECONF_DONE:
410 main_configure_done(conf);
411 break;
412 default:
413 return -1;
416 return 0;
419 static void __dead
420 main_shutdown(struct conf *conf)
422 proc_kill(conf->ps);
423 config_free();
424 free(conf->ps);
425 /* free(conf); */
427 log_info("parent terminating, pid %d", getpid());
429 if (pidfd != -1)
430 close(pidfd);
432 exit(0);