xref: /lighttpd1.4/src/http-header-glue.c (revision 70b1af06)
1 #include "first.h"
2 
3 #include "base.h"
4 #include "array.h"
5 #include "buffer.h"
6 #include "chunk.h"
7 #include "fdevent.h"
8 #include "log.h"
9 #include "etag.h"
10 #include "http_chunk.h"
11 #include "http_header.h"
12 #include "response.h"
13 #include "sock_addr.h"
14 #include "stat_cache.h"
15 
16 #include <stdlib.h>
17 #include <string.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 
21 #include <time.h>
22 
23 #include "sys-socket.h"
24 #include <unistd.h>
25 
26 /**
27  * max size of the HTTP response header from backends
28  * (differs from server.max-request-field-size for max request field size)
29  */
30 #define MAX_HTTP_RESPONSE_FIELD_SIZE 65535
31 
32 
33 static int http_response_buffer_append_authority(request_st * const r, buffer * const o) {
34 	if (!buffer_string_is_empty(&r->uri.authority)) {
35 		buffer_append_string_buffer(o, &r->uri.authority);
36 	} else {
37 		/* get the name of the currently connected socket */
38 		sock_addr our_addr;
39 		socklen_t our_addr_len;
40 
41 		our_addr.plain.sa_family = 0;
42 		our_addr_len = sizeof(our_addr);
43 
44 		if (-1 == getsockname(r->con->fd, (struct sockaddr *)&our_addr, &our_addr_len)
45 		    || our_addr_len > (socklen_t)sizeof(our_addr)) {
46 			r->http_status = 500;
47 			log_perror(r->conf.errh, __FILE__, __LINE__, "can't get sockname");
48 			return -1;
49 		}
50 
51 		if (our_addr.plain.sa_family == AF_INET
52 		    && our_addr.ipv4.sin_addr.s_addr == htonl(INADDR_LOOPBACK)) {
53 			static char lhost[32];
54 			static size_t lhost_len = 0;
55 			if (0 != lhost_len) {
56 				buffer_append_string_len(o, lhost, lhost_len);
57 			}
58 			else {
59 				size_t olen = buffer_string_length(o);
60 				if (0 == sock_addr_nameinfo_append_buffer(o, &our_addr, r->conf.errh)) {
61 					lhost_len = buffer_string_length(o) - olen;
62 					if (lhost_len < sizeof(lhost)) {
63 						memcpy(lhost, o->ptr+olen, lhost_len+1); /*(+1 for '\0')*/
64 					}
65 					else {
66 						lhost_len = 0;
67 					}
68 				}
69 				else {
70 					lhost_len = sizeof("localhost")-1;
71 					memcpy(lhost, "localhost", lhost_len+1); /*(+1 for '\0')*/
72 					buffer_append_string_len(o, lhost, lhost_len);
73 				}
74 			}
75 		} else if (!buffer_string_is_empty(r->server_name)) {
76 			buffer_append_string_buffer(o, r->server_name);
77 		} else
78 		/* Lookup name: secondly try to get hostname for bind address */
79 		if (0 != sock_addr_nameinfo_append_buffer(o, &our_addr, r->conf.errh)) {
80 			r->http_status = 500;
81 			return -1;
82 		}
83 
84 		{
85 			unsigned short listen_port = sock_addr_get_port(&our_addr);
86 			unsigned short default_port = 80;
87 			if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"))) {
88 				default_port = 443;
89 			}
90 			if (0 == listen_port) listen_port = r->con->srv->srvconf.port;
91 			if (default_port != listen_port) {
92 				buffer_append_string_len(o, CONST_STR_LEN(":"));
93 				buffer_append_int(o, listen_port);
94 			}
95 		}
96 	}
97 	return 0;
98 }
99 
100 int http_response_redirect_to_directory(request_st * const r, int status) {
101 	buffer *o = r->tmp_buf;
102 	buffer_copy_buffer(o, &r->uri.scheme);
103 	buffer_append_string_len(o, CONST_STR_LEN("://"));
104 	if (0 != http_response_buffer_append_authority(r, o)) {
105 		return -1;
106 	}
107 	buffer_append_string_encoded(o, CONST_BUF_LEN(&r->uri.path), ENCODING_REL_URI);
108 	buffer_append_string_len(o, CONST_STR_LEN("/"));
109 	if (!buffer_string_is_empty(&r->uri.query)) {
110 		buffer_append_string_len(o, CONST_STR_LEN("?"));
111 		buffer_append_string_buffer(o, &r->uri.query);
112 	}
113 
114 	if (status >= 300) {
115 		http_header_response_set(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location"), CONST_BUF_LEN(o));
116 		r->http_status = status;
117 		r->resp_body_finished = 1;
118 	}
119 	else {
120 		http_header_response_set(r, HTTP_HEADER_CONTENT_LOCATION, CONST_STR_LEN("Content-Location"), CONST_BUF_LEN(o));
121 	}
122 
123 	return 0;
124 }
125 
126 #define MTIME_CACHE_MAX 16
127 struct mtime_cache_type {
128     time_t mtime;  /* key */
129     buffer str;    /* buffer for string representation */
130 };
131 static struct mtime_cache_type mtime_cache[MTIME_CACHE_MAX];
132 static char mtime_cache_str[MTIME_CACHE_MAX][30];
133 /* 30-chars for "%a, %d %b %Y %H:%M:%S GMT" */
134 
135 void strftime_cache_reset(void) {
136     for (int i = 0; i < MTIME_CACHE_MAX; ++i) {
137         mtime_cache[i].mtime = (time_t)-1;
138         mtime_cache[i].str.ptr = mtime_cache_str[i];
139         mtime_cache[i].str.used = sizeof(mtime_cache_str[0]);
140         mtime_cache[i].str.size = sizeof(mtime_cache_str[0]);
141     }
142 }
143 
144 const buffer * strftime_cache_get(const time_t last_mod) {
145     static int mtime_cache_idx;
146 
147     for (int j = 0; j < MTIME_CACHE_MAX; ++j) {
148         if (mtime_cache[j].mtime == last_mod)
149             return &mtime_cache[j].str; /* found cache-entry */
150     }
151 
152     if (++mtime_cache_idx == MTIME_CACHE_MAX) mtime_cache_idx = 0;
153 
154     const int i = mtime_cache_idx;
155     mtime_cache[i].mtime = last_mod;
156     strftime(mtime_cache[i].str.ptr, sizeof(mtime_cache_str[0]),
157              "%a, %d %b %Y %H:%M:%S GMT", gmtime(&mtime_cache[i].mtime));
158 
159     return &mtime_cache[i].str;
160 }
161 
162 
163 int http_response_handle_cachable(request_st * const r, const buffer * const mtime) {
164 	const buffer *vb;
165 
166 	/*
167 	 * 14.26 If-None-Match
168 	 *    [...]
169 	 *    If none of the entity tags match, then the server MAY perform the
170 	 *    requested method as if the If-None-Match header field did not exist,
171 	 *    but MUST also ignore any If-Modified-Since header field(s) in the
172 	 *    request. That is, if no entity tags match, then the server MUST NOT
173 	 *    return a 304 (Not Modified) response.
174 	 */
175 
176 	if ((vb = http_header_request_get(r, HTTP_HEADER_IF_NONE_MATCH, CONST_STR_LEN("If-None-Match")))) {
177 		/*(weak etag comparison must not be used for ranged requests)*/
178 		int range_request =
179 		  (r->conf.range_requests
180 		   && (200 == r->http_status || 0 == r->http_status)
181 		   && NULL != http_header_request_get(r, HTTP_HEADER_RANGE, CONST_STR_LEN("Range")));
182 		if (etag_is_equal(&r->physical.etag, vb->ptr, !range_request)) {
183 			if (http_method_get_or_head(r->http_method)) {
184 				r->http_status = 304;
185 				return HANDLER_FINISHED;
186 			} else {
187 				r->http_status = 412;
188 				r->handler_module = NULL;
189 				return HANDLER_FINISHED;
190 			}
191 		}
192 	} else if (http_method_get_or_head(r->http_method)
193 		   && (vb = http_header_request_get(r, HTTP_HEADER_IF_MODIFIED_SINCE, CONST_STR_LEN("If-Modified-Since")))) {
194 		/* last-modified handling */
195 		size_t used_len;
196 		char *semicolon;
197 
198 		if (NULL == (semicolon = strchr(vb->ptr, ';'))) {
199 			used_len = buffer_string_length(vb);
200 		} else {
201 			used_len = semicolon - vb->ptr;
202 		}
203 
204 		if (buffer_is_equal_string(mtime, vb->ptr, used_len)) {
205 			if ('\0' == mtime->ptr[used_len]) r->http_status = 304;
206 			return HANDLER_FINISHED;
207 		} else {
208 			char buf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")];
209 			time_t t_header, t_file;
210 			struct tm tm;
211 
212 			/* convert to timestamp */
213 			if (used_len >= sizeof(buf)) return HANDLER_GO_ON;
214 
215 			memcpy(buf, vb->ptr, used_len);
216 			buf[used_len] = '\0';
217 
218 			if (NULL == strptime(buf, "%a, %d %b %Y %H:%M:%S GMT", &tm)) {
219 				/**
220 				 * parsing failed, let's get out of here
221 				 */
222 				return HANDLER_GO_ON;
223 			}
224 			tm.tm_isdst = 0;
225 			t_header = mktime(&tm);
226 
227 			strptime(mtime->ptr, "%a, %d %b %Y %H:%M:%S GMT", &tm);
228 			tm.tm_isdst = 0;
229 			t_file = mktime(&tm);
230 
231 			if (t_file > t_header) return HANDLER_GO_ON;
232 
233 			r->http_status = 304;
234 			return HANDLER_FINISHED;
235 		}
236 	}
237 
238 	return HANDLER_GO_ON;
239 }
240 
241 
242 void http_response_body_clear (request_st * const r, int preserve_length) {
243     r->resp_send_chunked = 0;
244     if (r->resp_htags & HTTP_HEADER_TRANSFER_ENCODING) {
245         http_header_response_unset(r, HTTP_HEADER_TRANSFER_ENCODING, CONST_STR_LEN("Transfer-Encoding"));
246     }
247     if (!preserve_length) { /* preserve for HEAD responses and no-content responses (204, 205, 304) */
248         r->content_length = -1;
249         if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) {
250             http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
251         }
252         /*(if not preserving Content-Length, do not preserve trailers, if any)*/
253         r->resp_decode_chunked = 0;
254         if (r->gw_dechunk) {
255             free(r->gw_dechunk->b.ptr);
256             free(r->gw_dechunk);
257             r->gw_dechunk = NULL;
258         }
259     }
260     chunkqueue_reset(r->write_queue);
261 }
262 
263 
264 void http_response_reset (request_st * const r) {
265     r->http_status = 0;
266     r->con->is_writable = 1;
267     r->resp_body_finished = 0;
268     r->resp_body_started = 0;
269     r->handler_module = NULL;
270     if (r->physical.path.ptr) { /*(skip for mod_fastcgi authorizer)*/
271         buffer_clear(&r->physical.doc_root);
272         buffer_clear(&r->physical.basedir);
273         buffer_clear(&r->physical.etag);
274         buffer_reset(&r->physical.path);
275         buffer_reset(&r->physical.rel_path);
276     }
277     r->resp_htags = 0;
278     array_reset_data_strings(&r->resp_headers);
279     http_response_body_clear(r, 0);
280 }
281 
282 
283 handler_t http_response_reqbody_read_error (request_st * const r, int http_status) {
284     r->keep_alive = 0;
285 
286     /*(do not change status if response headers already set and possibly sent)*/
287     if (0 != r->resp_header_len) return HANDLER_ERROR;
288 
289     http_response_body_clear(r, 0);
290     r->http_status = http_status;
291     r->handler_module = NULL;
292     return HANDLER_FINISHED;
293 }
294 
295 
296 static int http_response_parse_range(request_st * const r, buffer * const path, stat_cache_entry * const sce, const char * const range) {
297 	int multipart = 0;
298 	int error;
299 	off_t start, end;
300 	const char *s, *minus;
301 	static const char boundary[] = "fkj49sn38dcn3";
302 	const buffer *content_type = http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"));
303 
304 	start = 0;
305 	end = sce->st.st_size - 1;
306 
307 	r->content_length = 0;
308 
309 	for (s = range, error = 0;
310 	     !error && *s && NULL != (minus = strchr(s, '-')); ) {
311 		char *err;
312 		off_t la = 0, le;
313 		*((const char **)&err) = s; /*(quiet clang --analyze)*/
314 
315 		if (s != minus) {
316 			la = strtoll(s, &err, 10);
317 			if (err != minus) {
318 				/* should not have multiple range-unit in Range, but
319 				 * handle just in case multiple Range headers merged */
320 				while (*s == ' ' || *s == '\t') ++s;
321 				if (0 != strncmp(s, "bytes=", 6)) return -1;
322 				s += 6;
323 				if (s != minus) {
324 					la = strtoll(s, &err, 10);
325 					if (err != minus) return -1;
326 				}
327 			}
328 		}
329 
330 		if (s == minus) {
331 			/* -<stop> */
332 
333 			le = strtoll(s, &err, 10);
334 
335 			if (le == 0) {
336 				/* RFC 2616 - 14.35.1 */
337 
338 				r->http_status = 416;
339 				error = 1;
340 			} else if (*err == '\0') {
341 				/* end */
342 				s = err;
343 
344 				end = sce->st.st_size - 1;
345 				start = sce->st.st_size + le;
346 			} else if (*err == ',') {
347 				multipart = 1;
348 				s = err + 1;
349 
350 				end = sce->st.st_size - 1;
351 				start = sce->st.st_size + le;
352 			} else {
353 				error = 1;
354 			}
355 
356 		} else if (*(minus+1) == '\0' || *(minus+1) == ',') {
357 			/* <start>- */
358 
359 				/* ok */
360 
361 				if (*(err + 1) == '\0') {
362 					s = err + 1;
363 
364 					end = sce->st.st_size - 1;
365 					start = la;
366 
367 				} else if (*(err + 1) == ',') {
368 					multipart = 1;
369 					s = err + 2;
370 
371 					end = sce->st.st_size - 1;
372 					start = la;
373 				} else {
374 					error = 1;
375 				}
376 		} else {
377 			/* <start>-<stop> */
378 
379 				le = strtoll(minus+1, &err, 10);
380 
381 				/* RFC 2616 - 14.35.1 */
382 				if (la > le) {
383 					error = 1;
384 				}
385 
386 				if (*err == '\0') {
387 					/* ok, end*/
388 					s = err;
389 
390 					end = le;
391 					start = la;
392 				} else if (*err == ',') {
393 					multipart = 1;
394 					s = err + 1;
395 
396 					end = le;
397 					start = la;
398 				} else {
399 					/* error */
400 
401 					error = 1;
402 				}
403 		}
404 
405 		if (!error) {
406 			if (start < 0) start = 0;
407 
408 			/* RFC 2616 - 14.35.1 */
409 			if (end > sce->st.st_size - 1) end = sce->st.st_size - 1;
410 
411 			if (start > sce->st.st_size - 1) {
412 				error = 1;
413 
414 				r->http_status = 416;
415 			}
416 		}
417 
418 		if (!error) {
419 			if (multipart) {
420 				/* write boundary-header */
421 				buffer *b = r->tmp_buf;
422 				buffer_copy_string_len(b, CONST_STR_LEN("\r\n--"));
423 				buffer_append_string_len(b, boundary, sizeof(boundary)-1);
424 
425 				/* write Content-Range */
426 				buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Range: bytes "));
427 				buffer_append_int(b, start);
428 				buffer_append_string_len(b, CONST_STR_LEN("-"));
429 				buffer_append_int(b, end);
430 				buffer_append_string_len(b, CONST_STR_LEN("/"));
431 				buffer_append_int(b, sce->st.st_size);
432 
433 				if (content_type) {
434 					buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Type: "));
435 					buffer_append_string_buffer(b, content_type);
436 				}
437 
438 				/* write END-OF-HEADER */
439 				buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n"));
440 
441 				r->content_length += buffer_string_length(b);
442 				chunkqueue_append_mem(r->write_queue, CONST_BUF_LEN(b));
443 			}
444 
445 			chunkqueue_append_file(r->write_queue, path, start, end - start + 1);
446 			r->content_length += end - start + 1;
447 		}
448 	}
449 
450 	/* something went wrong */
451 	if (error) return -1;
452 
453 	buffer * const tb = r->tmp_buf;
454 
455 	if (multipart) {
456 		/* add boundary end */
457 		buffer_copy_string_len(tb, "\r\n--", 4);
458 		buffer_append_string_len(tb, boundary, sizeof(boundary)-1);
459 		buffer_append_string_len(tb, "--\r\n", 4);
460 
461 		r->content_length += buffer_string_length(tb);
462 		chunkqueue_append_mem(r->write_queue, CONST_BUF_LEN(tb));
463 
464 		/* set header-fields */
465 
466 		buffer_copy_string_len(tb, CONST_STR_LEN("multipart/byteranges; boundary="));
467 		buffer_append_string_len(tb, boundary, sizeof(boundary)-1);
468 
469 		/* overwrite content-type */
470 		http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(tb));
471 	} else {
472 		/* add Content-Range-header */
473 
474 		buffer_copy_string_len(tb, CONST_STR_LEN("bytes "));
475 		buffer_append_int(tb, start);
476 		buffer_append_string_len(tb, CONST_STR_LEN("-"));
477 		buffer_append_int(tb, end);
478 		buffer_append_string_len(tb, CONST_STR_LEN("/"));
479 		buffer_append_int(tb, sce->st.st_size);
480 
481 		http_header_response_set(r, HTTP_HEADER_OTHER, CONST_STR_LEN("Content-Range"), CONST_BUF_LEN(tb));
482 	}
483 
484 	/* ok, the file is set-up */
485 	return 0;
486 }
487 
488 
489 void http_response_send_file (request_st * const r, buffer * const path) {
490 	stat_cache_entry * const sce = stat_cache_get_entry(path);
491 	const buffer *mtime = NULL;
492 	const buffer *vb;
493 	int allow_caching = (0 == r->http_status || 200 == r->http_status);
494 
495 	if (NULL == sce) {
496 		r->http_status = (errno == ENOENT) ? 404 : 403;
497 		log_error(r->conf.errh, __FILE__, __LINE__,
498 		  "not a regular file: %s -> %s", r->uri.path.ptr, path->ptr);
499 		return;
500 	}
501 
502 	if (!r->conf.follow_symlink
503 	    && 0 != stat_cache_path_contains_symlink(path, r->conf.errh)) {
504 		r->http_status = 403;
505 		if (r->conf.log_request_handling) {
506 			log_error(r->conf.errh, __FILE__, __LINE__,
507 			  "-- access denied due symlink restriction");
508 			log_error(r->conf.errh, __FILE__, __LINE__,
509 			  "Path         : %s", path->ptr);
510 		}
511 		return;
512 	}
513 
514 	/* we only handle regular files */
515 	if (!S_ISREG(sce->st.st_mode)) {
516 		r->http_status = 403;
517 		if (r->conf.log_file_not_found) {
518 			log_error(r->conf.errh, __FILE__, __LINE__,
519 			  "not a regular file: %s -> %s",
520 			  r->uri.path.ptr, path->ptr);
521 		}
522 		return;
523 	}
524 
525 	/*(Note: O_NOFOLLOW affects only the final path segment,
526 	 * the target file, not any intermediate symlinks along path)*/
527 	const int fd = (0 != sce->st.st_size)
528 	  ? fdevent_open_cloexec(path->ptr, r->conf.follow_symlink, O_RDONLY, 0)
529 	  : -1;
530 	if (fd < 0 && 0 != sce->st.st_size) {
531 		r->http_status = (errno == ENOENT) ? 404 : 403;
532 		if (r->conf.log_request_handling) {
533 			log_perror(r->conf.errh, __FILE__, __LINE__,
534 			  "file open failed: %s", path->ptr);
535 		}
536 		return;
537 	}
538 
539 	/* set response content-type, if not set already */
540 
541 	if (NULL == http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"))) {
542 		const buffer *content_type = stat_cache_content_type_get(sce, r);
543 		if (buffer_string_is_empty(content_type)) {
544 			/* we are setting application/octet-stream, but also announce that
545 			 * this header field might change in the seconds few requests
546 			 *
547 			 * This should fix the aggressive caching of FF and the script download
548 			 * seen by the first installations
549 			 */
550 			http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("application/octet-stream"));
551 
552 			allow_caching = 0;
553 		} else {
554 			http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(content_type));
555 		}
556 	}
557 
558 	if (r->conf.range_requests) {
559 		http_header_response_append(r, HTTP_HEADER_OTHER, CONST_STR_LEN("Accept-Ranges"), CONST_STR_LEN("bytes"));
560 	}
561 
562 	if (allow_caching) {
563 		const buffer *etag = (0 != r->conf.etag_flags)
564 		  ? stat_cache_etag_get(sce, r->conf.etag_flags)
565 		  : NULL;
566 		if (!buffer_string_is_empty(etag)) {
567 			if (NULL == http_header_response_get(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"))) {
568 				/* generate e-tag */
569 				etag_mutate(&r->physical.etag, etag);
570 
571 				http_header_response_set(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"), CONST_BUF_LEN(&r->physical.etag));
572 			}
573 		}
574 
575 		/* prepare header */
576 		if (NULL == (mtime = http_header_response_get(r, HTTP_HEADER_LAST_MODIFIED, CONST_STR_LEN("Last-Modified")))) {
577 			mtime = strftime_cache_get(sce->st.st_mtime);
578 			http_header_response_set(r, HTTP_HEADER_LAST_MODIFIED, CONST_STR_LEN("Last-Modified"), CONST_BUF_LEN(mtime));
579 		}
580 
581 		if (HANDLER_FINISHED == http_response_handle_cachable(r, mtime)) {
582 			if (fd >= 0) close(fd);
583 			return;
584 		}
585 	}
586 
587 	if (fd < 0) { /* 0-length file */
588 		r->http_status = 200;
589 		r->resp_body_finished = 1;
590 		return;
591 	}
592 
593 	if (r->conf.range_requests
594 	    && (200 == r->http_status || 0 == r->http_status)
595 	    && NULL != (vb = http_header_request_get(r, HTTP_HEADER_RANGE, CONST_STR_LEN("Range")))
596 	    && NULL == http_header_response_get(r, HTTP_HEADER_CONTENT_ENCODING, CONST_STR_LEN("Content-Encoding"))) {
597 		const buffer *range = vb;
598 		int do_range_request = 1;
599 		/* check if we have a conditional GET */
600 
601 		if (NULL != (vb = http_header_request_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("If-Range")))) {
602 			/* if the value is the same as our ETag, we do a Range-request,
603 			 * otherwise a full 200 */
604 
605 			if (vb->ptr[0] == '"') {
606 				/**
607 				 * client wants a ETag
608 				 */
609 				if (!buffer_is_equal(vb, &r->physical.etag)) {
610 					do_range_request = 0;
611 				}
612 			} else if (!mtime) {
613 				/**
614 				 * we don't have a Last-Modified and can match the If-Range:
615 				 *
616 				 * sending all
617 				 */
618 				do_range_request = 0;
619 			} else if (!buffer_is_equal(vb, mtime)) {
620 				do_range_request = 0;
621 			}
622 		}
623 
624 		if (do_range_request
625 		    && !buffer_string_is_empty(range)
626 		    && 0 == strncmp(range->ptr, "bytes=", 6)) {
627 			/* support only "bytes" byte-unit */
628 			/* content prepared, I'm done */
629 			r->resp_body_finished = 1;
630 
631 			if (0 == http_response_parse_range(r, path, sce, range->ptr+6)) {
632 				r->http_status = 206;
633 			}
634 			close(fd);
635 			return;
636 		}
637 	}
638 
639 	/* if we are still here, prepare body */
640 
641 	/* we add it here for all requests
642 	 * the HEAD request will drop it afterwards again
643 	 */
644 
645 	if (0 == http_chunk_append_file_fd(r, path, fd, sce->st.st_size)) {
646 		r->http_status = 200;
647 		r->resp_body_finished = 1;
648 	}
649 	else {
650 		r->http_status = 500;
651 	}
652 }
653 
654 
655 static void http_response_xsendfile (request_st * const r, buffer * const path, const array * const xdocroot) {
656 	const int status = r->http_status;
657 	int valid = 1;
658 
659 	/* reset Content-Length, if set by backend
660 	 * Content-Length might later be set to size of X-Sendfile static file,
661 	 * determined by open(), fstat() to reduces race conditions if the file
662 	 * is modified between stat() (stat_cache_get_entry()) and open(). */
663 	if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) {
664 		http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
665 		r->content_length = -1;
666 	}
667 
668 	buffer_urldecode_path(path);
669 	if (!buffer_is_valid_UTF8(path)) {
670 		log_error(r->conf.errh, __FILE__, __LINE__,
671 		  "X-Sendfile invalid UTF-8 after url-decode: %s", path->ptr);
672 		if (r->http_status < 400) {
673 			r->http_status = 502;
674 			r->handler_module = NULL;
675 		}
676 		return;
677 	}
678 	buffer_path_simplify(path, path);
679 	if (r->conf.force_lowercase_filenames) {
680 		buffer_to_lower(path);
681 	}
682 
683 	/* check that path is under xdocroot(s)
684 	 * - xdocroot should have trailing slash appended at config time
685 	 * - r->conf.force_lowercase_filenames is not a server-wide setting,
686 	 *   and so can not be definitively applied to xdocroot at config time*/
687 	if (xdocroot) {
688 		size_t i, xlen = buffer_string_length(path);
689 		for (i = 0; i < xdocroot->used; ++i) {
690 			data_string *ds = (data_string *)xdocroot->data[i];
691 			size_t dlen = buffer_string_length(&ds->value);
692 			if (dlen <= xlen
693 			    && (!r->conf.force_lowercase_filenames
694 				? 0 == memcmp(path->ptr, ds->value.ptr, dlen)
695 				: buffer_eq_icase_ssn(path->ptr, ds->value.ptr, dlen))) {
696 				break;
697 			}
698 		}
699 		if (i == xdocroot->used && 0 != i) {
700 			log_error(r->conf.errh, __FILE__, __LINE__,
701 			  "X-Sendfile (%s) not under configured x-sendfile-docroot(s)", path->ptr);
702 			r->http_status = 403;
703 			valid = 0;
704 		}
705 	}
706 
707 	if (valid) http_response_send_file(r, path);
708 
709 	if (r->http_status >= 400 && status < 300) {
710 		r->handler_module = NULL;
711 	} else if (0 != status && 200 != status) {
712 		r->http_status = status;
713 	}
714 }
715 
716 
717 static void http_response_xsendfile2(request_st * const r, const buffer * const value, const array * const xdocroot) {
718     const char *pos = value->ptr;
719     buffer * const b = r->tmp_buf;
720     const int status = r->http_status;
721 
722     /* reset Content-Length, if set by backend */
723     if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) {
724         http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
725         r->content_length = -1;
726     }
727 
728     while (*pos) {
729         const char *filename, *range;
730         stat_cache_entry *sce;
731         off_t begin_range, end_range, range_len;
732 
733         while (' ' == *pos) pos++;
734         if (!*pos) break;
735 
736         filename = pos;
737         if (NULL == (range = strchr(pos, ' '))) {
738             /* missing range */
739             log_error(r->conf.errh, __FILE__, __LINE__,
740               "Couldn't find range after filename: %s", filename);
741             r->http_status = 502;
742             break;
743         }
744         buffer_copy_string_len(b, filename, range - filename);
745 
746         /* find end of range */
747         for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
748 
749         buffer_urldecode_path(b);
750         if (!buffer_is_valid_UTF8(b)) {
751             log_error(r->conf.errh, __FILE__, __LINE__,
752               "X-Sendfile2 invalid UTF-8 after url-decode: %s", b->ptr);
753             r->http_status = 502;
754             break;
755         }
756         buffer_path_simplify(b, b);
757         if (r->conf.force_lowercase_filenames) {
758             buffer_to_lower(b);
759         }
760         if (xdocroot) {
761             size_t i, xlen = buffer_string_length(b);
762             for (i = 0; i < xdocroot->used; ++i) {
763                 data_string *ds = (data_string *)xdocroot->data[i];
764                 size_t dlen = buffer_string_length(&ds->value);
765                 if (dlen <= xlen
766                     && (!r->conf.force_lowercase_filenames
767                     ? 0 == memcmp(b->ptr, ds->value.ptr, dlen)
768                     : buffer_eq_icase_ssn(b->ptr, ds->value.ptr, dlen))) {
769                     break;
770                 }
771             }
772             if (i == xdocroot->used && 0 != i) {
773                 log_error(r->conf.errh, __FILE__, __LINE__,
774                   "X-Sendfile2 (%s) not under configured x-sendfile-docroot(s)",
775                   b->ptr);
776                 r->http_status = 403;
777                 break;
778             }
779         }
780 
781         sce = stat_cache_get_entry(b);
782         if (NULL == sce) {
783             log_error(r->conf.errh, __FILE__, __LINE__,
784               "send-file error: couldn't get stat_cache entry for "
785               "X-Sendfile2: %s", b->ptr);
786             r->http_status = 404;
787             break;
788         } else if (!S_ISREG(sce->st.st_mode)) {
789             log_error(r->conf.errh, __FILE__, __LINE__,
790               "send-file error: wrong filetype for X-Sendfile2: %s", b->ptr);
791             r->http_status = 502;
792             break;
793         }
794         /* found the file */
795 
796         /* parse range */
797         end_range = sce->st.st_size - 1;
798         {
799             char *rpos = NULL;
800             errno = 0;
801             begin_range = strtoll(range, &rpos, 10);
802             if (errno != 0 || begin_range < 0 || rpos == range)
803                 goto range_failed;
804             if ('-' != *rpos++) goto range_failed;
805             if (rpos != pos) {
806                 range = rpos;
807                 end_range = strtoll(range, &rpos, 10);
808                 if (errno != 0 || end_range < 0 || rpos == range)
809                     goto range_failed;
810             }
811             if (rpos != pos) goto range_failed;
812 
813             goto range_success;
814 
815 range_failed:
816             log_error(r->conf.errh, __FILE__, __LINE__,
817               "Couldn't decode range after filename: %s", filename);
818             r->http_status = 502;
819             break;
820 
821 range_success: ;
822         }
823 
824         /* no parameters accepted */
825 
826         while (*pos == ' ') pos++;
827         if (*pos != '\0' && *pos != ',') {
828             r->http_status = 502;
829             break;
830         }
831 
832         range_len = end_range - begin_range + 1;
833         if (range_len < 0) {
834             r->http_status = 502;
835             break;
836         }
837         if (range_len != 0) {
838             if (0 !=
839                 http_chunk_append_file_range(r, b, begin_range, range_len)) {
840                 r->http_status = 502;
841                 break;
842             }
843         }
844 
845         if (*pos == ',') pos++;
846     }
847 
848     if (r->http_status >= 400 && status < 300) {
849 	r->handler_module = NULL;
850     } else if (0 != status && 200 != status) {
851         r->http_status = status;
852     }
853 }
854 
855 
856 void http_response_backend_error (request_st * const r) {
857 	if (r->resp_body_started) {
858 		/*(response might have been already started, kill the connection)*/
859 		/*(mode == DIRECT to avoid later call to http_response_backend_done())*/
860 		r->handler_module = NULL;  /*(avoid sending final chunked block)*/
861 		r->keep_alive = 0;
862 		r->resp_body_finished = 1;
863 	} /*(else error status set later by http_response_backend_done())*/
864 }
865 
866 void http_response_backend_done (request_st * const r) {
867 	/* (not CON_STATE_ERROR and not CON_STATE_RESPONSE_END,
868 	 *  i.e. not called from handle_connection_close or handle_request_reset
869 	 *  hooks, except maybe from errdoc handler, which later resets state)*/
870 	switch (r->state) {
871 	case CON_STATE_HANDLE_REQUEST:
872 	case CON_STATE_READ_POST:
873 		if (!r->resp_body_started) {
874 			/* Send an error if we haven't sent any data yet */
875 			r->http_status = 500;
876 			r->handler_module = NULL;
877 			break;
878 		} /* else fall through */
879 	case CON_STATE_WRITE:
880 		if (!r->resp_body_finished) {
881 			if (r->http_version == HTTP_VERSION_1_1)
882 				http_chunk_close(r);
883 			r->resp_body_finished = 1;
884 		}
885 	default:
886 		break;
887 	}
888 }
889 
890 
891 void http_response_upgrade_read_body_unknown(request_st * const r) {
892     /* act as transparent proxy */
893     if (!(r->conf.stream_request_body & FDEVENT_STREAM_REQUEST))
894         r->conf.stream_request_body |=
895           (FDEVENT_STREAM_REQUEST_BUFMIN | FDEVENT_STREAM_REQUEST);
896     if (!(r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE))
897         r->conf.stream_response_body |=
898           (FDEVENT_STREAM_RESPONSE_BUFMIN | FDEVENT_STREAM_RESPONSE);
899     r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
900     r->reqbody_length = -2;
901     r->keep_alive = 0;
902 }
903 
904 
905 static handler_t http_response_process_local_redir(request_st * const r, size_t blen) {
906     /* [RFC3875] The Common Gateway Interface (CGI) Version 1.1
907      * [RFC3875] 6.2.2 Local Redirect Response
908      *
909      *    The CGI script can return a URI path and query-string
910      *    ('local-pathquery') for a local resource in a Location header field.
911      *    This indicates to the server that it should reprocess the request
912      *    using the path specified.
913      *
914      *      local-redir-response = local-Location NL
915      *
916      *    The script MUST NOT return any other header fields or a message-body,
917      *    and the server MUST generate the response that it would have produced
918      *    in response to a request containing the URL
919      *
920      *      scheme "://" server-name ":" server-port local-pathquery
921      *
922      * (Might not have begun to receive body yet, but do skip local-redir
923      *  if we already have started receiving a response body (blen > 0))
924      * (Also, while not required by the RFC, do not send local-redir back
925      *  to same URL, since CGI should have handled it internally if it
926      *  really wanted to do that internally)
927      */
928 
929     /* r->http_status >= 300 && r->http_status < 400) */
930     size_t ulen = buffer_string_length(&r->uri.path);
931     const buffer *vb = http_header_response_get(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location"));
932     if (NULL != vb
933         && vb->ptr[0] == '/'
934         && (0 != strncmp(vb->ptr, r->uri.path.ptr, ulen)
935             || (   vb->ptr[ulen] != '\0'
936                 && vb->ptr[ulen] != '/'
937                 && vb->ptr[ulen] != '?'))
938         && 0 == blen
939         && !(r->resp_htags & HTTP_HEADER_STATUS) /*no "Status" or NPH response*/
940         && 1 == r->resp_headers.used) {
941         if (++r->loops_per_request > 5) {
942             log_error(r->conf.errh, __FILE__, __LINE__,
943               "too many internal loops while processing request: %s",
944               r->target_orig.ptr);
945             r->http_status = 500; /* Internal Server Error */
946             r->handler_module = NULL;
947             return HANDLER_FINISHED;
948         }
949 
950         buffer_copy_buffer(&r->target, vb);
951 
952         if (r->reqbody_length) {
953             if (r->reqbody_length
954                 != r->reqbody_queue->bytes_in) {
955                 r->keep_alive = 0;
956             }
957             r->reqbody_length = 0;
958             chunkqueue_reset(r->reqbody_queue);
959         }
960 
961         if (r->http_status != 307 && r->http_status != 308) {
962             /* Note: request body (if any) sent to initial dynamic handler
963              * and is not available to the internal redirect */
964             r->http_method = HTTP_METHOD_GET;
965         }
966 
967         /*(caller must reset request as follows)*/
968         /*http_response_reset(r);*/ /*(sets r->http_status = 0)*/
969         /*plugins_call_handle_request_reset(r);*/
970 
971         return HANDLER_COMEBACK;
972     }
973 
974     return HANDLER_GO_ON;
975 }
976 
977 
978 static int http_response_process_headers(request_st * const r, http_response_opts * const opts, buffer * const hdrs) {
979     char *ns;
980     const char *s;
981     int line = 0;
982     int status_is_set = 0;
983 
984     for (s = hdrs->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1, ++line) {
985         const char *key, *value;
986         int key_len;
987         enum http_header_e id;
988 
989         /* strip the \n */
990         ns[0] = '\0';
991         if (ns > s && ns[-1] == '\r') ns[-1] = '\0';
992 
993         if (0 == line && 0 == strncmp(s, "HTTP/1.", 7)) {
994             /* non-parsed headers ... we parse them anyway */
995             if ((s[7] == '1' || s[7] == '0') && s[8] == ' ') {
996                 /* after the space should be a status code for us */
997                 int status = http_header_str_to_code(s+9);
998                 if (status >= 100 && status < 1000) {
999                     status_is_set = 1;
1000                     r->resp_htags |= HTTP_HEADER_STATUS;
1001                     r->http_status = status;
1002                 } /* else we expected 3 digits and didn't get them */
1003             }
1004 
1005             if (0 == r->http_status) {
1006                 log_error(r->conf.errh, __FILE__, __LINE__,
1007                   "invalid HTTP status line: %s", s);
1008                 r->http_status = 502; /* Bad Gateway */
1009                 r->handler_module = NULL;
1010                 return -1;
1011             }
1012 
1013             continue;
1014         }
1015 
1016         /* parse the headers */
1017         key = s;
1018         if (NULL == (value = strchr(s, ':'))) {
1019             /* we expect: "<key>: <value>\r\n" */
1020             continue;
1021         }
1022 
1023         key_len = value - key;
1024         do { ++value; } while (*value == ' ' || *value == '\t'); /* skip LWS */
1025         id = http_header_hkey_get(key, key_len);
1026 
1027         if (opts->authorizer) {
1028             if (0 == r->http_status || 200 == r->http_status) {
1029                 if (id == HTTP_HEADER_STATUS) {
1030                     int status = http_header_str_to_code(value);
1031                     if (status >= 100 && status < 1000) {
1032                         r->http_status = status;
1033                     } else {
1034                         r->http_status = 502; /* Bad Gateway */
1035                         break;
1036                     }
1037                 }
1038                 else if (id == HTTP_HEADER_OTHER && key_len > 9
1039                          && (key[0] & 0xdf) == 'V'
1040                          && buffer_eq_icase_ssn(key,
1041                                                 CONST_STR_LEN("Variable-"))) {
1042                     http_header_env_append(r, key + 9, key_len - 9, value, strlen(value));
1043                 }
1044                 continue;
1045             }
1046         }
1047 
1048         switch (id) {
1049           case HTTP_HEADER_STATUS:
1050             {
1051                 if (opts->backend == BACKEND_PROXY) break; /*(pass w/o parse)*/
1052                 int status = http_header_str_to_code(value);
1053                 if (status >= 100 && status < 1000) {
1054                     r->http_status = status;
1055                     status_is_set = 1;
1056                 } else {
1057                     r->http_status = 502;
1058                     r->handler_module = NULL;
1059                 }
1060                 continue; /* do not send Status to client */
1061             }
1062             break;
1063           case HTTP_HEADER_UPGRADE:
1064             /*(technically, should also verify Connection: upgrade)*/
1065             /*(flag only for mod_proxy and mod_cgi (for now))*/
1066             if (opts->backend != BACKEND_PROXY
1067                 && opts->backend != BACKEND_CGI) {
1068                 id = HTTP_HEADER_OTHER;
1069             }
1070             if (r->http_version >= HTTP_VERSION_2) continue;
1071             break;
1072           case HTTP_HEADER_CONNECTION:
1073             if (opts->backend == BACKEND_PROXY) continue;
1074             /*(should parse for tokens and do case-insensitive match for "close"
1075              * but this is an imperfect though simplistic attempt to honor
1076              * backend request to close)*/
1077             if (NULL != strstr(value, "lose")) r->keep_alive = 0;
1078             if (r->http_version >= HTTP_VERSION_2) continue;
1079             break;
1080           case HTTP_HEADER_CONTENT_LENGTH:
1081             r->content_length = strtoul(value, NULL, 10);
1082             if (*value == '+') ++value;
1083             break;
1084           case HTTP_HEADER_TRANSFER_ENCODING:
1085             /*(assumes "Transfer-Encoding: chunked"; does not verify)*/
1086             r->resp_decode_chunked = 1;
1087             r->gw_dechunk = calloc(1, sizeof(response_dechunk));
1088             /* XXX: future: might consider using chunk_buffer_acquire()
1089              *      and chunk_buffer_release() for r->gw_dechunk->b */
1090             force_assert(r->gw_dechunk);
1091             continue;
1092           case HTTP_HEADER_HTTP2_SETTINGS:
1093             /* RFC7540 3.2.1
1094              *   A server MUST NOT send this header field. */
1095             /* (not bothering to remove HTTP2-Settings from Connection) */
1096             continue;
1097           default:
1098             break;
1099         }
1100 
1101         http_header_response_insert(r, id, key, key_len, value, strlen(value));
1102     }
1103 
1104     /* CGI/1.1 rev 03 - 7.2.1.2 */
1105     /* (proxy requires Status-Line, so never true for proxy)*/
1106     if (!status_is_set && (r->resp_htags & HTTP_HEADER_LOCATION)) {
1107         r->http_status = 302;
1108     }
1109 
1110     return 0;
1111 }
1112 
1113 
1114 __attribute_hot__
1115 __attribute_pure__
1116 static const char *
1117 http_response_end_of_header (const char * const restrict ptr)
1118 {
1119     /* find \n(\r)?\n sequence */
1120     for (const char *n=ptr-1, *nn=NULL; NULL != (n = strchr(n+1, '\n')); nn=n) {
1121         if (n - nn == 2 ? n[-1] == '\r' : n - nn == 1) return n+1;
1122     }
1123     return NULL;
1124 }
1125 
1126 
1127 __attribute_cold__
1128 static uint32_t
1129 http_response_discard_1xx (buffer * const restrict b, uint32_t len)
1130 {
1131     char * const ptr = b->ptr;
1132     const char * const n = http_response_end_of_header(ptr+12);
1133     if (NULL == n) return 0; /* * unfinished headers */
1134 
1135     /* discard 100 Continue headers */
1136     len -= (uint32_t)(n - ptr);
1137     memmove(ptr, n, len);
1138     buffer_string_set_length(b, len);
1139     return len;
1140 }
1141 
1142 
1143 __attribute_cold__
1144 __attribute_noinline__
1145 static uint32_t
1146 http_response_check_1xx (buffer * const restrict b, uint32_t len)
1147 {
1148     const char * const s = b->ptr;
1149     while (len > 7 && 0 == memcmp(s, "HTTP/1.", 7)) {
1150         /* discard HTTP/1.1 1xx responses other than 101 Switching Protocols */
1151         if (len > 12
1152             && s[8] == ' ' && s[9] == '1' && s[10] == '0' && s[11] != '1') {
1153             len = http_response_discard_1xx(b, len);
1154             continue;
1155         }
1156         break;
1157     }
1158     return len;
1159 }
1160 
1161 
1162 handler_t http_response_parse_headers(request_st * const r, http_response_opts * const opts, buffer * const b) {
1163     /**
1164      * possible formats of response headers:
1165      *
1166      * proxy or NPH (non-parsed headers):
1167      *
1168      *   HTTP/1.0 200 Ok\n
1169      *   Header: Value\n
1170      *   \n
1171      *
1172      * CGI:
1173      *
1174      *   Header: Value\n
1175      *   Status: 200\n
1176      *   \n
1177      *
1178      * and different mixes of \n and \r\n combinations
1179      *
1180      * Some users also forget about CGI and just send a response
1181      * and hope we handle it. No headers, no header-content separator
1182      */
1183 
1184     uint32_t header_len = buffer_string_length(b);
1185     if (header_len > 12 && b->ptr[9] == '1') {
1186         header_len = http_response_check_1xx(b, header_len);
1187         if (0 == header_len)
1188             return HANDLER_GO_ON; /* unfinished header */
1189     }
1190     /*("HTTP/1.1 200 " is at least 13 chars + \r\n)*/
1191     const int is_nph = (header_len > 12 && 0 == memcmp(b->ptr, "HTTP/1.", 7));
1192 
1193     int is_header_end = 0;
1194     uint32_t i = 0, blen;
1195     const char *bstart;
1196 
1197     if (b->ptr[0] == '\n' || (b->ptr[0] == '\r' && b->ptr[1] == '\n')) {
1198         /* no HTTP headers */
1199         i = (b->ptr[0] == '\n') ? 0 : 1;
1200         is_header_end = 1;
1201     } else if (is_nph || b->ptr[(i = strcspn(b->ptr, ":\n"))] == ':') {
1202         /* HTTP headers */
1203         const char *n = http_response_end_of_header(b->ptr+i+1);
1204         if (n) {
1205             i = (uint32_t)(n - b->ptr - 1);
1206             is_header_end = 1;
1207         }
1208     } else if (i == header_len) { /* (no newline yet; partial header line?) */
1209     } else if (opts->backend == BACKEND_CGI) {
1210         /* no HTTP headers, but a body (special-case for CGI compat) */
1211         /* no colon found; does not appear to be HTTP headers */
1212         if (0 != http_chunk_append_buffer(r, b)) {
1213             return HANDLER_ERROR;
1214         }
1215         r->http_status = 200; /* OK */
1216         r->resp_body_started = 1;
1217         return HANDLER_GO_ON;
1218     } else {
1219         /* invalid response headers */
1220         r->http_status = 502; /* Bad Gateway */
1221         r->handler_module = NULL;
1222         return HANDLER_FINISHED;
1223     }
1224 
1225     if (!is_header_end) {
1226         if (header_len > MAX_HTTP_RESPONSE_FIELD_SIZE) {
1227             log_error(r->conf.errh, __FILE__, __LINE__,
1228               "response headers too large for %s", r->uri.path.ptr);
1229             r->http_status = 502; /* Bad Gateway */
1230             r->handler_module = NULL;
1231             return HANDLER_FINISHED;
1232         }
1233         return HANDLER_GO_ON;
1234     }
1235 
1236     /* the body starts after the EOL */
1237     bstart = b->ptr + (i + 1);
1238     blen = header_len - (i + 1);
1239 
1240     /* strip the last \r?\n */
1241     if (i > 0 && (b->ptr[i - 1] == '\r')) {
1242         i--;
1243     }
1244 
1245     buffer_string_set_length(b, i);
1246 
1247     if (opts->backend == BACKEND_PROXY && !is_nph) {
1248         /* invalid response Status-Line from HTTP proxy */
1249         r->http_status = 502; /* Bad Gateway */
1250         r->handler_module = NULL;
1251         return HANDLER_FINISHED;
1252     }
1253 
1254     if (0 != http_response_process_headers(r, opts, b)) {
1255         return HANDLER_ERROR;
1256     }
1257 
1258     r->resp_body_started = 1;
1259 
1260     if (opts->authorizer
1261         && (r->http_status == 0 || r->http_status == 200)) {
1262         return HANDLER_GO_ON;
1263     }
1264 
1265     if (NULL == r->handler_module) {
1266         return HANDLER_FINISHED;
1267     }
1268 
1269     if (opts->local_redir && r->http_status >= 300 && r->http_status < 400){
1270         /*(r->resp_htags & HTTP_HEADER_LOCATION)*/
1271         handler_t rc = http_response_process_local_redir(r, blen);
1272         if (NULL == r->handler_module)
1273             r->resp_body_started = 0;
1274         if (rc != HANDLER_GO_ON) return rc;
1275     }
1276 
1277     if (opts->xsendfile_allow) {
1278         buffer *vb;
1279         /* X-Sendfile2 is deprecated; historical for fastcgi */
1280         if (opts->backend == BACKEND_FASTCGI
1281             && NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-Sendfile2")))) {
1282             http_response_xsendfile2(r, vb, opts->xsendfile_docroot);
1283             /* http_header_response_unset() shortcut for HTTP_HEADER_OTHER */
1284             buffer_clear(vb); /*(do not send to client)*/
1285             if (NULL == r->handler_module)
1286                 r->resp_body_started = 0;
1287             return HANDLER_FINISHED;
1288         } else if (NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-Sendfile")))
1289                    || (opts->backend == BACKEND_FASTCGI /* X-LIGHTTPD-send-file is deprecated; historical for fastcgi */
1290                        && NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-LIGHTTPD-send-file"))))) {
1291             http_response_xsendfile(r, vb, opts->xsendfile_docroot);
1292             /* http_header_response_unset() shortcut for HTTP_HEADER_OTHER */
1293             buffer_clear(vb); /*(do not send to client)*/
1294             if (NULL == r->handler_module)
1295                 r->resp_body_started = 0;
1296             return HANDLER_FINISHED;
1297         }
1298     }
1299 
1300     if (blen > 0) {
1301         if (0 != http_chunk_decode_append_mem(r, bstart, blen))
1302             return HANDLER_ERROR;
1303     }
1304 
1305     /* (callback for response headers complete) */
1306     return (opts->headers) ? opts->headers(r, opts) : HANDLER_GO_ON;
1307 }
1308 
1309 
1310 handler_t http_response_read(request_st * const r, http_response_opts * const opts, buffer * const b, fdnode * const fdn) {
1311     const int fd = fdn->fd;
1312     while (1) {
1313         ssize_t n;
1314         size_t avail = buffer_string_space(b);
1315         unsigned int toread = 0;
1316 
1317         if (0 == fdevent_ioctl_fionread(fd, opts->fdfmt, (int *)&toread)) {
1318             if (avail < toread) {
1319                 size_t blen = buffer_string_length(b);
1320                 if (toread + blen < 4096)
1321                     toread = 4095 - blen;
1322                 else if (toread > MAX_READ_LIMIT)
1323                     toread = MAX_READ_LIMIT;
1324             }
1325             else if (0 == toread) {
1326               #if 0
1327                 return (fdevent_fdnode_interest(fdn) & FDEVENT_IN)
1328                   ? HANDLER_FINISHED  /* read finished */
1329                   : HANDLER_GO_ON;    /* optimistic read; data not ready */
1330               #else
1331                 if (!(fdevent_fdnode_interest(fdn) & FDEVENT_IN)) {
1332                     if (!(r->conf.stream_response_body
1333                           & FDEVENT_STREAM_RESPONSE_POLLRDHUP))
1334                         return HANDLER_GO_ON;/*optimistic read; data not ready*/
1335                 }
1336                 if (0 == avail) /* let read() below indicate if EOF or EAGAIN */
1337                     toread = 1024;
1338               #endif
1339             }
1340         }
1341         else if (avail < 1024) {
1342             toread = 4095 - avail;
1343         }
1344 
1345         if (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN) {
1346             off_t cqlen = chunkqueue_length(r->write_queue);
1347             if (cqlen + (off_t)toread > 65536 - 4096) {
1348                 if (!r->con->is_writable) {
1349                     /*(defer removal of FDEVENT_IN interest since
1350                      * connection_state_machine() might be able to send data
1351                      * immediately, unless !con->is_writable, where
1352                      * connection_state_machine() might not loop back to call
1353                      * mod_proxy_handle_subrequest())*/
1354                     fdevent_fdnode_event_clr(r->con->srv->ev, fdn, FDEVENT_IN);
1355                 }
1356                 if (cqlen >= 65536-1) return HANDLER_GO_ON;
1357                 toread = 65536 - 1 - (unsigned int)cqlen;
1358                 /* Note: heuristic is fuzzy in that it limits how much to read
1359                  * from backend based on how much is pending to write to client.
1360                  * Modules where data from backend is framed (e.g. FastCGI) may
1361                  * want to limit how much is buffered from backend while waiting
1362                  * for a complete data frame or data packet from backend. */
1363             }
1364         }
1365 
1366         if (avail < toread) {
1367             /*(add avail+toread to reduce allocations when ioctl EOPNOTSUPP)*/
1368             avail = avail ? avail - 1 + toread : toread;
1369             buffer_string_prepare_append(b, avail);
1370         }
1371 
1372         n = read(fd, b->ptr+buffer_string_length(b), avail);
1373 
1374         if (n < 0) {
1375             switch (errno) {
1376               case EAGAIN:
1377              #ifdef EWOULDBLOCK
1378              #if EWOULDBLOCK != EAGAIN
1379               case EWOULDBLOCK:
1380              #endif
1381              #endif
1382               case EINTR:
1383                 return HANDLER_GO_ON;
1384               default:
1385                 log_perror(r->conf.errh, __FILE__, __LINE__,
1386                   "read() %d %d", r->con->fd, fd);
1387                 return HANDLER_ERROR;
1388             }
1389         }
1390 
1391         buffer_commit(b, (size_t)n);
1392       #ifdef __COVERITY__
1393         /* Coverity Scan overlooks the effect of buffer_commit() */
1394         b->ptr[buffer_string_length(b)+n] = '\0';
1395       #endif
1396 
1397         if (NULL != opts->parse) {
1398             handler_t rc = opts->parse(r, opts, b, (size_t)n);
1399             if (rc != HANDLER_GO_ON) return rc;
1400         } else if (0 == n) {
1401             /* note: no further data is sent to backend after read EOF on socket
1402              * (not checking for half-closed TCP socket)
1403              * (backend should read all data desired prior to closing socket,
1404              *  though might send app-level close data frame, if applicable) */
1405             return HANDLER_FINISHED; /* read finished */
1406         } else if (0 == r->resp_body_started) {
1407             /* split header from body */
1408             handler_t rc = http_response_parse_headers(r, opts, b);
1409             if (rc != HANDLER_GO_ON) return rc;
1410             /* accumulate response in b until headers completed (or error) */
1411             if (r->resp_body_started) buffer_clear(b);
1412         } else {
1413             if (0 != http_chunk_decode_append_buffer(r, b)) {
1414                 /* error writing to tempfile;
1415                  * truncate response or send 500 if nothing sent yet */
1416                 return HANDLER_ERROR;
1417             }
1418             buffer_clear(b);
1419         }
1420 
1421         if (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN) {
1422             if (chunkqueue_length(r->write_queue) > 65536 - 4096) {
1423                 /*(defer removal of FDEVENT_IN interest since
1424                  * connection_state_machine() might be able to send
1425                  * data immediately, unless !con->is_writable, where
1426                  * connection_state_machine() might not loop back to
1427                  * call the subrequest handler)*/
1428                 if (!r->con->is_writable)
1429                     fdevent_fdnode_event_clr(r->con->srv->ev, fdn, FDEVENT_IN);
1430                 break;
1431             }
1432         }
1433 
1434         if ((size_t)n < avail)
1435             break; /* emptied kernel read buffer or partial read */
1436     }
1437 
1438     return HANDLER_GO_ON;
1439 }
1440 
1441 
1442 int http_cgi_headers (request_st * const r, http_cgi_opts * const opts, http_cgi_header_append_cb cb, void *vdata) {
1443 
1444     /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1445 
1446     int rc = 0;
1447     const connection * const con = r->con;
1448     server_socket * const srv_sock = con->srv_socket;
1449     buffer * const tb = r->tmp_buf;
1450     const char *s;
1451     size_t n;
1452     char buf[LI_ITOSTRING_LENGTH];
1453     sock_addr *addr;
1454     sock_addr addrbuf;
1455     char b2[INET6_ADDRSTRLEN + 1];
1456 
1457     /* (CONTENT_LENGTH must be first for SCGI) */
1458     if (!opts->authorizer) {
1459         rc |= cb(vdata, CONST_STR_LEN("CONTENT_LENGTH"),
1460                  buf, li_itostrn(buf,sizeof(buf),r->reqbody_length));
1461     }
1462 
1463     if (!buffer_string_is_empty(&r->uri.query)) {
1464         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
1465                         CONST_BUF_LEN(&r->uri.query));
1466     } else {
1467         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
1468                         CONST_STR_LEN(""));
1469     }
1470     if (!buffer_string_is_empty(opts->strip_request_uri)) {
1471         /**
1472          * /app1/index/list
1473          *
1474          * stripping /app1 or /app1/ should lead to
1475          *
1476          * /index/list
1477          *
1478          */
1479         size_t len = buffer_string_length(opts->strip_request_uri);
1480         if ('/' == opts->strip_request_uri->ptr[len-1]) {
1481             --len;
1482         }
1483 
1484         if (buffer_string_length(&r->target_orig) >= len
1485             && 0 == memcmp(r->target_orig.ptr,
1486                            opts->strip_request_uri->ptr, len)
1487             && r->target_orig.ptr[len] == '/') {
1488             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
1489                             r->target_orig.ptr+len,
1490                             buffer_string_length(&r->target_orig)-len);
1491         } else {
1492             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
1493                             CONST_BUF_LEN(&r->target_orig));
1494         }
1495     } else {
1496         rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
1497                         CONST_BUF_LEN(&r->target_orig));
1498     }
1499     if (!buffer_is_equal(&r->target, &r->target_orig)) {
1500         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_URI"),
1501                         CONST_BUF_LEN(&r->target));
1502     }
1503     /* set REDIRECT_STATUS for php compiled with --force-redirect
1504      * (if REDIRECT_STATUS has not already been set by error handler) */
1505     if (0 == r->error_handler_saved_status) {
1506         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_STATUS"),
1507                         CONST_STR_LEN("200"));
1508     }
1509 
1510     /*
1511      * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1512      * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1513      * (6.1.14, 6.1.6, 6.1.7)
1514      */
1515     if (!opts->authorizer) {
1516         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_NAME"),
1517                         CONST_BUF_LEN(&r->uri.path));
1518         if (!buffer_string_is_empty(&r->pathinfo)) {
1519             rc |= cb(vdata, CONST_STR_LEN("PATH_INFO"),
1520                             CONST_BUF_LEN(&r->pathinfo));
1521             /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1522             if (!buffer_string_is_empty(opts->docroot)) {
1523                 buffer_copy_buffer(tb, opts->docroot);
1524             } else {
1525                 buffer_copy_buffer(tb, &r->physical.basedir);
1526             }
1527             buffer_append_string_buffer(tb, &r->pathinfo);
1528             rc |= cb(vdata, CONST_STR_LEN("PATH_TRANSLATED"),
1529                             CONST_BUF_LEN(tb));
1530         }
1531     }
1532 
1533    /*
1534     * SCRIPT_FILENAME and DOCUMENT_ROOT for php
1535     * The PHP manual http://www.php.net/manual/en/reserved.variables.php
1536     * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1537     * (see php.ini cgi.fix_pathinfo = 1 config parameter)
1538     */
1539 
1540     if (!buffer_string_is_empty(opts->docroot)) {
1541         /* alternate docroot, e.g. for remote FastCGI or SCGI server */
1542         buffer_copy_buffer(tb, opts->docroot);
1543         buffer_append_string_buffer(tb, &r->uri.path);
1544         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
1545                         CONST_BUF_LEN(tb));
1546         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
1547                         CONST_BUF_LEN(opts->docroot));
1548     } else {
1549         if (opts->break_scriptfilename_for_php) {
1550             /* php.ini config cgi.fix_pathinfo = 1 need a broken SCRIPT_FILENAME
1551              * to find out what PATH_INFO is itself
1552              *
1553              * see src/sapi/cgi_main.c, init_request_info()
1554              */
1555             buffer_copy_buffer(tb, &r->physical.path);
1556             buffer_append_string_buffer(tb, &r->pathinfo);
1557             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
1558                             CONST_BUF_LEN(tb));
1559         } else {
1560             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
1561                             CONST_BUF_LEN(&r->physical.path));
1562         }
1563         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
1564                         CONST_BUF_LEN(&r->physical.basedir));
1565     }
1566 
1567     s = get_http_method_name(r->http_method);
1568     force_assert(s);
1569     rc |= cb(vdata, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
1570 
1571     s = get_http_version_name(r->http_version);
1572     force_assert(s);
1573     rc |= cb(vdata, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
1574 
1575     rc |= cb(vdata, CONST_STR_LEN("SERVER_SOFTWARE"),
1576                     CONST_BUF_LEN(r->conf.server_tag));
1577 
1578     rc |= cb(vdata, CONST_STR_LEN("GATEWAY_INTERFACE"),
1579                     CONST_STR_LEN("CGI/1.1"));
1580 
1581     rc |= cb(vdata, CONST_STR_LEN("REQUEST_SCHEME"),
1582                     CONST_BUF_LEN(&r->uri.scheme));
1583 
1584     if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"))) {
1585         rc |= cb(vdata, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1586     }
1587 
1588     addr = &srv_sock->addr;
1589     rc |= cb(vdata, CONST_STR_LEN("SERVER_PORT"),
1590              buf, li_utostrn(buf,sizeof(buf),sock_addr_get_port(addr)));
1591 
1592     switch (addr->plain.sa_family) {
1593     case AF_INET:
1594     case AF_INET6:
1595         if (sock_addr_is_addr_wildcard(addr)) {
1596             socklen_t addrlen = sizeof(addrbuf);
1597             if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){
1598                 addr = &addrbuf;
1599             } else {
1600                 s = "";
1601                 break;
1602             }
1603         }
1604         s = sock_addr_inet_ntop(addr, b2, sizeof(b2)-1);
1605         if (NULL == s) s = "";
1606         break;
1607     default:
1608         s = "";
1609         break;
1610     }
1611     force_assert(s);
1612     rc |= cb(vdata, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
1613 
1614     if (!buffer_string_is_empty(r->server_name)) {
1615         size_t len = buffer_string_length(r->server_name);
1616 
1617         if (r->server_name->ptr[0] == '[') {
1618             const char *colon = strstr(r->server_name->ptr, "]:");
1619             if (colon) len = (colon + 1) - r->server_name->ptr;
1620         } else {
1621             const char *colon = strchr(r->server_name->ptr, ':');
1622             if (colon) len = colon - r->server_name->ptr;
1623         }
1624 
1625         rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"),
1626                         r->server_name->ptr, len);
1627     } else {
1628         /* set to be same as SERVER_ADDR (above) */
1629         rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
1630     }
1631 
1632     rc |= cb(vdata, CONST_STR_LEN("REMOTE_ADDR"),
1633                     CONST_BUF_LEN(con->dst_addr_buf));
1634 
1635     rc |= cb(vdata, CONST_STR_LEN("REMOTE_PORT"), buf,
1636              li_utostrn(buf,sizeof(buf),sock_addr_get_port(&con->dst_addr)));
1637 
1638     for (n = 0; n < r->rqst_headers.used; n++) {
1639         data_string *ds = (data_string *)r->rqst_headers.data[n];
1640         if (!buffer_string_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
1641             /* Security: Do not emit HTTP_PROXY in environment.
1642              * Some executables use HTTP_PROXY to configure
1643              * outgoing proxy.  See also https://httpoxy.org/ */
1644             if (buffer_is_equal_caseless_string(&ds->key,
1645                                                 CONST_STR_LEN("Proxy"))) {
1646                 continue;
1647             }
1648             buffer_copy_string_encoded_cgi_varnames(tb,
1649                                                     CONST_BUF_LEN(&ds->key), 1);
1650             rc |= cb(vdata, CONST_BUF_LEN(tb),
1651                             CONST_BUF_LEN(&ds->value));
1652         }
1653     }
1654 
1655     con->srv->request_env(r);
1656 
1657     for (n = 0; n < r->env.used; n++) {
1658         data_string *ds = (data_string *)r->env.data[n];
1659         if (!buffer_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
1660             buffer_copy_string_encoded_cgi_varnames(tb,
1661                                                     CONST_BUF_LEN(&ds->key), 0);
1662             rc |= cb(vdata, CONST_BUF_LEN(tb),
1663                             CONST_BUF_LEN(&ds->value));
1664         }
1665     }
1666 
1667     return rc;
1668 }
1669