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