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