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