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  */
16 
17 #include "gmid.h"
18 
19 #include <sys/stat.h>
20 
21 #include <assert.h>
22 #include <errno.h>
23 #include <event.h>
24 #include <fcntl.h>
25 #include <fnmatch.h>
26 #include <limits.h>
27 #include <string.h>
28 
29 int shutting_down;
30 
31 struct client	 clients[MAX_USERS];
32 
33 static struct tls	*ctx;
34 
35 static struct event e4, e6, imsgev, siginfo, sigusr2;
36 static int has_ipv6, has_siginfo;
37 
38 int connected_clients;
39 
40 static inline int matches(const char*, const char*);
41 
42 static inline void yield_read(int, struct client*, statefn);
43 static inline void yield_write(int, struct client*, statefn);
44 
45 static int	 check_path(struct client*, const char*, int*);
46 static void	 open_file(struct client*);
47 static void	 check_for_cgi(struct client*);
48 static void	 handle_handshake(int, short, void*);
49 static const char *strip_path(const char*, int);
50 static void	 fmt_sbuf(const char*, struct client*, const char*);
51 static int	 apply_block_return(struct client*);
52 static int	 apply_require_ca(struct client*);
53 static void	 handle_open_conn(int, short, void*);
54 static void	 handle_start_reply(int, short, void*);
55 static size_t	 host_nth(struct vhost*);
56 static void	 start_cgi(const char*, const char*, struct client*);
57 static void	 open_dir(struct client*);
58 static void	 redirect_canonical_dir(struct client*);
59 static void	 enter_handle_dirlist(int, short, void*);
60 static void	 handle_dirlist(int, short, void*);
61 static int 	 read_next_dir_entry(struct client*);
62 static void	 send_directory_listing(int, short, void*);
63 static void	 handle_cgi_reply(int, short, void*);
64 static void	 handle_copy(int, short, void*);
65 static void	 do_accept(int, short, void*);
66 static void	 handle_imsg_cgi_res(struct imsgbuf*, struct imsg*, size_t);
67 static void	 handle_imsg_fcgi_fd(struct imsgbuf*, struct imsg*, size_t);
68 static void	 handle_imsg_quit(struct imsgbuf*, struct imsg*, size_t);
69 static void	 handle_siginfo(int, short, void*);
70 
71 static imsg_handlerfn *handlers[] = {
72 	[IMSG_QUIT] = handle_imsg_quit,
73 	[IMSG_CGI_RES] = handle_imsg_cgi_res,
74 	[IMSG_FCGI_FD] = handle_imsg_fcgi_fd,
75 };
76 
77 static inline int
matches(const char * pattern,const char * path)78 matches(const char *pattern, const char *path)
79 {
80 	if (*path == '/')
81 		path++;
82 	return !fnmatch(pattern, path, 0);
83 }
84 
85 static inline void
yield_read(int fd,struct client * c,statefn fn)86 yield_read(int fd, struct client *c, statefn fn)
87 {
88 	event_once(fd, EV_READ, fn, c, NULL);
89 }
90 
91 static inline void
yield_write(int fd,struct client * c,statefn fn)92 yield_write(int fd, struct client *c, statefn fn)
93 {
94 	event_once(fd, EV_WRITE, fn, c, NULL);
95 }
96 
97 const char *
vhost_lang(struct vhost * v,const char * path)98 vhost_lang(struct vhost *v, const char *path)
99 {
100 	struct location *loc;
101 
102 	if (v == NULL || path == NULL)
103 		return NULL;
104 
105 	loc = TAILQ_FIRST(&v->locations);
106 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
107 		if (loc->lang != NULL) {
108 			if (matches(loc->match, path))
109 				return loc->lang;
110 		}
111 	}
112 
113 	return TAILQ_FIRST(&v->locations)->lang;
114 }
115 
116 const char *
vhost_default_mime(struct vhost * v,const char * path)117 vhost_default_mime(struct vhost *v, const char *path)
118 {
119 	struct location *loc;
120 	const char *default_mime = "application/octet-stream";
121 
122 	if (v == NULL || path == NULL)
123 		return default_mime;
124 
125 	loc = TAILQ_FIRST(&v->locations);
126 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
127 		if (loc->default_mime != NULL) {
128 			if (matches(loc->match, path))
129 				return loc->default_mime;
130 		}
131 	}
132 
133 	loc = TAILQ_FIRST(&v->locations);
134 	if (loc->default_mime != NULL)
135 		return loc->default_mime;
136 	return default_mime;
137 }
138 
139 const char *
vhost_index(struct vhost * v,const char * path)140 vhost_index(struct vhost *v, const char *path)
141 {
142 	struct location *loc;
143 	const char *index = "index.gmi";
144 
145 	if (v == NULL || path == NULL)
146 		return index;
147 
148 	loc = TAILQ_FIRST(&v->locations);
149 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
150 		if (loc->index != NULL) {
151 			if (matches(loc->match, path))
152 				return loc->index;
153 		}
154 	}
155 
156 	loc = TAILQ_FIRST(&v->locations);
157 	if (loc->index != NULL)
158 		return loc->index;
159 	return index;
160 }
161 
162 int
vhost_auto_index(struct vhost * v,const char * path)163 vhost_auto_index(struct vhost *v, const char *path)
164 {
165 	struct location *loc;
166 
167 	if (v == NULL || path == NULL)
168 		return 0;
169 
170 	loc = TAILQ_FIRST(&v->locations);
171 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
172 		if (loc->auto_index != 0) {
173 			if (matches(loc->match, path))
174 				return loc->auto_index == 1;
175 		}
176 	}
177 
178 	loc = TAILQ_FIRST(&v->locations);
179 	return loc->auto_index == 1;
180 }
181 
182 int
vhost_block_return(struct vhost * v,const char * path,int * code,const char ** fmt)183 vhost_block_return(struct vhost *v, const char *path, int *code, const char **fmt)
184 {
185 	struct location *loc;
186 
187 	if (v == NULL || path == NULL)
188 		return 0;
189 
190 	loc = TAILQ_FIRST(&v->locations);
191 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
192 		if (loc->block_code != 0) {
193 			if (matches(loc->match, path)) {
194 				*code = loc->block_code;
195 				*fmt = loc->block_fmt;
196 				return 1;
197 			}
198 		}
199 	}
200 
201 	loc = TAILQ_FIRST(&v->locations);
202 	*code = loc->block_code;
203 	*fmt = loc->block_fmt;
204 	return loc->block_code != 0;
205 }
206 
207 int
vhost_fastcgi(struct vhost * v,const char * path)208 vhost_fastcgi(struct vhost *v, const char *path)
209 {
210 	struct location *loc;
211 
212 	if (v == NULL || path == NULL)
213 		return -1;
214 
215 	loc = TAILQ_FIRST(&v->locations);
216 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
217 		if (loc->fcgi != -1)
218 			if (matches(loc->match, path))
219 				return loc->fcgi;
220 	}
221 
222 	loc = TAILQ_FIRST(&v->locations);
223 	return loc->fcgi;
224 }
225 
226 int
vhost_dirfd(struct vhost * v,const char * path,size_t * retloc)227 vhost_dirfd(struct vhost *v, const char *path, size_t *retloc)
228 {
229 	struct location *loc;
230 	size_t		 l = 0;
231 
232 	if (v == NULL || path == NULL)
233 		return -1;
234 
235 	loc = TAILQ_FIRST(&v->locations);
236 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
237 		l++;
238 		if (loc->dirfd != -1)
239 			if (matches(loc->match, path)) {
240 				*retloc = l;
241 				return loc->dirfd;
242 			}
243 	}
244 
245 	*retloc = 0;
246 	loc = TAILQ_FIRST(&v->locations);
247 	return loc->dirfd;
248 }
249 
250 int
vhost_strip(struct vhost * v,const char * path)251 vhost_strip(struct vhost *v, const char *path)
252 {
253 	struct location *loc;
254 
255 	if (v == NULL || path == NULL)
256 		return 0;
257 
258 	loc = TAILQ_FIRST(&v->locations);
259 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
260 		if (loc->strip != 0) {
261 			if (matches(loc->match, path))
262 				return loc->strip;
263 		}
264 	}
265 
266 	loc = TAILQ_FIRST(&v->locations);
267 	return loc->strip;
268 }
269 
270 X509_STORE *
vhost_require_ca(struct vhost * v,const char * path)271 vhost_require_ca(struct vhost *v, const char *path)
272 {
273 	struct location *loc;
274 
275 	if (v == NULL || path == NULL)
276 		return NULL;
277 
278 	loc = TAILQ_FIRST(&v->locations);
279 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
280 		if (loc->reqca != NULL) {
281 			if (matches(loc->match, path))
282 				return loc->reqca;
283 		}
284 	}
285 
286 	loc = TAILQ_FIRST(&v->locations);
287 	return loc->reqca;
288 }
289 
290 int
vhost_disable_log(struct vhost * v,const char * path)291 vhost_disable_log(struct vhost *v, const char *path)
292 {
293 	struct location *loc;
294 
295 	if (v == NULL || path == NULL)
296 		return 0;
297 
298 	loc = TAILQ_FIRST(&v->locations);
299 	while ((loc = TAILQ_NEXT(loc, locations)) != NULL) {
300 		if (loc->disable_log && matches(loc->match, path))
301 				return 1;
302 	}
303 
304 	loc = TAILQ_FIRST(&v->locations);
305 	return loc->disable_log;
306 }
307 
308 static int
check_path(struct client * c,const char * path,int * fd)309 check_path(struct client *c, const char *path, int *fd)
310 {
311 	struct stat sb;
312 	const char *p;
313 	int dirfd, strip;
314 
315 	assert(path != NULL);
316 
317 	/*
318 	 * in send_dir we add an initial / (to be redirect-friendly),
319 	 * but here we want to skip it
320 	 */
321 	if (*path == '/')
322 		path++;
323 
324 	strip = vhost_strip(c->host, path);
325 	p = strip_path(path, strip);
326 
327 	if (*p == '/')
328 		p = p+1;
329 	if (*p == '\0')
330 		p = ".";
331 
332 	dirfd = vhost_dirfd(c->host, path, &c->loc);
333 	log_debug(c, "check_path: strip=%d path=%s original=%s",
334 	    strip, p, path);
335 	if (*fd == -1 && (*fd = openat(dirfd, p, O_RDONLY)) == -1)
336 		return FILE_MISSING;
337 
338 	if (fstat(*fd, &sb) == -1) {
339 		log_notice(c, "failed stat for %s: %s", path, strerror(errno));
340 		return FILE_MISSING;
341 	}
342 
343 	if (S_ISDIR(sb.st_mode))
344 		return FILE_DIRECTORY;
345 
346 	if (sb.st_mode & S_IXUSR)
347 		return FILE_EXECUTABLE;
348 
349 	return FILE_EXISTS;
350 }
351 
352 static void
open_file(struct client * c)353 open_file(struct client *c)
354 {
355 	switch (check_path(c, c->iri.path, &c->pfd)) {
356 	case FILE_EXECUTABLE:
357 		if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
358 			start_cgi(c->iri.path, "", c);
359 			return;
360 		}
361 
362 		/* fallthrough */
363 
364 	case FILE_EXISTS:
365 		c->next = handle_copy;
366 		start_reply(c, SUCCESS, mime(c->host, c->iri.path));
367 		return;
368 
369 	case FILE_DIRECTORY:
370 		open_dir(c);
371 		return;
372 
373 	case FILE_MISSING:
374 		if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
375 			check_for_cgi(c);
376 			return;
377 		}
378 		start_reply(c, NOT_FOUND, "not found");
379 		return;
380 
381 	default:
382 		/* unreachable */
383 		abort();
384 	}
385 }
386 
387 /*
388  * the inverse of this algorithm, i.e. starting from the start of the
389  * path + strlen(cgi), and checking if each component, should be
390  * faster.  But it's tedious to write.  This does the opposite: starts
391  * from the end and strip one component at a time, until either an
392  * executable is found or we emptied the path.
393  */
394 static void
check_for_cgi(struct client * c)395 check_for_cgi(struct client *c)
396 {
397 	char path[PATH_MAX];
398 	char *end;
399 
400 	strlcpy(path, c->iri.path, sizeof(path));
401 	end = strchr(path, '\0');
402 
403 	while (end > path) {
404 		/*
405 		 * go up one level.  UNIX paths are simple and POSIX
406 		 * dirname, with its ambiguities on if the given
407 		 * pointer is changed or not, gives me headaches.
408 		 */
409 		while (*end != '/' && end > path)
410 			end--;
411 
412 		if (end == path)
413 			break;
414 
415 		*end = '\0';
416 
417 		switch (check_path(c, path, &c->pfd)) {
418 		case FILE_EXECUTABLE:
419 			start_cgi(path, end+1, c);
420 			return;
421 		case FILE_MISSING:
422 			break;
423 		default:
424 			goto err;
425 		}
426 
427 		*end = '/';
428 		end--;
429 	}
430 
431 err:
432 	start_reply(c, NOT_FOUND, "not found");
433 	return;
434 }
435 
436 void
mark_nonblock(int fd)437 mark_nonblock(int fd)
438 {
439 	int flags;
440 
441 	if ((flags = fcntl(fd, F_GETFL)) == -1)
442 		fatal("fcntl(F_GETFL): %s", strerror(errno));
443 	if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
444 		fatal("fcntl(F_SETFL): %s", strerror(errno));
445 }
446 
447 static void
handle_handshake(int fd,short ev,void * d)448 handle_handshake(int fd, short ev, void *d)
449 {
450 	struct client *c = d;
451 	struct vhost *h;
452 	struct alist *a;
453 	const char *servname;
454 	const char *parse_err = "unknown error";
455 
456 	switch (tls_handshake(c->ctx)) {
457 	case 0:  /* success */
458 	case -1: /* already handshaked */
459 		break;
460 	case TLS_WANT_POLLIN:
461 		yield_read(fd, c, &handle_handshake);
462 		return;
463 	case TLS_WANT_POLLOUT:
464 		yield_write(fd, c, &handle_handshake);
465 		return;
466 	default:
467 		/* unreachable */
468 		abort();
469 	}
470 
471 	servname = tls_conn_servername(c->ctx);
472 	if (!puny_decode(servname, c->domain, sizeof(c->domain), &parse_err)) {
473 		log_info(c, "puny_decode: %s", parse_err);
474 		goto err;
475 	}
476 
477 	TAILQ_FOREACH(h, &hosts, vhosts) {
478 		if (matches(h->domain, c->domain))
479 			goto found;
480 		TAILQ_FOREACH(a, &h->aliases, aliases) {
481 			if (matches(a->alias, c->domain))
482 				goto found;
483 		}
484 	}
485 
486 found:
487 	log_debug(c, "handshake: SNI: \"%s\"; decoded: \"%s\"; matched: \"%s\"",
488 	    servname != NULL ? servname : "(null)",
489 	    c->domain,
490 	    h != NULL ? h->domain : "(null)");
491 
492 	if (h != NULL) {
493 		c->host = h;
494 		handle_open_conn(fd, ev, c);
495 		return;
496 	}
497 
498 err:
499 	if (servname != NULL)
500 		strlcpy(c->req, servname, sizeof(c->req));
501 	else
502 		strlcpy(c->req, "null", sizeof(c->req));
503 
504 	start_reply(c, BAD_REQUEST, "Wrong/malformed host or missing SNI");
505 }
506 
507 static const char *
strip_path(const char * path,int strip)508 strip_path(const char *path, int strip)
509 {
510 	char *t;
511 
512 	while (strip > 0) {
513 		if ((t = strchr(path, '/')) == NULL) {
514 			path = strchr(path, '\0');
515 			break;
516 		}
517 		path = t;
518 		strip--;
519 	}
520 
521 	return path;
522 }
523 
524 static void
fmt_sbuf(const char * fmt,struct client * c,const char * path)525 fmt_sbuf(const char *fmt, struct client *c, const char *path)
526 {
527 	size_t i;
528         char buf[32];
529 
530 	memset(buf, 0, sizeof(buf));
531 	for (i = 0; *fmt; ++fmt) {
532 		if (i == sizeof(buf)-1 || *fmt == '%') {
533 			strlcat(c->sbuf, buf, sizeof(c->sbuf));
534 			memset(buf, 0, sizeof(buf));
535 			i = 0;
536 		}
537 
538 		if (*fmt != '%') {
539 			buf[i++] = *fmt;
540 			continue;
541 		}
542 
543 		switch (*++fmt) {
544 		case '%':
545 			strlcat(c->sbuf, "%", sizeof(c->sbuf));
546 			break;
547 		case 'p':
548 			if (*path != '/')
549 				strlcat(c->sbuf, "/", sizeof(c->sbuf));
550 			strlcat(c->sbuf, path, sizeof(c->sbuf));
551 			break;
552 		case 'q':
553 			strlcat(c->sbuf, c->iri.query, sizeof(c->sbuf));
554 			break;
555 		case 'P':
556 			snprintf(buf, sizeof(buf), "%d", conf.port);
557 			strlcat(c->sbuf, buf, sizeof(c->sbuf));
558 			memset(buf, 0, sizeof(buf));
559 			break;
560 		case 'N':
561 			strlcat(c->sbuf, c->domain, sizeof(c->sbuf));
562 			break;
563 		default:
564 			fatal("%s: unknown fmt specifier %c",
565 			    __func__, *fmt);
566 		}
567 	}
568 
569 	if (i != 0)
570 		strlcat(c->sbuf, buf, sizeof(c->sbuf));
571 }
572 
573 /* 1 if a matching `block return' (and apply it), 0 otherwise */
574 static int
apply_block_return(struct client * c)575 apply_block_return(struct client *c)
576 {
577 	const char *fmt, *path;
578 	int code;
579 
580 	if (!vhost_block_return(c->host, c->iri.path, &code, &fmt))
581 		return 0;
582 
583 	path = strip_path(c->iri.path, vhost_strip(c->host, c->iri.path));
584 	fmt_sbuf(fmt, c, path);
585 
586 	start_reply(c, code, c->sbuf);
587 	return 1;
588 }
589 
590 /* 1 if matching `fcgi' (and apply it), 0 otherwise */
591 static int
apply_fastcgi(struct client * c)592 apply_fastcgi(struct client *c)
593 {
594 	int		 id;
595 	struct fcgi	*f;
596 
597 	if ((id = vhost_fastcgi(c->host, c->iri.path)) == -1)
598 		return 0;
599 
600 	switch ((f = &fcgi[id])->s) {
601 	case FCGI_OFF:
602 		f->s = FCGI_INFLIGHT;
603 		log_info(c, "opening fastcgi connection for (%s,%s,%s)",
604 		    f->path, f->port, f->prog);
605 		imsg_compose(&exibuf, IMSG_FCGI_REQ, 0, 0, -1,
606 		    &id, sizeof(id));
607 		imsg_flush(&exibuf);
608                 /* fallthrough */
609 	case FCGI_INFLIGHT:
610                 c->fcgi = id;
611 		break;
612 	case FCGI_READY:
613                 c->fcgi = id;
614 		send_fcgi_req(f, c);
615 		break;
616 	}
617 
618 	return 1;
619 }
620 
621 /* 1 if matching `require client ca' fails (and apply it), 0 otherwise */
622 static int
apply_require_ca(struct client * c)623 apply_require_ca(struct client *c)
624 {
625 	X509_STORE	*store;
626 	const uint8_t	*cert;
627 	size_t		 len;
628 
629 	if ((store = vhost_require_ca(c->host, c->iri.path)) == NULL)
630 		return 0;
631 
632 	if (!tls_peer_cert_provided(c->ctx)) {
633 		start_reply(c, CLIENT_CERT_REQ, "client certificate required");
634 		return 1;
635 	}
636 
637 	cert = tls_peer_cert_chain_pem(c->ctx, &len);
638 	if (!validate_against_ca(store, cert, len)) {
639 		start_reply(c, CERT_NOT_AUTH, "certificate not authorised");
640 		return 1;
641 	}
642 
643 	return 0;
644 }
645 
646 static void
handle_open_conn(int fd,short ev,void * d)647 handle_open_conn(int fd, short ev, void *d)
648 {
649 	struct client *c = d;
650 	const char *parse_err = "invalid request";
651 	char decoded[DOMAIN_NAME_LEN];
652 
653 	bzero(c->req, sizeof(c->req));
654 	bzero(&c->iri, sizeof(c->iri));
655 
656 	switch (tls_read(c->ctx, c->req, sizeof(c->req)-1)) {
657 	case -1:
658 		log_err(c, "tls_read: %s", tls_error(c->ctx));
659 		close_conn(fd, ev, c);
660 		return;
661 
662 	case TLS_WANT_POLLIN:
663 		yield_read(fd, c, &handle_open_conn);
664 		return;
665 
666 	case TLS_WANT_POLLOUT:
667 		yield_write(fd, c, &handle_open_conn);
668 		return;
669 	}
670 
671 	if (!trim_req_iri(c->req, &parse_err)
672 	    || !parse_iri(c->req, &c->iri, &parse_err)
673 	    || !puny_decode(c->iri.host, decoded, sizeof(decoded), &parse_err)) {
674 		log_info(c, "iri parse error: %s", parse_err);
675 		start_reply(c, BAD_REQUEST, "invalid request");
676 		return;
677 	}
678 
679 	if (c->iri.port_no != conf.port
680 	    || strcmp(c->iri.schema, "gemini")
681 	    || strcmp(decoded, c->domain)) {
682 		start_reply(c, PROXY_REFUSED, "won't proxy request");
683 		return;
684 	}
685 
686 	if (apply_require_ca(c))
687 		return;
688 
689 	if (apply_block_return(c))
690 		return;
691 
692 	if (apply_fastcgi(c))
693 		return;
694 
695 	if (c->host->entrypoint != NULL) {
696 		c->loc = 0;
697 		start_cgi(c->host->entrypoint, c->iri.path, c);
698 		return;
699 	}
700 
701 	open_file(c);
702 }
703 
704 void
start_reply(struct client * c,int code,const char * meta)705 start_reply(struct client *c, int code, const char *meta)
706 {
707 	c->code = code;
708 	c->meta = meta;
709 	handle_start_reply(c->fd, 0, c);
710 }
711 
712 static void
handle_start_reply(int fd,short ev,void * d)713 handle_start_reply(int fd, short ev, void *d)
714 {
715 	struct client *c = d;
716 	char buf[1030];		/* status + ' ' + max reply len + \r\n\0 */
717 	const char *lang;
718 	size_t len;
719 
720 	lang = vhost_lang(c->host, c->iri.path);
721 
722 	snprintf(buf, sizeof(buf), "%d ", c->code);
723 	strlcat(buf, c->meta, sizeof(buf));
724 	if (!strcmp(c->meta, "text/gemini") && lang != NULL) {
725 		strlcat(buf, "; lang=", sizeof(buf));
726 		strlcat(buf, lang, sizeof(buf));
727 	}
728 
729 	len = strlcat(buf, "\r\n", sizeof(buf));
730 	assert(len < sizeof(buf));
731 
732 	switch (tls_write(c->ctx, buf, len)) {
733 	case -1:
734 		close_conn(fd, ev, c);
735 		return;
736 	case TLS_WANT_POLLIN:
737 		yield_read(fd, c, &handle_start_reply);
738 		return;
739 	case TLS_WANT_POLLOUT:
740 		yield_write(fd, c, &handle_start_reply);
741 		return;
742 	}
743 
744 	if (!vhost_disable_log(c->host, c->iri.path))
745 		log_request(c, buf, sizeof(buf));
746 
747 	if (c->code != SUCCESS)
748 		close_conn(fd, ev, c);
749 	else
750 		c->next(fd, ev, c);
751 }
752 
753 static size_t
host_nth(struct vhost * h)754 host_nth(struct vhost *h)
755 {
756 	struct vhost	*v;
757 	size_t		 i = 0;
758 
759 	TAILQ_FOREACH(v, &hosts, vhosts) {
760 		if (v == h)
761 			return i;
762 		i++;
763 	}
764 
765 	abort();
766 }
767 
768 static void
start_cgi(const char * spath,const char * relpath,struct client * c)769 start_cgi(const char *spath, const char *relpath, struct client *c)
770 {
771 	char addr[NI_MAXHOST];
772 	const char *t;
773 	struct cgireq req;
774 	int e;
775 
776 	e = getnameinfo((struct sockaddr*)&c->addr, sizeof(c->addr),
777 	    addr, sizeof(addr),
778 	    NULL, 0,
779 	    NI_NUMERICHOST);
780 	if (e != 0)
781 		fatal("getnameinfo failed");
782 
783 	memset(&req, 0, sizeof(req));
784 
785 	memcpy(req.buf, c->req, sizeof(req.buf));
786 
787 	req.iri_schema_off = c->iri.schema - c->req;
788 	req.iri_host_off = c->iri.host - c->req;
789 	req.iri_port_off = c->iri.port - c->req;
790 	req.iri_path_off = c->iri.path - c->req;
791 	req.iri_query_off = c->iri.query - c->req;
792 	req.iri_fragment_off = c->iri.fragment - c->req;
793 
794 	req.iri_portno = c->iri.port_no;
795 
796 	strlcpy(req.spath, spath, sizeof(req.spath));
797 	strlcpy(req.relpath, relpath, sizeof(req.relpath));
798 	strlcpy(req.addr, addr, sizeof(req.addr));
799 
800 	if ((t = tls_peer_cert_subject(c->ctx)) != NULL)
801 		strlcpy(req.subject, t, sizeof(req.subject));
802 	if ((t = tls_peer_cert_issuer(c->ctx)) != NULL)
803 		strlcpy(req.issuer, t, sizeof(req.issuer));
804 	if ((t = tls_peer_cert_hash(c->ctx)) != NULL)
805 		strlcpy(req.hash, t, sizeof(req.hash));
806 	if ((t = tls_conn_version(c->ctx)) != NULL)
807 		strlcpy(req.version, t, sizeof(req.version));
808 	if ((t = tls_conn_cipher(c->ctx)) != NULL)
809 		strlcpy(req.cipher, t, sizeof(req.cipher));
810 
811 	req.cipher_strength = tls_conn_cipher_strength(c->ctx);
812 	req.notbefore = tls_peer_cert_notbefore(c->ctx);
813 	req.notafter = tls_peer_cert_notafter(c->ctx);
814 
815 	req.host_off = host_nth(c->host);
816 	req.loc_off = c->loc;
817 
818 	imsg_compose(&exibuf, IMSG_CGI_REQ, c->id, 0, -1, &req, sizeof(req));
819 	imsg_flush(&exibuf);
820 
821 	close(c->pfd);
822 }
823 
824 static void
open_dir(struct client * c)825 open_dir(struct client *c)
826 {
827 	size_t len;
828 	int dirfd, root;
829 	char *before_file;
830 
831 	root = !strcmp(c->iri.path, "/") || *c->iri.path == '\0';
832 
833 	len = strlen(c->iri.path);
834 	if (len > 0 && !ends_with(c->iri.path, "/")) {
835 		redirect_canonical_dir(c);
836 		return;
837 	}
838 
839 	strlcpy(c->sbuf, "/", sizeof(c->sbuf));
840 	strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
841 	if (!ends_with(c->sbuf, "/"))
842 		strlcat(c->sbuf, "/", sizeof(c->sbuf));
843 	before_file = strchr(c->sbuf, '\0');
844 	len = strlcat(c->sbuf, vhost_index(c->host, c->iri.path),
845 	    sizeof(c->sbuf));
846 	if (len >= sizeof(c->sbuf)) {
847 		start_reply(c, TEMP_FAILURE, "internal server error");
848 		return;
849 	}
850 
851 	c->iri.path = c->sbuf;
852 
853 	/* close later unless we have to generate the dir listing */
854 	dirfd = c->pfd;
855 	c->pfd = -1;
856 
857 	switch (check_path(c, c->iri.path, &c->pfd)) {
858 	case FILE_EXECUTABLE:
859 		if (c->host->cgi != NULL && matches(c->host->cgi, c->iri.path)) {
860 			start_cgi(c->iri.path, "", c);
861 			break;
862 		}
863 
864 		/* fallthrough */
865 
866 	case FILE_EXISTS:
867 		c->next = handle_copy;
868 		start_reply(c, SUCCESS, mime(c->host, c->iri.path));
869 		break;
870 
871 	case FILE_DIRECTORY:
872 		start_reply(c, TEMP_REDIRECT, c->sbuf);
873 		break;
874 
875 	case FILE_MISSING:
876 		*before_file = '\0';
877 
878 		if (!vhost_auto_index(c->host, c->iri.path)) {
879 			start_reply(c, NOT_FOUND, "not found");
880 			break;
881 		}
882 
883 		c->next = enter_handle_dirlist;
884 
885 		c->dirlen = scandir_fd(dirfd, &c->dir,
886 		    root ? select_non_dotdot : select_non_dot,
887 		    alphasort);
888 		if (c->dirlen == -1) {
889 			log_err(c, "scandir_fd(%d) (vhost:%s) %s: %s",
890 			    c->pfd, c->host->domain, c->iri.path, strerror(errno));
891 			start_reply(c, TEMP_FAILURE, "internal server error");
892 			return;
893 		}
894 		c->diroff = 0;
895 		c->off = 0;
896 
897                 start_reply(c, SUCCESS, "text/gemini");
898 		return;
899 
900 	default:
901 		/* unreachable */
902 		abort();
903 	}
904 
905 	close(dirfd);
906 }
907 
908 static void
redirect_canonical_dir(struct client * c)909 redirect_canonical_dir(struct client *c)
910 {
911 	size_t len;
912 
913 	strlcpy(c->sbuf, "/", sizeof(c->sbuf));
914 	strlcat(c->sbuf, c->iri.path, sizeof(c->sbuf));
915 	len = strlcat(c->sbuf, "/", sizeof(c->sbuf));
916 
917 	if (len >= sizeof(c->sbuf)) {
918 		start_reply(c, TEMP_FAILURE, "internal server error");
919 		return;
920 	}
921 
922 	start_reply(c, TEMP_REDIRECT, c->sbuf);
923 }
924 
925 static void
enter_handle_dirlist(int fd,short ev,void * d)926 enter_handle_dirlist(int fd, short ev, void *d)
927 {
928 	struct client *c = d;
929 	char b[PATH_MAX];
930 	size_t l;
931 
932 	strlcpy(b, c->iri.path, sizeof(b));
933 	l = snprintf(c->sbuf, sizeof(c->sbuf),
934 	    "# Index of %s\n\n", b);
935 	if (l >= sizeof(c->sbuf)) {
936 		/*
937 		 * This is impossible, given that we have enough space
938 		 * in c->sbuf to hold the ancilliary string plus the
939 		 * full path; but it wouldn't read nice without some
940 		 * error checking, and I'd like to avoid a strlen.
941 		 */
942 		close_conn(fd, ev, c);
943 		return;
944 	}
945 
946 	c->len = l;
947 	handle_dirlist(fd, ev, c);
948 }
949 
950 static void
handle_dirlist(int fd,short ev,void * d)951 handle_dirlist(int fd, short ev, void *d)
952 {
953 	struct client *c = d;
954 	ssize_t r;
955 
956 	while (c->len > 0) {
957 		switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
958 		case -1:
959 			close_conn(fd, ev, c);
960 			return;
961 		case TLS_WANT_POLLOUT:
962 			yield_read(fd, c, &handle_dirlist);
963 			return;
964 		case TLS_WANT_POLLIN:
965 			yield_write(fd, c, &handle_dirlist);
966 			return;
967 		default:
968 			c->off += r;
969 			c->len -= r;
970 		}
971 	}
972 
973 	send_directory_listing(fd, ev, c);
974 }
975 
976 static int
read_next_dir_entry(struct client * c)977 read_next_dir_entry(struct client *c)
978 {
979 	if (c->diroff == c->dirlen)
980 		return 0;
981 
982 	/* XXX: url escape */
983 	snprintf(c->sbuf, sizeof(c->sbuf), "=> %s\n",
984 	    c->dir[c->diroff]->d_name);
985 
986 	free(c->dir[c->diroff]);
987 	c->diroff++;
988 
989 	c->len = strlen(c->sbuf);
990 	c->off = 0;
991 	return 1;
992 }
993 
994 static void
send_directory_listing(int fd,short ev,void * d)995 send_directory_listing(int fd, short ev, void *d)
996 {
997 	struct client *c = d;
998 	ssize_t r;
999 
1000 	while (1) {
1001 		if (c->len == 0) {
1002 			if (!read_next_dir_entry(c))
1003 				goto end;
1004 		}
1005 
1006 		while (c->len > 0) {
1007 			switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1008 			case -1:
1009 				goto end;
1010 
1011 			case TLS_WANT_POLLOUT:
1012 				yield_read(fd, c, &send_directory_listing);
1013 				return;
1014 
1015 			case TLS_WANT_POLLIN:
1016 				yield_write(fd, c, &send_directory_listing);
1017 				return;
1018 
1019 			default:
1020 				c->off += r;
1021 				c->len -= r;
1022 				break;
1023 			}
1024 		}
1025 	}
1026 
1027 end:
1028 	close_conn(fd, ev, d);
1029 }
1030 
1031 /* accumulate the meta line from the cgi script. */
1032 static void
handle_cgi_reply(int fd,short ev,void * d)1033 handle_cgi_reply(int fd, short ev, void *d)
1034 {
1035 	struct client *c = d;
1036 	void	*buf, *e;
1037 	size_t	 len;
1038 	ssize_t	 r;
1039 
1040 
1041 	buf = c->sbuf + c->len;
1042 	len = sizeof(c->sbuf) - c->len;
1043 
1044 	r = read(c->pfd, buf, len);
1045 	if (r == 0 || r == -1) {
1046 		start_reply(c, CGI_ERROR, "CGI error");
1047 		return;
1048 	}
1049 
1050 	c->len += r;
1051 
1052 	/* TODO: error if the CGI script don't reply correctly */
1053 	e = strchr(c->sbuf, '\n');
1054 	if (e != NULL || c->len == sizeof(c->sbuf)) {
1055 		log_request(c, c->sbuf, c->len);
1056 
1057 		c->off = 0;
1058 		handle_copy(fd, ev, c);
1059 		return;
1060 	}
1061 
1062 	yield_read(fd, c, &handle_cgi_reply);
1063 }
1064 
1065 static void
handle_copy(int fd,short ev,void * d)1066 handle_copy(int fd, short ev, void *d)
1067 {
1068 	struct client *c = d;
1069 	ssize_t r;
1070 
1071 	while (1) {
1072 		while (c->len > 0) {
1073 			switch (r = tls_write(c->ctx, c->sbuf + c->off, c->len)) {
1074 			case -1:
1075 				goto end;
1076 
1077 			case TLS_WANT_POLLOUT:
1078 				yield_write(c->fd, c, &handle_copy);
1079 				return;
1080 
1081 			case TLS_WANT_POLLIN:
1082 				yield_read(c->fd, c, &handle_copy);
1083 				return;
1084 
1085 			default:
1086                                 c->off += r;
1087 				c->len -= r;
1088 				break;
1089 			}
1090 		}
1091 
1092 		switch (r = read(c->pfd, c->sbuf, sizeof(c->sbuf))) {
1093 		case 0:
1094 			goto end;
1095 		case -1:
1096 			if (errno == EAGAIN || errno == EWOULDBLOCK) {
1097 				yield_read(c->pfd, c, &handle_copy);
1098 				return;
1099 			}
1100 			goto end;
1101 		default:
1102 			c->len = r;
1103 			c->off = 0;
1104 		}
1105 	}
1106 
1107 end:
1108 	close_conn(c->fd, ev, d);
1109 }
1110 
1111 void
close_conn(int fd,short ev,void * d)1112 close_conn(int fd, short ev, void *d)
1113 {
1114 	struct client	*c = d;
1115 	struct mbuf	*mbuf;
1116 
1117 	switch (tls_close(c->ctx)) {
1118 	case TLS_WANT_POLLIN:
1119 		yield_read(c->fd, c, &close_conn);
1120 		return;
1121 	case TLS_WANT_POLLOUT:
1122 		yield_read(c->fd, c, &close_conn);
1123 		return;
1124 	}
1125 
1126 	connected_clients--;
1127 
1128 	while ((mbuf = TAILQ_FIRST(&c->mbufhead)) != NULL) {
1129 		TAILQ_REMOVE(&c->mbufhead, mbuf, mbufs);
1130 		free(mbuf);
1131 	}
1132 
1133 	tls_free(c->ctx);
1134 	c->ctx = NULL;
1135 
1136 	if (c->pfd != -1)
1137 		close(c->pfd);
1138 
1139 	if (c->dir != NULL)
1140 		free(c->dir);
1141 
1142 	close(c->fd);
1143 	c->fd = -1;
1144 }
1145 
1146 static void
do_accept(int sock,short et,void * d)1147 do_accept(int sock, short et, void *d)
1148 {
1149 	struct client *c;
1150 	struct sockaddr_storage addr;
1151 	struct sockaddr *saddr;
1152 	socklen_t len;
1153 	int i, fd;
1154 
1155 	(void)et;
1156 
1157 	saddr = (struct sockaddr*)&addr;
1158 	len = sizeof(addr);
1159 	if ((fd = accept(sock, saddr, &len)) == -1) {
1160 		if (errno == EWOULDBLOCK || errno == EAGAIN ||
1161 		    errno == ECONNABORTED)
1162 			return;
1163 		fatal("accept: %s", strerror(errno));
1164 	}
1165 
1166 	mark_nonblock(fd);
1167 
1168 	for (i = 0; i < MAX_USERS; ++i) {
1169 		c = &clients[i];
1170 		if (c->fd == -1) {
1171 			memset(c, 0, sizeof(*c));
1172 			c->id = i;
1173 			if (tls_accept_socket(ctx, &c->ctx, fd) == -1)
1174 				break; /* goodbye fd! */
1175 
1176 			c->fd = fd;
1177 			c->pfd = -1;
1178 			c->dir = NULL;
1179 			c->addr = addr;
1180 			c->fcgi = -1;
1181 
1182 			yield_read(fd, c, &handle_handshake);
1183 			connected_clients++;
1184 			return;
1185 		}
1186 	}
1187 
1188 	close(fd);
1189 }
1190 
1191 static struct client *
client_by_id(int id)1192 client_by_id(int id)
1193 {
1194 	if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1195 		fatal("in client_by_id: invalid id %d", id);
1196 	return &clients[id];
1197 }
1198 
1199 struct client *
try_client_by_id(int id)1200 try_client_by_id(int id)
1201 {
1202 	if ((size_t)id > sizeof(clients)/sizeof(clients[0]))
1203                 return NULL;
1204 	return &clients[id];
1205 }
1206 
1207 static void
handle_imsg_cgi_res(struct imsgbuf * ibuf,struct imsg * imsg,size_t len)1208 handle_imsg_cgi_res(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1209 {
1210 	struct client *c;
1211 
1212 	c = client_by_id(imsg->hdr.peerid);
1213 
1214 	if ((c->pfd = imsg->fd) == -1)
1215 		start_reply(c, TEMP_FAILURE, "internal server error");
1216 	else
1217 		yield_read(c->pfd, c, &handle_cgi_reply);
1218 }
1219 
1220 static void
handle_imsg_fcgi_fd(struct imsgbuf * ibuf,struct imsg * imsg,size_t len)1221 handle_imsg_fcgi_fd(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1222 {
1223 	struct client	*c;
1224 	struct fcgi	*f;
1225 	int		 i, id;
1226 
1227 	id = imsg->hdr.peerid;
1228 	f = &fcgi[id];
1229 
1230 	if ((f->fd = imsg->fd) != -1) {
1231 		f->s = FCGI_READY;
1232 		event_set(&f->e, imsg->fd, EV_READ | EV_PERSIST, &handle_fcgi,
1233 		    &fcgi[id]);
1234 		event_add(&f->e, NULL);
1235 	} else {
1236 		f->s = FCGI_OFF;
1237 	}
1238 
1239 	for (i = 0; i < MAX_USERS; ++i) {
1240 		c = &clients[i];
1241 		if (c->fd == -1)
1242 			continue;
1243 		if (c->fcgi != id)
1244 			continue;
1245 
1246 		if (f->fd == -1) {
1247 			c->fcgi = -1;
1248 			start_reply(c, TEMP_FAILURE, "internal server error");
1249 		} else
1250 			send_fcgi_req(f, c);
1251 	}
1252 }
1253 
1254 static void
handle_imsg_quit(struct imsgbuf * ibuf,struct imsg * imsg,size_t len)1255 handle_imsg_quit(struct imsgbuf *ibuf, struct imsg *imsg, size_t len)
1256 {
1257 	size_t i;
1258 
1259 	(void)imsg;
1260 	(void)len;
1261 
1262 	/*
1263 	 * don't call event_loopbreak since we want to finish to
1264 	 * handle the ongoing connections.
1265 	 */
1266 
1267 	shutting_down = 1;
1268 
1269 	event_del(&e4);
1270 	if (has_ipv6)
1271 		event_del(&e6);
1272 	if (has_siginfo)
1273 		signal_del(&siginfo);
1274 	event_del(&imsgev);
1275 	signal_del(&sigusr2);
1276 
1277 	for (i = 0; i < FCGI_MAX; ++i) {
1278 		if (fcgi[i].path == NULL && fcgi[i].prog == NULL)
1279 			break;
1280 
1281 		if (!event_pending(&fcgi[i].e, EV_READ, NULL) ||
1282 		    fcgi[i].pending != 0)
1283 			continue;
1284 
1285 		fcgi_close_backend(&fcgi[i]);
1286 	}
1287 }
1288 
1289 static void
handle_dispatch_imsg(int fd,short ev,void * d)1290 handle_dispatch_imsg(int fd, short ev, void *d)
1291 {
1292 	struct imsgbuf *ibuf = d;
1293 	dispatch_imsg(ibuf, handlers, sizeof(handlers));
1294 }
1295 
1296 static void
handle_siginfo(int fd,short ev,void * d)1297 handle_siginfo(int fd, short ev, void *d)
1298 {
1299 	(void)fd;
1300 	(void)ev;
1301 	(void)d;
1302 
1303 	log_info(NULL, "%d connected clients", connected_clients);
1304 }
1305 
1306 void
loop(struct tls * ctx_,int sock4,int sock6,struct imsgbuf * ibuf)1307 loop(struct tls *ctx_, int sock4, int sock6, struct imsgbuf *ibuf)
1308 {
1309 	size_t i;
1310 
1311 	ctx = ctx_;
1312 
1313 	event_init();
1314 
1315 	memset(&clients, 0, sizeof(clients));
1316 	for (i = 0; i < MAX_USERS; ++i)
1317 		clients[i].fd = -1;
1318 
1319 	event_set(&e4, sock4, EV_READ | EV_PERSIST, &do_accept, NULL);
1320 	event_add(&e4, NULL);
1321 
1322 	if (sock6 != -1) {
1323 		has_ipv6 = 1;
1324 		event_set(&e6, sock6, EV_READ | EV_PERSIST, &do_accept, NULL);
1325 		event_add(&e6, NULL);
1326 	}
1327 
1328 	event_set(&imsgev, ibuf->fd, EV_READ | EV_PERSIST, handle_dispatch_imsg, ibuf);
1329 	event_add(&imsgev, NULL);
1330 
1331 #ifdef SIGINFO
1332 	has_siginfo = 1;
1333 	signal_set(&siginfo, SIGINFO, &handle_siginfo, NULL);
1334 	signal_add(&siginfo, NULL);
1335 #endif
1336 	signal_set(&sigusr2, SIGUSR2, &handle_siginfo, NULL);
1337 	signal_add(&sigusr2, NULL);
1338 
1339 	sandbox_server_process();
1340 	event_dispatch();
1341 	_exit(0);
1342 }
1343