server_fcgi.c revision 1.79
1/*	$OpenBSD: server_fcgi.c,v 1.79 2019/05/08 19:57:45 reyk 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
59struct 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
68struct fcgi_begin_request_body {
69	uint16_t	role;
70	uint8_t		flags;
71	uint8_t		reserved[5];
72} __packed;
73
74struct server_fcgi_param {
75	int		total_len;
76	uint8_t		buf[FCGI_RECORD_SIZE];
77};
78
79int	server_fcgi_header(struct client *, unsigned int);
80void	server_fcgi_read(struct bufferevent *, void *);
81int	server_fcgi_writeheader(struct client *, struct kv *, void *);
82int	server_fcgi_writechunk(struct client *);
83int	server_fcgi_getheaders(struct client *);
84int	fcgi_add_param(struct server_fcgi_param *, const char *, const char *,
85	    struct client *);
86
87int
88server_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				*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	stripped = server_root_strip(alias, srv_conf->strip);
198	if ((pathlen = asprintf(&script, "%s%s", srv_conf->root, stripped))
199	    == -1) {
200		errstr = "failed to get script name";
201		goto fail;
202	}
203
204	scriptlen = path_info(script);
205	/*
206	 * no part of root should show up in PATH_INFO.
207	 * therefore scriptlen should be >= strlen(root)
208	 */
209	if (scriptlen < strlen(srv_conf->root))
210		scriptlen = strlen(srv_conf->root);
211	if ((int)scriptlen < pathlen) {
212		if (fcgi_add_param(&param, "PATH_INFO",
213		    script + scriptlen, clt) == -1) {
214			errstr = "failed to encode param";
215			goto fail;
216		}
217		script[scriptlen] = '\0';
218	} else {
219		/* RFC 3875 mandates that PATH_INFO is empty if not set */
220		if (fcgi_add_param(&param, "PATH_INFO", "", clt) == -1) {
221			errstr = "failed to encode param";
222			goto fail;
223		}
224	}
225
226	/*
227	 * calculate length of http SCRIPT_NAME:
228	 * add length of stripped prefix,
229	 * subtract length of prepended local root
230	 */
231	scriptlen += (stripped - alias) - strlen(srv_conf->root);
232	if ((str = strndup(alias, scriptlen)) == NULL)
233		goto fail;
234	ret = fcgi_add_param(&param, "SCRIPT_NAME", str, clt);
235	free(str);
236	if (ret == -1) {
237		errstr = "failed to encode param";
238		goto fail;
239	}
240	if (fcgi_add_param(&param, "SCRIPT_FILENAME", script, clt) == -1) {
241		errstr = "failed to encode param";
242		goto fail;
243	}
244
245	if (desc->http_query) {
246		if (fcgi_add_param(&param, "QUERY_STRING", desc->http_query,
247		    clt) == -1) {
248			errstr = "failed to encode param";
249			goto fail;
250		}
251	} else if (fcgi_add_param(&param, "QUERY_STRING", "", clt) == -1) {
252		errstr = "failed to encode param";
253		goto fail;
254	}
255
256	if (fcgi_add_param(&param, "DOCUMENT_ROOT", srv_conf->root,
257	    clt) == -1) {
258		errstr = "failed to encode param";
259		goto fail;
260	}
261	if (fcgi_add_param(&param, "DOCUMENT_URI", alias,
262	    clt) == -1) {
263		errstr = "failed to encode param";
264		goto fail;
265	}
266	if (fcgi_add_param(&param, "GATEWAY_INTERFACE", "CGI/1.1",
267	    clt) == -1) {
268		errstr = "failed to encode param";
269		goto fail;
270	}
271
272	if (srv_conf->flags & SRVFLAG_AUTH) {
273		if (fcgi_add_param(&param, "REMOTE_USER",
274		    clt->clt_remote_user, clt) == -1) {
275			errstr = "failed to encode param";
276			goto fail;
277		}
278	}
279
280	/* Add HTTP_* headers */
281	if (server_headers(clt, desc, server_fcgi_writeheader, &param) == -1) {
282		errstr = "failed to encode param";
283		goto fail;
284	}
285
286	if (srv_conf->flags & SRVFLAG_TLS) {
287		if (fcgi_add_param(&param, "HTTPS", "on", clt) == -1) {
288			errstr = "failed to encode param";
289			goto fail;
290		}
291		if (srv_conf->tls_flags != 0 && fcgi_add_param(&param,
292		    "TLS_PEER_VERIFY", printb_flags(srv_conf->tls_flags,
293		    TLSFLAG_BITS), clt) == -1) {
294			errstr = "failed to encode param";
295			goto fail;
296		}
297	}
298
299	TAILQ_FOREACH(fcgiparam, &srv_conf->fcgiparams, entry) {
300		if (fcgi_add_param(&param, fcgiparam->name, fcgiparam->value,
301		    clt) == -1) {
302			errstr = "failed to encode param";
303			goto fail;
304		}
305	}
306
307	(void)print_host(&clt->clt_ss, hbuf, sizeof(hbuf));
308	if (fcgi_add_param(&param, "REMOTE_ADDR", hbuf, clt) == -1) {
309		errstr = "failed to encode param";
310		goto fail;
311	}
312
313	(void)snprintf(hbuf, sizeof(hbuf), "%d", ntohs(clt->clt_port));
314	if (fcgi_add_param(&param, "REMOTE_PORT", hbuf, clt) == -1) {
315		errstr = "failed to encode param";
316		goto fail;
317	}
318
319	if (fcgi_add_param(&param, "REQUEST_METHOD",
320	    server_httpmethod_byid(desc->http_method), clt) == -1) {
321		errstr = "failed to encode param";
322		goto fail;
323	}
324
325	if (!desc->http_query) {
326		if (fcgi_add_param(&param, "REQUEST_URI", desc->http_path,
327		    clt) == -1) {
328			errstr = "failed to encode param";
329			goto fail;
330		}
331	} else {
332		if (asprintf(&str, "%s?%s", desc->http_path,
333		    desc->http_query) == -1) {
334			errstr = "failed to encode param";
335			goto fail;
336		}
337		ret = fcgi_add_param(&param, "REQUEST_URI", str, clt);
338		free(str);
339		if (ret == -1) {
340			errstr = "failed to encode param";
341			goto fail;
342		}
343	}
344
345	(void)print_host(&clt->clt_srv_ss, hbuf, sizeof(hbuf));
346	if (fcgi_add_param(&param, "SERVER_ADDR", hbuf, clt) == -1) {
347		errstr = "failed to encode param";
348		goto fail;
349	}
350
351	(void)snprintf(hbuf, sizeof(hbuf), "%d",
352	    ntohs(server_socket_getport(&clt->clt_srv_ss)));
353	if (fcgi_add_param(&param, "SERVER_PORT", hbuf, clt) == -1) {
354		errstr = "failed to encode param";
355		goto fail;
356	}
357
358	if (fcgi_add_param(&param, "SERVER_NAME", srv_conf->name,
359	    clt) == -1) {
360		errstr = "failed to encode param";
361		goto fail;
362	}
363
364	if (fcgi_add_param(&param, "SERVER_PROTOCOL", desc->http_version,
365	    clt) == -1) {
366		errstr = "failed to encode param";
367		goto fail;
368	}
369
370	if (fcgi_add_param(&param, "SERVER_SOFTWARE", HTTPD_SERVERNAME,
371	    clt) == -1) {
372		errstr = "failed to encode param";
373		goto fail;
374	}
375
376	if (param.total_len != 0) {	/* send last params record */
377		if (bufferevent_write(clt->clt_srvbev, &param.buf,
378		    sizeof(struct fcgi_record_header) +
379		    ntohs(h->content_len)) == -1) {
380			errstr = "failed to write to client evbuffer";
381			goto fail;
382		}
383	}
384
385	/* send "no more params" message */
386	h->content_len = 0;
387	if (bufferevent_write(clt->clt_srvbev, &param.buf,
388	    sizeof(struct fcgi_record_header)) == -1) {
389		errstr = "failed to write to client evbuffer";
390		goto fail;
391	}
392
393	bufferevent_settimeout(clt->clt_srvbev,
394	    srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
395	bufferevent_enable(clt->clt_srvbev, EV_READ|EV_WRITE);
396	if (clt->clt_toread != 0) {
397		server_read_httpcontent(clt->clt_bev, clt);
398		bufferevent_enable(clt->clt_bev, EV_READ);
399	} else {
400		bufferevent_disable(clt->clt_bev, EV_READ);
401		fcgi_add_stdin(clt, NULL);
402	}
403
404	if (strcmp(desc->http_version, "HTTP/1.1") == 0) {
405		clt->clt_fcgi.chunked = 1;
406	} else {
407		/* HTTP/1.0 does not support chunked encoding */
408		clt->clt_fcgi.chunked = 0;
409		clt->clt_persist = 0;
410	}
411	clt->clt_fcgi.end = 0;
412	clt->clt_done = 0;
413
414	free(script);
415	return (0);
416 fail:
417	free(script);
418	if (errstr == NULL)
419		errstr = strerror(errno);
420	if (fd != -1 && clt->clt_fd != fd)
421		close(fd);
422	server_abort_http(clt, 500, errstr);
423	return (-1);
424}
425
426int
427fcgi_add_stdin(struct client *clt, struct evbuffer *evbuf)
428{
429	struct fcgi_record_header	h;
430
431	memset(&h, 0, sizeof(h));
432	h.version = 1;
433	h.type = FCGI_STDIN;
434	h.id = htons(1);
435	h.padding_len = 0;
436
437	if (evbuf == NULL) {
438		h.content_len = 0;
439		return bufferevent_write(clt->clt_srvbev, &h,
440		    sizeof(struct fcgi_record_header));
441	} else {
442		h.content_len = htons(EVBUFFER_LENGTH(evbuf));
443		if (bufferevent_write(clt->clt_srvbev, &h,
444		    sizeof(struct fcgi_record_header)) == -1)
445			return -1;
446		return bufferevent_write_buffer(clt->clt_srvbev, evbuf);
447	}
448	return (0);
449}
450
451int
452fcgi_add_param(struct server_fcgi_param *p, const char *key,
453    const char *val, struct client *clt)
454{
455	struct fcgi_record_header	*h;
456	int				 len = 0;
457	int				 key_len = strlen(key);
458	int				 val_len = strlen(val);
459	uint8_t				*param;
460
461	len += key_len + val_len;
462	len += key_len > 127 ? 4 : 1;
463	len += val_len > 127 ? 4 : 1;
464
465	DPRINTF("%s: %s[%d] => %s[%d], total_len: %d", __func__, key, key_len,
466	    val, val_len, p->total_len);
467
468	if (len > FCGI_CONTENT_SIZE)
469		return (-1);
470
471	if (p->total_len + len > FCGI_CONTENT_SIZE) {
472		if (bufferevent_write(clt->clt_srvbev, p->buf,
473		    sizeof(struct fcgi_record_header) + p->total_len) == -1)
474			return (-1);
475		p->total_len = 0;
476	}
477
478	h = (struct fcgi_record_header *)p->buf;
479	param = p->buf + sizeof(*h) + p->total_len;
480
481	if (key_len > 127) {
482		*param++ = ((key_len >> 24) & 0xff) | 0x80;
483		*param++ = ((key_len >> 16) & 0xff);
484		*param++ = ((key_len >> 8) & 0xff);
485		*param++ = (key_len & 0xff);
486	} else
487		*param++ = key_len;
488
489	if (val_len > 127) {
490		*param++ = ((val_len >> 24) & 0xff) | 0x80;
491		*param++ = ((val_len >> 16) & 0xff);
492		*param++ = ((val_len >> 8) & 0xff);
493		*param++ = (val_len & 0xff);
494	} else
495		*param++ = val_len;
496
497	memcpy(param, key, key_len);
498	param += key_len;
499	memcpy(param, val, val_len);
500
501	p->total_len += len;
502
503	h->content_len = htons(p->total_len);
504	return (0);
505}
506
507void
508server_fcgi_read(struct bufferevent *bev, void *arg)
509{
510	uint8_t				 buf[FCGI_RECORD_SIZE];
511	struct client			*clt = (struct client *) arg;
512	struct fcgi_record_header	*h;
513	size_t				 len;
514	char				*ptr;
515
516	do {
517		len = bufferevent_read(bev, buf, clt->clt_fcgi.toread);
518		if (evbuffer_add(clt->clt_srvevb, buf, len) == -1) {
519			server_abort_http(clt, 500, "short write");
520			return;
521		}
522		clt->clt_fcgi.toread -= len;
523		DPRINTF("%s: len: %lu toread: %d state: %d type: %d",
524		    __func__, len, clt->clt_fcgi.toread,
525		    clt->clt_fcgi.state, clt->clt_fcgi.type);
526
527		if (clt->clt_fcgi.toread != 0)
528			return;
529
530		switch (clt->clt_fcgi.state) {
531		case FCGI_READ_HEADER:
532			clt->clt_fcgi.state = FCGI_READ_CONTENT;
533			h = (struct fcgi_record_header *)
534			    EVBUFFER_DATA(clt->clt_srvevb);
535			DPRINTF("%s: record header: version %d type %d id %d "
536			    "content len %d padding %d", __func__,
537			    h->version, h->type, ntohs(h->id),
538			    ntohs(h->content_len), h->padding_len);
539			clt->clt_fcgi.type = h->type;
540			clt->clt_fcgi.toread = ntohs(h->content_len);
541			clt->clt_fcgi.padding_len = h->padding_len;
542			evbuffer_drain(clt->clt_srvevb,
543			    EVBUFFER_LENGTH(clt->clt_srvevb));
544			if (clt->clt_fcgi.toread != 0)
545				break;
546			else if (clt->clt_fcgi.type == FCGI_STDOUT &&
547			    !clt->clt_chunk) {
548				server_abort_http(clt, 500, "empty stdout");
549				return;
550			}
551
552			/* fallthrough if content_len == 0 */
553		case FCGI_READ_CONTENT:
554			switch (clt->clt_fcgi.type) {
555			case FCGI_STDERR:
556				if (EVBUFFER_LENGTH(clt->clt_srvevb) > 0 &&
557				    (ptr = get_string(
558				    EVBUFFER_DATA(clt->clt_srvevb),
559				    EVBUFFER_LENGTH(clt->clt_srvevb)))
560				    != NULL) {
561					server_sendlog(clt->clt_srv_conf,
562					    IMSG_LOG_ERROR, "%s", ptr);
563					free(ptr);
564				}
565				break;
566			case FCGI_STDOUT:
567				++clt->clt_chunk;
568				if (!clt->clt_fcgi.headersdone) {
569					clt->clt_fcgi.headersdone =
570					    server_fcgi_getheaders(clt);
571					if (clt->clt_fcgi.headersdone) {
572						if (server_fcgi_header(clt,
573						    clt->clt_fcgi.status)
574						    == -1) {
575							server_abort_http(clt,
576							    500,
577							    "malformed fcgi "
578							    "headers");
579							return;
580						}
581					}
582					if (!EVBUFFER_LENGTH(clt->clt_srvevb))
583						break;
584				}
585				/* FALLTHROUGH */
586			case FCGI_END_REQUEST:
587				if (server_fcgi_writechunk(clt) == -1) {
588					server_abort_http(clt, 500,
589					    "encoding error");
590					return;
591				}
592				break;
593			}
594			evbuffer_drain(clt->clt_srvevb,
595			    EVBUFFER_LENGTH(clt->clt_srvevb));
596			if (!clt->clt_fcgi.padding_len) {
597				clt->clt_fcgi.state = FCGI_READ_HEADER;
598				clt->clt_fcgi.toread =
599				    sizeof(struct fcgi_record_header);
600			} else {
601				clt->clt_fcgi.state = FCGI_READ_PADDING;
602				clt->clt_fcgi.toread =
603				    clt->clt_fcgi.padding_len;
604			}
605			break;
606		case FCGI_READ_PADDING:
607			evbuffer_drain(clt->clt_srvevb,
608			    EVBUFFER_LENGTH(clt->clt_srvevb));
609			clt->clt_fcgi.state = FCGI_READ_HEADER;
610			clt->clt_fcgi.toread =
611			    sizeof(struct fcgi_record_header);
612			break;
613		}
614	} while (len > 0);
615}
616
617int
618server_fcgi_header(struct client *clt, unsigned int code)
619{
620	struct server_config	*srv_conf = clt->clt_srv_conf;
621	struct http_descriptor	*desc = clt->clt_descreq;
622	struct http_descriptor	*resp = clt->clt_descresp;
623	const char		*error;
624	char			 tmbuf[32];
625	struct kv		*kv, *cl, key;
626
627	if (desc == NULL || (error = server_httperror_byid(code)) == NULL)
628		return (-1);
629
630	if (server_log_http(clt, code, 0) == -1)
631		return (-1);
632
633	/* Add error codes */
634	if (kv_setkey(&resp->http_pathquery, "%u", code) == -1 ||
635	    kv_set(&resp->http_pathquery, "%s", error) == -1)
636		return (-1);
637
638	/* Add headers */
639	if (kv_add(&resp->http_headers, "Server", HTTPD_SERVERNAME) == NULL)
640		return (-1);
641
642	/* Set chunked encoding */
643	if (clt->clt_fcgi.chunked) {
644		/* XXX Should we keep and handle Content-Length instead? */
645		key.kv_key = "Content-Length";
646		if ((kv = kv_find(&resp->http_headers, &key)) != NULL)
647			kv_delete(&resp->http_headers, kv);
648
649		/*
650		 * XXX What if the FastCGI added some kind of Transfer-Encoding?
651		 * XXX like gzip, deflate or even "chunked"?
652		 */
653		if (kv_add(&resp->http_headers,
654		    "Transfer-Encoding", "chunked") == NULL)
655			return (-1);
656	}
657
658	/* Is it a persistent connection? */
659	if (clt->clt_persist) {
660		if (kv_add(&resp->http_headers,
661		    "Connection", "keep-alive") == NULL)
662			return (-1);
663	} else if (kv_add(&resp->http_headers, "Connection", "close") == NULL)
664		return (-1);
665
666	/* HSTS header */
667	if (srv_conf->flags & SRVFLAG_SERVER_HSTS &&
668	    srv_conf->flags & SRVFLAG_TLS) {
669		if ((cl =
670		    kv_add(&resp->http_headers, "Strict-Transport-Security",
671		    NULL)) == NULL ||
672		    kv_set(cl, "max-age=%d%s%s", srv_conf->hsts_max_age,
673		    srv_conf->hsts_flags & HSTSFLAG_SUBDOMAINS ?
674		    "; includeSubDomains" : "",
675		    srv_conf->hsts_flags & HSTSFLAG_PRELOAD ?
676		    "; preload" : "") == -1)
677			return (-1);
678	}
679
680	/* Date header is mandatory and should be added as late as possible */
681	key.kv_key = "Date";
682	if ((kv = kv_find(&resp->http_headers, &key)) == NULL &&
683	    (server_http_time(time(NULL), tmbuf, sizeof(tmbuf)) <= 0 ||
684	    kv_add(&resp->http_headers, "Date", tmbuf) == NULL))
685		return (-1);
686
687	/* Write initial header (fcgi might append more) */
688	if (server_writeresponse_http(clt) == -1 ||
689	    server_bufferevent_print(clt, "\r\n") == -1 ||
690	    server_headers(clt, resp, server_writeheader_http, NULL) == -1 ||
691	    server_bufferevent_print(clt, "\r\n") == -1)
692		return (-1);
693
694	return (0);
695}
696
697int
698server_fcgi_writeheader(struct client *clt, struct kv *hdr, void *arg)
699{
700	struct server_fcgi_param	*param = arg;
701	char				*val, *name, *p;
702	const char			*key;
703	int				 ret;
704
705	if (hdr->kv_flags & KV_FLAG_INVALID)
706		return (0);
707
708	/* The key might have been updated in the parent */
709	if (hdr->kv_parent != NULL && hdr->kv_parent->kv_key != NULL)
710		key = hdr->kv_parent->kv_key;
711	else
712		key = hdr->kv_key;
713
714	val = hdr->kv_value;
715
716	if (strcasecmp(key, "Content-Length") == 0 ||
717	    strcasecmp(key, "Content-Type") == 0) {
718		if ((name = strdup(key)) == NULL)
719			return (-1);
720	} else {
721		if (asprintf(&name, "HTTP_%s", key) == -1)
722			return (-1);
723	}
724
725	/*
726	 * RFC 7230 defines a header field-name as a "token" and a "token"
727	 * is defined as one or more characters for which isalpha or
728	 * isdigit is true plus a list of additional characters.
729	 * According to RFC 3875 a CGI environment variable is created
730	 * by converting all letters to upper case and replacing '-'
731	 * with '_'.
732	 */
733	for (p = name; *p != '\0'; p++) {
734		if (isalpha((unsigned char)*p))
735			*p = toupper((unsigned char)*p);
736		else if (!(*p == '!' || *p == '#' || *p == '$' || *p == '%' ||
737		    *p == '&' || *p == '\'' || *p == '*' || *p == '+' ||
738		    *p == '.' || *p == '^' || *p == '_' || *p == '`' ||
739		    *p == '|' || *p == '~' || isdigit((unsigned char)*p)))
740			*p = '_';
741	}
742
743	ret = fcgi_add_param(param, name, val, clt);
744	free(name);
745
746	return (ret);
747}
748
749int
750server_fcgi_writechunk(struct client *clt)
751{
752	struct evbuffer *evb = clt->clt_srvevb;
753	size_t		 len;
754
755	if (clt->clt_fcgi.type == FCGI_END_REQUEST) {
756		len = 0;
757	} else
758		len = EVBUFFER_LENGTH(evb);
759
760	if (clt->clt_fcgi.chunked) {
761		/* If len is 0, make sure to write the end marker only once */
762		if (len == 0 && clt->clt_fcgi.end++)
763			return (0);
764		if (server_bufferevent_printf(clt, "%zx\r\n", len) == -1 ||
765		    server_bufferevent_write_chunk(clt, evb, len) == -1 ||
766		    server_bufferevent_print(clt, "\r\n") == -1)
767			return (-1);
768	} else if (len)
769		return (server_bufferevent_write_buffer(clt, evb));
770
771	return (0);
772}
773
774int
775server_fcgi_getheaders(struct client *clt)
776{
777	struct http_descriptor	*resp = clt->clt_descresp;
778	struct evbuffer		*evb = clt->clt_srvevb;
779	int			 code, ret;
780	char			*line, *key, *value;
781	const char		*errstr;
782
783	while ((line = evbuffer_getline(evb)) != NULL && *line != '\0') {
784		key = line;
785
786		if ((value = strchr(key, ':')) == NULL)
787			break;
788
789		*value++ = '\0';
790		value += strspn(value, " \t");
791
792		DPRINTF("%s: %s: %s", __func__, key, value);
793
794		if (strcasecmp("Status", key) == 0) {
795			value[strcspn(value, " \t")] = '\0';
796			code = (int)strtonum(value, 100, 600, &errstr);
797			if (errstr != NULL || server_httperror_byid(
798			    code) == NULL)
799				code = 200;
800			clt->clt_fcgi.status = code;
801		} else {
802			(void)kv_add(&resp->http_headers, key, value);
803		}
804		free(line);
805	}
806
807	ret = (line != NULL && *line == '\0');
808
809	free(line);
810	return ret;
811}
812