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