xref: /openbsd/usr.sbin/httpd/server_fcgi.c (revision 4cfece93)
1 /*	$OpenBSD: server_fcgi.c,v 1.81 2020/02/09 09:44:04 florian Exp $	*/
2 
3 /*
4  * Copyright (c) 2014 Florian Obser <florian@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/time.h>
21 #include <sys/socket.h>
22 #include <sys/un.h>
23 
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 
27 #include <limits.h>
28 #include <errno.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdio.h>
32 #include <time.h>
33 #include <ctype.h>
34 #include <event.h>
35 #include <unistd.h>
36 
37 #include "httpd.h"
38 #include "http.h"
39 
40 #define FCGI_PADDING_SIZE	 255
41 #define FCGI_RECORD_SIZE	 \
42     (sizeof(struct fcgi_record_header) + FCGI_CONTENT_SIZE + FCGI_PADDING_SIZE)
43 
44 #define FCGI_BEGIN_REQUEST	 1
45 #define FCGI_ABORT_REQUEST	 2
46 #define FCGI_END_REQUEST	 3
47 #define FCGI_PARAMS		 4
48 #define FCGI_STDIN		 5
49 #define FCGI_STDOUT		 6
50 #define FCGI_STDERR		 7
51 #define FCGI_DATA		 8
52 #define FCGI_GET_VALUES		 9
53 #define FCGI_GET_VALUES_RESULT	10
54 #define FCGI_UNKNOWN_TYPE	11
55 #define FCGI_MAXTYPE		(FCGI_UNKNOWN_TYPE)
56 
57 #define FCGI_RESPONDER		 1
58 
59 struct fcgi_record_header {
60 	uint8_t		version;
61 	uint8_t		type;
62 	uint16_t	id;
63 	uint16_t	content_len;
64 	uint8_t		padding_len;
65 	uint8_t		reserved;
66 } __packed;
67 
68 struct fcgi_begin_request_body {
69 	uint16_t	role;
70 	uint8_t		flags;
71 	uint8_t		reserved[5];
72 } __packed;
73 
74 struct server_fcgi_param {
75 	int		total_len;
76 	uint8_t		buf[FCGI_RECORD_SIZE];
77 };
78 
79 int	server_fcgi_header(struct client *, unsigned int);
80 void	server_fcgi_read(struct bufferevent *, void *);
81 int	server_fcgi_writeheader(struct client *, struct kv *, void *);
82 int	server_fcgi_writechunk(struct client *);
83 int	server_fcgi_getheaders(struct client *);
84 int	fcgi_add_param(struct server_fcgi_param *, const char *, const char *,
85 	    struct client *);
86 
87 int
88 server_fcgi(struct httpd *env, struct client *clt)
89 {
90 	struct server_fcgi_param	 param;
91 	struct server_config		*srv_conf = clt->clt_srv_conf;
92 	struct http_descriptor		*desc = clt->clt_descreq;
93 	struct fcgi_record_header	*h;
94 	struct fcgi_begin_request_body	*begin;
95 	struct fastcgi_param		*fcgiparam;
96 	char				 hbuf[HOST_NAME_MAX+1];
97 	size_t				 scriptlen;
98 	int				 pathlen;
99 	int				 fd = -1, ret;
100 	const char			*stripped, *p, *alias, *errstr = NULL;
101 	char				*query_alias, *str, *script = NULL;
102 
103 	if (srv_conf->socket[0] == ':') {
104 		struct sockaddr_storage	 ss;
105 		in_port_t		 port;
106 
107 		p = srv_conf->socket + 1;
108 
109 		port = strtonum(p, 0, 0xffff, &errstr);
110 		if (errstr != NULL) {
111 			log_warn("%s: strtonum %s, %s", __func__, p, errstr);
112 			goto fail;
113 		}
114 		memset(&ss, 0, sizeof(ss));
115 		ss.ss_family = AF_INET;
116 		((struct sockaddr_in *)
117 		    &ss)->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
118 		port = htons(port);
119 
120 		if ((fd = server_socket_connect(&ss, port, srv_conf)) == -1)
121 			goto fail;
122 	} else {
123 		struct sockaddr_un	 sun;
124 
125 		if ((fd = socket(AF_UNIX,
126 		    SOCK_STREAM | SOCK_NONBLOCK, 0)) == -1)
127 			goto fail;
128 
129 		memset(&sun, 0, sizeof(sun));
130 		sun.sun_family = AF_UNIX;
131 		if (strlcpy(sun.sun_path, srv_conf->socket,
132 		    sizeof(sun.sun_path)) >= sizeof(sun.sun_path)) {
133 			errstr = "socket path to long";
134 			goto fail;
135 		}
136 
137 		if (connect(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1)
138 			goto fail;
139 	}
140 
141 	memset(hbuf, 0, sizeof(hbuf));
142 	clt->clt_fcgi.state = FCGI_READ_HEADER;
143 	clt->clt_fcgi.toread = sizeof(struct fcgi_record_header);
144 	clt->clt_fcgi.status = 200;
145 	clt->clt_fcgi.headersdone = 0;
146 
147 	if (clt->clt_srvevb != NULL)
148 		evbuffer_free(clt->clt_srvevb);
149 
150 	clt->clt_srvevb = evbuffer_new();
151 	if (clt->clt_srvevb == NULL) {
152 		errstr = "failed to allocate evbuffer";
153 		goto fail;
154 	}
155 
156 	close(clt->clt_fd);
157 	clt->clt_fd = fd;
158 
159 	if (clt->clt_srvbev != NULL)
160 		bufferevent_free(clt->clt_srvbev);
161 
162 	clt->clt_srvbev_throttled = 0;
163 	clt->clt_srvbev = bufferevent_new(fd, server_fcgi_read,
164 	    NULL, server_file_error, clt);
165 	if (clt->clt_srvbev == NULL) {
166 		errstr = "failed to allocate fcgi buffer event";
167 		goto fail;
168 	}
169 
170 	memset(&param, 0, sizeof(param));
171 
172 	h = (struct fcgi_record_header *)&param.buf;
173 	h->version = 1;
174 	h->type = FCGI_BEGIN_REQUEST;
175 	h->id = htons(1);
176 	h->content_len = htons(sizeof(struct fcgi_begin_request_body));
177 	h->padding_len = 0;
178 
179 	begin = (struct fcgi_begin_request_body *)&param.buf[sizeof(struct
180 	    fcgi_record_header)];
181 	begin->role = htons(FCGI_RESPONDER);
182 
183 	if (bufferevent_write(clt->clt_srvbev, &param.buf,
184 	    sizeof(struct fcgi_record_header) +
185 	    sizeof(struct fcgi_begin_request_body)) == -1) {
186 		errstr = "failed to write to evbuffer";
187 		goto fail;
188 	}
189 
190 	h->type = FCGI_PARAMS;
191 	h->content_len = param.total_len = 0;
192 
193 	alias = desc->http_path_alias != NULL
194 	    ? desc->http_path_alias
195 	    : desc->http_path;
196 
197 	query_alias = desc->http_query_alias != NULL
198 	    ? desc->http_query_alias
199 	    : desc->http_query;
200 
201 	stripped = server_root_strip(alias, srv_conf->strip);
202 	if ((pathlen = asprintf(&script, "%s%s", srv_conf->root, stripped))
203 	    == -1) {
204 		errstr = "failed to get script name";
205 		goto fail;
206 	}
207 
208 	scriptlen = path_info(script);
209 	/*
210 	 * no part of root should show up in PATH_INFO.
211 	 * therefore scriptlen should be >= strlen(root)
212 	 */
213 	if (scriptlen < strlen(srv_conf->root))
214 		scriptlen = strlen(srv_conf->root);
215 	if ((int)scriptlen < pathlen) {
216 		if (fcgi_add_param(&param, "PATH_INFO",
217 		    script + scriptlen, clt) == -1) {
218 			errstr = "failed to encode param";
219 			goto fail;
220 		}
221 		script[scriptlen] = '\0';
222 	} else {
223 		/* RFC 3875 mandates that PATH_INFO is empty if not set */
224 		if (fcgi_add_param(&param, "PATH_INFO", "", clt) == -1) {
225 			errstr = "failed to encode param";
226 			goto fail;
227 		}
228 	}
229 
230 	/*
231 	 * calculate length of http SCRIPT_NAME:
232 	 * add length of stripped prefix,
233 	 * subtract length of prepended local root
234 	 */
235 	scriptlen += (stripped - alias) - strlen(srv_conf->root);
236 	if ((str = strndup(alias, scriptlen)) == NULL)
237 		goto fail;
238 	ret = fcgi_add_param(&param, "SCRIPT_NAME", str, clt);
239 	free(str);
240 	if (ret == -1) {
241 		errstr = "failed to encode param";
242 		goto fail;
243 	}
244 	if (fcgi_add_param(&param, "SCRIPT_FILENAME", server_root_strip(script,
245 	    srv_conf->fcgistrip), clt) == -1) {
246 		errstr = "failed to encode param";
247 		goto fail;
248 	}
249 
250 	if (query_alias) {
251 		if (fcgi_add_param(&param, "QUERY_STRING", query_alias,
252 		    clt) == -1) {
253 			errstr = "failed to encode param";
254 			goto fail;
255 		}
256 	} else if (fcgi_add_param(&param, "QUERY_STRING", "", clt) == -1) {
257 		errstr = "failed to encode param";
258 		goto fail;
259 	}
260 
261 	if (fcgi_add_param(&param, "DOCUMENT_ROOT", server_root_strip(
262 	    srv_conf->root, srv_conf->fcgistrip), clt) == -1) {
263 		errstr = "failed to encode param";
264 		goto fail;
265 	}
266 	if (fcgi_add_param(&param, "DOCUMENT_URI", alias,
267 	    clt) == -1) {
268 		errstr = "failed to encode param";
269 		goto fail;
270 	}
271 	if (fcgi_add_param(&param, "GATEWAY_INTERFACE", "CGI/1.1",
272 	    clt) == -1) {
273 		errstr = "failed to encode param";
274 		goto fail;
275 	}
276 
277 	if (srv_conf->flags & SRVFLAG_AUTH) {
278 		if (fcgi_add_param(&param, "REMOTE_USER",
279 		    clt->clt_remote_user, clt) == -1) {
280 			errstr = "failed to encode param";
281 			goto fail;
282 		}
283 	}
284 
285 	/* Add HTTP_* headers */
286 	if (server_headers(clt, desc, server_fcgi_writeheader, &param) == -1) {
287 		errstr = "failed to encode param";
288 		goto fail;
289 	}
290 
291 	if (srv_conf->flags & SRVFLAG_TLS) {
292 		if (fcgi_add_param(&param, "HTTPS", "on", clt) == -1) {
293 			errstr = "failed to encode param";
294 			goto fail;
295 		}
296 		if (srv_conf->tls_flags != 0 && fcgi_add_param(&param,
297 		    "TLS_PEER_VERIFY", printb_flags(srv_conf->tls_flags,
298 		    TLSFLAG_BITS), clt) == -1) {
299 			errstr = "failed to encode param";
300 			goto fail;
301 		}
302 	}
303 
304 	TAILQ_FOREACH(fcgiparam, &srv_conf->fcgiparams, entry) {
305 		if (fcgi_add_param(&param, fcgiparam->name, fcgiparam->value,
306 		    clt) == -1) {
307 			errstr = "failed to encode param";
308 			goto fail;
309 		}
310 	}
311 
312 	(void)print_host(&clt->clt_ss, hbuf, sizeof(hbuf));
313 	if (fcgi_add_param(&param, "REMOTE_ADDR", hbuf, clt) == -1) {
314 		errstr = "failed to encode param";
315 		goto fail;
316 	}
317 
318 	(void)snprintf(hbuf, sizeof(hbuf), "%d", ntohs(clt->clt_port));
319 	if (fcgi_add_param(&param, "REMOTE_PORT", hbuf, clt) == -1) {
320 		errstr = "failed to encode param";
321 		goto fail;
322 	}
323 
324 	if (fcgi_add_param(&param, "REQUEST_METHOD",
325 	    server_httpmethod_byid(desc->http_method), clt) == -1) {
326 		errstr = "failed to encode param";
327 		goto fail;
328 	}
329 
330 	if (!desc->http_query) {
331 		if (fcgi_add_param(&param, "REQUEST_URI", desc->http_path,
332 		    clt) == -1) {
333 			errstr = "failed to encode param";
334 			goto fail;
335 		}
336 	} else {
337 		if (asprintf(&str, "%s?%s", desc->http_path,
338 		    desc->http_query) == -1) {
339 			errstr = "failed to encode param";
340 			goto fail;
341 		}
342 		ret = fcgi_add_param(&param, "REQUEST_URI", str, clt);
343 		free(str);
344 		if (ret == -1) {
345 			errstr = "failed to encode param";
346 			goto fail;
347 		}
348 	}
349 
350 	(void)print_host(&clt->clt_srv_ss, hbuf, sizeof(hbuf));
351 	if (fcgi_add_param(&param, "SERVER_ADDR", hbuf, clt) == -1) {
352 		errstr = "failed to encode param";
353 		goto fail;
354 	}
355 
356 	(void)snprintf(hbuf, sizeof(hbuf), "%d",
357 	    ntohs(server_socket_getport(&clt->clt_srv_ss)));
358 	if (fcgi_add_param(&param, "SERVER_PORT", hbuf, clt) == -1) {
359 		errstr = "failed to encode param";
360 		goto fail;
361 	}
362 
363 	if (fcgi_add_param(&param, "SERVER_NAME", srv_conf->name,
364 	    clt) == -1) {
365 		errstr = "failed to encode param";
366 		goto fail;
367 	}
368 
369 	if (fcgi_add_param(&param, "SERVER_PROTOCOL", desc->http_version,
370 	    clt) == -1) {
371 		errstr = "failed to encode param";
372 		goto fail;
373 	}
374 
375 	if (fcgi_add_param(&param, "SERVER_SOFTWARE", HTTPD_SERVERNAME,
376 	    clt) == -1) {
377 		errstr = "failed to encode param";
378 		goto fail;
379 	}
380 
381 	if (param.total_len != 0) {	/* send last params record */
382 		if (bufferevent_write(clt->clt_srvbev, &param.buf,
383 		    sizeof(struct fcgi_record_header) +
384 		    ntohs(h->content_len)) == -1) {
385 			errstr = "failed to write to client evbuffer";
386 			goto fail;
387 		}
388 	}
389 
390 	/* send "no more params" message */
391 	h->content_len = 0;
392 	if (bufferevent_write(clt->clt_srvbev, &param.buf,
393 	    sizeof(struct fcgi_record_header)) == -1) {
394 		errstr = "failed to write to client evbuffer";
395 		goto fail;
396 	}
397 
398 	bufferevent_settimeout(clt->clt_srvbev,
399 	    srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
400 	bufferevent_enable(clt->clt_srvbev, EV_READ|EV_WRITE);
401 	if (clt->clt_toread != 0) {
402 		server_read_httpcontent(clt->clt_bev, clt);
403 		bufferevent_enable(clt->clt_bev, EV_READ);
404 	} else {
405 		bufferevent_disable(clt->clt_bev, EV_READ);
406 		fcgi_add_stdin(clt, NULL);
407 	}
408 
409 	if (strcmp(desc->http_version, "HTTP/1.1") == 0) {
410 		clt->clt_fcgi.chunked = 1;
411 	} else {
412 		/* HTTP/1.0 does not support chunked encoding */
413 		clt->clt_fcgi.chunked = 0;
414 		clt->clt_persist = 0;
415 	}
416 	clt->clt_fcgi.end = 0;
417 	clt->clt_done = 0;
418 
419 	free(script);
420 	return (0);
421  fail:
422 	free(script);
423 	if (errstr == NULL)
424 		errstr = strerror(errno);
425 	if (fd != -1 && clt->clt_fd != fd)
426 		close(fd);
427 	server_abort_http(clt, 500, errstr);
428 	return (-1);
429 }
430 
431 int
432 fcgi_add_stdin(struct client *clt, struct evbuffer *evbuf)
433 {
434 	struct fcgi_record_header	h;
435 
436 	memset(&h, 0, sizeof(h));
437 	h.version = 1;
438 	h.type = FCGI_STDIN;
439 	h.id = htons(1);
440 	h.padding_len = 0;
441 
442 	if (evbuf == NULL) {
443 		h.content_len = 0;
444 		return bufferevent_write(clt->clt_srvbev, &h,
445 		    sizeof(struct fcgi_record_header));
446 	} else {
447 		h.content_len = htons(EVBUFFER_LENGTH(evbuf));
448 		if (bufferevent_write(clt->clt_srvbev, &h,
449 		    sizeof(struct fcgi_record_header)) == -1)
450 			return -1;
451 		return bufferevent_write_buffer(clt->clt_srvbev, evbuf);
452 	}
453 	return (0);
454 }
455 
456 int
457 fcgi_add_param(struct server_fcgi_param *p, const char *key,
458     const char *val, struct client *clt)
459 {
460 	struct fcgi_record_header	*h;
461 	int				 len = 0;
462 	int				 key_len = strlen(key);
463 	int				 val_len = strlen(val);
464 	uint8_t				*param;
465 
466 	len += key_len + val_len;
467 	len += key_len > 127 ? 4 : 1;
468 	len += val_len > 127 ? 4 : 1;
469 
470 	DPRINTF("%s: %s[%d] => %s[%d], total_len: %d", __func__, key, key_len,
471 	    val, val_len, p->total_len);
472 
473 	if (len > FCGI_CONTENT_SIZE)
474 		return (-1);
475 
476 	if (p->total_len + len > FCGI_CONTENT_SIZE) {
477 		if (bufferevent_write(clt->clt_srvbev, p->buf,
478 		    sizeof(struct fcgi_record_header) + p->total_len) == -1)
479 			return (-1);
480 		p->total_len = 0;
481 	}
482 
483 	h = (struct fcgi_record_header *)p->buf;
484 	param = p->buf + sizeof(*h) + p->total_len;
485 
486 	if (key_len > 127) {
487 		*param++ = ((key_len >> 24) & 0xff) | 0x80;
488 		*param++ = ((key_len >> 16) & 0xff);
489 		*param++ = ((key_len >> 8) & 0xff);
490 		*param++ = (key_len & 0xff);
491 	} else
492 		*param++ = key_len;
493 
494 	if (val_len > 127) {
495 		*param++ = ((val_len >> 24) & 0xff) | 0x80;
496 		*param++ = ((val_len >> 16) & 0xff);
497 		*param++ = ((val_len >> 8) & 0xff);
498 		*param++ = (val_len & 0xff);
499 	} else
500 		*param++ = val_len;
501 
502 	memcpy(param, key, key_len);
503 	param += key_len;
504 	memcpy(param, val, val_len);
505 
506 	p->total_len += len;
507 
508 	h->content_len = htons(p->total_len);
509 	return (0);
510 }
511 
512 void
513 server_fcgi_read(struct bufferevent *bev, void *arg)
514 {
515 	uint8_t				 buf[FCGI_RECORD_SIZE];
516 	struct client			*clt = (struct client *) arg;
517 	struct fcgi_record_header	*h;
518 	size_t				 len;
519 	char				*ptr;
520 
521 	do {
522 		len = bufferevent_read(bev, buf, clt->clt_fcgi.toread);
523 		if (evbuffer_add(clt->clt_srvevb, buf, len) == -1) {
524 			server_abort_http(clt, 500, "short write");
525 			return;
526 		}
527 		clt->clt_fcgi.toread -= len;
528 		DPRINTF("%s: len: %lu toread: %d state: %d type: %d",
529 		    __func__, len, clt->clt_fcgi.toread,
530 		    clt->clt_fcgi.state, clt->clt_fcgi.type);
531 
532 		if (clt->clt_fcgi.toread != 0)
533 			return;
534 
535 		switch (clt->clt_fcgi.state) {
536 		case FCGI_READ_HEADER:
537 			clt->clt_fcgi.state = FCGI_READ_CONTENT;
538 			h = (struct fcgi_record_header *)
539 			    EVBUFFER_DATA(clt->clt_srvevb);
540 			DPRINTF("%s: record header: version %d type %d id %d "
541 			    "content len %d padding %d", __func__,
542 			    h->version, h->type, ntohs(h->id),
543 			    ntohs(h->content_len), h->padding_len);
544 			clt->clt_fcgi.type = h->type;
545 			clt->clt_fcgi.toread = ntohs(h->content_len);
546 			clt->clt_fcgi.padding_len = h->padding_len;
547 			evbuffer_drain(clt->clt_srvevb,
548 			    EVBUFFER_LENGTH(clt->clt_srvevb));
549 			if (clt->clt_fcgi.toread != 0)
550 				break;
551 			else if (clt->clt_fcgi.type == FCGI_STDOUT &&
552 			    !clt->clt_chunk) {
553 				server_abort_http(clt, 500, "empty stdout");
554 				return;
555 			}
556 
557 			/* fallthrough if content_len == 0 */
558 		case FCGI_READ_CONTENT:
559 			switch (clt->clt_fcgi.type) {
560 			case FCGI_STDERR:
561 				if (EVBUFFER_LENGTH(clt->clt_srvevb) > 0 &&
562 				    (ptr = get_string(
563 				    EVBUFFER_DATA(clt->clt_srvevb),
564 				    EVBUFFER_LENGTH(clt->clt_srvevb)))
565 				    != NULL) {
566 					server_sendlog(clt->clt_srv_conf,
567 					    IMSG_LOG_ERROR, "%s", ptr);
568 					free(ptr);
569 				}
570 				break;
571 			case FCGI_STDOUT:
572 				++clt->clt_chunk;
573 				if (!clt->clt_fcgi.headersdone) {
574 					clt->clt_fcgi.headersdone =
575 					    server_fcgi_getheaders(clt);
576 					if (clt->clt_fcgi.headersdone) {
577 						if (server_fcgi_header(clt,
578 						    clt->clt_fcgi.status)
579 						    == -1) {
580 							server_abort_http(clt,
581 							    500,
582 							    "malformed fcgi "
583 							    "headers");
584 							return;
585 						}
586 					}
587 					if (!EVBUFFER_LENGTH(clt->clt_srvevb))
588 						break;
589 				}
590 				/* FALLTHROUGH */
591 			case FCGI_END_REQUEST:
592 				if (server_fcgi_writechunk(clt) == -1) {
593 					server_abort_http(clt, 500,
594 					    "encoding error");
595 					return;
596 				}
597 				break;
598 			}
599 			evbuffer_drain(clt->clt_srvevb,
600 			    EVBUFFER_LENGTH(clt->clt_srvevb));
601 			if (!clt->clt_fcgi.padding_len) {
602 				clt->clt_fcgi.state = FCGI_READ_HEADER;
603 				clt->clt_fcgi.toread =
604 				    sizeof(struct fcgi_record_header);
605 			} else {
606 				clt->clt_fcgi.state = FCGI_READ_PADDING;
607 				clt->clt_fcgi.toread =
608 				    clt->clt_fcgi.padding_len;
609 			}
610 			break;
611 		case FCGI_READ_PADDING:
612 			evbuffer_drain(clt->clt_srvevb,
613 			    EVBUFFER_LENGTH(clt->clt_srvevb));
614 			clt->clt_fcgi.state = FCGI_READ_HEADER;
615 			clt->clt_fcgi.toread =
616 			    sizeof(struct fcgi_record_header);
617 			break;
618 		}
619 	} while (len > 0);
620 }
621 
622 int
623 server_fcgi_header(struct client *clt, unsigned int code)
624 {
625 	struct server_config	*srv_conf = clt->clt_srv_conf;
626 	struct http_descriptor	*desc = clt->clt_descreq;
627 	struct http_descriptor	*resp = clt->clt_descresp;
628 	const char		*error;
629 	char			 tmbuf[32];
630 	struct kv		*kv, *cl, key;
631 
632 	if (desc == NULL || (error = server_httperror_byid(code)) == NULL)
633 		return (-1);
634 
635 	if (server_log_http(clt, code, 0) == -1)
636 		return (-1);
637 
638 	/* Add error codes */
639 	if (kv_setkey(&resp->http_pathquery, "%u", code) == -1 ||
640 	    kv_set(&resp->http_pathquery, "%s", error) == -1)
641 		return (-1);
642 
643 	/* Add headers */
644 	if (kv_add(&resp->http_headers, "Server", HTTPD_SERVERNAME) == NULL)
645 		return (-1);
646 
647 	/* Set chunked encoding */
648 	if (clt->clt_fcgi.chunked) {
649 		/* XXX Should we keep and handle Content-Length instead? */
650 		key.kv_key = "Content-Length";
651 		if ((kv = kv_find(&resp->http_headers, &key)) != NULL)
652 			kv_delete(&resp->http_headers, kv);
653 
654 		/*
655 		 * XXX What if the FastCGI added some kind of Transfer-Encoding?
656 		 * XXX like gzip, deflate or even "chunked"?
657 		 */
658 		if (kv_add(&resp->http_headers,
659 		    "Transfer-Encoding", "chunked") == NULL)
660 			return (-1);
661 	}
662 
663 	/* Is it a persistent connection? */
664 	if (clt->clt_persist) {
665 		if (kv_add(&resp->http_headers,
666 		    "Connection", "keep-alive") == NULL)
667 			return (-1);
668 	} else if (kv_add(&resp->http_headers, "Connection", "close") == NULL)
669 		return (-1);
670 
671 	/* HSTS header */
672 	if (srv_conf->flags & SRVFLAG_SERVER_HSTS &&
673 	    srv_conf->flags & SRVFLAG_TLS) {
674 		if ((cl =
675 		    kv_add(&resp->http_headers, "Strict-Transport-Security",
676 		    NULL)) == NULL ||
677 		    kv_set(cl, "max-age=%d%s%s", srv_conf->hsts_max_age,
678 		    srv_conf->hsts_flags & HSTSFLAG_SUBDOMAINS ?
679 		    "; includeSubDomains" : "",
680 		    srv_conf->hsts_flags & HSTSFLAG_PRELOAD ?
681 		    "; preload" : "") == -1)
682 			return (-1);
683 	}
684 
685 	/* Date header is mandatory and should be added as late as possible */
686 	key.kv_key = "Date";
687 	if ((kv = kv_find(&resp->http_headers, &key)) == NULL &&
688 	    (server_http_time(time(NULL), tmbuf, sizeof(tmbuf)) <= 0 ||
689 	    kv_add(&resp->http_headers, "Date", tmbuf) == NULL))
690 		return (-1);
691 
692 	/* Write initial header (fcgi might append more) */
693 	if (server_writeresponse_http(clt) == -1 ||
694 	    server_bufferevent_print(clt, "\r\n") == -1 ||
695 	    server_headers(clt, resp, server_writeheader_http, NULL) == -1 ||
696 	    server_bufferevent_print(clt, "\r\n") == -1)
697 		return (-1);
698 
699 	return (0);
700 }
701 
702 int
703 server_fcgi_writeheader(struct client *clt, struct kv *hdr, void *arg)
704 {
705 	struct server_fcgi_param	*param = arg;
706 	char				*val, *name, *p;
707 	const char			*key;
708 	int				 ret;
709 
710 	if (hdr->kv_flags & KV_FLAG_INVALID)
711 		return (0);
712 
713 	/* The key might have been updated in the parent */
714 	if (hdr->kv_parent != NULL && hdr->kv_parent->kv_key != NULL)
715 		key = hdr->kv_parent->kv_key;
716 	else
717 		key = hdr->kv_key;
718 
719 	val = hdr->kv_value;
720 
721 	if (strcasecmp(key, "Content-Length") == 0 ||
722 	    strcasecmp(key, "Content-Type") == 0) {
723 		if ((name = strdup(key)) == NULL)
724 			return (-1);
725 	} else {
726 		if (asprintf(&name, "HTTP_%s", key) == -1)
727 			return (-1);
728 	}
729 
730 	/*
731 	 * RFC 7230 defines a header field-name as a "token" and a "token"
732 	 * is defined as one or more characters for which isalpha or
733 	 * isdigit is true plus a list of additional characters.
734 	 * According to RFC 3875 a CGI environment variable is created
735 	 * by converting all letters to upper case and replacing '-'
736 	 * with '_'.
737 	 */
738 	for (p = name; *p != '\0'; p++) {
739 		if (isalpha((unsigned char)*p))
740 			*p = toupper((unsigned char)*p);
741 		else if (!(*p == '!' || *p == '#' || *p == '$' || *p == '%' ||
742 		    *p == '&' || *p == '\'' || *p == '*' || *p == '+' ||
743 		    *p == '.' || *p == '^' || *p == '_' || *p == '`' ||
744 		    *p == '|' || *p == '~' || isdigit((unsigned char)*p)))
745 			*p = '_';
746 	}
747 
748 	ret = fcgi_add_param(param, name, val, clt);
749 	free(name);
750 
751 	return (ret);
752 }
753 
754 int
755 server_fcgi_writechunk(struct client *clt)
756 {
757 	struct evbuffer *evb = clt->clt_srvevb;
758 	size_t		 len;
759 
760 	if (clt->clt_fcgi.type == FCGI_END_REQUEST) {
761 		len = 0;
762 	} else
763 		len = EVBUFFER_LENGTH(evb);
764 
765 	if (clt->clt_fcgi.chunked) {
766 		/* If len is 0, make sure to write the end marker only once */
767 		if (len == 0 && clt->clt_fcgi.end++)
768 			return (0);
769 		if (server_bufferevent_printf(clt, "%zx\r\n", len) == -1 ||
770 		    server_bufferevent_write_chunk(clt, evb, len) == -1 ||
771 		    server_bufferevent_print(clt, "\r\n") == -1)
772 			return (-1);
773 	} else if (len)
774 		return (server_bufferevent_write_buffer(clt, evb));
775 
776 	return (0);
777 }
778 
779 int
780 server_fcgi_getheaders(struct client *clt)
781 {
782 	struct http_descriptor	*resp = clt->clt_descresp;
783 	struct evbuffer		*evb = clt->clt_srvevb;
784 	int			 code, ret;
785 	char			*line, *key, *value;
786 	const char		*errstr;
787 
788 	while ((line = evbuffer_getline(evb)) != NULL && *line != '\0') {
789 		key = line;
790 
791 		if ((value = strchr(key, ':')) == NULL)
792 			break;
793 
794 		*value++ = '\0';
795 		value += strspn(value, " \t");
796 
797 		DPRINTF("%s: %s: %s", __func__, key, value);
798 
799 		if (strcasecmp("Status", key) == 0) {
800 			value[strcspn(value, " \t")] = '\0';
801 			code = (int)strtonum(value, 100, 600, &errstr);
802 			if (errstr != NULL || server_httperror_byid(
803 			    code) == NULL)
804 				code = 200;
805 			clt->clt_fcgi.status = code;
806 		} else {
807 			(void)kv_add(&resp->http_headers, key, value);
808 		}
809 		free(line);
810 	}
811 
812 	ret = (line != NULL && *line == '\0');
813 
814 	free(line);
815 	return ret;
816 }
817