xref: /lighttpd1.4/src/http-header-glue.c (revision 9570cc2f)
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 	/* mod_compress might set several data directly, don't overwrite them */
495 
496 	/* set response content-type, if not set already */
497 
498 	if (NULL == http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"))) {
499 		const buffer *content_type = stat_cache_content_type_get(sce, r);
500 		if (buffer_string_is_empty(content_type)) {
501 			/* we are setting application/octet-stream, but also announce that
502 			 * this header field might change in the seconds few requests
503 			 *
504 			 * This should fix the aggressive caching of FF and the script download
505 			 * seen by the first installations
506 			 */
507 			http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("application/octet-stream"));
508 
509 			allow_caching = 0;
510 		} else {
511 			http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(content_type));
512 		}
513 	}
514 
515 	if (r->conf.range_requests) {
516 		http_header_response_append(r, HTTP_HEADER_OTHER, CONST_STR_LEN("Accept-Ranges"), CONST_STR_LEN("bytes"));
517 	}
518 
519 	if (allow_caching) {
520 		const buffer *etag = (0 != r->conf.etag_flags)
521 		  ? stat_cache_etag_get(sce, r->conf.etag_flags)
522 		  : NULL;
523 		if (!buffer_string_is_empty(etag)) {
524 			if (NULL == http_header_response_get(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"))) {
525 				/* generate e-tag */
526 				etag_mutate(&r->physical.etag, etag);
527 
528 				http_header_response_set(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"), CONST_BUF_LEN(&r->physical.etag));
529 			}
530 		}
531 
532 		/* prepare header */
533 		if (NULL == (mtime = http_header_response_get(r, HTTP_HEADER_LAST_MODIFIED, CONST_STR_LEN("Last-Modified")))) {
534 			mtime = strftime_cache_get(sce->st.st_mtime);
535 			http_header_response_set(r, HTTP_HEADER_LAST_MODIFIED, CONST_STR_LEN("Last-Modified"), CONST_BUF_LEN(mtime));
536 		}
537 
538 		if (HANDLER_FINISHED == http_response_handle_cachable(r, mtime)) {
539 			if (fd >= 0) close(fd);
540 			return;
541 		}
542 	}
543 
544 	if (fd < 0) { /* 0-length file */
545 		r->http_status = 200;
546 		r->resp_body_finished = 1;
547 		return;
548 	}
549 
550 	if (r->conf.range_requests
551 	    && (200 == r->http_status || 0 == r->http_status)
552 	    && NULL != (vb = http_header_request_get(r, HTTP_HEADER_RANGE, CONST_STR_LEN("Range")))
553 	    && NULL == http_header_response_get(r, HTTP_HEADER_CONTENT_ENCODING, CONST_STR_LEN("Content-Encoding"))) {
554 		const buffer *range = vb;
555 		int do_range_request = 1;
556 		/* check if we have a conditional GET */
557 
558 		if (NULL != (vb = http_header_request_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("If-Range")))) {
559 			/* if the value is the same as our ETag, we do a Range-request,
560 			 * otherwise a full 200 */
561 
562 			if (vb->ptr[0] == '"') {
563 				/**
564 				 * client wants a ETag
565 				 */
566 				if (!buffer_is_equal(vb, &r->physical.etag)) {
567 					do_range_request = 0;
568 				}
569 			} else if (!mtime) {
570 				/**
571 				 * we don't have a Last-Modified and can match the If-Range:
572 				 *
573 				 * sending all
574 				 */
575 				do_range_request = 0;
576 			} else if (!buffer_is_equal(vb, mtime)) {
577 				do_range_request = 0;
578 			}
579 		}
580 
581 		if (do_range_request
582 		    && !buffer_string_is_empty(range)
583 		    && 0 == strncmp(range->ptr, "bytes=", 6)) {
584 			/* support only "bytes" byte-unit */
585 			/* content prepared, I'm done */
586 			r->resp_body_finished = 1;
587 
588 			if (0 == http_response_parse_range(r, path, sce, range->ptr+6)) {
589 				r->http_status = 206;
590 			}
591 			close(fd);
592 			return;
593 		}
594 	}
595 
596 	/* if we are still here, prepare body */
597 
598 	/* we add it here for all requests
599 	 * the HEAD request will drop it afterwards again
600 	 */
601 
602 	if (0 == http_chunk_append_file_fd(r, path, fd, sce->st.st_size)) {
603 		r->http_status = 200;
604 		r->resp_body_finished = 1;
605 	}
606 	else {
607 		r->http_status = 500;
608 	}
609 }
610 
611 
612 static void http_response_xsendfile (request_st * const r, buffer * const path, const array * const xdocroot) {
613 	const int status = r->http_status;
614 	int valid = 1;
615 
616 	/* reset Content-Length, if set by backend
617 	 * Content-Length might later be set to size of X-Sendfile static file,
618 	 * determined by open(), fstat() to reduces race conditions if the file
619 	 * is modified between stat() (stat_cache_get_entry()) and open(). */
620 	if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) {
621 		http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
622 		r->content_length = -1;
623 	}
624 
625 	buffer_urldecode_path(path);
626 	if (!buffer_is_valid_UTF8(path)) {
627 		log_error(r->conf.errh, __FILE__, __LINE__,
628 		  "X-Sendfile invalid UTF-8 after url-decode: %s", path->ptr);
629 		if (r->http_status < 400) {
630 			r->http_status = 502;
631 			r->handler_module = NULL;
632 		}
633 		return;
634 	}
635 	buffer_path_simplify(path, path);
636 	if (r->conf.force_lowercase_filenames) {
637 		buffer_to_lower(path);
638 	}
639 
640 	/* check that path is under xdocroot(s)
641 	 * - xdocroot should have trailing slash appended at config time
642 	 * - r->conf.force_lowercase_filenames is not a server-wide setting,
643 	 *   and so can not be definitively applied to xdocroot at config time*/
644 	if (xdocroot) {
645 		size_t i, xlen = buffer_string_length(path);
646 		for (i = 0; i < xdocroot->used; ++i) {
647 			data_string *ds = (data_string *)xdocroot->data[i];
648 			size_t dlen = buffer_string_length(&ds->value);
649 			if (dlen <= xlen
650 			    && (!r->conf.force_lowercase_filenames
651 				? 0 == memcmp(path->ptr, ds->value.ptr, dlen)
652 				: buffer_eq_icase_ssn(path->ptr, ds->value.ptr, dlen))) {
653 				break;
654 			}
655 		}
656 		if (i == xdocroot->used && 0 != i) {
657 			log_error(r->conf.errh, __FILE__, __LINE__,
658 			  "X-Sendfile (%s) not under configured x-sendfile-docroot(s)", path->ptr);
659 			r->http_status = 403;
660 			valid = 0;
661 		}
662 	}
663 
664 	if (valid) http_response_send_file(r, path);
665 
666 	if (r->http_status >= 400 && status < 300) {
667 		r->handler_module = NULL;
668 	} else if (0 != status && 200 != status) {
669 		r->http_status = status;
670 	}
671 }
672 
673 
674 static void http_response_xsendfile2(request_st * const r, const buffer * const value, const array * const xdocroot) {
675     const char *pos = value->ptr;
676     buffer * const b = r->tmp_buf;
677     const int status = r->http_status;
678 
679     /* reset Content-Length, if set by backend */
680     if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) {
681         http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
682         r->content_length = -1;
683     }
684 
685     while (*pos) {
686         const char *filename, *range;
687         stat_cache_entry *sce;
688         off_t begin_range, end_range, range_len;
689 
690         while (' ' == *pos) pos++;
691         if (!*pos) break;
692 
693         filename = pos;
694         if (NULL == (range = strchr(pos, ' '))) {
695             /* missing range */
696             log_error(r->conf.errh, __FILE__, __LINE__,
697               "Couldn't find range after filename: %s", filename);
698             r->http_status = 502;
699             break;
700         }
701         buffer_copy_string_len(b, filename, range - filename);
702 
703         /* find end of range */
704         for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ;
705 
706         buffer_urldecode_path(b);
707         if (!buffer_is_valid_UTF8(b)) {
708             log_error(r->conf.errh, __FILE__, __LINE__,
709               "X-Sendfile2 invalid UTF-8 after url-decode: %s", b->ptr);
710             r->http_status = 502;
711             break;
712         }
713         buffer_path_simplify(b, b);
714         if (r->conf.force_lowercase_filenames) {
715             buffer_to_lower(b);
716         }
717         if (xdocroot) {
718             size_t i, xlen = buffer_string_length(b);
719             for (i = 0; i < xdocroot->used; ++i) {
720                 data_string *ds = (data_string *)xdocroot->data[i];
721                 size_t dlen = buffer_string_length(&ds->value);
722                 if (dlen <= xlen
723                     && (!r->conf.force_lowercase_filenames
724                     ? 0 == memcmp(b->ptr, ds->value.ptr, dlen)
725                     : buffer_eq_icase_ssn(b->ptr, ds->value.ptr, dlen))) {
726                     break;
727                 }
728             }
729             if (i == xdocroot->used && 0 != i) {
730                 log_error(r->conf.errh, __FILE__, __LINE__,
731                   "X-Sendfile2 (%s) not under configured x-sendfile-docroot(s)",
732                   b->ptr);
733                 r->http_status = 403;
734                 break;
735             }
736         }
737 
738         sce = stat_cache_get_entry(b);
739         if (NULL == sce) {
740             log_error(r->conf.errh, __FILE__, __LINE__,
741               "send-file error: couldn't get stat_cache entry for "
742               "X-Sendfile2: %s", b->ptr);
743             r->http_status = 404;
744             break;
745         } else if (!S_ISREG(sce->st.st_mode)) {
746             log_error(r->conf.errh, __FILE__, __LINE__,
747               "send-file error: wrong filetype for X-Sendfile2: %s", b->ptr);
748             r->http_status = 502;
749             break;
750         }
751         /* found the file */
752 
753         /* parse range */
754         end_range = sce->st.st_size - 1;
755         {
756             char *rpos = NULL;
757             errno = 0;
758             begin_range = strtoll(range, &rpos, 10);
759             if (errno != 0 || begin_range < 0 || rpos == range)
760                 goto range_failed;
761             if ('-' != *rpos++) goto range_failed;
762             if (rpos != pos) {
763                 range = rpos;
764                 end_range = strtoll(range, &rpos, 10);
765                 if (errno != 0 || end_range < 0 || rpos == range)
766                     goto range_failed;
767             }
768             if (rpos != pos) goto range_failed;
769 
770             goto range_success;
771 
772 range_failed:
773             log_error(r->conf.errh, __FILE__, __LINE__,
774               "Couldn't decode range after filename: %s", filename);
775             r->http_status = 502;
776             break;
777 
778 range_success: ;
779         }
780 
781         /* no parameters accepted */
782 
783         while (*pos == ' ') pos++;
784         if (*pos != '\0' && *pos != ',') {
785             r->http_status = 502;
786             break;
787         }
788 
789         range_len = end_range - begin_range + 1;
790         if (range_len < 0) {
791             r->http_status = 502;
792             break;
793         }
794         if (range_len != 0) {
795             if (0 !=
796                 http_chunk_append_file_range(r, b, begin_range, range_len)) {
797                 r->http_status = 502;
798                 break;
799             }
800         }
801 
802         if (*pos == ',') pos++;
803     }
804 
805     if (r->http_status >= 400 && status < 300) {
806 	r->handler_module = NULL;
807     } else if (0 != status && 200 != status) {
808         r->http_status = status;
809     }
810 }
811 
812 
813 void http_response_backend_error (request_st * const r) {
814 	if (r->resp_body_started) {
815 		/*(response might have been already started, kill the connection)*/
816 		/*(mode == DIRECT to avoid later call to http_response_backend_done())*/
817 		r->handler_module = NULL;  /*(avoid sending final chunked block)*/
818 		r->keep_alive = 0;
819 		r->resp_body_finished = 1;
820 	} /*(else error status set later by http_response_backend_done())*/
821 }
822 
823 void http_response_backend_done (request_st * const r) {
824 	/* (not CON_STATE_ERROR and not CON_STATE_RESPONSE_END,
825 	 *  i.e. not called from handle_connection_close or connection_reset
826 	 *  hooks, except maybe from errdoc handler, which later resets state)*/
827 	switch (r->state) {
828 	case CON_STATE_HANDLE_REQUEST:
829 	case CON_STATE_READ_POST:
830 		if (!r->resp_body_started) {
831 			/* Send an error if we haven't sent any data yet */
832 			r->http_status = 500;
833 			r->handler_module = NULL;
834 			break;
835 		} /* else fall through */
836 	case CON_STATE_WRITE:
837 		if (!r->resp_body_finished) {
838 			http_chunk_close(r);
839 			r->resp_body_finished = 1;
840 		}
841 	default:
842 		break;
843 	}
844 }
845 
846 
847 void http_response_upgrade_read_body_unknown(request_st * const r) {
848     /* act as transparent proxy */
849     if (!(r->conf.stream_request_body & FDEVENT_STREAM_REQUEST))
850         r->conf.stream_request_body |=
851           (FDEVENT_STREAM_REQUEST_BUFMIN | FDEVENT_STREAM_REQUEST);
852     if (!(r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE))
853         r->conf.stream_response_body |=
854           (FDEVENT_STREAM_RESPONSE_BUFMIN | FDEVENT_STREAM_RESPONSE);
855     r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN;
856     r->reqbody_length = -2;
857     r->keep_alive = 0;
858 }
859 
860 
861 static handler_t http_response_process_local_redir(request_st * const r, size_t blen) {
862     /* [RFC3875] The Common Gateway Interface (CGI) Version 1.1
863      * [RFC3875] 6.2.2 Local Redirect Response
864      *
865      *    The CGI script can return a URI path and query-string
866      *    ('local-pathquery') for a local resource in a Location header field.
867      *    This indicates to the server that it should reprocess the request
868      *    using the path specified.
869      *
870      *      local-redir-response = local-Location NL
871      *
872      *    The script MUST NOT return any other header fields or a message-body,
873      *    and the server MUST generate the response that it would have produced
874      *    in response to a request containing the URL
875      *
876      *      scheme "://" server-name ":" server-port local-pathquery
877      *
878      * (Might not have begun to receive body yet, but do skip local-redir
879      *  if we already have started receiving a response body (blen > 0))
880      * (Also, while not required by the RFC, do not send local-redir back
881      *  to same URL, since CGI should have handled it internally if it
882      *  really wanted to do that internally)
883      */
884 
885     /* r->http_status >= 300 && r->http_status < 400) */
886     size_t ulen = buffer_string_length(&r->uri.path);
887     const buffer *vb = http_header_response_get(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location"));
888     if (NULL != vb
889         && vb->ptr[0] == '/'
890         && (0 != strncmp(vb->ptr, r->uri.path.ptr, ulen)
891             || (   vb->ptr[ulen] != '\0'
892                 && vb->ptr[ulen] != '/'
893                 && vb->ptr[ulen] != '?'))
894         && 0 == blen
895         && !(r->resp_htags & HTTP_HEADER_STATUS) /*no "Status" or NPH response*/
896         && 1 == r->resp_headers.used) {
897         if (++r->loops_per_request > 5) {
898             log_error(r->conf.errh, __FILE__, __LINE__,
899               "too many internal loops while processing request: %s",
900               r->target_orig.ptr);
901             r->http_status = 500; /* Internal Server Error */
902             r->handler_module = NULL;
903             return HANDLER_FINISHED;
904         }
905 
906         buffer_copy_buffer(&r->target, vb);
907 
908         if (r->reqbody_length) {
909             if (r->reqbody_length
910                 != r->reqbody_queue->bytes_in) {
911                 r->keep_alive = 0;
912             }
913             r->reqbody_length = 0;
914             chunkqueue_reset(r->reqbody_queue);
915         }
916 
917         if (r->http_status != 307 && r->http_status != 308) {
918             /* Note: request body (if any) sent to initial dynamic handler
919              * and is not available to the internal redirect */
920             r->http_method = HTTP_METHOD_GET;
921         }
922 
923         /*(caller must reset request as follows)*/
924         /*connection_response_reset(r);*/ /*(sets r->http_status = 0)*/
925         /*plugins_call_connection_reset(r);*/
926 
927         return HANDLER_COMEBACK;
928     }
929 
930     return HANDLER_GO_ON;
931 }
932 
933 
934 static int http_response_process_headers(request_st * const r, http_response_opts * const opts, buffer * const hdrs) {
935     char *ns;
936     const char *s;
937     int line = 0;
938     int status_is_set = 0;
939 
940     for (s = hdrs->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1, ++line) {
941         const char *key, *value;
942         int key_len;
943         enum http_header_e id;
944 
945         /* strip the \n */
946         ns[0] = '\0';
947         if (ns > s && ns[-1] == '\r') ns[-1] = '\0';
948 
949         if (0 == line && 0 == strncmp(s, "HTTP/1.", 7)) {
950             /* non-parsed headers ... we parse them anyway */
951             if ((s[7] == '1' || s[7] == '0') && s[8] == ' ') {
952                 /* after the space should be a status code for us */
953                 int status = http_header_str_to_code(s+9);
954                 if (status >= 100 && status < 1000) {
955                     status_is_set = 1;
956                     r->resp_htags |= HTTP_HEADER_STATUS;
957                     r->http_status = status;
958                 } /* else we expected 3 digits and didn't get them */
959             }
960 
961             if (0 == r->http_status) {
962                 log_error(r->conf.errh, __FILE__, __LINE__,
963                   "invalid HTTP status line: %s", s);
964                 r->http_status = 502; /* Bad Gateway */
965                 r->handler_module = NULL;
966                 return -1;
967             }
968 
969             continue;
970         }
971 
972         /* parse the headers */
973         key = s;
974         if (NULL == (value = strchr(s, ':'))) {
975             /* we expect: "<key>: <value>\r\n" */
976             continue;
977         }
978 
979         key_len = value - key;
980         do { ++value; } while (*value == ' ' || *value == '\t'); /* skip LWS */
981         id = http_header_hkey_get(key, key_len);
982 
983         if (opts->authorizer) {
984             if (0 == r->http_status || 200 == r->http_status) {
985                 if (id == HTTP_HEADER_STATUS) {
986                     int status = http_header_str_to_code(value);
987                     if (status >= 100 && status < 1000) {
988                         r->http_status = status;
989                     } else {
990                         r->http_status = 502; /* Bad Gateway */
991                         break;
992                     }
993                 }
994                 else if (id == HTTP_HEADER_OTHER && key_len > 9
995                          && (key[0] & 0xdf) == 'V'
996                          && buffer_eq_icase_ssn(key,
997                                                 CONST_STR_LEN("Variable-"))) {
998                     http_header_env_append(r, key + 9, key_len - 9, value, strlen(value));
999                 }
1000                 continue;
1001             }
1002         }
1003 
1004         switch (id) {
1005           case HTTP_HEADER_STATUS:
1006             {
1007                 if (opts->backend == BACKEND_PROXY) break; /*(pass w/o parse)*/
1008                 int status = http_header_str_to_code(value);
1009                 if (status >= 100 && status < 1000) {
1010                     r->http_status = status;
1011                     status_is_set = 1;
1012                 } else {
1013                     r->http_status = 502;
1014                     r->handler_module = NULL;
1015                 }
1016                 continue; /* do not send Status to client */
1017             }
1018             break;
1019           case HTTP_HEADER_UPGRADE:
1020             /*(technically, should also verify Connection: upgrade)*/
1021             /*(flag only for mod_proxy and mod_cgi (for now))*/
1022             if (opts->backend != BACKEND_PROXY
1023                 && opts->backend != BACKEND_CGI) {
1024                 id = HTTP_HEADER_OTHER;
1025             }
1026             break;
1027           case HTTP_HEADER_CONNECTION:
1028             if (opts->backend == BACKEND_PROXY) continue;
1029             /*(should parse for tokens and do case-insensitive match for "close"
1030              * but this is an imperfect though simplistic attempt to honor
1031              * backend request to close)*/
1032             if (NULL != strstr(value, "lose")) r->keep_alive = 0;
1033             break;
1034           case HTTP_HEADER_CONTENT_LENGTH:
1035             r->content_length = strtoul(value, NULL, 10);
1036             if (*value == '+') ++value;
1037             break;
1038           case HTTP_HEADER_TRANSFER_ENCODING:
1039             break;
1040           default:
1041             break;
1042         }
1043 
1044         http_header_response_insert(r, id, key, key_len, value, strlen(value));
1045     }
1046 
1047     /* CGI/1.1 rev 03 - 7.2.1.2 */
1048     /* (proxy requires Status-Line, so never true for proxy)*/
1049     if (!status_is_set && (r->resp_htags & HTTP_HEADER_LOCATION)) {
1050         r->http_status = 302;
1051     }
1052 
1053     return 0;
1054 }
1055 
1056 
1057 handler_t http_response_parse_headers(request_st * const r, http_response_opts * const opts, buffer * const b) {
1058     /**
1059      * possible formats of response headers:
1060      *
1061      * proxy or NPH (non-parsed headers):
1062      *
1063      *   HTTP/1.0 200 Ok\n
1064      *   Header: Value\n
1065      *   \n
1066      *
1067      * CGI:
1068      *
1069      *   Header: Value\n
1070      *   Status: 200\n
1071      *   \n
1072      *
1073      * and different mixes of \n and \r\n combinations
1074      *
1075      * Some users also forget about CGI and just send a response
1076      * and hope we handle it. No headers, no header-content separator
1077      */
1078 
1079     int is_nph = (0 == strncmp(b->ptr, "HTTP/1.", 7)); /*nph (non-parsed hdrs)*/
1080     int is_header_end = 0;
1081     size_t last_eol = 0;
1082     size_t i = 0, header_len = buffer_string_length(b);
1083     const char *bstart;
1084     size_t blen;
1085 
1086     if (b->ptr[0] == '\n' || (b->ptr[0] == '\r' && b->ptr[1] == '\n')) {
1087         /* no HTTP headers */
1088         i = (b->ptr[0] == '\n') ? 0 : 1;
1089         is_header_end = 1;
1090     } else if (is_nph || b->ptr[(i = strcspn(b->ptr, ":\n"))] == ':') {
1091         /* HTTP headers */
1092         ++i;
1093         for (char *c; NULL != (c = strchr(b->ptr+i, '\n')); ++i) {
1094             i = (uintptr_t)(c - b->ptr);
1095             /**
1096              * check if we saw a \n(\r)?\n sequence
1097              */
1098             if (last_eol > 0 &&
1099                 ((i - last_eol == 1) ||
1100                  (i - last_eol == 2 && b->ptr[i - 1] == '\r'))) {
1101                 is_header_end = 1;
1102                 break;
1103             }
1104 
1105             last_eol = i;
1106         }
1107     } else if (i == header_len) { /* (no newline yet; partial header line?) */
1108     } else if (opts->backend == BACKEND_CGI) {
1109         /* no HTTP headers, but a body (special-case for CGI compat) */
1110         /* no colon found; does not appear to be HTTP headers */
1111         if (0 != http_chunk_append_buffer(r, b)) {
1112             return HANDLER_ERROR;
1113         }
1114         r->http_status = 200; /* OK */
1115         r->resp_body_started = 1;
1116         return HANDLER_GO_ON;
1117     } else {
1118         /* invalid response headers */
1119         r->http_status = 502; /* Bad Gateway */
1120         r->handler_module = NULL;
1121         return HANDLER_FINISHED;
1122     }
1123 
1124     if (!is_header_end) {
1125         /*(reuse MAX_HTTP_REQUEST_HEADER as max size
1126          * for response headers from backends)*/
1127         if (header_len > MAX_HTTP_REQUEST_HEADER) {
1128             log_error(r->conf.errh, __FILE__, __LINE__,
1129               "response headers too large for %s", r->uri.path.ptr);
1130             r->http_status = 502; /* Bad Gateway */
1131             r->handler_module = NULL;
1132             return HANDLER_FINISHED;
1133         }
1134         return HANDLER_GO_ON;
1135     }
1136 
1137     /* the body starts after the EOL */
1138     bstart = b->ptr + (i + 1);
1139     blen = header_len - (i + 1);
1140 
1141     /* strip the last \r?\n */
1142     if (i > 0 && (b->ptr[i - 1] == '\r')) {
1143         i--;
1144     }
1145 
1146     buffer_string_set_length(b, i);
1147 
1148     if (opts->backend == BACKEND_PROXY && !is_nph) {
1149         /* invalid response Status-Line from HTTP proxy */
1150         r->http_status = 502; /* Bad Gateway */
1151         r->handler_module = NULL;
1152         return HANDLER_FINISHED;
1153     }
1154 
1155     if (0 != http_response_process_headers(r, opts, b)) {
1156         return HANDLER_ERROR;
1157     }
1158 
1159     r->resp_body_started = 1;
1160 
1161     if (opts->authorizer
1162         && (r->http_status == 0 || r->http_status == 200)) {
1163         return HANDLER_GO_ON;
1164     }
1165 
1166     if (NULL == r->handler_module) {
1167         return HANDLER_FINISHED;
1168     }
1169 
1170     if (opts->local_redir && r->http_status >= 300 && r->http_status < 400){
1171         /*(r->resp_htags & HTTP_HEADER_LOCATION)*/
1172         handler_t rc = http_response_process_local_redir(r, blen);
1173         if (NULL == r->handler_module)
1174             r->resp_body_started = 0;
1175         if (rc != HANDLER_GO_ON) return rc;
1176     }
1177 
1178     if (opts->xsendfile_allow) {
1179         buffer *vb;
1180         /* X-Sendfile2 is deprecated; historical for fastcgi */
1181         if (opts->backend == BACKEND_FASTCGI
1182             && NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-Sendfile2")))) {
1183             http_response_xsendfile2(r, vb, opts->xsendfile_docroot);
1184             /* http_header_response_unset() shortcut for HTTP_HEADER_OTHER */
1185             buffer_clear(vb); /*(do not send to client)*/
1186             if (NULL == r->handler_module)
1187                 r->resp_body_started = 0;
1188             return HANDLER_FINISHED;
1189         } else if (NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-Sendfile")))
1190                    || (opts->backend == BACKEND_FASTCGI /* X-LIGHTTPD-send-file is deprecated; historical for fastcgi */
1191                        && NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-LIGHTTPD-send-file"))))) {
1192             http_response_xsendfile(r, vb, opts->xsendfile_docroot);
1193             /* http_header_response_unset() shortcut for HTTP_HEADER_OTHER */
1194             buffer_clear(vb); /*(do not send to client)*/
1195             if (NULL == r->handler_module)
1196                 r->resp_body_started = 0;
1197             return HANDLER_FINISHED;
1198         }
1199     }
1200 
1201     if (blen > 0) {
1202         if (0 != http_chunk_append_mem(r, bstart, blen)) {
1203             return HANDLER_ERROR;
1204         }
1205     }
1206 
1207     /* (callback for response headers complete) */
1208     return (opts->headers) ? opts->headers(r, opts) : HANDLER_GO_ON;
1209 }
1210 
1211 
1212 handler_t http_response_read(request_st * const r, http_response_opts * const opts, buffer * const b, fdnode * const fdn) {
1213     const int fd = fdn->fd;
1214     while (1) {
1215         ssize_t n;
1216         size_t avail = buffer_string_space(b);
1217         unsigned int toread = 0;
1218 
1219         if (0 == fdevent_ioctl_fionread(fd, opts->fdfmt, (int *)&toread)) {
1220             if (avail < toread) {
1221                 size_t blen = buffer_string_length(b);
1222                 if (toread + blen < 4096)
1223                     toread = 4095 - blen;
1224                 else if (toread > MAX_READ_LIMIT)
1225                     toread = MAX_READ_LIMIT;
1226             }
1227             else if (0 == toread) {
1228               #if 0
1229                 return (fdevent_fdnode_interest(fdn) & FDEVENT_IN)
1230                   ? HANDLER_FINISHED  /* read finished */
1231                   : HANDLER_GO_ON;    /* optimistic read; data not ready */
1232               #else
1233                 if (!(fdevent_fdnode_interest(fdn) & FDEVENT_IN)) {
1234                     if (!(r->conf.stream_response_body
1235                           & FDEVENT_STREAM_RESPONSE_POLLRDHUP))
1236                         return HANDLER_GO_ON;/*optimistic read; data not ready*/
1237                 }
1238                 if (0 == avail) /* let read() below indicate if EOF or EAGAIN */
1239                     toread = 1024;
1240               #endif
1241             }
1242         }
1243         else if (avail < 1024) {
1244             toread = 4095 - avail;
1245         }
1246 
1247         if (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN) {
1248             off_t cqlen = chunkqueue_length(r->write_queue);
1249             if (cqlen + (off_t)toread > 65536 - 4096) {
1250                 if (!r->con->is_writable) {
1251                     /*(defer removal of FDEVENT_IN interest since
1252                      * connection_state_machine() might be able to send data
1253                      * immediately, unless !con->is_writable, where
1254                      * connection_state_machine() might not loop back to call
1255                      * mod_proxy_handle_subrequest())*/
1256                     fdevent_fdnode_event_clr(r->con->srv->ev, fdn, FDEVENT_IN);
1257                 }
1258                 if (cqlen >= 65536-1) return HANDLER_GO_ON;
1259                 toread = 65536 - 1 - (unsigned int)cqlen;
1260                 /* Note: heuristic is fuzzy in that it limits how much to read
1261                  * from backend based on how much is pending to write to client.
1262                  * Modules where data from backend is framed (e.g. FastCGI) may
1263                  * want to limit how much is buffered from backend while waiting
1264                  * for a complete data frame or data packet from backend. */
1265             }
1266         }
1267 
1268         if (avail < toread) {
1269             /*(add avail+toread to reduce allocations when ioctl EOPNOTSUPP)*/
1270             avail = avail ? avail - 1 + toread : toread;
1271             buffer_string_prepare_append(b, avail);
1272         }
1273 
1274         n = read(fd, b->ptr+buffer_string_length(b), avail);
1275 
1276         if (n < 0) {
1277             switch (errno) {
1278               case EAGAIN:
1279              #ifdef EWOULDBLOCK
1280              #if EWOULDBLOCK != EAGAIN
1281               case EWOULDBLOCK:
1282              #endif
1283              #endif
1284               case EINTR:
1285                 return HANDLER_GO_ON;
1286               default:
1287                 log_perror(r->conf.errh, __FILE__, __LINE__,
1288                   "read() %d %d", r->con->fd, fd);
1289                 return HANDLER_ERROR;
1290             }
1291         }
1292 
1293         buffer_commit(b, (size_t)n);
1294 
1295         if (NULL != opts->parse) {
1296             handler_t rc = opts->parse(r, opts, b, (size_t)n);
1297             if (rc != HANDLER_GO_ON) return rc;
1298         } else if (0 == n) {
1299             /* note: no further data is sent to backend after read EOF on socket
1300              * (not checking for half-closed TCP socket)
1301              * (backend should read all data desired prior to closing socket,
1302              *  though might send app-level close data frame, if applicable) */
1303             return HANDLER_FINISHED; /* read finished */
1304         } else if (0 == r->resp_body_started) {
1305             /* split header from body */
1306             handler_t rc = http_response_parse_headers(r, opts, b);
1307             if (rc != HANDLER_GO_ON) return rc;
1308             /* accumulate response in b until headers completed (or error) */
1309             if (r->resp_body_started) buffer_clear(b);
1310         } else {
1311             if (0 != http_chunk_append_buffer(r, b)) {
1312                 /* error writing to tempfile;
1313                  * truncate response or send 500 if nothing sent yet */
1314                 return HANDLER_ERROR;
1315             }
1316             buffer_clear(b);
1317         }
1318 
1319         if (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN) {
1320             if (chunkqueue_length(r->write_queue) > 65536 - 4096) {
1321                 /*(defer removal of FDEVENT_IN interest since
1322                  * connection_state_machine() might be able to send
1323                  * data immediately, unless !con->is_writable, where
1324                  * connection_state_machine() might not loop back to
1325                  * call the subrequest handler)*/
1326                 if (!r->con->is_writable)
1327                     fdevent_fdnode_event_clr(r->con->srv->ev, fdn, FDEVENT_IN);
1328                 break;
1329             }
1330         }
1331 
1332         if ((size_t)n < avail)
1333             break; /* emptied kernel read buffer or partial read */
1334     }
1335 
1336     return HANDLER_GO_ON;
1337 }
1338 
1339 
1340 int http_cgi_headers (request_st * const r, http_cgi_opts * const opts, http_cgi_header_append_cb cb, void *vdata) {
1341 
1342     /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */
1343 
1344     int rc = 0;
1345     const connection * const con = r->con;
1346     server_socket * const srv_sock = con->srv_socket;
1347     buffer * const tb = r->tmp_buf;
1348     const char *s;
1349     size_t n;
1350     char buf[LI_ITOSTRING_LENGTH];
1351     sock_addr *addr;
1352     sock_addr addrbuf;
1353     char b2[INET6_ADDRSTRLEN + 1];
1354 
1355     /* (CONTENT_LENGTH must be first for SCGI) */
1356     if (!opts->authorizer) {
1357         rc |= cb(vdata, CONST_STR_LEN("CONTENT_LENGTH"),
1358                  buf, li_itostrn(buf,sizeof(buf),r->reqbody_length));
1359     }
1360 
1361     if (!buffer_string_is_empty(&r->uri.query)) {
1362         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
1363                         CONST_BUF_LEN(&r->uri.query));
1364     } else {
1365         rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"),
1366                         CONST_STR_LEN(""));
1367     }
1368     if (!buffer_string_is_empty(opts->strip_request_uri)) {
1369         /**
1370          * /app1/index/list
1371          *
1372          * stripping /app1 or /app1/ should lead to
1373          *
1374          * /index/list
1375          *
1376          */
1377         size_t len = buffer_string_length(opts->strip_request_uri);
1378         if ('/' == opts->strip_request_uri->ptr[len-1]) {
1379             --len;
1380         }
1381 
1382         if (buffer_string_length(&r->target_orig) >= len
1383             && 0 == memcmp(r->target_orig.ptr,
1384                            opts->strip_request_uri->ptr, len)
1385             && r->target_orig.ptr[len] == '/') {
1386             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
1387                             r->target_orig.ptr+len,
1388                             buffer_string_length(&r->target_orig)-len);
1389         } else {
1390             rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
1391                             CONST_BUF_LEN(&r->target_orig));
1392         }
1393     } else {
1394         rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"),
1395                         CONST_BUF_LEN(&r->target_orig));
1396     }
1397     if (!buffer_is_equal(&r->target, &r->target_orig)) {
1398         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_URI"),
1399                         CONST_BUF_LEN(&r->target));
1400     }
1401     /* set REDIRECT_STATUS for php compiled with --force-redirect
1402      * (if REDIRECT_STATUS has not already been set by error handler) */
1403     if (0 == r->error_handler_saved_status) {
1404         rc |= cb(vdata, CONST_STR_LEN("REDIRECT_STATUS"),
1405                         CONST_STR_LEN("200"));
1406     }
1407 
1408     /*
1409      * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to
1410      * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html
1411      * (6.1.14, 6.1.6, 6.1.7)
1412      */
1413     if (!opts->authorizer) {
1414         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_NAME"),
1415                         CONST_BUF_LEN(&r->uri.path));
1416         if (!buffer_string_is_empty(&r->pathinfo)) {
1417             rc |= cb(vdata, CONST_STR_LEN("PATH_INFO"),
1418                             CONST_BUF_LEN(&r->pathinfo));
1419             /* PATH_TRANSLATED is only defined if PATH_INFO is set */
1420             if (!buffer_string_is_empty(opts->docroot)) {
1421                 buffer_copy_buffer(tb, opts->docroot);
1422             } else {
1423                 buffer_copy_buffer(tb, &r->physical.basedir);
1424             }
1425             buffer_append_string_buffer(tb, &r->pathinfo);
1426             rc |= cb(vdata, CONST_STR_LEN("PATH_TRANSLATED"),
1427                             CONST_BUF_LEN(tb));
1428         }
1429     }
1430 
1431    /*
1432     * SCRIPT_FILENAME and DOCUMENT_ROOT for php
1433     * The PHP manual http://www.php.net/manual/en/reserved.variables.php
1434     * treatment of PATH_TRANSLATED is different from the one of CGI specs.
1435     * (see php.ini cgi.fix_pathinfo = 1 config parameter)
1436     */
1437 
1438     if (!buffer_string_is_empty(opts->docroot)) {
1439         /* alternate docroot, e.g. for remote FastCGI or SCGI server */
1440         buffer_copy_buffer(tb, opts->docroot);
1441         buffer_append_string_buffer(tb, &r->uri.path);
1442         rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
1443                         CONST_BUF_LEN(tb));
1444         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
1445                         CONST_BUF_LEN(opts->docroot));
1446     } else {
1447         if (opts->break_scriptfilename_for_php) {
1448             /* php.ini config cgi.fix_pathinfo = 1 need a broken SCRIPT_FILENAME
1449              * to find out what PATH_INFO is itself
1450              *
1451              * see src/sapi/cgi_main.c, init_request_info()
1452              */
1453             buffer_copy_buffer(tb, &r->physical.path);
1454             buffer_append_string_buffer(tb, &r->pathinfo);
1455             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
1456                             CONST_BUF_LEN(tb));
1457         } else {
1458             rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"),
1459                             CONST_BUF_LEN(&r->physical.path));
1460         }
1461         rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"),
1462                         CONST_BUF_LEN(&r->physical.basedir));
1463     }
1464 
1465     s = get_http_method_name(r->http_method);
1466     force_assert(s);
1467     rc |= cb(vdata, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s));
1468 
1469     s = get_http_version_name(r->http_version);
1470     force_assert(s);
1471     rc |= cb(vdata, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s));
1472 
1473     rc |= cb(vdata, CONST_STR_LEN("SERVER_SOFTWARE"),
1474                     CONST_BUF_LEN(r->conf.server_tag));
1475 
1476     rc |= cb(vdata, CONST_STR_LEN("GATEWAY_INTERFACE"),
1477                     CONST_STR_LEN("CGI/1.1"));
1478 
1479     rc |= cb(vdata, CONST_STR_LEN("REQUEST_SCHEME"),
1480                     CONST_BUF_LEN(&r->uri.scheme));
1481 
1482     if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"))) {
1483         rc |= cb(vdata, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on"));
1484     }
1485 
1486     addr = &srv_sock->addr;
1487     rc |= cb(vdata, CONST_STR_LEN("SERVER_PORT"),
1488              buf, li_utostrn(buf,sizeof(buf),sock_addr_get_port(addr)));
1489 
1490     switch (addr->plain.sa_family) {
1491     case AF_INET:
1492     case AF_INET6:
1493         if (sock_addr_is_addr_wildcard(addr)) {
1494             socklen_t addrlen = sizeof(addrbuf);
1495             if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){
1496                 addr = &addrbuf;
1497             } else {
1498                 s = "";
1499                 break;
1500             }
1501         }
1502         s = sock_addr_inet_ntop(addr, b2, sizeof(b2)-1);
1503         if (NULL == s) s = "";
1504         break;
1505     default:
1506         s = "";
1507         break;
1508     }
1509     force_assert(s);
1510     rc |= cb(vdata, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s));
1511 
1512     if (!buffer_string_is_empty(r->server_name)) {
1513         size_t len = buffer_string_length(r->server_name);
1514 
1515         if (r->server_name->ptr[0] == '[') {
1516             const char *colon = strstr(r->server_name->ptr, "]:");
1517             if (colon) len = (colon + 1) - r->server_name->ptr;
1518         } else {
1519             const char *colon = strchr(r->server_name->ptr, ':');
1520             if (colon) len = colon - r->server_name->ptr;
1521         }
1522 
1523         rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"),
1524                         r->server_name->ptr, len);
1525     } else {
1526         /* set to be same as SERVER_ADDR (above) */
1527         rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), s, strlen(s));
1528     }
1529 
1530     rc |= cb(vdata, CONST_STR_LEN("REMOTE_ADDR"),
1531                     CONST_BUF_LEN(con->dst_addr_buf));
1532 
1533     rc |= cb(vdata, CONST_STR_LEN("REMOTE_PORT"), buf,
1534              li_utostrn(buf,sizeof(buf),sock_addr_get_port(&con->dst_addr)));
1535 
1536     for (n = 0; n < r->rqst_headers.used; n++) {
1537         data_string *ds = (data_string *)r->rqst_headers.data[n];
1538         if (!buffer_string_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
1539             /* Security: Do not emit HTTP_PROXY in environment.
1540              * Some executables use HTTP_PROXY to configure
1541              * outgoing proxy.  See also https://httpoxy.org/ */
1542             if (buffer_is_equal_caseless_string(&ds->key,
1543                                                 CONST_STR_LEN("Proxy"))) {
1544                 continue;
1545             }
1546             buffer_copy_string_encoded_cgi_varnames(tb,
1547                                                     CONST_BUF_LEN(&ds->key), 1);
1548             rc |= cb(vdata, CONST_BUF_LEN(tb),
1549                             CONST_BUF_LEN(&ds->value));
1550         }
1551     }
1552 
1553     con->srv->request_env(r);
1554 
1555     for (n = 0; n < r->env.used; n++) {
1556         data_string *ds = (data_string *)r->env.data[n];
1557         if (!buffer_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) {
1558             buffer_copy_string_encoded_cgi_varnames(tb,
1559                                                     CONST_BUF_LEN(&ds->key), 0);
1560             rc |= cb(vdata, CONST_BUF_LEN(tb),
1561                             CONST_BUF_LEN(&ds->value));
1562         }
1563     }
1564 
1565     return rc;
1566 }
1567