xref: /openbsd-src/usr.sbin/httpd/server_http.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /*	$OpenBSD: server_http.c,v 1.150 2022/03/02 11:10:43 florian Exp $	*/
2 
3 /*
4  * Copyright (c) 2020 Matthias Pressfreund <mpfr@fn.de>
5  * Copyright (c) 2006 - 2018 Reyk Floeter <reyk@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/types.h>
21 #include <sys/queue.h>
22 #include <sys/socket.h>
23 #include <sys/tree.h>
24 #include <sys/stat.h>
25 
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 
29 #include <errno.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <limits.h>
34 #include <fnmatch.h>
35 #include <stdio.h>
36 #include <time.h>
37 #include <resolv.h>
38 #include <event.h>
39 #include <ctype.h>
40 #include <vis.h>
41 #include <fcntl.h>
42 
43 #include "httpd.h"
44 #include "http.h"
45 #include "patterns.h"
46 
47 static int	 server_httpmethod_cmp(const void *, const void *);
48 static int	 server_httperror_cmp(const void *, const void *);
49 void		 server_httpdesc_free(struct http_descriptor *);
50 int		 server_http_authenticate(struct server_config *,
51 		    struct client *);
52 static int	 http_version_num(char *);
53 char		*server_expand_http(struct client *, const char *,
54 		    char *, size_t);
55 char		*replace_var(char *, const char *, const char *);
56 char		*read_errdoc(const char *, const char *);
57 
58 static struct http_method	 http_methods[] = HTTP_METHODS;
59 static struct http_error	 http_errors[] = HTTP_ERRORS;
60 
61 void
62 server_http(void)
63 {
64 	DPRINTF("%s: sorting lookup tables, pid %d", __func__, getpid());
65 
66 	/* Sort the HTTP lookup arrays */
67 	qsort(http_methods, sizeof(http_methods) /
68 	    sizeof(http_methods[0]) - 1,
69 	    sizeof(http_methods[0]), server_httpmethod_cmp);
70 	qsort(http_errors, sizeof(http_errors) /
71 	    sizeof(http_errors[0]) - 1,
72 	    sizeof(http_errors[0]), server_httperror_cmp);
73 }
74 
75 void
76 server_http_init(struct server *srv)
77 {
78 	/* nothing */
79 }
80 
81 int
82 server_httpdesc_init(struct client *clt)
83 {
84 	struct http_descriptor	*desc;
85 
86 	if ((desc = calloc(1, sizeof(*desc))) == NULL)
87 		return (-1);
88 	RB_INIT(&desc->http_headers);
89 	clt->clt_descreq = desc;
90 
91 	if ((desc = calloc(1, sizeof(*desc))) == NULL) {
92 		/* req will be cleaned up later */
93 		return (-1);
94 	}
95 	RB_INIT(&desc->http_headers);
96 	clt->clt_descresp = desc;
97 
98 	return (0);
99 }
100 
101 void
102 server_httpdesc_free(struct http_descriptor *desc)
103 {
104 	if (desc == NULL)
105 		return;
106 
107 	free(desc->http_path);
108 	desc->http_path = NULL;
109 	free(desc->http_path_orig);
110 	desc->http_path_orig = NULL;
111 	free(desc->http_path_alias);
112 	desc->http_path_alias = NULL;
113 	free(desc->http_query);
114 	desc->http_query = NULL;
115 	free(desc->http_query_alias);
116 	desc->http_query_alias = NULL;
117 	free(desc->http_version);
118 	desc->http_version = NULL;
119 	free(desc->http_host);
120 	desc->http_host = NULL;
121 
122 	kv_purge(&desc->http_headers);
123 	desc->http_lastheader = NULL;
124 	desc->http_method = 0;
125 	desc->http_chunked = 0;
126 }
127 
128 int
129 server_http_authenticate(struct server_config *srv_conf, struct client *clt)
130 {
131 	char			 decoded[1024];
132 	FILE			*fp = NULL;
133 	struct http_descriptor	*desc = clt->clt_descreq;
134 	const struct auth	*auth = srv_conf->auth;
135 	struct kv		*ba, key;
136 	size_t			 linesize = 0;
137 	ssize_t			 linelen;
138 	int			 ret = -1;
139 	char			*line = NULL, *user = NULL, *pass = NULL;
140 	char			*clt_user = NULL, *clt_pass = NULL;
141 
142 	memset(decoded, 0, sizeof(decoded));
143 	key.kv_key = "Authorization";
144 
145 	if ((ba = kv_find(&desc->http_headers, &key)) == NULL ||
146 	    ba->kv_value == NULL)
147 		goto done;
148 
149 	if (strncmp(ba->kv_value, "Basic ", strlen("Basic ")) != 0)
150 		goto done;
151 
152 	if (b64_pton(strchr(ba->kv_value, ' ') + 1, (uint8_t *)decoded,
153 	    sizeof(decoded)) <= 0)
154 		goto done;
155 
156 	if ((clt_pass = strchr(decoded, ':')) == NULL)
157 		goto done;
158 
159 	clt_user = decoded;
160 	*clt_pass++ = '\0';
161 	if ((clt->clt_remote_user = strdup(clt_user)) == NULL)
162 		goto done;
163 
164 	if ((fp = fopen(auth->auth_htpasswd, "r")) == NULL)
165 		goto done;
166 
167 	while ((linelen = getline(&line, &linesize, fp)) != -1) {
168 		if (line[linelen - 1] == '\n')
169 			line[linelen - 1] = '\0';
170 		user = line;
171 		pass = strchr(line, ':');
172 
173 		if (pass == NULL) {
174 			explicit_bzero(line, linelen);
175 			continue;
176 		}
177 
178 		*pass++ = '\0';
179 
180 		if (strcmp(clt_user, user) != 0) {
181 			explicit_bzero(line, linelen);
182 			continue;
183 		}
184 
185 		if (crypt_checkpass(clt_pass, pass) == 0) {
186 			explicit_bzero(line, linelen);
187 			ret = 0;
188 			break;
189 		}
190 	}
191 done:
192 	free(line);
193 	if (fp != NULL)
194 		fclose(fp);
195 
196 	if (ba != NULL && ba->kv_value != NULL) {
197 		explicit_bzero(ba->kv_value, strlen(ba->kv_value));
198 		explicit_bzero(decoded, sizeof(decoded));
199 	}
200 
201 	return (ret);
202 }
203 
204 static int
205 http_version_num(char *version)
206 {
207 	if (strlen(version) != 8 || strncmp(version, "HTTP/", 5) != 0
208 	    || !isdigit((unsigned char)version[5]) || version[6] != '.'
209 	    || !isdigit((unsigned char)version[7]))
210 		return (-1);
211 	if (version[5] == '0' && version[7] == '9')
212 		return (9);
213 	if (version[5] == '1') {
214 		if (version[7] == '0')
215 			return (10);
216 		else
217 			/* any other version 1.x gets downgraded to 1.1 */
218 			return (11);
219 	}
220 	return (0);
221 }
222 
223 void
224 server_read_http(struct bufferevent *bev, void *arg)
225 {
226 	struct client		*clt = arg;
227 	struct http_descriptor	*desc = clt->clt_descreq;
228 	struct evbuffer		*src = EVBUFFER_INPUT(bev);
229 	char			*line = NULL, *key, *value;
230 	const char		*errstr;
231 	char			*http_version, *query;
232 	size_t			 size, linelen;
233 	int			 version;
234 	struct kv		*hdr = NULL;
235 
236 	getmonotime(&clt->clt_tv_last);
237 
238 	size = EVBUFFER_LENGTH(src);
239 	DPRINTF("%s: session %d: size %lu, to read %lld",
240 	    __func__, clt->clt_id, size, clt->clt_toread);
241 	if (!size) {
242 		clt->clt_toread = TOREAD_HTTP_HEADER;
243 		goto done;
244 	}
245 
246 	while (!clt->clt_headersdone) {
247 		if (!clt->clt_line) {
248 			/* Peek into the buffer to see if it looks like HTTP */
249 			key = EVBUFFER_DATA(src);
250 			if (!isalpha((unsigned char)*key)) {
251 				server_abort_http(clt, 400,
252 				    "invalid request line");
253 				goto abort;
254 			}
255 		}
256 
257 		if ((line = evbuffer_readln(src,
258 		    &linelen, EVBUFFER_EOL_CRLF_STRICT)) == NULL) {
259 			/* No newline found after too many bytes */
260 			if (size > SERVER_MAXHEADERLENGTH) {
261 				server_abort_http(clt, 413,
262 				    "request line too long");
263 				goto abort;
264 			}
265 			break;
266 		}
267 
268 		/*
269 		 * An empty line indicates the end of the request.
270 		 * libevent already stripped the \r\n for us.
271 		 */
272 		if (!linelen) {
273 			clt->clt_headersdone = 1;
274 			free(line);
275 			break;
276 		}
277 		key = line;
278 
279 		/* Limit the total header length minus \r\n */
280 		clt->clt_headerlen += linelen;
281 		if (clt->clt_headerlen > SERVER_MAXHEADERLENGTH) {
282 			server_abort_http(clt, 413, "request too large");
283 			goto abort;
284 		}
285 
286 		/*
287 		 * The first line is the GET/POST/PUT/... request,
288 		 * subsequent lines are HTTP headers.
289 		 */
290 		if (++clt->clt_line == 1)
291 			value = strchr(key, ' ');
292 		else if (*key == ' ' || *key == '\t')
293 			/* Multiline headers wrap with a space or tab */
294 			value = NULL;
295 		else {
296 			/* Not a multiline header, should have a : */
297 			value = strchr(key, ':');
298 			if (value == NULL) {
299 				server_abort_http(clt, 400, "malformed");
300 				goto abort;
301 			}
302 		}
303 		if (value == NULL) {
304 			if (clt->clt_line == 1) {
305 				server_abort_http(clt, 400, "malformed");
306 				goto abort;
307 			}
308 
309 			/* Append line to the last header, if present */
310 			if (kv_extend(&desc->http_headers,
311 			    desc->http_lastheader, line) == NULL)
312 				goto fail;
313 
314 			free(line);
315 			continue;
316 		}
317 		if (*value == ':') {
318 			*value++ = '\0';
319 			value += strspn(value, " \t\r\n");
320 		} else {
321 			*value++ = '\0';
322 		}
323 
324 		DPRINTF("%s: session %d: header '%s: %s'", __func__,
325 		    clt->clt_id, key, value);
326 
327 		/*
328 		 * Identify and handle specific HTTP request methods
329 		 */
330 		if (clt->clt_line == 1) {
331 			if ((desc->http_method = server_httpmethod_byname(key))
332 			    == HTTP_METHOD_NONE) {
333 				server_abort_http(clt, 400, "malformed");
334 				goto abort;
335 			}
336 
337 			/*
338 			 * Decode request path and query
339 			 */
340 			desc->http_path = strdup(value);
341 			if (desc->http_path == NULL)
342 				goto fail;
343 
344 			http_version = strchr(desc->http_path, ' ');
345 			if (http_version == NULL) {
346 				server_abort_http(clt, 400, "malformed");
347 				goto abort;
348 			}
349 
350 			*http_version++ = '\0';
351 
352 			/*
353 			 * We have to allocate the strings because they could
354 			 * be changed independently by the filters later.
355 			 * Allow HTTP version 0.9 to 1.1.
356 			 * Downgrade http version > 1.1 <= 1.9 to version 1.1.
357 			 * Return HTTP Version Not Supported for anything else.
358 			 */
359 
360 			version = http_version_num(http_version);
361 
362 			if (version == -1) {
363 				server_abort_http(clt, 400, "malformed");
364 				goto abort;
365 			} else if (version == 0) {
366 				server_abort_http(clt, 505, "bad http version");
367 				goto abort;
368 			} else if (version == 11) {
369 				if ((desc->http_version =
370 				    strdup("HTTP/1.1")) == NULL)
371 					goto fail;
372 			} else {
373 				if ((desc->http_version =
374 				    strdup(http_version)) == NULL)
375 					goto fail;
376 			}
377 
378 			query = strchr(desc->http_path, '?');
379 			if (query != NULL) {
380 				*query++ = '\0';
381 
382 				if ((desc->http_query = strdup(query)) == NULL)
383 					goto fail;
384 			}
385 
386 		} else if (desc->http_method != HTTP_METHOD_NONE &&
387 		    strcasecmp("Content-Length", key) == 0) {
388 			if (desc->http_method == HTTP_METHOD_TRACE ||
389 			    desc->http_method == HTTP_METHOD_CONNECT) {
390 				/*
391 				 * These method should not have a body
392 				 * and thus no Content-Length header.
393 				 */
394 				server_abort_http(clt, 400, "malformed");
395 				goto abort;
396 			}
397 
398 			/*
399 			 * Need to read data from the client after the
400 			 * HTTP header.
401 			 * XXX What about non-standard clients not using
402 			 * the carriage return? And some browsers seem to
403 			 * include the line length in the content-length.
404 			 */
405 			clt->clt_toread = strtonum(value, 0, LLONG_MAX,
406 			    &errstr);
407 			if (errstr) {
408 				server_abort_http(clt, 500, errstr);
409 				goto abort;
410 			}
411 		}
412 
413 		if (strcasecmp("Transfer-Encoding", key) == 0 &&
414 		    strcasecmp("chunked", value) == 0)
415 			desc->http_chunked = 1;
416 
417 		if (clt->clt_line != 1) {
418 			if ((hdr = kv_add(&desc->http_headers, key,
419 			    value)) == NULL)
420 				goto fail;
421 
422 			desc->http_lastheader = hdr;
423 		}
424 
425 		free(line);
426 	}
427 	if (clt->clt_headersdone) {
428 		if (desc->http_method == HTTP_METHOD_NONE) {
429 			server_abort_http(clt, 406, "no method");
430 			return;
431 		}
432 
433 		switch (desc->http_method) {
434 		case HTTP_METHOD_CONNECT:
435 			/* Data stream */
436 			clt->clt_toread = TOREAD_UNLIMITED;
437 			bev->readcb = server_read;
438 			break;
439 		case HTTP_METHOD_GET:
440 		case HTTP_METHOD_HEAD:
441 		/* WebDAV methods */
442 		case HTTP_METHOD_COPY:
443 		case HTTP_METHOD_MOVE:
444 			clt->clt_toread = 0;
445 			break;
446 		case HTTP_METHOD_DELETE:
447 		case HTTP_METHOD_OPTIONS:
448 		case HTTP_METHOD_POST:
449 		case HTTP_METHOD_PUT:
450 		case HTTP_METHOD_RESPONSE:
451 		/* WebDAV methods */
452 		case HTTP_METHOD_PROPFIND:
453 		case HTTP_METHOD_PROPPATCH:
454 		case HTTP_METHOD_MKCOL:
455 		case HTTP_METHOD_LOCK:
456 		case HTTP_METHOD_UNLOCK:
457 		case HTTP_METHOD_VERSION_CONTROL:
458 		case HTTP_METHOD_REPORT:
459 		case HTTP_METHOD_CHECKOUT:
460 		case HTTP_METHOD_CHECKIN:
461 		case HTTP_METHOD_UNCHECKOUT:
462 		case HTTP_METHOD_MKWORKSPACE:
463 		case HTTP_METHOD_UPDATE:
464 		case HTTP_METHOD_LABEL:
465 		case HTTP_METHOD_MERGE:
466 		case HTTP_METHOD_BASELINE_CONTROL:
467 		case HTTP_METHOD_MKACTIVITY:
468 		case HTTP_METHOD_ORDERPATCH:
469 		case HTTP_METHOD_ACL:
470 		case HTTP_METHOD_MKREDIRECTREF:
471 		case HTTP_METHOD_UPDATEREDIRECTREF:
472 		case HTTP_METHOD_SEARCH:
473 		case HTTP_METHOD_PATCH:
474 			/* HTTP request payload */
475 			if (clt->clt_toread > 0)
476 				bev->readcb = server_read_httpcontent;
477 
478 			/* Single-pass HTTP body */
479 			if (clt->clt_toread < 0) {
480 				clt->clt_toread = TOREAD_UNLIMITED;
481 				bev->readcb = server_read;
482 			}
483 			break;
484 		default:
485 			server_abort_http(clt, 405, "method not allowed");
486 			return;
487 		}
488 		if (desc->http_chunked) {
489 			/* Chunked transfer encoding */
490 			clt->clt_toread = TOREAD_HTTP_CHUNK_LENGTH;
491 			bev->readcb = server_read_httpchunks;
492 		}
493 
494  done:
495 		if (clt->clt_toread != 0)
496 			bufferevent_disable(bev, EV_READ);
497 		server_response(httpd_env, clt);
498 		return;
499 	}
500 	if (clt->clt_done) {
501 		server_close(clt, "done");
502 		return;
503 	}
504 	if (EVBUFFER_LENGTH(src) && bev->readcb != server_read_http)
505 		bev->readcb(bev, arg);
506 	bufferevent_enable(bev, EV_READ);
507 	return;
508  fail:
509 	server_abort_http(clt, 500, strerror(errno));
510  abort:
511 	free(line);
512 }
513 
514 void
515 server_read_httpcontent(struct bufferevent *bev, void *arg)
516 {
517 	struct client		*clt = arg;
518 	struct evbuffer		*src = EVBUFFER_INPUT(bev);
519 	size_t			 size;
520 
521 	getmonotime(&clt->clt_tv_last);
522 
523 	size = EVBUFFER_LENGTH(src);
524 	DPRINTF("%s: session %d: size %lu, to read %lld", __func__,
525 	    clt->clt_id, size, clt->clt_toread);
526 	if (!size)
527 		return;
528 
529 	if (clt->clt_toread > 0) {
530 		/* Read content data */
531 		if ((off_t)size > clt->clt_toread) {
532 			size = clt->clt_toread;
533 			if (fcgi_add_stdin(clt, src) == -1)
534 				goto fail;
535 			clt->clt_toread = 0;
536 		} else {
537 			if (fcgi_add_stdin(clt, src) == -1)
538 				goto fail;
539 			clt->clt_toread -= size;
540 		}
541 		DPRINTF("%s: done, size %lu, to read %lld", __func__,
542 		    size, clt->clt_toread);
543 	}
544 	if (clt->clt_toread == 0) {
545 		fcgi_add_stdin(clt, NULL);
546 		clt->clt_toread = TOREAD_HTTP_HEADER;
547 		bufferevent_disable(bev, EV_READ);
548 		bev->readcb = server_read_http;
549 		return;
550 	}
551 	if (clt->clt_done)
552 		goto done;
553 	if (bev->readcb != server_read_httpcontent)
554 		bev->readcb(bev, arg);
555 
556 	return;
557  done:
558 	return;
559  fail:
560 	server_close(clt, strerror(errno));
561 }
562 
563 void
564 server_read_httpchunks(struct bufferevent *bev, void *arg)
565 {
566 	struct client		*clt = arg;
567 	struct evbuffer		*src = EVBUFFER_INPUT(bev);
568 	char			*line;
569 	long long		 llval;
570 	size_t			 size;
571 
572 	getmonotime(&clt->clt_tv_last);
573 
574 	size = EVBUFFER_LENGTH(src);
575 	DPRINTF("%s: session %d: size %lu, to read %lld", __func__,
576 	    clt->clt_id, size, clt->clt_toread);
577 	if (!size)
578 		return;
579 
580 	if (clt->clt_toread > 0) {
581 		/* Read chunk data */
582 		if ((off_t)size > clt->clt_toread) {
583 			size = clt->clt_toread;
584 			if (server_bufferevent_write_chunk(clt, src, size)
585 			    == -1)
586 				goto fail;
587 			clt->clt_toread = 0;
588 		} else {
589 			if (server_bufferevent_write_buffer(clt, src) == -1)
590 				goto fail;
591 			clt->clt_toread -= size;
592 		}
593 		DPRINTF("%s: done, size %lu, to read %lld", __func__,
594 		    size, clt->clt_toread);
595 	}
596 	switch (clt->clt_toread) {
597 	case TOREAD_HTTP_CHUNK_LENGTH:
598 		line = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF_STRICT);
599 		if (line == NULL) {
600 			/* Ignore empty line, continue */
601 			bufferevent_enable(bev, EV_READ);
602 			return;
603 		}
604 		if (strlen(line) == 0) {
605 			free(line);
606 			goto next;
607 		}
608 
609 		/*
610 		 * Read prepended chunk size in hex, ignore the trailer.
611 		 * The returned signed value must not be negative.
612 		 */
613 		if (sscanf(line, "%llx", &llval) != 1 || llval < 0) {
614 			free(line);
615 			server_close(clt, "invalid chunk size");
616 			return;
617 		}
618 
619 		if (server_bufferevent_print(clt, line) == -1 ||
620 		    server_bufferevent_print(clt, "\r\n") == -1) {
621 			free(line);
622 			goto fail;
623 		}
624 		free(line);
625 
626 		if ((clt->clt_toread = llval) == 0) {
627 			DPRINTF("%s: last chunk", __func__);
628 			clt->clt_toread = TOREAD_HTTP_CHUNK_TRAILER;
629 		}
630 		break;
631 	case TOREAD_HTTP_CHUNK_TRAILER:
632 		/* Last chunk is 0 bytes followed by trailer and empty line */
633 		line = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF_STRICT);
634 		if (line == NULL) {
635 			/* Ignore empty line, continue */
636 			bufferevent_enable(bev, EV_READ);
637 			return;
638 		}
639 		if (server_bufferevent_print(clt, line) == -1 ||
640 		    server_bufferevent_print(clt, "\r\n") == -1) {
641 			free(line);
642 			goto fail;
643 		}
644 		if (strlen(line) == 0) {
645 			/* Switch to HTTP header mode */
646 			clt->clt_toread = TOREAD_HTTP_HEADER;
647 			bev->readcb = server_read_http;
648 		}
649 		free(line);
650 		break;
651 	case 0:
652 		/* Chunk is terminated by an empty newline */
653 		line = evbuffer_readln(src, NULL, EVBUFFER_EOL_CRLF_STRICT);
654 		free(line);
655 		if (server_bufferevent_print(clt, "\r\n") == -1)
656 			goto fail;
657 		clt->clt_toread = TOREAD_HTTP_CHUNK_LENGTH;
658 		break;
659 	}
660 
661  next:
662 	if (clt->clt_done)
663 		goto done;
664 	if (EVBUFFER_LENGTH(src))
665 		bev->readcb(bev, arg);
666 	bufferevent_enable(bev, EV_READ);
667 	return;
668 
669  done:
670 	server_close(clt, "last http chunk read (done)");
671 	return;
672  fail:
673 	server_close(clt, strerror(errno));
674 }
675 
676 void
677 server_read_httprange(struct bufferevent *bev, void *arg)
678 {
679 	struct client		*clt = arg;
680 	struct evbuffer		*src = EVBUFFER_INPUT(bev);
681 	size_t			 size;
682 	struct media_type	*media;
683 	struct range_data	*r = &clt->clt_ranges;
684 	struct range		*range;
685 
686 	getmonotime(&clt->clt_tv_last);
687 
688 	if (r->range_toread > 0) {
689 		size = EVBUFFER_LENGTH(src);
690 		if (!size)
691 			return;
692 
693 		/* Read chunk data */
694 		if ((off_t)size > r->range_toread) {
695 			size = r->range_toread;
696 			if (server_bufferevent_write_chunk(clt, src, size)
697 			    == -1)
698 				goto fail;
699 			r->range_toread = 0;
700 		} else {
701 			if (server_bufferevent_write_buffer(clt, src) == -1)
702 				goto fail;
703 			r->range_toread -= size;
704 		}
705 		if (r->range_toread < 1)
706 			r->range_toread = TOREAD_HTTP_RANGE;
707 		DPRINTF("%s: done, size %lu, to read %lld", __func__,
708 		    size, r->range_toread);
709 	}
710 
711 	switch (r->range_toread) {
712 	case TOREAD_HTTP_RANGE:
713 		if (r->range_index >= r->range_count) {
714 			if (r->range_count > 1) {
715 				/* Add end marker */
716 				if (server_bufferevent_printf(clt,
717 				    "\r\n--%llu--\r\n",
718 				    clt->clt_boundary) == -1)
719 					goto fail;
720 			}
721 			r->range_toread = TOREAD_HTTP_NONE;
722 			break;
723 		}
724 
725 		range = &r->range[r->range_index];
726 
727 		if (r->range_count > 1) {
728 			media = r->range_media;
729 			if (server_bufferevent_printf(clt,
730 			    "\r\n--%llu\r\n"
731 			    "Content-Type: %s/%s\r\n"
732 			    "Content-Range: bytes %lld-%lld/%zu\r\n\r\n",
733 			    clt->clt_boundary,
734 			    media->media_type, media->media_subtype,
735 			    range->start, range->end, r->range_total) == -1)
736 				goto fail;
737 		}
738 		r->range_toread = range->end - range->start + 1;
739 
740 		if (lseek(clt->clt_fd, range->start, SEEK_SET) == -1)
741 			goto fail;
742 
743 		/* Throw away bytes that are already in the input buffer */
744 		evbuffer_drain(src, EVBUFFER_LENGTH(src));
745 
746 		/* Increment for the next part */
747 		r->range_index++;
748 		break;
749 	case TOREAD_HTTP_NONE:
750 		goto done;
751 	case 0:
752 		break;
753 	}
754 
755 	if (clt->clt_done)
756 		goto done;
757 
758 	if (EVBUFFER_LENGTH(EVBUFFER_OUTPUT(clt->clt_bev)) > (size_t)
759 	    SERVER_MAX_PREFETCH * clt->clt_sndbufsiz) {
760 		bufferevent_disable(clt->clt_srvbev, EV_READ);
761 		clt->clt_srvbev_throttled = 1;
762 	}
763 
764 	return;
765  done:
766 	(*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg);
767 	return;
768  fail:
769 	server_close(clt, strerror(errno));
770 }
771 
772 void
773 server_reset_http(struct client *clt)
774 {
775 	struct server		*srv = clt->clt_srv;
776 
777 	server_log(clt, NULL);
778 
779 	server_httpdesc_free(clt->clt_descreq);
780 	server_httpdesc_free(clt->clt_descresp);
781 	clt->clt_headerlen = 0;
782 	clt->clt_headersdone = 0;
783 	clt->clt_done = 0;
784 	clt->clt_line = 0;
785 	clt->clt_chunk = 0;
786 	free(clt->clt_remote_user);
787 	clt->clt_remote_user = NULL;
788 	clt->clt_bev->readcb = server_read_http;
789 	clt->clt_srv_conf = &srv->srv_conf;
790 	str_match_free(&clt->clt_srv_match);
791 }
792 
793 ssize_t
794 server_http_time(time_t t, char *tmbuf, size_t len)
795 {
796 	struct tm		 tm;
797 
798 	/* New HTTP/1.1 RFC 7231 prefers IMF-fixdate from RFC 5322 */
799 	if (t == -1 || gmtime_r(&t, &tm) == NULL)
800 		return (-1);
801 	else
802 		return (strftime(tmbuf, len, "%a, %d %h %Y %T %Z", &tm));
803 }
804 
805 const char *
806 server_http_host(struct sockaddr_storage *ss, char *buf, size_t len)
807 {
808 	char		hbuf[HOST_NAME_MAX+1];
809 	in_port_t	port;
810 
811 	if (print_host(ss, buf, len) == NULL)
812 		return (NULL);
813 
814 	port = ntohs(server_socket_getport(ss));
815 	if (port == HTTP_PORT)
816 		return (buf);
817 
818 	switch (ss->ss_family) {
819 	case AF_INET:
820 		if ((size_t)snprintf(hbuf, sizeof(hbuf),
821 		    "%s:%u", buf, port) >= sizeof(hbuf))
822 			return (NULL);
823 		break;
824 	case AF_INET6:
825 		if ((size_t)snprintf(hbuf, sizeof(hbuf),
826 		    "[%s]:%u", buf, port) >= sizeof(hbuf))
827 			return (NULL);
828 		break;
829 	}
830 
831 	if (strlcpy(buf, hbuf, len) >= len)
832 		return (NULL);
833 
834 	return (buf);
835 }
836 
837 char *
838 server_http_parsehost(char *host, char *buf, size_t len, int *portval)
839 {
840 	char		*start, *end, *port;
841 	const char	*errstr = NULL;
842 
843 	if (strlcpy(buf, host, len) >= len) {
844 		log_debug("%s: host name too long", __func__);
845 		return (NULL);
846 	}
847 
848 	start = buf;
849 	end = port = NULL;
850 
851 	if (*start == '[' && (end = strchr(start, ']')) != NULL) {
852 		/* Address enclosed in [] with port, eg. [2001:db8::1]:80 */
853 		start++;
854 		*end++ = '\0';
855 		if ((port = strchr(end, ':')) == NULL || *port == '\0')
856 			port = NULL;
857 		else
858 			port++;
859 		memmove(buf, start, strlen(start) + 1);
860 	} else if ((end = strchr(start, ':')) != NULL) {
861 		/* Name or address with port, eg. www.example.com:80 */
862 		*end++ = '\0';
863 		port = end;
864 	} else {
865 		/* Name or address with default port, eg. www.example.com */
866 		port = NULL;
867 	}
868 
869 	if (port != NULL) {
870 		/* Save the requested port */
871 		*portval = strtonum(port, 0, 0xffff, &errstr);
872 		if (errstr != NULL) {
873 			log_debug("%s: invalid port: %s", __func__,
874 			    strerror(errno));
875 			return (NULL);
876 		}
877 		*portval = htons(*portval);
878 	} else {
879 		/* Port not given, indicate the default port */
880 		*portval = -1;
881 	}
882 
883 	return (start);
884 }
885 
886 void
887 server_abort_http(struct client *clt, unsigned int code, const char *msg)
888 {
889 	struct server_config	*srv_conf = clt->clt_srv_conf;
890 	struct bufferevent	*bev = clt->clt_bev;
891 	struct http_descriptor	*desc = clt->clt_descreq;
892 	const char		*httperr = NULL, *style;
893 	char			*httpmsg, *body = NULL, *extraheader = NULL;
894 	char			 tmbuf[32], hbuf[128], *hstsheader = NULL;
895 	char			*clenheader = NULL;
896 	char			 buf[IBUF_READ_SIZE];
897 	char			*escapedmsg = NULL;
898 	char			 cstr[5];
899 	ssize_t			 bodylen;
900 
901 	if (code == 0) {
902 		server_close(clt, "dropped");
903 		return;
904 	}
905 
906 	if ((httperr = server_httperror_byid(code)) == NULL)
907 		httperr = "Unknown Error";
908 
909 	if (bev == NULL)
910 		goto done;
911 
912 	if (server_log_http(clt, code, 0) == -1)
913 		goto done;
914 
915 	/* Some system information */
916 	if (print_host(&srv_conf->ss, hbuf, sizeof(hbuf)) == NULL)
917 		goto done;
918 
919 	if (server_http_time(time(NULL), tmbuf, sizeof(tmbuf)) <= 0)
920 		goto done;
921 
922 	/* Do not send details of the Internal Server Error */
923 	switch (code) {
924 	case 301:
925 	case 302:
926 	case 303:
927 	case 307:
928 	case 308:
929 		if (msg == NULL)
930 			break;
931 		memset(buf, 0, sizeof(buf));
932 		if (server_expand_http(clt, msg, buf, sizeof(buf)) == NULL)
933 			goto done;
934 		if (asprintf(&extraheader, "Location: %s\r\n", buf) == -1) {
935 			code = 500;
936 			extraheader = NULL;
937 		}
938 		msg = buf;
939 		break;
940 	case 401:
941 		if (msg == NULL)
942 			break;
943 		if (stravis(&escapedmsg, msg, VIS_DQ) == -1) {
944 			code = 500;
945 			extraheader = NULL;
946 		} else if (asprintf(&extraheader,
947 		    "WWW-Authenticate: Basic realm=\"%s\"\r\n", escapedmsg)
948 		    == -1) {
949 			code = 500;
950 			extraheader = NULL;
951 		}
952 		break;
953 	case 416:
954 		if (msg == NULL)
955 			break;
956 		if (asprintf(&extraheader,
957 		    "Content-Range: %s\r\n", msg) == -1) {
958 			code = 500;
959 			extraheader = NULL;
960 		}
961 		break;
962 	default:
963 		/*
964 		 * Do not send details of the error.  Traditionally,
965 		 * web servers responsed with the request path on 40x
966 		 * errors which could be abused to inject JavaScript etc.
967 		 * Instead of sanitizing the path here, we just don't
968 		 * reprint it.
969 		 */
970 		break;
971 	}
972 
973 	free(escapedmsg);
974 
975 	if ((srv_conf->flags & SRVFLAG_ERRDOCS) == 0)
976 		goto builtin; /* errdocs not enabled */
977 	if ((size_t)snprintf(cstr, sizeof(cstr), "%03u", code) >= sizeof(cstr))
978 		goto builtin;
979 
980 	if ((body = read_errdoc(srv_conf->errdocroot, cstr)) == NULL &&
981 	    (body = read_errdoc(srv_conf->errdocroot, HTTPD_ERRDOCTEMPLATE))
982 	    == NULL)
983 		goto builtin;
984 
985 	body = replace_var(body, "$HTTP_ERROR", httperr);
986 	body = replace_var(body, "$RESPONSE_CODE", cstr);
987 	body = replace_var(body, "$SERVER_SOFTWARE", HTTPD_SERVERNAME);
988 	bodylen = strlen(body);
989 	goto send;
990 
991  builtin:
992 	/* A CSS stylesheet allows minimal customization by the user */
993 	style = "body { background-color: white; color: black; font-family: "
994 	    "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
995 	    "hr { border: 0; border-bottom: 1px dashed; }\n"
996 	    "@media (prefers-color-scheme: dark) {\n"
997 	    "body { background-color: #1E1F21; color: #EEEFF1; }\n"
998 	    "a { color: #BAD7FF; }\n}";
999 
1000 	/* Generate simple HTML error document */
1001 	if ((bodylen = asprintf(&body,
1002 	    "<!DOCTYPE html>\n"
1003 	    "<html>\n"
1004 	    "<head>\n"
1005 	    "<meta charset=\"utf-8\">\n"
1006 	    "<title>%03d %s</title>\n"
1007 	    "<style type=\"text/css\"><!--\n%s\n--></style>\n"
1008 	    "</head>\n"
1009 	    "<body>\n"
1010 	    "<h1>%03d %s</h1>\n"
1011 	    "<hr>\n<address>%s</address>\n"
1012 	    "</body>\n"
1013 	    "</html>\n",
1014 	    code, httperr, style, code, httperr, HTTPD_SERVERNAME)) == -1) {
1015 		body = NULL;
1016 		goto done;
1017 	}
1018 
1019  send:
1020 	if (srv_conf->flags & SRVFLAG_SERVER_HSTS &&
1021 	    srv_conf->flags & SRVFLAG_TLS) {
1022 		if (asprintf(&hstsheader, "Strict-Transport-Security: "
1023 		    "max-age=%d%s%s\r\n", srv_conf->hsts_max_age,
1024 		    srv_conf->hsts_flags & HSTSFLAG_SUBDOMAINS ?
1025 		    "; includeSubDomains" : "",
1026 		    srv_conf->hsts_flags & HSTSFLAG_PRELOAD ?
1027 		    "; preload" : "") == -1) {
1028 			hstsheader = NULL;
1029 			goto done;
1030 		}
1031 	}
1032 
1033 	if ((code >= 100 && code < 200) || code == 204)
1034 		clenheader = NULL;
1035 	else {
1036 		if (asprintf(&clenheader,
1037 		    "Content-Length: %zd\r\n", bodylen) == -1) {
1038 			clenheader = NULL;
1039 			goto done;
1040 		}
1041 	}
1042 
1043 	/* Add basic HTTP headers */
1044 	if (asprintf(&httpmsg,
1045 	    "HTTP/1.0 %03d %s\r\n"
1046 	    "Date: %s\r\n"
1047 	    "Server: %s\r\n"
1048 	    "Connection: close\r\n"
1049 	    "Content-Type: text/html\r\n"
1050 	    "%s"
1051 	    "%s"
1052 	    "%s"
1053 	    "\r\n"
1054 	    "%s",
1055 	    code, httperr, tmbuf, HTTPD_SERVERNAME,
1056 	    clenheader == NULL ? "" : clenheader,
1057 	    extraheader == NULL ? "" : extraheader,
1058 	    hstsheader == NULL ? "" : hstsheader,
1059 	    desc->http_method == HTTP_METHOD_HEAD || clenheader == NULL ?
1060 	    "" : body) == -1)
1061 		goto done;
1062 
1063 	/* Dump the message without checking for success */
1064 	server_dump(clt, httpmsg, strlen(httpmsg));
1065 	free(httpmsg);
1066 
1067  done:
1068 	free(body);
1069 	free(extraheader);
1070 	free(hstsheader);
1071 	free(clenheader);
1072 	if (msg == NULL)
1073 		msg = "\"\"";
1074 	if (asprintf(&httpmsg, "%s (%03d %s)", msg, code, httperr) == -1) {
1075 		server_close(clt, msg);
1076 	} else {
1077 		server_close(clt, httpmsg);
1078 		free(httpmsg);
1079 	}
1080 }
1081 
1082 void
1083 server_close_http(struct client *clt)
1084 {
1085 	struct http_descriptor *desc;
1086 
1087 	desc = clt->clt_descreq;
1088 	server_httpdesc_free(desc);
1089 	free(desc);
1090 	clt->clt_descreq = NULL;
1091 
1092 	desc = clt->clt_descresp;
1093 	server_httpdesc_free(desc);
1094 	free(desc);
1095 	clt->clt_descresp = NULL;
1096 	free(clt->clt_remote_user);
1097 	clt->clt_remote_user = NULL;
1098 
1099 	str_match_free(&clt->clt_srv_match);
1100 }
1101 
1102 char *
1103 server_expand_http(struct client *clt, const char *val, char *buf,
1104     size_t len)
1105 {
1106 	struct http_descriptor	*desc = clt->clt_descreq;
1107 	struct server_config	*srv_conf = clt->clt_srv_conf;
1108 	char			 ibuf[128], *str, *path, *query;
1109 	const char		*errstr = NULL, *p;
1110 	size_t			 size;
1111 	int			 n, ret;
1112 
1113 	if (strlcpy(buf, val, len) >= len)
1114 		return (NULL);
1115 
1116 	/* Find previously matched substrings by index */
1117 	for (p = val; clt->clt_srv_match.sm_nmatch &&
1118 	    (p = strstr(p, "%")) != NULL; p++) {
1119 		if (!isdigit((unsigned char)*(p + 1)))
1120 			continue;
1121 
1122 		/* Copy number, leading '%' char and add trailing \0 */
1123 		size = strspn(p + 1, "0123456789") + 2;
1124 		if (size  >= sizeof(ibuf))
1125 			return (NULL);
1126 		(void)strlcpy(ibuf, p, size);
1127 		n = strtonum(ibuf + 1, 0,
1128 		    clt->clt_srv_match.sm_nmatch - 1, &errstr);
1129 		if (errstr != NULL)
1130 			return (NULL);
1131 
1132 		/* Expand variable with matched value */
1133 		if ((str = url_encode(clt->clt_srv_match.sm_match[n])) == NULL)
1134 			return (NULL);
1135 		ret = expand_string(buf, len, ibuf, str);
1136 		free(str);
1137 		if (ret != 0)
1138 			return (NULL);
1139 	}
1140 	if (strstr(val, "$DOCUMENT_URI") != NULL) {
1141 		if ((path = url_encode(desc->http_path)) == NULL)
1142 			return (NULL);
1143 		ret = expand_string(buf, len, "$DOCUMENT_URI", path);
1144 		free(path);
1145 		if (ret != 0)
1146 			return (NULL);
1147 	}
1148 	if (strstr(val, "$QUERY_STRING_ENC") != NULL) {
1149 		if (desc->http_query == NULL) {
1150 			ret = expand_string(buf, len, "$QUERY_STRING_ENC", "");
1151 		} else {
1152 			if ((query = url_encode(desc->http_query)) == NULL)
1153 				return (NULL);
1154 			ret = expand_string(buf, len, "$QUERY_STRING_ENC", query);
1155 			free(query);
1156 		}
1157 		if (ret != 0)
1158 			return (NULL);
1159 	}
1160 	if (strstr(val, "$QUERY_STRING") != NULL) {
1161 		if (desc->http_query == NULL) {
1162 			ret = expand_string(buf, len, "$QUERY_STRING", "");
1163 		} else {
1164 			ret = expand_string(buf, len, "$QUERY_STRING",
1165 			    desc->http_query);
1166 		}
1167 		if (ret != 0)
1168 			return (NULL);
1169 	}
1170 	if (strstr(val, "$HTTP_HOST") != NULL) {
1171 		if (desc->http_host == NULL)
1172 			return (NULL);
1173 		if ((str = url_encode(desc->http_host)) == NULL)
1174 			return (NULL);
1175 		expand_string(buf, len, "$HTTP_HOST", str);
1176 		free(str);
1177 	}
1178 	if (strstr(val, "$REMOTE_") != NULL) {
1179 		if (strstr(val, "$REMOTE_ADDR") != NULL) {
1180 			if (print_host(&clt->clt_ss,
1181 			    ibuf, sizeof(ibuf)) == NULL)
1182 				return (NULL);
1183 			if (expand_string(buf, len,
1184 			    "$REMOTE_ADDR", ibuf) != 0)
1185 				return (NULL);
1186 		}
1187 		if (strstr(val, "$REMOTE_PORT") != NULL) {
1188 			snprintf(ibuf, sizeof(ibuf),
1189 			    "%u", ntohs(clt->clt_port));
1190 			if (expand_string(buf, len,
1191 			    "$REMOTE_PORT", ibuf) != 0)
1192 				return (NULL);
1193 		}
1194 		if (strstr(val, "$REMOTE_USER") != NULL) {
1195 			if ((srv_conf->flags & SRVFLAG_AUTH) &&
1196 			    clt->clt_remote_user != NULL) {
1197 				if ((str = url_encode(clt->clt_remote_user))
1198 				    == NULL)
1199 					return (NULL);
1200 			} else
1201 				str = strdup("");
1202 			ret = expand_string(buf, len, "$REMOTE_USER", str);
1203 			free(str);
1204 			if (ret != 0)
1205 				return (NULL);
1206 		}
1207 	}
1208 	if (strstr(val, "$REQUEST_URI") != NULL) {
1209 		if ((path = url_encode(desc->http_path)) == NULL)
1210 			return (NULL);
1211 		if (desc->http_query == NULL) {
1212 			str = path;
1213 		} else {
1214 			ret = asprintf(&str, "%s?%s", path, desc->http_query);
1215 			free(path);
1216 			if (ret == -1)
1217 				return (NULL);
1218 		}
1219 
1220 		ret = expand_string(buf, len, "$REQUEST_URI", str);
1221 		free(str);
1222 		if (ret != 0)
1223 			return (NULL);
1224 	}
1225 	if (strstr(val, "$REQUEST_SCHEME") != NULL) {
1226 		if (srv_conf->flags & SRVFLAG_TLS) {
1227 			ret = expand_string(buf, len, "$REQUEST_SCHEME", "https");
1228 		} else {
1229 			ret = expand_string(buf, len, "$REQUEST_SCHEME", "http");
1230 		}
1231 		if (ret != 0)
1232 			return (NULL);
1233 	}
1234 	if (strstr(val, "$SERVER_") != NULL) {
1235 		if (strstr(val, "$SERVER_ADDR") != NULL) {
1236 			if (print_host(&srv_conf->ss,
1237 			    ibuf, sizeof(ibuf)) == NULL)
1238 				return (NULL);
1239 			if (expand_string(buf, len,
1240 			    "$SERVER_ADDR", ibuf) != 0)
1241 				return (NULL);
1242 		}
1243 		if (strstr(val, "$SERVER_PORT") != NULL) {
1244 			snprintf(ibuf, sizeof(ibuf), "%u",
1245 			    ntohs(srv_conf->port));
1246 			if (expand_string(buf, len,
1247 			    "$SERVER_PORT", ibuf) != 0)
1248 				return (NULL);
1249 		}
1250 		if (strstr(val, "$SERVER_NAME") != NULL) {
1251 			if ((str = url_encode(srv_conf->name))
1252 			     == NULL)
1253 				return (NULL);
1254 			ret = expand_string(buf, len, "$SERVER_NAME", str);
1255 			free(str);
1256 			if (ret != 0)
1257 				return (NULL);
1258 		}
1259 	}
1260 
1261 	return (buf);
1262 }
1263 
1264 int
1265 server_response(struct httpd *httpd, struct client *clt)
1266 {
1267 	char			 path[PATH_MAX];
1268 	char			 hostname[HOST_NAME_MAX+1];
1269 	struct http_descriptor	*desc = clt->clt_descreq;
1270 	struct http_descriptor	*resp = clt->clt_descresp;
1271 	struct server		*srv = clt->clt_srv;
1272 	struct server_config	*srv_conf = &srv->srv_conf;
1273 	struct kv		*kv, key, *host;
1274 	struct str_find		 sm;
1275 	int			 portval = -1, ret;
1276 	char			*hostval, *query;
1277 	const char		*errstr = NULL;
1278 
1279 	/* Preserve original path */
1280 	if (desc->http_path == NULL ||
1281 	    (desc->http_path_orig = strdup(desc->http_path)) == NULL)
1282 		goto fail;
1283 
1284 	/* Decode the URL */
1285 	if (url_decode(desc->http_path) == NULL)
1286 		goto fail;
1287 
1288 	/* Canonicalize the request path */
1289 	if (canonicalize_path(desc->http_path, path, sizeof(path)) == NULL)
1290 		goto fail;
1291 	free(desc->http_path);
1292 	if ((desc->http_path = strdup(path)) == NULL)
1293 		goto fail;
1294 
1295 	key.kv_key = "Host";
1296 	if ((host = kv_find(&desc->http_headers, &key)) != NULL &&
1297 	    host->kv_value == NULL)
1298 		host = NULL;
1299 
1300 	if (strcmp(desc->http_version, "HTTP/1.1") == 0) {
1301 		/* Host header is mandatory */
1302 		if (host == NULL)
1303 			goto fail;
1304 
1305 		/* Is the connection persistent? */
1306 		key.kv_key = "Connection";
1307 		if ((kv = kv_find(&desc->http_headers, &key)) != NULL &&
1308 		    strcasecmp("close", kv->kv_value) == 0)
1309 			clt->clt_persist = 0;
1310 		else
1311 			clt->clt_persist++;
1312 	} else {
1313 		/* Is the connection persistent? */
1314 		key.kv_key = "Connection";
1315 		if ((kv = kv_find(&desc->http_headers, &key)) != NULL &&
1316 		    strcasecmp("keep-alive", kv->kv_value) == 0)
1317 			clt->clt_persist++;
1318 		else
1319 			clt->clt_persist = 0;
1320 	}
1321 
1322 	/*
1323 	 * Do we have a Host header and matching configuration?
1324 	 * XXX the Host can also appear in the URL path.
1325 	 */
1326 	if (host != NULL) {
1327 		if ((hostval = server_http_parsehost(host->kv_value,
1328 		    hostname, sizeof(hostname), &portval)) == NULL)
1329 			goto fail;
1330 
1331 		TAILQ_FOREACH(srv_conf, &srv->srv_hosts, entry) {
1332 #ifdef DEBUG
1333 			if ((srv_conf->flags & SRVFLAG_LOCATION) == 0) {
1334 				DPRINTF("%s: virtual host \"%s:%u\""
1335 				    " host \"%s\" (\"%s\")",
1336 				    __func__, srv_conf->name,
1337 				    ntohs(srv_conf->port), host->kv_value,
1338 				    hostname);
1339 			}
1340 #endif
1341 			if (srv_conf->flags & SRVFLAG_LOCATION)
1342 				continue;
1343 			else if (srv_conf->flags & SRVFLAG_SERVER_MATCH) {
1344 				str_find(hostname, srv_conf->name,
1345 				    &sm, 1, &errstr);
1346 				ret = errstr == NULL ? 0 : -1;
1347 			} else {
1348 				ret = fnmatch(srv_conf->name,
1349 				    hostname, FNM_CASEFOLD);
1350 			}
1351 			if (ret == 0 &&
1352 			    (portval == -1 || portval == srv_conf->port)) {
1353 				/* Replace host configuration */
1354 				clt->clt_srv_conf = srv_conf;
1355 				srv_conf = NULL;
1356 				break;
1357 			}
1358 		}
1359 	}
1360 
1361 	if (srv_conf != NULL) {
1362 		/* Use the actual server IP address */
1363 		if (server_http_host(&clt->clt_srv_ss, hostname,
1364 		    sizeof(hostname)) == NULL)
1365 			goto fail;
1366 	} else {
1367 		/* Host header was valid and found */
1368 		if (strlcpy(hostname, host->kv_value, sizeof(hostname)) >=
1369 		    sizeof(hostname))
1370 			goto fail;
1371 		srv_conf = clt->clt_srv_conf;
1372 	}
1373 
1374 	if (clt->clt_persist >= srv_conf->maxrequests)
1375 		clt->clt_persist = 0;
1376 
1377 	/* pipelining should end after the first "idempotent" method */
1378 	if (clt->clt_pipelining && clt->clt_toread > 0)
1379 		clt->clt_persist = 0;
1380 
1381 	if ((desc->http_host = strdup(hostname)) == NULL)
1382 		goto fail;
1383 
1384 	/* Now fill in the mandatory parts of the response descriptor */
1385 	resp->http_method = desc->http_method;
1386 	if ((resp->http_version = strdup(desc->http_version)) == NULL)
1387 		goto fail;
1388 
1389 	/* Now search for the location */
1390 	if ((srv_conf = server_getlocation(clt, desc->http_path)) == NULL) {
1391 		server_abort_http(clt, 500, desc->http_path);
1392 		return (-1);
1393 	}
1394 
1395 	/* Optional rewrite */
1396 	if (srv_conf->flags & SRVFLAG_PATH_REWRITE) {
1397 		/* Expand macros */
1398 		if (server_expand_http(clt, srv_conf->path,
1399 		    path, sizeof(path)) == NULL)
1400 			goto fail;
1401 
1402 		/*
1403 		 * Reset and update the query.  The updated query must already
1404 		 * be URL encoded - either specified by the user or by using the
1405 		 * original $QUERY_STRING.
1406 		 */
1407 		free(desc->http_query_alias);
1408 		desc->http_query_alias = NULL;
1409 		if ((query = strchr(path, '?')) != NULL) {
1410 			*query++ = '\0';
1411 			if ((desc->http_query_alias = strdup(query)) == NULL)
1412 				goto fail;
1413 		}
1414 
1415 		/* Canonicalize the updated request path */
1416 		if (canonicalize_path(path,
1417 		    path, sizeof(path)) == NULL)
1418 			goto fail;
1419 
1420 		log_debug("%s: rewrote %s?%s -> %s?%s", __func__,
1421 		    desc->http_path, desc->http_query ? desc->http_query : "",
1422 		    path, query ? query : "");
1423 
1424 		free(desc->http_path_alias);
1425 		if ((desc->http_path_alias = strdup(path)) == NULL)
1426 			goto fail;
1427 
1428 		/* Now search for the updated location */
1429 		if ((srv_conf = server_getlocation(clt,
1430 		    desc->http_path_alias)) == NULL) {
1431 			server_abort_http(clt, 500, desc->http_path_alias);
1432 			return (-1);
1433 		}
1434 	}
1435 
1436 	if (clt->clt_toread > 0 && (size_t)clt->clt_toread >
1437 	    srv_conf->maxrequestbody) {
1438 		server_abort_http(clt, 413, "request body too large");
1439 		return (-1);
1440 	}
1441 
1442 	if (srv_conf->flags & SRVFLAG_BLOCK) {
1443 		server_abort_http(clt, srv_conf->return_code,
1444 		    srv_conf->return_uri);
1445 		return (-1);
1446 	} else if (srv_conf->flags & SRVFLAG_AUTH &&
1447 	    server_http_authenticate(srv_conf, clt) == -1) {
1448 		server_abort_http(clt, 401, srv_conf->auth_realm);
1449 		return (-1);
1450 	} else
1451 		return (server_file(httpd, clt));
1452  fail:
1453 	server_abort_http(clt, 400, "bad request");
1454 	return (-1);
1455 }
1456 
1457 const char *
1458 server_root_strip(const char *path, int n)
1459 {
1460 	const char *p;
1461 
1462 	/* Strip strip leading directories. Leading '/' is ignored. */
1463 	for (; n > 0 && *path != '\0'; n--)
1464 		if ((p = strchr(++path, '/')) == NULL)
1465 			path = strchr(path, '\0');
1466 		else
1467 			path = p;
1468 
1469 	return (path);
1470 }
1471 
1472 struct server_config *
1473 server_getlocation(struct client *clt, const char *path)
1474 {
1475 	struct server		*srv = clt->clt_srv;
1476 	struct server_config	*srv_conf = clt->clt_srv_conf, *location;
1477 	const char		*errstr = NULL;
1478 	int			 ret;
1479 
1480 	/* Now search for the location */
1481 	TAILQ_FOREACH(location, &srv->srv_hosts, entry) {
1482 #ifdef DEBUG
1483 		if (location->flags & SRVFLAG_LOCATION) {
1484 			DPRINTF("%s: location \"%s\" path \"%s\"",
1485 			    __func__, location->location, path);
1486 		}
1487 #endif
1488 		if ((location->flags & SRVFLAG_LOCATION) &&
1489 		    location->parent_id == srv_conf->parent_id) {
1490 			errstr = NULL;
1491 			if (location->flags & SRVFLAG_LOCATION_MATCH) {
1492 				ret = str_match(path, location->location,
1493 				    &clt->clt_srv_match, &errstr);
1494 			} else {
1495 				ret = fnmatch(location->location,
1496 				    path, FNM_CASEFOLD);
1497 			}
1498 			if (ret == 0 && errstr == NULL) {
1499 				if ((ret = server_locationaccesstest(location,
1500 				    path)) == -1)
1501 					return (NULL);
1502 
1503 				if (ret)
1504 					continue;
1505 				/* Replace host configuration */
1506 				clt->clt_srv_conf = srv_conf = location;
1507 				break;
1508 			}
1509 		}
1510 	}
1511 
1512 	return (srv_conf);
1513 }
1514 
1515 int
1516 server_locationaccesstest(struct server_config *srv_conf, const char *path)
1517 {
1518 	int		 rootfd, ret;
1519 	struct stat	 sb;
1520 
1521 	if (((SRVFLAG_LOCATION_FOUND | SRVFLAG_LOCATION_NOT_FOUND) &
1522 	    srv_conf->flags) == 0)
1523 		return (0);
1524 
1525 	if ((rootfd = open(srv_conf->root, O_RDONLY)) == -1)
1526 		return (-1);
1527 
1528 	path = server_root_strip(path, srv_conf->strip) + 1;
1529 	if ((ret = faccessat(rootfd, path, R_OK, 0)) != -1)
1530 		ret = fstatat(rootfd, path, &sb, 0);
1531 	close(rootfd);
1532 	return ((ret == -1 && SRVFLAG_LOCATION_FOUND & srv_conf->flags) ||
1533 	    (ret == 0 && SRVFLAG_LOCATION_NOT_FOUND & srv_conf->flags));
1534 }
1535 
1536 int
1537 server_response_http(struct client *clt, unsigned int code,
1538     struct media_type *media, off_t size, time_t mtime)
1539 {
1540 	struct server_config	*srv_conf = clt->clt_srv_conf;
1541 	struct http_descriptor	*desc = clt->clt_descreq;
1542 	struct http_descriptor	*resp = clt->clt_descresp;
1543 	const char		*error;
1544 	struct kv		*ct, *cl;
1545 	char			 tmbuf[32];
1546 
1547 	if (desc == NULL || media == NULL ||
1548 	    (error = server_httperror_byid(code)) == NULL)
1549 		return (-1);
1550 
1551 	if (server_log_http(clt, code, size >= 0 ? size : 0) == -1)
1552 		return (-1);
1553 
1554 	/* Add error codes */
1555 	if (kv_setkey(&resp->http_pathquery, "%u", code) == -1 ||
1556 	    kv_set(&resp->http_pathquery, "%s", error) == -1)
1557 		return (-1);
1558 
1559 	/* Add headers */
1560 	if (kv_add(&resp->http_headers, "Server", HTTPD_SERVERNAME) == NULL)
1561 		return (-1);
1562 
1563 	/* Is it a persistent connection? */
1564 	if (clt->clt_persist) {
1565 		if (kv_add(&resp->http_headers,
1566 		    "Connection", "keep-alive") == NULL)
1567 			return (-1);
1568 	} else if (kv_add(&resp->http_headers, "Connection", "close") == NULL)
1569 		return (-1);
1570 
1571 	/* Set media type */
1572 	if ((ct = kv_add(&resp->http_headers, "Content-Type", NULL)) == NULL ||
1573 	    kv_set(ct, "%s/%s", media->media_type, media->media_subtype) == -1)
1574 		return (-1);
1575 
1576 	/* Set content length, if specified */
1577 	if (size >= 0 && ((cl =
1578 	    kv_add(&resp->http_headers, "Content-Length", NULL)) == NULL ||
1579 	    kv_set(cl, "%lld", (long long)size) == -1))
1580 		return (-1);
1581 
1582 	/* Set last modification time */
1583 	if (server_http_time(mtime, tmbuf, sizeof(tmbuf)) <= 0 ||
1584 	    kv_add(&resp->http_headers, "Last-Modified", tmbuf) == NULL)
1585 		return (-1);
1586 
1587 	/* HSTS header */
1588 	if (srv_conf->flags & SRVFLAG_SERVER_HSTS &&
1589 	    srv_conf->flags & SRVFLAG_TLS) {
1590 		if ((cl =
1591 		    kv_add(&resp->http_headers, "Strict-Transport-Security",
1592 		    NULL)) == NULL ||
1593 		    kv_set(cl, "max-age=%d%s%s", srv_conf->hsts_max_age,
1594 		    srv_conf->hsts_flags & HSTSFLAG_SUBDOMAINS ?
1595 		    "; includeSubDomains" : "",
1596 		    srv_conf->hsts_flags & HSTSFLAG_PRELOAD ?
1597 		    "; preload" : "") == -1)
1598 			return (-1);
1599 	}
1600 
1601 	/* Date header is mandatory and should be added as late as possible */
1602 	if (server_http_time(time(NULL), tmbuf, sizeof(tmbuf)) <= 0 ||
1603 	    kv_add(&resp->http_headers, "Date", tmbuf) == NULL)
1604 		return (-1);
1605 
1606 	/* Write completed header */
1607 	if (server_writeresponse_http(clt) == -1 ||
1608 	    server_bufferevent_print(clt, "\r\n") == -1 ||
1609 	    server_headers(clt, resp, server_writeheader_http, NULL) == -1 ||
1610 	    server_bufferevent_print(clt, "\r\n") == -1)
1611 		return (-1);
1612 
1613 	if (size <= 0 || resp->http_method == HTTP_METHOD_HEAD) {
1614 		bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
1615 		if (clt->clt_persist)
1616 			clt->clt_toread = TOREAD_HTTP_HEADER;
1617 		else
1618 			clt->clt_toread = TOREAD_HTTP_NONE;
1619 		clt->clt_done = 0;
1620 		return (0);
1621 	}
1622 
1623 	return (1);
1624 }
1625 
1626 int
1627 server_writeresponse_http(struct client *clt)
1628 {
1629 	struct http_descriptor	*desc = clt->clt_descresp;
1630 
1631 	DPRINTF("version: %s rescode: %s resmsg: %s", desc->http_version,
1632 	    desc->http_rescode, desc->http_resmesg);
1633 
1634 	if (server_bufferevent_print(clt, desc->http_version) == -1 ||
1635 	    server_bufferevent_print(clt, " ") == -1 ||
1636 	    server_bufferevent_print(clt, desc->http_rescode) == -1 ||
1637 	    server_bufferevent_print(clt, " ") == -1 ||
1638 	    server_bufferevent_print(clt, desc->http_resmesg) == -1)
1639 		return (-1);
1640 
1641 	return (0);
1642 }
1643 
1644 int
1645 server_writeheader_http(struct client *clt, struct kv *hdr, void *arg)
1646 {
1647 	char			*ptr;
1648 	const char		*key;
1649 
1650 	/* The key might have been updated in the parent */
1651 	if (hdr->kv_parent != NULL && hdr->kv_parent->kv_key != NULL)
1652 		key = hdr->kv_parent->kv_key;
1653 	else
1654 		key = hdr->kv_key;
1655 
1656 	ptr = hdr->kv_value;
1657 	if (server_bufferevent_print(clt, key) == -1 ||
1658 	    (ptr != NULL &&
1659 	    (server_bufferevent_print(clt, ": ") == -1 ||
1660 	    server_bufferevent_print(clt, ptr) == -1 ||
1661 	    server_bufferevent_print(clt, "\r\n") == -1)))
1662 		return (-1);
1663 	DPRINTF("%s: %s: %s", __func__, key,
1664 	    hdr->kv_value == NULL ? "" : hdr->kv_value);
1665 
1666 	return (0);
1667 }
1668 
1669 int
1670 server_headers(struct client *clt, void *descp,
1671     int (*hdr_cb)(struct client *, struct kv *, void *), void *arg)
1672 {
1673 	struct kv		*hdr, *kv;
1674 	struct http_descriptor	*desc = descp;
1675 
1676 	RB_FOREACH(hdr, kvtree, &desc->http_headers) {
1677 		if ((hdr_cb)(clt, hdr, arg) == -1)
1678 			return (-1);
1679 		TAILQ_FOREACH(kv, &hdr->kv_children, kv_entry) {
1680 			if ((hdr_cb)(clt, kv, arg) == -1)
1681 				return (-1);
1682 		}
1683 	}
1684 
1685 	return (0);
1686 }
1687 
1688 enum httpmethod
1689 server_httpmethod_byname(const char *name)
1690 {
1691 	enum httpmethod		 id = HTTP_METHOD_NONE;
1692 	struct http_method	 method, *res = NULL;
1693 
1694 	/* Set up key */
1695 	method.method_name = name;
1696 
1697 	if ((res = bsearch(&method, http_methods,
1698 	    sizeof(http_methods) / sizeof(http_methods[0]) - 1,
1699 	    sizeof(http_methods[0]), server_httpmethod_cmp)) != NULL)
1700 		id = res->method_id;
1701 
1702 	return (id);
1703 }
1704 
1705 const char *
1706 server_httpmethod_byid(unsigned int id)
1707 {
1708 	const char	*name = "<UNKNOWN>";
1709 	int		 i;
1710 
1711 	for (i = 0; http_methods[i].method_name != NULL; i++) {
1712 		if (http_methods[i].method_id == id) {
1713 			name = http_methods[i].method_name;
1714 			break;
1715 		}
1716 	}
1717 
1718 	return (name);
1719 }
1720 
1721 static int
1722 server_httpmethod_cmp(const void *a, const void *b)
1723 {
1724 	const struct http_method *ma = a;
1725 	const struct http_method *mb = b;
1726 
1727 	/*
1728 	 * RFC 2616 section 5.1.1 says that the method is case
1729 	 * sensitive so we don't do a strcasecmp here.
1730 	 */
1731 	return (strcmp(ma->method_name, mb->method_name));
1732 }
1733 
1734 const char *
1735 server_httperror_byid(unsigned int id)
1736 {
1737 	struct http_error	 error, *res;
1738 
1739 	/* Set up key */
1740 	error.error_code = (int)id;
1741 
1742 	if ((res = bsearch(&error, http_errors,
1743 	    sizeof(http_errors) / sizeof(http_errors[0]) - 1,
1744 	    sizeof(http_errors[0]), server_httperror_cmp)) != NULL)
1745 		return (res->error_name);
1746 
1747 	return (NULL);
1748 }
1749 
1750 static int
1751 server_httperror_cmp(const void *a, const void *b)
1752 {
1753 	const struct http_error *ea = a;
1754 	const struct http_error *eb = b;
1755 	return (ea->error_code - eb->error_code);
1756 }
1757 
1758 /*
1759  * return -1 on failure, strlen() of read file otherwise.
1760  * body is NULL on failure, contents of file with trailing \0 otherwise.
1761  */
1762 char *
1763 read_errdoc(const char *root, const char *file)
1764 {
1765 	struct stat	 sb;
1766 	char		*path;
1767 	int	 	 fd;
1768 	char	 	*ret = NULL;
1769 
1770 	if (asprintf(&path, "%s/%s.html", root, file) == -1)
1771 		fatal("asprintf");
1772 	if ((fd = open(path, O_RDONLY)) == -1) {
1773 		free(path);
1774 		log_warn("%s: open", __func__);
1775 		return (NULL);
1776 	}
1777 	free(path);
1778 	if (fstat(fd, &sb) < 0) {
1779 		log_warn("%s: stat", __func__);
1780 		return (NULL);
1781 	}
1782 
1783 	if ((ret = calloc(1, sb.st_size + 1)) == NULL)
1784 		fatal("calloc");
1785 	if (sb.st_size == 0)
1786 		return (ret);
1787 	if (read(fd, ret, sb.st_size) != sb.st_size) {
1788 		log_warn("%s: read", __func__);
1789 		close(fd);
1790 		free(ret);
1791 		ret = NULL;
1792 		return (ret);
1793 	}
1794 	close(fd);
1795 
1796 	return (ret);
1797 }
1798 
1799 char *
1800 replace_var(char *str, const char *var, const char *repl)
1801 {
1802 	char	*iv, *r;
1803 	size_t	 vlen;
1804 
1805 	vlen = strlen(var);
1806 	while ((iv = strstr(str, var)) != NULL) {
1807 		*iv = '\0';
1808 		if (asprintf(&r, "%s%s%s", str, repl, &iv[vlen]) == -1)
1809 			fatal("asprintf");
1810 		free(str);
1811 		str = r;
1812 	}
1813 	return (str);
1814 }
1815 
1816 int
1817 server_log_http(struct client *clt, unsigned int code, size_t len)
1818 {
1819 	static char		 tstamp[64];
1820 	static char		 ip[INET6_ADDRSTRLEN];
1821 	time_t			 t;
1822 	struct kv		 key, *agent, *referrer, *xff, *xfp;
1823 	struct tm		*tm;
1824 	struct server_config	*srv_conf;
1825 	struct http_descriptor	*desc;
1826 	int			 ret = -1;
1827 	char			*user = NULL;
1828 	char			*path = NULL;
1829 	char			*version = NULL;
1830 	char			*referrer_v = NULL;
1831 	char			*agent_v = NULL;
1832 	char			*xff_v = NULL;
1833 	char			*xfp_v = NULL;
1834 
1835 	if ((srv_conf = clt->clt_srv_conf) == NULL)
1836 		return (-1);
1837 	if ((srv_conf->flags & SRVFLAG_LOG) == 0)
1838 		return (0);
1839 	if ((desc = clt->clt_descreq) == NULL)
1840 		return (-1);
1841 
1842 	if ((t = time(NULL)) == -1)
1843 		return (-1);
1844 	if ((tm = localtime(&t)) == NULL)
1845 		return (-1);
1846 	if (strftime(tstamp, sizeof(tstamp), "%d/%b/%Y:%H:%M:%S %z", tm) == 0)
1847 		return (-1);
1848 
1849 	if (print_host(&clt->clt_ss, ip, sizeof(ip)) == NULL)
1850 		return (-1);
1851 
1852 	/*
1853 	 * For details on common log format, see:
1854 	 * https://httpd.apache.org/docs/current/mod/mod_log_config.html
1855 	 *
1856 	 * httpd's format is similar to these Apache LogFormats:
1857 	 * "%v %h %l %u %t \"%r\" %>s %B"
1858 	 * "%v %h %l %u %t \"%r\" %>s %B \"%{Referer}i\" \"%{User-agent}i\""
1859 	 */
1860 	switch (srv_conf->logformat) {
1861 	case LOG_FORMAT_COMMON:
1862 		/* Use vis to encode input values from the header */
1863 		if (clt->clt_remote_user &&
1864 		    stravis(&user, clt->clt_remote_user, HTTPD_LOGVIS) == -1)
1865 			goto done;
1866 		if (desc->http_version &&
1867 		    stravis(&version, desc->http_version, HTTPD_LOGVIS) == -1)
1868 			goto done;
1869 
1870 		/* The following should be URL-encoded */
1871 		if (desc->http_path &&
1872 		    (path = url_encode(desc->http_path)) == NULL)
1873 			goto done;
1874 
1875 		ret = evbuffer_add_printf(clt->clt_log,
1876 		    "%s %s - %s [%s] \"%s %s%s%s%s%s\" %03d %zu\n",
1877 		    srv_conf->name, ip, clt->clt_remote_user == NULL ? "-" :
1878 		    user, tstamp,
1879 		    server_httpmethod_byid(desc->http_method),
1880 		    desc->http_path == NULL ? "" : path,
1881 		    desc->http_query == NULL ? "" : "?",
1882 		    desc->http_query == NULL ? "" : desc->http_query,
1883 		    desc->http_version == NULL ? "" : " ",
1884 		    desc->http_version == NULL ? "" : version,
1885 		    code, len);
1886 
1887 		break;
1888 
1889 	case LOG_FORMAT_COMBINED:
1890 	case LOG_FORMAT_FORWARDED:
1891 		key.kv_key = "Referer"; /* sic */
1892 		if ((referrer = kv_find(&desc->http_headers, &key)) != NULL &&
1893 		    referrer->kv_value == NULL)
1894 			referrer = NULL;
1895 
1896 		key.kv_key = "User-Agent";
1897 		if ((agent = kv_find(&desc->http_headers, &key)) != NULL &&
1898 		    agent->kv_value == NULL)
1899 			agent = NULL;
1900 
1901 		/* Use vis to encode input values from the header */
1902 		if (clt->clt_remote_user &&
1903 		    stravis(&user, clt->clt_remote_user, HTTPD_LOGVIS) == -1)
1904 			goto done;
1905 		if (clt->clt_remote_user == NULL &&
1906 		    clt->clt_tls_ctx != NULL &&
1907 		    (srv_conf->tls_flags & TLSFLAG_CA) &&
1908 		    tls_peer_cert_subject(clt->clt_tls_ctx) != NULL &&
1909 		    stravis(&user, tls_peer_cert_subject(clt->clt_tls_ctx),
1910 		    HTTPD_LOGVIS) == -1)
1911 			goto done;
1912 		if (desc->http_version &&
1913 		    stravis(&version, desc->http_version, HTTPD_LOGVIS) == -1)
1914 			goto done;
1915 		if (agent &&
1916 		    stravis(&agent_v, agent->kv_value, HTTPD_LOGVIS) == -1)
1917 			goto done;
1918 
1919 		/* The following should be URL-encoded */
1920 		if (desc->http_path &&
1921 		    (path = url_encode(desc->http_path)) == NULL)
1922 			goto done;
1923 		if (referrer &&
1924 		    (referrer_v = url_encode(referrer->kv_value)) == NULL)
1925 			goto done;
1926 
1927 		if ((ret = evbuffer_add_printf(clt->clt_log,
1928 		    "%s %s - %s [%s] \"%s %s%s%s%s%s\""
1929 		    " %03d %zu \"%s\" \"%s\"",
1930 		    srv_conf->name, ip, user == NULL ? "-" :
1931 		    user, tstamp,
1932 		    server_httpmethod_byid(desc->http_method),
1933 		    desc->http_path == NULL ? "" : path,
1934 		    desc->http_query == NULL ? "" : "?",
1935 		    desc->http_query == NULL ? "" : desc->http_query,
1936 		    desc->http_version == NULL ? "" : " ",
1937 		    desc->http_version == NULL ? "" : version,
1938 		    code, len,
1939 		    referrer == NULL ? "" : referrer_v,
1940 		    agent == NULL ? "" : agent_v)) == -1)
1941 			break;
1942 
1943 		if (srv_conf->logformat == LOG_FORMAT_COMBINED)
1944 			goto finish;
1945 
1946 		xff = xfp = NULL;
1947 
1948 		key.kv_key = "X-Forwarded-For";
1949 		if ((xff = kv_find(&desc->http_headers, &key)) != NULL
1950 		    && xff->kv_value == NULL)
1951 			xff = NULL;
1952 
1953 		if (xff &&
1954 		    stravis(&xff_v, xff->kv_value, HTTPD_LOGVIS) == -1)
1955 			goto finish;
1956 
1957 		key.kv_key = "X-Forwarded-Port";
1958 		if ((xfp = kv_find(&desc->http_headers, &key)) != NULL &&
1959 		    (xfp->kv_value == NULL))
1960 			xfp = NULL;
1961 
1962 		if (xfp &&
1963 		    stravis(&xfp_v, xfp->kv_value, HTTPD_LOGVIS) == -1)
1964 			goto finish;
1965 
1966 		if ((ret = evbuffer_add_printf(clt->clt_log, " %s %s",
1967 		    xff == NULL ? "-" : xff_v,
1968 		    xfp == NULL ? "-" : xfp_v)) == -1)
1969 			break;
1970 finish:
1971 		ret = evbuffer_add_printf(clt->clt_log, "\n");
1972 
1973 		break;
1974 
1975 	case LOG_FORMAT_CONNECTION:
1976 		/* URL-encode the path */
1977 		if (desc->http_path &&
1978 		    (path = url_encode(desc->http_path)) == NULL)
1979 			goto done;
1980 
1981 		ret = evbuffer_add_printf(clt->clt_log, " [%s]",
1982 		    desc->http_path == NULL ? "" : path);
1983 
1984 		break;
1985 	}
1986 
1987 done:
1988 	free(user);
1989 	free(path);
1990 	free(version);
1991 	free(referrer_v);
1992 	free(agent_v);
1993 	free(xff_v);
1994 	free(xfp_v);
1995 
1996 	return (ret);
1997 }
1998