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