server_fcgi.c revision 1.58
1/*	$OpenBSD: server_fcgi.c,v 1.58 2015/07/19 16:34:35 blambert 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 *, u_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 to 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 = 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	server_abort_http(clt, 500, errstr);
402	return (-1);
403}
404
405int
406fcgi_add_stdin(struct client *clt, struct evbuffer *evbuf)
407{
408	struct fcgi_record_header	h;
409
410	memset(&h, 0, sizeof(h));
411	h.version = 1;
412	h.type = FCGI_STDIN;
413	h.id = htons(1);
414	h.padding_len = 0;
415
416	if (evbuf == NULL) {
417		h.content_len = 0;
418		return bufferevent_write(clt->clt_srvbev, &h,
419		    sizeof(struct fcgi_record_header));
420	} else {
421		h.content_len = htons(EVBUFFER_LENGTH(evbuf));
422		if (bufferevent_write(clt->clt_srvbev, &h,
423		    sizeof(struct fcgi_record_header)) == -1)
424			return -1;
425		return bufferevent_write_buffer(clt->clt_srvbev, evbuf);
426	}
427	return (0);
428}
429
430int
431fcgi_add_param(struct server_fcgi_param *p, const char *key,
432    const char *val, struct client *clt)
433{
434	struct fcgi_record_header	*h;
435	int				 len = 0;
436	int				 key_len = strlen(key);
437	int				 val_len = strlen(val);
438	uint8_t				*param;
439
440	len += key_len + val_len;
441	len += key_len > 127 ? 4 : 1;
442	len += val_len > 127 ? 4 : 1;
443
444	DPRINTF("%s: %s[%d] => %s[%d], total_len: %d", __func__, key, key_len,
445	    val, val_len, p->total_len);
446
447	if (len > FCGI_CONTENT_SIZE)
448		return (-1);
449
450	if (p->total_len + len > FCGI_CONTENT_SIZE) {
451		if (bufferevent_write(clt->clt_srvbev, p->buf,
452		    sizeof(struct fcgi_record_header) + p->total_len) == -1)
453			return (-1);
454		p->total_len = 0;
455	}
456
457	h = (struct fcgi_record_header *)p->buf;
458	param = p->buf + sizeof(*h) + p->total_len;
459
460	if (key_len > 127) {
461		*param++ = ((key_len >> 24) & 0xff) | 0x80;
462		*param++ = ((key_len >> 16) & 0xff);
463		*param++ = ((key_len >> 8) & 0xff);
464		*param++ = (key_len & 0xff);
465	} else
466		*param++ = key_len;
467
468	if (val_len > 127) {
469		*param++ = ((val_len >> 24) & 0xff) | 0x80;
470		*param++ = ((val_len >> 16) & 0xff);
471		*param++ = ((val_len >> 8) & 0xff);
472		*param++ = (val_len & 0xff);
473	} else
474		*param++ = val_len;
475
476	memcpy(param, key, key_len);
477	param += key_len;
478	memcpy(param, val, val_len);
479
480	p->total_len += len;
481
482	h->content_len = htons(p->total_len);
483	return (0);
484}
485
486void
487server_fcgi_read(struct bufferevent *bev, void *arg)
488{
489	uint8_t				 buf[FCGI_RECORD_SIZE];
490	struct client			*clt = (struct client *) arg;
491	struct fcgi_record_header	*h;
492	size_t				 len;
493	char				*ptr;
494
495	do {
496		len = bufferevent_read(bev, buf, clt->clt_fcgi_toread);
497		if (evbuffer_add(clt->clt_srvevb, buf, len) == -1) {
498			server_abort_http(clt, 500, "short write");
499			return;
500		}
501		clt->clt_fcgi_toread -= len;
502		DPRINTF("%s: len: %lu toread: %d state: %d type: %d",
503		    __func__, len, clt->clt_fcgi_toread,
504		    clt->clt_fcgi_state, clt->clt_fcgi_type);
505
506		if (clt->clt_fcgi_toread != 0)
507			return;
508
509		switch (clt->clt_fcgi_state) {
510		case FCGI_READ_HEADER:
511			clt->clt_fcgi_state = FCGI_READ_CONTENT;
512			h = (struct fcgi_record_header *)
513			    EVBUFFER_DATA(clt->clt_srvevb);
514			DPRINTF("%s: record header: version %d type %d id %d "
515			    "content len %d padding %d", __func__,
516			    h->version, h->type, ntohs(h->id),
517			    ntohs(h->content_len), h->padding_len);
518			clt->clt_fcgi_type = h->type;
519			clt->clt_fcgi_toread = ntohs(h->content_len);
520			clt->clt_fcgi_padding_len = h->padding_len;
521			evbuffer_drain(clt->clt_srvevb,
522			    EVBUFFER_LENGTH(clt->clt_srvevb));
523			if (clt->clt_fcgi_toread != 0)
524				break;
525			else if (clt->clt_fcgi_type == FCGI_STDOUT &&
526			    !clt->clt_chunk) {
527				server_abort_http(clt, 500, "empty stdout");
528				return;
529			}
530
531			/* fallthrough if content_len == 0 */
532		case FCGI_READ_CONTENT:
533			switch (clt->clt_fcgi_type) {
534			case FCGI_STDERR:
535				if (EVBUFFER_LENGTH(clt->clt_srvevb) > 0 &&
536				    (ptr = get_string(
537				    EVBUFFER_DATA(clt->clt_srvevb),
538				    EVBUFFER_LENGTH(clt->clt_srvevb)))
539				    != NULL) {
540					server_sendlog(clt->clt_srv_conf,
541					    IMSG_LOG_ERROR, "%s", ptr);
542					free(ptr);
543				}
544				break;
545			case FCGI_STDOUT:
546				if (++clt->clt_chunk == 1) {
547					if (server_fcgi_header(clt,
548					    server_fcgi_getheaders(clt))
549					    == -1) {
550						server_abort_http(clt, 500,
551						    "malformed fcgi headers");
552						return;
553					}
554					if (!EVBUFFER_LENGTH(clt->clt_srvevb))
555						break;
556				}
557				/* FALLTHROUGH */
558			case FCGI_END_REQUEST:
559				if (server_fcgi_writechunk(clt) == -1) {
560					server_abort_http(clt, 500,
561					    "encoding error");
562					return;
563				}
564				break;
565			}
566			evbuffer_drain(clt->clt_srvevb,
567			    EVBUFFER_LENGTH(clt->clt_srvevb));
568			if (!clt->clt_fcgi_padding_len) {
569				clt->clt_fcgi_state = FCGI_READ_HEADER;
570				clt->clt_fcgi_toread =
571				    sizeof(struct fcgi_record_header);
572			} else {
573				clt->clt_fcgi_state = FCGI_READ_PADDING;
574				clt->clt_fcgi_toread =
575				    clt->clt_fcgi_padding_len;
576			}
577			break;
578		case FCGI_READ_PADDING:
579			evbuffer_drain(clt->clt_srvevb,
580			    EVBUFFER_LENGTH(clt->clt_srvevb));
581			clt->clt_fcgi_state = FCGI_READ_HEADER;
582			clt->clt_fcgi_toread =
583			    sizeof(struct fcgi_record_header);
584			break;
585		}
586	} while (len > 0);
587}
588
589int
590server_fcgi_header(struct client *clt, u_int code)
591{
592	struct http_descriptor	*desc = clt->clt_descreq;
593	struct http_descriptor	*resp = clt->clt_descresp;
594	const char		*error;
595	char			 tmbuf[32];
596	struct kv		*kv, key;
597
598	if (desc == NULL || (error = server_httperror_byid(code)) == NULL)
599		return (-1);
600
601	if (server_log_http(clt, code, 0) == -1)
602		return (-1);
603
604	/* Add error codes */
605	if (kv_setkey(&resp->http_pathquery, "%lu", code) == -1 ||
606	    kv_set(&resp->http_pathquery, "%s", error) == -1)
607		return (-1);
608
609	/* Add headers */
610	if (kv_add(&resp->http_headers, "Server", HTTPD_SERVERNAME) == NULL)
611		return (-1);
612
613	/* Set chunked encoding */
614	if (clt->clt_fcgi_chunked) {
615		/* XXX Should we keep and handle Content-Length instead? */
616		key.kv_key = "Content-Length";
617		if ((kv = kv_find(&resp->http_headers, &key)) != NULL)
618			kv_delete(&resp->http_headers, kv);
619
620		/*
621		 * XXX What if the FastCGI added some kind of Transfer-Encoding?
622		 * XXX like gzip, deflate or even "chunked"?
623		 */
624		if (kv_add(&resp->http_headers,
625		    "Transfer-Encoding", "chunked") == NULL)
626			return (-1);
627	}
628
629	/* Is it a persistent connection? */
630	if (clt->clt_persist) {
631		if (kv_add(&resp->http_headers,
632		    "Connection", "keep-alive") == NULL)
633			return (-1);
634	} else if (kv_add(&resp->http_headers, "Connection", "close") == NULL)
635		return (-1);
636
637	/* Date header is mandatory and should be added as late as possible */
638	if (server_http_time(time(NULL), tmbuf, sizeof(tmbuf)) <= 0 ||
639	    kv_add(&resp->http_headers, "Date", tmbuf) == NULL)
640		return (-1);
641
642	/* Write initial header (fcgi might append more) */
643	if (server_writeresponse_http(clt) == -1 ||
644	    server_bufferevent_print(clt, "\r\n") == -1 ||
645	    server_headers(clt, resp, server_writeheader_http, NULL) == -1 ||
646	    server_bufferevent_print(clt, "\r\n") == -1)
647		return (-1);
648
649	return (0);
650}
651
652int
653server_fcgi_writeheader(struct client *clt, struct kv *hdr, void *arg)
654{
655	struct server_fcgi_param	*param = arg;
656	char				*val, *name, *p;
657	const char			*key;
658	int				 ret;
659
660	if (hdr->kv_flags & KV_FLAG_INVALID)
661		return (0);
662
663	/* The key might have been updated in the parent */
664	if (hdr->kv_parent != NULL && hdr->kv_parent->kv_key != NULL)
665		key = hdr->kv_parent->kv_key;
666	else
667		key = hdr->kv_key;
668
669	val = hdr->kv_value;
670
671	if (strcasecmp(key, "Content-Length") == 0 ||
672	    strcasecmp(key, "Content-Type") == 0) {
673		if ((name = strdup(key)) == NULL)
674			return (-1);
675	} else {
676		if (asprintf(&name, "HTTP_%s", key) == -1)
677			return (-1);
678	}
679
680	/*
681	 * RFC 7230 defines a header field-name as a "token" and a "token"
682	 * is defined as one or more characters for which isalpha or
683	 * isdigit is true plus a list of additional characters.
684	 * According to RFC 3875 a CGI environment variable is created
685	 * by converting all letters to upper case and replacing '-'
686	 * with '_'.
687	 */
688	for (p = name; *p != '\0'; p++) {
689		if (isalpha((unsigned char)*p))
690			*p = toupper((unsigned char)*p);
691		else if (!(*p == '!' || *p == '#' || *p == '$' || *p == '%' ||
692		    *p == '&' || *p == '\'' || *p == '*' || *p == '+' ||
693		    *p == '.' || *p == '^' || *p == '_' || *p == '`' ||
694		    *p == '|' || *p == '~' || isdigit((unsigned char)*p)))
695			*p = '_';
696	}
697
698	ret = fcgi_add_param(param, name, val, clt);
699	free(name);
700
701	return (ret);
702}
703
704int
705server_fcgi_writechunk(struct client *clt)
706{
707	struct evbuffer *evb = clt->clt_srvevb;
708	size_t		 len;
709
710	if (clt->clt_fcgi_type == FCGI_END_REQUEST) {
711		len = 0;
712	} else
713		len = EVBUFFER_LENGTH(evb);
714
715	if (clt->clt_fcgi_chunked) {
716		/* If len is 0, make sure to write the end marker only once */
717		if (len == 0 && clt->clt_fcgi_end++)
718			return (0);
719		if (server_bufferevent_printf(clt, "%zx\r\n", len) == -1 ||
720		    server_bufferevent_write_chunk(clt, evb, len) == -1 ||
721		    server_bufferevent_print(clt, "\r\n") == -1)
722			return (-1);
723	} else if (len)
724		return (server_bufferevent_write_buffer(clt, evb));
725
726	return (0);
727}
728
729int
730server_fcgi_getheaders(struct client *clt)
731{
732	struct http_descriptor	*resp = clt->clt_descresp;
733	struct evbuffer		*evb = clt->clt_srvevb;
734	int			 code = 200;
735	char			*line, *key, *value;
736	const char		*errstr;
737
738	while ((line = evbuffer_getline(evb)) != NULL && *line != '\0') {
739		key = line;
740
741		if ((value = strchr(key, ':')) == NULL)
742			break;
743		if (*value == ':') {
744			*value++ = '\0';
745			value += strspn(value, " \t");
746		} else {
747			*value++ = '\0';
748		}
749
750		DPRINTF("%s: %s: %s", __func__, key, value);
751
752		if (strcasecmp("Status", key) == 0) {
753			value[strcspn(value, " \t")] = '\0';
754			code = (int)strtonum(value, 100, 600, &errstr);
755			if (errstr != NULL || server_httperror_byid(
756			    code) == NULL)
757				code = 200;
758		} else {
759			(void)kv_add(&resp->http_headers, key, value);
760		}
761		free(line);
762	}
763
764	return (code);
765}
766