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