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