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_quit(struct imsgbuf*, struct imsg*, size_t);
35 static void handle_dispatch_imsg(int, short, void*);
37 static imsg_handlerfn *handlers[] = {
38 [IMSG_FCGI_REQ] = handle_imsg_fcgi_req,
39 [IMSG_CGI_REQ] = handle_imsg_cgi_req,
40 [IMSG_QUIT] = handle_imsg_quit,
41 };
43 static inline void
44 safe_setenv(const char *name, const char *val)
45 {
46 if (val == NULL)
47 val = "";
48 setenv(name, val, 1);
49 }
51 static char *
52 xasprintf(const char *fmt, ...)
53 {
54 va_list ap;
55 char *s;
57 va_start(ap, fmt);
58 if (vasprintf(&s, fmt, ap) == -1)
59 s = NULL;
60 va_end(ap);
62 return s;
63 }
65 static void
66 do_exec(const char *ex, const char *spath, char *query)
67 {
68 char **argv, buf[PATH_MAX], *sname, *t;
69 size_t i, n;
71 /* restore the default handlers */
72 signal(SIGPIPE, SIG_DFL);
73 signal(SIGCHLD, SIG_DFL);
74 signal(SIGHUP, SIG_DFL);
75 signal(SIGINT, SIG_DFL);
76 signal(SIGTERM, SIG_DFL);
78 strlcpy(buf, spath, sizeof(buf));
79 sname = basename(buf);
81 if (query == NULL || strchr(query, '=') != NULL) {
82 if ((argv = calloc(2, sizeof(char*))) == NULL)
83 err(1, "calloc");
84 argv[0] = sname;
85 execvp(ex, argv);
86 warn("execvp: %s", argv[0]);
87 return;
88 }
90 n = 1;
91 for (t = query ;; t++, n++) {
92 if ((t = strchr(t, '+')) == NULL)
93 break;
94 }
96 if ((argv = calloc(n+2, sizeof(char*))) == NULL)
97 err(1, "calloc");
99 argv[0] = sname;
100 for (i = 0; i < n; ++i) {
101 t = strchr(query, '+');
102 if (t != NULL)
103 *t = '\0';
104 argv[i+1] = pct_decode_str(query);
105 query = t+1;
108 execvp(ex, argv);
109 warn("execvp: %s", argv[0]);
112 static inline void
113 setenv_time(const char *var, time_t t)
115 char timebuf[21];
116 struct tm tminfo;
118 if (t == -1)
119 return;
121 strftime(timebuf, sizeof(timebuf), "%FT%TZ",
122 gmtime_r(&t, &tminfo));
123 setenv(var, timebuf, 1);
126 /* fd or -1 on error */
127 static int
128 launch_cgi(struct iri *iri, struct cgireq *req, struct vhost *vhost,
129 struct location *loc)
131 int p[2], errp[2]; /* read end, write end */
133 if (pipe(p) == -1)
134 return -1;
135 if (pipe(errp) == -1)
136 return -1;
138 switch (fork()) {
139 case -1:
140 log_err(NULL, "fork failed: %s", strerror(errno));
141 close(p[0]);
142 close(p[1]);
143 close(errp[0]);
144 close(errp[1]);
145 return -1;
147 case 0: { /* child */
148 char *ex, *pwd;
149 char iribuf[GEMINI_URL_LEN];
150 char path[PATH_MAX];
151 struct envlist *e;
153 close(p[0]);
154 if (dup2(p[1], 1) == -1)
155 goto childerr;
157 close(errp[0]);
158 if (dup2(errp[1], 2) == -1)
159 goto childerr;
161 ex = xasprintf("%s/%s", loc->dir, req->spath);
163 serialize_iri(iri, iribuf, sizeof(iribuf));
165 safe_setenv("GATEWAY_INTERFACE", "CGI/1.1");
166 safe_setenv("GEMINI_DOCUMENT_ROOT", loc->dir);
167 safe_setenv("GEMINI_SCRIPT_FILENAME",
168 xasprintf("%s/%s", loc->dir, req->spath));
169 safe_setenv("GEMINI_URL", iribuf);
171 strlcpy(path, "/", sizeof(path));
172 strlcat(path, req->spath, sizeof(path));
173 safe_setenv("GEMINI_URL_PATH", path);
175 if (*req->relpath != '\0') {
176 strlcpy(path, "/", sizeof(path));
177 strlcat(path, req->relpath, sizeof(path));
178 safe_setenv("PATH_INFO", path);
180 strlcpy(path, loc->dir, sizeof(path));
181 strlcat(path, "/", sizeof(path));
182 strlcat(path, req->relpath, sizeof(path));
183 safe_setenv("PATH_TRANSLATED", path);
186 safe_setenv("QUERY_STRING", iri->query);
187 safe_setenv("REMOTE_ADDR", req->addr);
188 safe_setenv("REMOTE_HOST", req->addr);
189 safe_setenv("REQUEST_METHOD", "");
191 strlcpy(path, "/", sizeof(path));
192 strlcat(path, req->spath, sizeof(path));
193 safe_setenv("SCRIPT_NAME", path);
195 safe_setenv("SERVER_NAME", iri->host);
197 snprintf(path, sizeof(path), "%d", conf.port);
198 safe_setenv("SERVER_PORT", path);
200 safe_setenv("SERVER_PROTOCOL", "GEMINI");
201 safe_setenv("SERVER_SOFTWARE", GMID_VERSION);
203 if (*req->subject != '\0')
204 safe_setenv("AUTH_TYPE", "Certificate");
205 else
206 safe_setenv("AUTH_TYPE", "");
208 safe_setenv("REMOTE_USER", req->subject);
209 safe_setenv("TLS_CLIENT_ISSUER", req->issuer);
210 safe_setenv("TLS_CLIENT_HASH", req->hash);
211 safe_setenv("TLS_VERSION", req->version);
212 safe_setenv("TLS_CIPHER", req->cipher);
214 snprintf(path, sizeof(path), "%d", req->cipher_strength);
215 safe_setenv("TLS_CIPHER_STRENGTH", path);
217 setenv_time("TLS_CLIENT_NOT_AFTER", req->notafter);
218 setenv_time("TLS_CLIENT_NOT_BEFORE", req->notbefore);
220 TAILQ_FOREACH(e, &vhost->env, envs) {
221 safe_setenv(e->name, e->value);
224 strlcpy(path, ex, sizeof(path));
226 pwd = dirname(path);
227 if (chdir(pwd)) {
228 warn("chdir");
229 goto childerr;
232 do_exec(ex, req->spath, iri->query);
233 goto childerr;
236 default:
237 close(p[1]);
238 close(errp[0]);
239 close(errp[1]);
240 mark_nonblock(p[0]);
241 return p[0];
244 childerr:
245 dprintf(p[1], "%d internal server error\r\n", TEMP_FAILURE);
246 _exit(1);
249 static struct vhost *
250 host_nth(size_t n)
252 struct vhost *h;
254 TAILQ_FOREACH(h, &hosts, vhosts) {
255 if (n == 0)
256 return h;
257 n--;
260 return NULL;
263 static struct location *
264 loc_nth(struct vhost *vhost, size_t n)
266 struct location *loc;
268 TAILQ_FOREACH(loc, &vhost->locations, locations) {
269 if (n == 0)
270 return loc;
271 n--;
274 return NULL;
277 static void
278 handle_imsg_cgi_req(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
280 struct vhost *h;
281 struct location *l;
282 struct cgireq req;
283 struct iri iri;
284 int fd;
286 if (datalen != sizeof(req))
287 abort();
289 memcpy(&req, imsg->data, datalen);
291 iri.schema = req.iri_schema_off + req.buf;
292 iri.host = req.iri_host_off + req.buf;
293 iri.port = req.iri_port_off + req.buf;
294 iri.path = req.iri_path_off + req.buf;
295 iri.query = req.iri_query_off + req.buf;
296 iri.fragment = req.iri_fragment_off + req.buf;
298 /* patch the query, otherwise do_exec will always pass "" as
299 * first argument to the script. */
300 if (*iri.query == '\0')
301 iri.query = NULL;
303 if ((h = host_nth(req.host_off)) == NULL)
304 abort();
306 if ((l = loc_nth(h, req.loc_off)) == NULL)
307 abort();
309 fd = launch_cgi(&iri, &req, h, l);
310 imsg_compose(ibuf, IMSG_CGI_RES, imsg->hdr.peerid, 0, fd, NULL, 0);
311 imsg_flush(ibuf);
314 static int
315 fcgi_open_prog(struct fcgi *f)
317 int s[2];
318 pid_t p;
320 /* XXX! */
322 if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, s) == -1)
323 err(1, "socketpair");
325 switch (p = fork()) {
326 case -1:
327 err(1, "fork");
328 case 0:
329 close(s[0]);
330 if (dup2(s[1], 0) == -1)
331 err(1, "dup2");
332 execl(f->prog, f->prog, NULL);
333 err(1, "execl %s", f->prog);
334 default:
335 close(s[1]);
336 return s[0];
340 static int
341 fcgi_open_sock(struct fcgi *f)
343 struct sockaddr_un addr;
344 int fd;
346 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
347 log_err(NULL, "socket: %s", strerror(errno));
348 return -1;
351 memset(&addr, 0, sizeof(addr));
352 addr.sun_family = AF_UNIX;
353 strlcpy(addr.sun_path, f->path, sizeof(addr.sun_path));
355 if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
356 log_warn(NULL, "failed to connect to %s: %s", f->path,
357 strerror(errno));
358 close(fd);
359 return -1;
362 return fd;
365 static int
366 fcgi_open_conn(struct fcgi *f)
368 struct addrinfo hints, *servinfo, *p;
369 int r, sock;
371 memset(&hints, 0, sizeof(hints));
372 hints.ai_family = AF_UNSPEC;
373 hints.ai_socktype = SOCK_STREAM;
374 hints.ai_flags = AI_ADDRCONFIG;
376 if ((r = getaddrinfo(f->path, f->port, &hints, &servinfo)) != 0) {
377 log_warn(NULL, "getaddrinfo %s:%s: %s", f->path, f->port,
378 gai_strerror(r));
379 return -1;
382 for (p = servinfo; p != NULL; p = p->ai_next) {
383 sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
384 if (sock == -1)
385 continue;
386 if (connect(sock, p->ai_addr, p->ai_addrlen) == -1) {
387 close(sock);
388 continue;
390 break;
393 if (p == NULL) {
394 log_warn(NULL, "couldn't connect to %s:%s", f->path, f->port);
395 sock = -1;
398 freeaddrinfo(servinfo);
399 return sock;
402 static void
403 handle_imsg_fcgi_req(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
405 struct fcgi *f;
406 int id, fd;
408 if (datalen != sizeof(id))
409 abort();
410 memcpy(&id, imsg->data, datalen);
412 if (id > FCGI_MAX || (fcgi[id].path == NULL && fcgi[id].prog == NULL))
413 abort();
415 f = &fcgi[id];
416 if (f->prog != NULL)
417 fd = fcgi_open_prog(f);
418 else if (f->port != NULL)
419 fd = fcgi_open_conn(f);
420 else
421 fd = fcgi_open_sock(f);
423 imsg_compose(ibuf, IMSG_FCGI_FD, id, 0, fd, NULL, 0);
424 imsg_flush(ibuf);
427 static void
428 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t datalen)
430 int i;
432 (void)ibuf;
433 (void)imsg;
434 (void)datalen;
436 for (i = 0; i < conf.prefork; ++i) {
437 imsg_compose(&servibuf[i], IMSG_QUIT, 0, 0, -1, NULL, 0);
438 imsg_flush(&exibuf);
439 close(servibuf[i].fd);
442 event_loopbreak();
445 static void
446 handle_dispatch_imsg(int fd, short ev, void *d)
448 struct imsgbuf *ibuf = d;
449 dispatch_imsg(ibuf, handlers, sizeof(handlers));
452 int
453 executor_main(struct imsgbuf *ibuf)
455 struct event evs[PROC_MAX], imsgev;
456 int i;
458 event_init();
460 if (ibuf != NULL) {
461 event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST,
462 handle_dispatch_imsg, ibuf);
463 event_add(&imsgev, NULL);
466 for (i = 0; i < conf.prefork; ++i) {
467 event_set(&evs[i], servibuf[i].fd, EV_READ | EV_PERSIST,
468 handle_dispatch_imsg, &servibuf[i]);
469 event_add(&evs[i], NULL);
472 sandbox_executor_process();
474 event_dispatch();
476 return 1;