server_fcgi.c revision 1.68
1/*	$OpenBSD: server_fcgi.c,v 1.68 2016/04/24 20:09:45 chrisz 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		size_t			 len;
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		len = strlcpy(sun.sun_path,
132		    srv_conf->socket, sizeof(sun.sun_path));
133		if (len >= sizeof(sun.sun_path)) {
134			errstr = "socket path too long";
135			goto fail;
136		}
137		sun.sun_len = len;
138
139		if (connect(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1)
140			goto fail;
141	}
142
143	memset(hbuf, 0, sizeof(hbuf));
144	clt->clt_fcgi_state = FCGI_READ_HEADER;
145	clt->clt_fcgi_toread = sizeof(struct fcgi_record_header);
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
292	(void)print_host(&clt->clt_ss, hbuf, sizeof(hbuf));
293	if (fcgi_add_param(&param, "REMOTE_ADDR", hbuf, clt) == -1) {
294		errstr = "failed to encode param";
295		goto fail;
296	}
297
298	(void)snprintf(hbuf, sizeof(hbuf), "%d", ntohs(clt->clt_port));
299	if (fcgi_add_param(&param, "REMOTE_PORT", hbuf, clt) == -1) {
300		errstr = "failed to encode param";
301		goto fail;
302	}
303
304	if (fcgi_add_param(&param, "REQUEST_METHOD",
305	    server_httpmethod_byid(desc->http_method), clt) == -1) {
306		errstr = "failed to encode param";
307		goto fail;
308	}
309
310	if (!desc->http_query) {
311		if (fcgi_add_param(&param, "REQUEST_URI", desc->http_path,
312		    clt) == -1) {
313			errstr = "failed to encode param";
314			goto fail;
315		}
316	} else {
317		if (asprintf(&str, "%s?%s", desc->http_path,
318		    desc->http_query) == -1) {
319			errstr = "failed to encode param";
320			goto fail;
321		}
322		ret = fcgi_add_param(&param, "REQUEST_URI", str, clt);
323		free(str);
324		if (ret == -1) {
325			errstr = "failed to encode param";
326			goto fail;
327		}
328	}
329
330	(void)print_host(&clt->clt_srv_ss, hbuf, sizeof(hbuf));
331	if (fcgi_add_param(&param, "SERVER_ADDR", hbuf, clt) == -1) {
332		errstr = "failed to encode param";
333		goto fail;
334	}
335
336	(void)snprintf(hbuf, sizeof(hbuf), "%d",
337	    ntohs(server_socket_getport(&clt->clt_srv_ss)));
338	if (fcgi_add_param(&param, "SERVER_PORT", hbuf, clt) == -1) {
339		errstr = "failed to encode param";
340		goto fail;
341	}
342
343	if (fcgi_add_param(&param, "SERVER_NAME", srv_conf->name,
344	    clt) == -1) {
345		errstr = "failed to encode param";
346		goto fail;
347	}
348
349	if (fcgi_add_param(&param, "SERVER_PROTOCOL", desc->http_version,
350	    clt) == -1) {
351		errstr = "failed to encode param";
352		goto fail;
353	}
354
355	if (fcgi_add_param(&param, "SERVER_SOFTWARE", HTTPD_SERVERNAME,
356	    clt) == -1) {
357		errstr = "failed to encode param";
358		goto fail;
359	}
360
361	if (param.total_len != 0) {	/* send last params record */
362		if (bufferevent_write(clt->clt_srvbev, &param.buf,
363		    sizeof(struct fcgi_record_header) +
364		    ntohs(h->content_len)) == -1) {
365			errstr = "failed to write to client evbuffer";
366			goto fail;
367		}
368	}
369
370	/* send "no more params" message */
371	h->content_len = 0;
372	if (bufferevent_write(clt->clt_srvbev, &param.buf,
373	    sizeof(struct fcgi_record_header)) == -1) {
374		errstr = "failed to write to client evbuffer";
375		goto fail;
376	}
377
378	bufferevent_settimeout(clt->clt_srvbev,
379	    srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
380	bufferevent_enable(clt->clt_srvbev, EV_READ|EV_WRITE);
381	if (clt->clt_toread != 0) {
382		server_read_httpcontent(clt->clt_bev, clt);
383		bufferevent_enable(clt->clt_bev, EV_READ);
384	} else {
385		bufferevent_disable(clt->clt_bev, EV_READ);
386		fcgi_add_stdin(clt, NULL);
387	}
388
389	if (strcmp(desc->http_version, "HTTP/1.1") == 0) {
390		clt->clt_fcgi_chunked = 1;
391	} else {
392		/* HTTP/1.0 does not support chunked encoding */
393		clt->clt_fcgi_chunked = 0;
394		clt->clt_persist = 0;
395	}
396	clt->clt_fcgi_end = 0;
397	clt->clt_done = 0;
398
399	free(script);
400	return (0);
401 fail:
402	free(script);
403	if (errstr == NULL)
404		errstr = strerror(errno);
405	if (fd != -1 && clt->clt_fd != fd)
406		close(fd);
407	server_abort_http(clt, 500, errstr);
408	return (-1);
409}
410
411int
412fcgi_add_stdin(struct client *clt, struct evbuffer *evbuf)
413{
414	struct fcgi_record_header	h;
415
416	memset(&h, 0, sizeof(h));
417	h.version = 1;
418	h.type = FCGI_STDIN;
419	h.id = htons(1);
420	h.padding_len = 0;
421
422	if (evbuf == NULL) {
423		h.content_len = 0;
424		return bufferevent_write(clt->clt_srvbev, &h,
425		    sizeof(struct fcgi_record_header));
426	} else {
427		h.content_len = htons(EVBUFFER_LENGTH(evbuf));
428		if (bufferevent_write(clt->clt_srvbev, &h,
429		    sizeof(struct fcgi_record_header)) == -1)
430			return -1;
431		return bufferevent_write_buffer(clt->clt_srvbev, evbuf);
432	}
433	return (0);
434}
435
436int
437fcgi_add_param(struct server_fcgi_param *p, const char *key,
438    const char *val, struct client *clt)
439{
440	struct fcgi_record_header	*h;
441	int				 len = 0;
442	int				 key_len = strlen(key);
443	int				 val_len = strlen(val);
444	uint8_t				*param;
445
446	len += key_len + val_len;
447	len += key_len > 127 ? 4 : 1;
448	len += val_len > 127 ? 4 : 1;
449
450	DPRINTF("%s: %s[%d] => %s[%d], total_len: %d", __func__, key, key_len,
451	    val, val_len, p->total_len);
452
453	if (len > FCGI_CONTENT_SIZE)
454		return (-1);
455
456	if (p->total_len + len > FCGI_CONTENT_SIZE) {
457		if (bufferevent_write(clt->clt_srvbev, p->buf,
458		    sizeof(struct fcgi_record_header) + p->total_len) == -1)
459			return (-1);
460		p->total_len = 0;
461	}
462
463	h = (struct fcgi_record_header *)p->buf;
464	param = p->buf + sizeof(*h) + p->total_len;
465
466	if (key_len > 127) {
467		*param++ = ((key_len >> 24) & 0xff) | 0x80;
468		*param++ = ((key_len >> 16) & 0xff);
469		*param++ = ((key_len >> 8) & 0xff);
470		*param++ = (key_len & 0xff);
471	} else
472		*param++ = key_len;
473
474	if (val_len > 127) {
475		*param++ = ((val_len >> 24) & 0xff) | 0x80;
476		*param++ = ((val_len >> 16) & 0xff);
477		*param++ = ((val_len >> 8) & 0xff);
478		*param++ = (val_len & 0xff);
479	} else
480		*param++ = val_len;
481
482	memcpy(param, key, key_len);
483	param += key_len;
484	memcpy(param, val, val_len);
485
486	p->total_len += len;
487
488	h->content_len = htons(p->total_len);
489	return (0);
490}
491
492void
493server_fcgi_read(struct bufferevent *bev, void *arg)
494{
495	uint8_t				 buf[FCGI_RECORD_SIZE];
496	struct client			*clt = (struct client *) arg;
497	struct fcgi_record_header	*h;
498	size_t				 len;
499	char				*ptr;
500
501	do {
502		len = bufferevent_read(bev, buf, clt->clt_fcgi_toread);
503		if (evbuffer_add(clt->clt_srvevb, buf, len) == -1) {
504			server_abort_http(clt, 500, "short write");
505			return;
506		}
507		clt->clt_fcgi_toread -= len;
508		DPRINTF("%s: len: %lu toread: %d state: %d type: %d",
509		    __func__, len, clt->clt_fcgi_toread,
510		    clt->clt_fcgi_state, clt->clt_fcgi_type);
511
512		if (clt->clt_fcgi_toread != 0)
513			return;
514
515		switch (clt->clt_fcgi_state) {
516		case FCGI_READ_HEADER:
517			clt->clt_fcgi_state = FCGI_READ_CONTENT;
518			h = (struct fcgi_record_header *)
519			    EVBUFFER_DATA(clt->clt_srvevb);
520			DPRINTF("%s: record header: version %d type %d id %d "
521			    "content len %d padding %d", __func__,
522			    h->version, h->type, ntohs(h->id),
523			    ntohs(h->content_len), h->padding_len);
524			clt->clt_fcgi_type = h->type;
525			clt->clt_fcgi_toread = ntohs(h->content_len);
526			clt->clt_fcgi_padding_len = h->padding_len;
527			evbuffer_drain(clt->clt_srvevb,
528			    EVBUFFER_LENGTH(clt->clt_srvevb));
529			if (clt->clt_fcgi_toread != 0)
530				break;
531			else if (clt->clt_fcgi_type == FCGI_STDOUT &&
532			    !clt->clt_chunk) {
533				server_abort_http(clt, 500, "empty stdout");
534				return;
535			}
536
537			/* fallthrough if content_len == 0 */
538		case FCGI_READ_CONTENT:
539			switch (clt->clt_fcgi_type) {
540			case FCGI_STDERR:
541				if (EVBUFFER_LENGTH(clt->clt_srvevb) > 0 &&
542				    (ptr = get_string(
543				    EVBUFFER_DATA(clt->clt_srvevb),
544				    EVBUFFER_LENGTH(clt->clt_srvevb)))
545				    != NULL) {
546					server_sendlog(clt->clt_srv_conf,
547					    IMSG_LOG_ERROR, "%s", ptr);
548					free(ptr);
549				}
550				break;
551			case FCGI_STDOUT:
552				if (++clt->clt_chunk == 1) {
553					if (server_fcgi_header(clt,
554					    server_fcgi_getheaders(clt))
555					    == -1) {
556						server_abort_http(clt, 500,
557						    "malformed fcgi headers");
558						return;
559					}
560					if (!EVBUFFER_LENGTH(clt->clt_srvevb))
561						break;
562				}
563				/* FALLTHROUGH */
564			case FCGI_END_REQUEST:
565				if (server_fcgi_writechunk(clt) == -1) {
566					server_abort_http(clt, 500,
567					    "encoding error");
568					return;
569				}
570				break;
571			}
572			evbuffer_drain(clt->clt_srvevb,
573			    EVBUFFER_LENGTH(clt->clt_srvevb));
574			if (!clt->clt_fcgi_padding_len) {
575				clt->clt_fcgi_state = FCGI_READ_HEADER;
576				clt->clt_fcgi_toread =
577				    sizeof(struct fcgi_record_header);
578			} else {
579				clt->clt_fcgi_state = FCGI_READ_PADDING;
580				clt->clt_fcgi_toread =
581				    clt->clt_fcgi_padding_len;
582			}
583			break;
584		case FCGI_READ_PADDING:
585			evbuffer_drain(clt->clt_srvevb,
586			    EVBUFFER_LENGTH(clt->clt_srvevb));
587			clt->clt_fcgi_state = FCGI_READ_HEADER;
588			clt->clt_fcgi_toread =
589			    sizeof(struct fcgi_record_header);
590			break;
591		}
592	} while (len > 0);
593}
594
595int
596server_fcgi_header(struct client *clt, unsigned int code)
597{
598	struct server_config	*srv_conf = clt->clt_srv_conf;
599	struct http_descriptor	*desc = clt->clt_descreq;
600	struct http_descriptor	*resp = clt->clt_descresp;
601	const char		*error;
602	char			 tmbuf[32];
603	struct kv		*kv, *cl, key;
604
605	if (desc == NULL || (error = server_httperror_byid(code)) == NULL)
606		return (-1);
607
608	if (server_log_http(clt, code, 0) == -1)
609		return (-1);
610
611	/* Add error codes */
612	if (kv_setkey(&resp->http_pathquery, "%u", code) == -1 ||
613	    kv_set(&resp->http_pathquery, "%s", error) == -1)
614		return (-1);
615
616	/* Add headers */
617	if (kv_add(&resp->http_headers, "Server", HTTPD_SERVERNAME) == NULL)
618		return (-1);
619
620	/* Set chunked encoding */
621	if (clt->clt_fcgi_chunked) {
622		/* XXX Should we keep and handle Content-Length instead? */
623		key.kv_key = "Content-Length";
624		if ((kv = kv_find(&resp->http_headers, &key)) != NULL)
625			kv_delete(&resp->http_headers, kv);
626
627		/*
628		 * XXX What if the FastCGI added some kind of Transfer-Encoding?
629		 * XXX like gzip, deflate or even "chunked"?
630		 */
631		if (kv_add(&resp->http_headers,
632		    "Transfer-Encoding", "chunked") == NULL)
633			return (-1);
634	}
635
636	/* Is it a persistent connection? */
637	if (clt->clt_persist) {
638		if (kv_add(&resp->http_headers,
639		    "Connection", "keep-alive") == NULL)
640			return (-1);
641	} else if (kv_add(&resp->http_headers, "Connection", "close") == NULL)
642		return (-1);
643
644	/* HSTS header */
645	if (srv_conf->flags & SRVFLAG_SERVER_HSTS) {
646		if ((cl =
647		    kv_add(&resp->http_headers, "Strict-Transport-Security",
648		    NULL)) == NULL ||
649		    kv_set(cl, "max-age=%d%s%s", srv_conf->hsts_max_age,
650		    srv_conf->hsts_flags & HSTSFLAG_SUBDOMAINS ?
651		    "; includeSubDomains" : "",
652		    srv_conf->hsts_flags & HSTSFLAG_PRELOAD ?
653		    "; preload" : "") == -1)
654			return (-1);
655	}
656
657	/* Date header is mandatory and should be added as late as possible */
658	if (server_http_time(time(NULL), tmbuf, sizeof(tmbuf)) <= 0 ||
659	    kv_add(&resp->http_headers, "Date", tmbuf) == NULL)
660		return (-1);
661
662	/* Write initial header (fcgi might append more) */
663	if (server_writeresponse_http(clt) == -1 ||
664	    server_bufferevent_print(clt, "\r\n") == -1 ||
665	    server_headers(clt, resp, server_writeheader_http, NULL) == -1 ||
666	    server_bufferevent_print(clt, "\r\n") == -1)
667		return (-1);
668
669	return (0);
670}
671
672int
673server_fcgi_writeheader(struct client *clt, struct kv *hdr, void *arg)
674{
675	struct server_fcgi_param	*param = arg;
676	char				*val, *name, *p;
677	const char			*key;
678	int				 ret;
679
680	if (hdr->kv_flags & KV_FLAG_INVALID)
681		return (0);
682
683	/* The key might have been updated in the parent */
684	if (hdr->kv_parent != NULL && hdr->kv_parent->kv_key != NULL)
685		key = hdr->kv_parent->kv_key;
686	else
687		key = hdr->kv_key;
688
689	val = hdr->kv_value;
690
691	if (strcasecmp(key, "Content-Length") == 0 ||
692	    strcasecmp(key, "Content-Type") == 0) {
693		if ((name = strdup(key)) == NULL)
694			return (-1);
695	} else {
696		if (asprintf(&name, "HTTP_%s", key) == -1)
697			return (-1);
698	}
699
700	/*
701	 * RFC 7230 defines a header field-name as a "token" and a "token"
702	 * is defined as one or more characters for which isalpha or
703	 * isdigit is true plus a list of additional characters.
704	 * According to RFC 3875 a CGI environment variable is created
705	 * by converting all letters to upper case and replacing '-'
706	 * with '_'.
707	 */
708	for (p = name; *p != '\0'; p++) {
709		if (isalpha((unsigned char)*p))
710			*p = toupper((unsigned char)*p);
711		else if (!(*p == '!' || *p == '#' || *p == '$' || *p == '%' ||
712		    *p == '&' || *p == '\'' || *p == '*' || *p == '+' ||
713		    *p == '.' || *p == '^' || *p == '_' || *p == '`' ||
714		    *p == '|' || *p == '~' || isdigit((unsigned char)*p)))
715			*p = '_';
716	}
717
718	ret = fcgi_add_param(param, name, val, clt);
719	free(name);
720
721	return (ret);
722}
723
724int
725server_fcgi_writechunk(struct client *clt)
726{
727	struct evbuffer *evb = clt->clt_srvevb;
728	size_t		 len;
729
730	if (clt->clt_fcgi_type == FCGI_END_REQUEST) {
731		len = 0;
732	} else
733		len = EVBUFFER_LENGTH(evb);
734
735	if (clt->clt_fcgi_chunked) {
736		/* If len is 0, make sure to write the end marker only once */
737		if (len == 0 && clt->clt_fcgi_end++)
738			return (0);
739		if (server_bufferevent_printf(clt, "%zx\r\n", len) == -1 ||
740		    server_bufferevent_write_chunk(clt, evb, len) == -1 ||
741		    server_bufferevent_print(clt, "\r\n") == -1)
742			return (-1);
743	} else if (len)
744		return (server_bufferevent_write_buffer(clt, evb));
745
746	return (0);
747}
748
749int
750server_fcgi_getheaders(struct client *clt)
751{
752	struct http_descriptor	*resp = clt->clt_descresp;
753	struct evbuffer		*evb = clt->clt_srvevb;
754	int			 code = 200;
755	char			*line, *key, *value;
756	const char		*errstr;
757
758	while ((line = evbuffer_getline(evb)) != NULL && *line != '\0') {
759		key = line;
760
761		if ((value = strchr(key, ':')) == NULL)
762			break;
763		if (*value == ':') {
764			*value++ = '\0';
765			value += strspn(value, " \t");
766		} else {
767			*value++ = '\0';
768		}
769
770		DPRINTF("%s: %s: %s", __func__, key, value);
771
772		if (strcasecmp("Status", key) == 0) {
773			value[strcspn(value, " \t")] = '\0';
774			code = (int)strtonum(value, 100, 600, &errstr);
775			if (errstr != NULL || server_httperror_byid(
776			    code) == NULL)
777				code = 200;
778		} else {
779			(void)kv_add(&resp->http_headers, key, value);
780		}
781		free(line);
782	}
783
784	return (code);
785}
786