Blob


1 /*
2 * Copyright (c) 2021 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/un.h>
21 #include <err.h>
22 #include <errno.h>
24 #include <event.h>
25 #include <fcntl.h>
26 #include <libgen.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdarg.h>
30 #include <string.h>
32 static void handle_imsg_cgi_req(struct imsgbuf*, struct imsg*, size_t);
33 static void handle_imsg_fcgi_req(struct imsgbuf*, struct imsg*, size_t);
34 static void handle_imsg_conn_req(struct imsgbuf *, struct imsg *, size_t);
35 static void handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
36 static void handle_dispatch_imsg(int, short, void*);
38 static imsg_handlerfn *handlers[] = {
39 [IMSG_FCGI_REQ] = handle_imsg_fcgi_req,
40 [IMSG_CGI_REQ] = handle_imsg_cgi_req,
41 [IMSG_CONN_REQ] = handle_imsg_conn_req,
42 [IMSG_QUIT] = handle_imsg_quit,
43 };
45 static inline void
46 safe_setenv(const char *name, const char *val)
47 {
48 if (val == NULL)
49 val = "";
50 setenv(name, val, 1);
51 }
53 static char *
54 xasprintf(const char *fmt, ...)
55 {
56 va_list ap;
57 char *s;
59 va_start(ap, fmt);
60 if (vasprintf(&s, fmt, ap) == -1)
61 s = NULL;
62 va_end(ap);
64 return s;
65 }
67 static void
68 do_exec(const char *ex, const char *spath, char *query)
69 {
70 char **argv, buf[PATH_MAX], *sname, *t;
71 size_t i, n;
73 /* restore the default handlers */
74 signal(SIGPIPE, SIG_DFL);
75 signal(SIGCHLD, SIG_DFL);
76 signal(SIGHUP, SIG_DFL);
77 signal(SIGINT, SIG_DFL);
78 signal(SIGTERM, SIG_DFL);
80 strlcpy(buf, spath, sizeof(buf));
81 sname = basename(buf);
83 if (query == NULL || strchr(query, '=') != NULL) {
84 if ((argv = calloc(2, sizeof(char*))) == NULL)
85 err(1, "calloc");
86 argv[0] = sname;
87 execvp(ex, argv);
88 warn("execvp: %s", argv[0]);
89 return;
90 }
92 n = 1;
93 for (t = query ;; t++, n++) {
94 if ((t = strchr(t, '+')) == NULL)
95 break;
96 }
98 if ((argv = calloc(n+2, sizeof(char*))) == NULL)
99 err(1, "calloc");
101 argv[0] = sname;
102 for (i = 0; i < n; ++i) {
103 t = strchr(query, '+');
104 if (t != NULL)
105 *t = '\0';
106 argv[i+1] = pct_decode_str(query);
107 query = t+1;
110 execvp(ex, argv);
111 warn("execvp: %s", argv[0]);
114 static inline void
115 setenv_time(const char *var, time_t t)
117 char timebuf[21];
118 struct tm tminfo;
120 if (t == -1)
121 return;
123 strftime(timebuf, sizeof(timebuf), "%FT%TZ",
124 gmtime_r(&t, &tminfo));
125 setenv(var, timebuf, 1);
128 /* fd or -1 on error */
129 static int
130 launch_cgi(struct iri *iri, struct cgireq *req, struct vhost *vhost,
131 struct location *loc)
133 int p[2], errp[2]; /* read end, write end */
135 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, p) == -1)
136 return -1;
137 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, errp) == -1)
138 return -1;
140 switch (fork()) {
141 case -1:
142 log_err(NULL, "fork failed: %s", strerror(errno));
143 close(p[0]);
144 close(p[1]);
145 close(errp[0]);
146 close(errp[1]);
147 return -1;
149 case 0: { /* child */
150 char *ex, *pwd, *qs;
151 char iribuf[GEMINI_URL_LEN];
152 char path[PATH_MAX];
153 struct envlist *e;
155 close(p[0]);
156 if (dup2(p[1], 1) == -1)
157 goto childerr;
159 close(errp[0]);
160 if (dup2(errp[1], 2) == -1)
161 goto childerr;
163 ex = xasprintf("%s/%s", loc->dir, req->spath);
165 serialize_iri(iri, iribuf, sizeof(iribuf));
167 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
168 safe_setenv("GEMINI_DOCUMENT_ROOT", loc->dir);
169 safe_setenv("GEMINI_SCRIPT_FILENAME",
170 xasprintf("%s/%s", loc->dir, req->spath));
171 safe_setenv("GEMINI_URL", iribuf);
173 strlcpy(path, "/", sizeof(path));
174 strlcat(path, req->spath, sizeof(path));
175 safe_setenv("GEMINI_URL_PATH", path);
177 if (*req->relpath != '\0') {
178 strlcpy(path, "/", sizeof(path));
179 strlcat(path, req->relpath, sizeof(path));
180 safe_setenv("PATH_INFO", path);
182 strlcpy(path, loc->dir, sizeof(path));
183 strlcat(path, "/", sizeof(path));
184 strlcat(path, req->relpath, sizeof(path));
185 safe_setenv("PATH_TRANSLATED", path);
188 if (iri->query != NULL &&
189 strchr(iri->query, '=') == NULL &&
190 (qs = strdup(iri->query)) != NULL) {
191 pct_decode_str(qs);
192 safe_setenv("GEMINI_SEARCH_STRING", qs);
193 free(qs);
196 safe_setenv("QUERY_STRING", iri->query);
197 safe_setenv("REMOTE_ADDR", req->addr);
198 safe_setenv("REMOTE_HOST", req->addr);
199 safe_setenv("REQUEST_METHOD", "");
201 strlcpy(path, "/", sizeof(path));
202 strlcat(path, req->spath, sizeof(path));
203 safe_setenv("SCRIPT_NAME", path);
205 safe_setenv("SERVER_NAME", iri->host);
207 snprintf(path, sizeof(path), "%d", conf.port);
208 safe_setenv("SERVER_PORT", path);
210 safe_setenv("SERVER_PROTOCOL", "GEMINI");
211 safe_setenv("SERVER_SOFTWARE", GMID_VERSION);
213 if (*req->subject != '\0')
214 safe_setenv("AUTH_TYPE", "Certificate");
215 else
216 safe_setenv("AUTH_TYPE", "");
218 safe_setenv("REMOTE_USER", req->subject);
219 safe_setenv("TLS_CLIENT_ISSUER", req->issuer);
220 safe_setenv("TLS_CLIENT_HASH", req->hash);
221 safe_setenv("TLS_VERSION", req->version);
222 safe_setenv("TLS_CIPHER", req->cipher);
224 snprintf(path, sizeof(path), "%d", req->cipher_strength);
225 safe_setenv("TLS_CIPHER_STRENGTH", path);
227 setenv_time("TLS_CLIENT_NOT_AFTER", req->notafter);
228 setenv_time("TLS_CLIENT_NOT_BEFORE", req->notbefore);
230 TAILQ_FOREACH(e, &vhost->env, envs) {
231 safe_setenv(e->name, e->value);
234 strlcpy(path, ex, sizeof(path));
236 pwd = dirname(path);
237 if (chdir(pwd)) {
238 warn("chdir");
239 goto childerr;
242 do_exec(ex, req->spath, iri->query);
243 goto childerr;
246 default:
247 close(p[1]);
248 close(errp[0]);
249 close(errp[1]);
250 mark_nonblock(p[0]);
251 return p[0];
254 childerr:
255 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
256 _exit(1);
259 static struct vhost *
260 host_nth(size_t n)
262 struct vhost *h;
264 TAILQ_FOREACH(h, &hosts, vhosts) {
265 if (n == 0)
266 return h;
267 n--;
270 return NULL;
273 static struct location *
274 loc_nth(struct vhost *vhost, size_t n)
276 struct location *loc;
278 TAILQ_FOREACH(loc, &vhost->locations, locations) {
279 if (n == 0)
280 return loc;
281 n--;
284 return NULL;
287 static void
288 handle_imsg_cgi_req(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
290 struct vhost *h;
291 struct location *l;
292 struct cgireq req;
293 struct iri iri;
294 int fd;
296 if (datalen != sizeof(req))
297 abort();
299 memcpy(&req, imsg->data, sizeof(req));
301 iri.schema = req.iri_schema_off + req.buf;
302 iri.host = req.iri_host_off + req.buf;
303 iri.port = req.iri_port_off + req.buf;
304 iri.path = req.iri_path_off + req.buf;
305 iri.query = req.iri_query_off + req.buf;
306 iri.fragment = req.iri_fragment_off + req.buf;
308 /* patch the query, otherwise do_exec will always pass "" as
309 * first argument to the script. */
310 if (*iri.query == '\0')
311 iri.query = NULL;
313 if ((h = host_nth(req.host_off)) == NULL)
314 abort();
316 if ((l = loc_nth(h, req.loc_off)) == NULL)
317 abort();
319 fd = launch_cgi(&iri, &req, h, l);
320 imsg_compose(ibuf, IMSG_CGI_RES, imsg->hdr.peerid, 0, fd, NULL, 0);
321 imsg_flush(ibuf);
324 static int
325 fcgi_open_prog(struct fcgi *f)
327 int s[2];
328 pid_t p;
330 /* XXX! */
332 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, s) == -1)
333 err(1, "socketpair");
335 switch (p = fork()) {
336 case -1:
337 err(1, "fork");
338 case 0:
339 close(s[0]);
340 if (dup2(s[1], 0) == -1)
341 err(1, "dup2");
342 execl(f->prog, f->prog, NULL);
343 err(1, "execl %s", f->prog);
344 default:
345 close(s[1]);
346 return s[0];
350 static int
351 fcgi_open_sock(struct fcgi *f)
353 struct sockaddr_un addr;
354 int fd;
356 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
357 log_err(NULL, "socket: %s", strerror(errno));
358 return -1;
361 memset(&addr, 0, sizeof(addr));
362 addr.sun_family = AF_UNIX;
363 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
365 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
366 log_warn(NULL, "failed to connect to %s: %s", f->path,
367 strerror(errno));
368 close(fd);
369 return -1;
372 return fd;
375 static int
376 fcgi_open_conn(struct fcgi *f)
378 struct addrinfo hints, *servinfo, *p;
379 int r, sock;
381 memset(&hints, 0, sizeof(hints));
382 hints.ai_family = AF_UNSPEC;
383 hints.ai_socktype = SOCK_STREAM;
384 hints.ai_flags = AI_ADDRCONFIG;
386 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
387 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
388 gai_strerror(r));
389 return -1;
392 for (p = servinfo; p != NULL; p = p->ai_next) {
393 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
394 if (sock == -1)
395 continue;
396 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
397 close(sock);
398 continue;
400 break;
403 if (p == NULL) {
404 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
405 sock = -1;
408 freeaddrinfo(servinfo);
409 return sock;
412 static void
413 handle_imsg_fcgi_req(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
415 struct fcgi *f;
416 int id, fd;
418 if (datalen != sizeof(id))
419 abort();
420 memcpy(&id, imsg->data, sizeof(id));
422 if (id > FCGI_MAX || (fcgi[id].path == NULL && fcgi[id].prog == NULL))
423 abort();
425 f = &fcgi[id];
426 if (f->prog != NULL)
427 fd = fcgi_open_prog(f);
428 else if (f->port != NULL)
429 fd = fcgi_open_conn(f);
430 else
431 fd = fcgi_open_sock(f);
433 imsg_compose(ibuf, IMSG_FCGI_FD, imsg->hdr.peerid, 0, fd, NULL, 0);
434 imsg_flush(ibuf);
437 static void
438 handle_imsg_conn_req(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
440 struct addrinfo hints, *res, *res0;
441 struct connreq req;
442 int r, sock;
444 if (datalen != sizeof(req))
445 abort();
446 memcpy(&req, imsg->data, sizeof(req));
447 req.flag = 0;
449 memset(&hints, 0, sizeof(hints));
450 hints.ai_family = AF_UNSPEC;
451 hints.ai_socktype = SOCK_STREAM;
453 /* XXX: do this asynchronously if possible */
454 r = getaddrinfo(req.host, req.port, &hints, &res0);
455 if (r != 0) {
456 log_warn(NULL, "getaddrinfo(\"%s\", \"%s\"): %s",
457 req.host, req.port, gai_strerror(r));
458 goto err;
461 for (res = res0; res; res = res->ai_next) {
462 sock = socket(res->ai_family, res->ai_socktype,
463 res->ai_protocol);
464 if (sock == -1)
465 continue;
467 if (connect(sock, res->ai_addr, res->ai_addrlen) == -1) {
468 close(sock);
469 sock = -1;
470 continue;
473 break;
476 freeaddrinfo(res0);
478 if (sock == -1) {
479 log_warn(NULL, "can't connect to %s:%s", req.host,
480 req.port);
481 goto err;
484 imsg_compose(ibuf, IMSG_CONN_FD, imsg->hdr.peerid, 0, sock, NULL, 0);
485 imsg_flush(ibuf);
486 return;
488 err:
489 imsg_compose(ibuf, IMSG_CONN_FD, imsg->hdr.peerid, 0, -1, NULL, 0);
490 imsg_flush(ibuf);
493 static void
494 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
496 int i;
498 for (i = 0; i < conf.prefork; ++i) {
499 imsg_compose(&servibuf[i], IMSG_QUIT, 0, 0, -1, NULL, 0);
500 imsg_flush(&exibuf);
501 close(servibuf[i].fd);
504 event_loopbreak();
507 static void
508 handle_dispatch_imsg(int fd, short ev, void *d)
510 struct imsgbuf *ibuf = d;
511 dispatch_imsg(ibuf, handlers, sizeof(handlers));
514 int
515 executor_main(struct imsgbuf *ibuf)
517 struct event evs[PROC_MAX], imsgev;
518 int i;
520 event_init();
522 if (ibuf != NULL) {
523 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
524 handle_dispatch_imsg, ibuf);
525 event_add(&imsgev, NULL);
528 for (i = 0; i < conf.prefork; ++i) {
529 event_set(&evs[i], servibuf[i].fd, EV_READ | EV_PERSIST,
530 handle_dispatch_imsg, &servibuf[i]);
531 event_add(&evs[i], NULL);
534 sandbox_executor_process();
536 event_dispatch();
538 return 1;