xref: /lighttpd1.4/src/request.c (revision 9570cc2f)
1 /*
2  * request - HTTP request processing
3  *
4  * Fully-rewritten from original EXCEPT for request_check_hostname()
5  * Copyright(c) 2018 Glenn Strauss gstrauss()gluelogic.com  All rights reserved
6  * License: BSD 3-clause (same as lighttpd)
7  */
8 #include "first.h"
9 
10 #include "request.h"
11 #include "burl.h"
12 #include "http_header.h"
13 #include "http_kv.h"
14 #include "log.h"
15 #include "sock_addr.h"
16 
17 #include <limits.h>
18 #include <stdlib.h>
19 #include <string.h>
20 
21 static int request_check_hostname(buffer * const host) {
22 	enum { DOMAINLABEL, TOPLABEL } stage = TOPLABEL;
23 	size_t i;
24 	int label_len = 0;
25 	size_t host_len, hostport_len;
26 	char *colon;
27 	int is_ip = -1; /* -1 don't know yet, 0 no, 1 yes */
28 	int level = 0;
29 
30 	/*
31 	 *       hostport      = host [ ":" port ]
32 	 *       host          = hostname | IPv4address | IPv6address
33 	 *       hostname      = *( domainlabel "." ) toplabel [ "." ]
34 	 *       domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
35 	 *       toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
36 	 *       IPv4address   = 1*digit "." 1*digit "." 1*digit "." 1*digit
37 	 *       IPv6address   = "[" ... "]"
38 	 *       port          = *digit
39 	 */
40 
41 	/* IPv6 address */
42 	if (host->ptr[0] == '[') {
43 		char *c = host->ptr + 1;
44 		int colon_cnt = 0;
45 
46 		/* check the address inside [...] */
47 		for (; *c && *c != ']'; c++) {
48 			if (*c == ':') {
49 				if (++colon_cnt > 7) {
50 					return -1;
51 				}
52 			} else if (!light_isxdigit(*c) && '.' != *c) {
53 				return -1;
54 			}
55 		}
56 
57 		/* missing ] */
58 		if (!*c) {
59 			return -1;
60 		}
61 
62 		/* check port */
63 		if (*(c+1) == ':') {
64 			for (c += 2; *c; c++) {
65 				if (!light_isdigit(*c)) {
66 					return -1;
67 				}
68 			}
69 		}
70 		else if ('\0' != *(c+1)) {
71 			/* only a port is allowed to follow [...] */
72 			return -1;
73 		}
74 		return 0;
75 	}
76 
77 	hostport_len = host_len = buffer_string_length(host);
78 
79 	if (NULL != (colon = memchr(host->ptr, ':', host_len))) {
80 		char *c = colon + 1;
81 
82 		/* check portnumber */
83 		for (; *c; c++) {
84 			if (!light_isdigit(*c)) return -1;
85 		}
86 
87 		/* remove the port from the host-len */
88 		host_len = colon - host->ptr;
89 	}
90 
91 	/* Host is empty */
92 	if (host_len == 0) return -1;
93 
94 	/* if the hostname ends in a "." strip it */
95 	if (host->ptr[host_len-1] == '.') {
96 		/* shift port info one left */
97 		if (NULL != colon) memmove(colon-1, colon, hostport_len - host_len);
98 		buffer_string_set_length(host, --hostport_len);
99 		if (--host_len == 0) return -1;
100 	}
101 
102 
103 	/* scan from the right and skip the \0 */
104 	for (i = host_len; i-- > 0; ) {
105 		const char c = host->ptr[i];
106 
107 		switch (stage) {
108 		case TOPLABEL:
109 			if (c == '.') {
110 				/* only switch stage, if this is not the last character */
111 				if (i != host_len - 1) {
112 					if (label_len == 0) {
113 						return -1;
114 					}
115 
116 					/* check the first character at right of the dot */
117 					if (is_ip == 0) {
118 						if (!light_isalnum(host->ptr[i+1])) {
119 							return -1;
120 						}
121 					} else if (!light_isdigit(host->ptr[i+1])) {
122 						is_ip = 0;
123 					} else if ('-' == host->ptr[i+1]) {
124 						return -1;
125 					} else {
126 						/* just digits */
127 						is_ip = 1;
128 					}
129 
130 					stage = DOMAINLABEL;
131 
132 					label_len = 0;
133 					level++;
134 				} else if (i == 0) {
135 					/* just a dot and nothing else is evil */
136 					return -1;
137 				}
138 			} else if (i == 0) {
139 				/* the first character of the hostname */
140 				if (!light_isalnum(c)) {
141 					return -1;
142 				}
143 				label_len++;
144 			} else {
145 				if (c != '-' && !light_isalnum(c)) {
146 					return -1;
147 				}
148 				if (is_ip == -1) {
149 					if (!light_isdigit(c)) is_ip = 0;
150 				}
151 				label_len++;
152 			}
153 
154 			break;
155 		case DOMAINLABEL:
156 			if (is_ip == 1) {
157 				if (c == '.') {
158 					if (label_len == 0) {
159 						return -1;
160 					}
161 
162 					label_len = 0;
163 					level++;
164 				} else if (!light_isdigit(c)) {
165 					return -1;
166 				} else {
167 					label_len++;
168 				}
169 			} else {
170 				if (c == '.') {
171 					if (label_len == 0) {
172 						return -1;
173 					}
174 
175 					/* c is either - or alphanum here */
176 					if ('-' == host->ptr[i+1]) {
177 						return -1;
178 					}
179 
180 					label_len = 0;
181 					level++;
182 				} else if (i == 0) {
183 					if (!light_isalnum(c)) {
184 						return -1;
185 					}
186 					label_len++;
187 				} else {
188 					if (c != '-' && !light_isalnum(c)) {
189 						return -1;
190 					}
191 					label_len++;
192 				}
193 			}
194 
195 			break;
196 		}
197 	}
198 
199 	/* a IP has to consist of 4 parts */
200 	if (is_ip == 1 && level != 3) {
201 		return -1;
202 	}
203 
204 	if (label_len == 0) {
205 		return -1;
206 	}
207 
208 	return 0;
209 }
210 
211 int http_request_host_normalize(buffer * const b, const int scheme_port) {
212     /*
213      * check for and canonicalize numeric IP address and portnum (optional)
214      * (IP address may be followed by ":portnum" (optional))
215      * - IPv6: "[...]"
216      * - IPv4: "x.x.x.x"
217      * - IPv4: 12345678   (32-bit decimal number)
218      * - IPv4: 012345678  (32-bit octal number)
219      * - IPv4: 0x12345678 (32-bit hex number)
220      *
221      * allow any chars (except ':' and '\0' and stray '[' or ']')
222      *   (other code may check chars more strictly or more pedantically)
223      * ':'  delimits (optional) port at end of string
224      * "[]" wraps IPv6 address literal
225      * '\0' should have been rejected earlier were it present
226      *
227      * any chars includes, but is not limited to:
228      * - allow '-' any where, even at beginning of word
229      *     (security caution: might be confused for cmd flag if passed to shell)
230      * - allow all-digit TLDs
231      *     (might be mistaken for IPv4 addr by inet_aton()
232      *      unless non-digits appear in subdomain)
233      */
234 
235     /* Note: not using getaddrinfo() since it does not support "[]" around IPv6
236      * and is not as lenient as inet_aton() and inet_addr() for IPv4 strings.
237      * Not using inet_pton() (when available) on IPv4 for similar reasons. */
238 
239     const char * const p = b->ptr;
240     const size_t blen = buffer_string_length(b);
241     long port = 0;
242 
243     if (*p != '[') {
244         char * const colon = (char *)memchr(p, ':', blen);
245         if (colon) {
246             if (*p == ':') return -1; /*(empty host then port, or naked IPv6)*/
247             if (colon[1] != '\0') {
248                 char *e;
249                 port = strtol(colon+1, &e, 0); /*(allow decimal, octal, hex)*/
250                 if (0 < port && port <= USHRT_MAX && *e == '\0') {
251                     /* valid port */
252                 } else {
253                     return -1;
254                 }
255             } /*(else ignore stray colon at string end)*/
256             buffer_string_set_length(b, (size_t)(colon - p)); /*(remove port str)*/
257         }
258 
259         if (light_isdigit(*p)) do {
260             /* (IPv4 address literal or domain starting w/ digit (e.g. 3com))*/
261             /* (check one-element cache of normalized IPv4 address string) */
262             static struct { char s[INET_ADDRSTRLEN]; size_t n; } laddr;
263             size_t n = colon ? (size_t)(colon - p) : blen;
264             sock_addr addr;
265             if (n == laddr.n && 0 == memcmp(p, laddr.s, n)) break;
266             if (1 == sock_addr_inet_pton(&addr, p, AF_INET, 0)) {
267                 sock_addr_inet_ntop_copy_buffer(b, &addr);
268                 n = buffer_string_length(b);
269                 if (n < sizeof(laddr.s)) memcpy(laddr.s, b->ptr, (laddr.n = n));
270             }
271         } while (0);
272     } else do { /* IPv6 addr */
273       #if defined(HAVE_IPV6) && defined(HAVE_INET_PTON)
274 
275         /* (check one-element cache of normalized IPv4 address string) */
276         static struct { char s[INET6_ADDRSTRLEN]; size_t n; } laddr;
277         sock_addr addr;
278         char *bracket = b->ptr+blen-1;
279         char *percent = strchr(b->ptr+1, '%');
280         size_t len;
281         int rc;
282         char buf[INET6_ADDRSTRLEN+16]; /*(+16 for potential %interface name)*/
283         if (blen <= 2) return -1; /*(invalid "[]")*/
284         if (*bracket != ']') {
285             bracket = (char *)memchr(b->ptr+1, ']', blen-1);
286             if (NULL == bracket || bracket[1] != ':'  || bracket - b->ptr == 1){
287                return -1;
288             }
289             if (bracket[2] != '\0') { /*(ignore stray colon at string end)*/
290                 char *e;
291                 port = strtol(bracket+2, &e, 0); /*(allow decimal, octal, hex)*/
292                 if (0 < port && port <= USHRT_MAX && *e == '\0') {
293                     /* valid port */
294                 } else {
295                     return -1;
296                 }
297             }
298         }
299 
300         len = (size_t)((percent ? percent : bracket) - (b->ptr+1));
301         if (laddr.n == len && 0 == memcmp(laddr.s, b->ptr+1, len)) {
302             /* truncate after ']' and re-add normalized port, if needed */
303             buffer_string_set_length(b, (size_t)(bracket - b->ptr + 1));
304             break;
305         }
306 
307         *bracket = '\0';/*(terminate IPv6 string)*/
308         if (percent) *percent = '\0'; /*(remove %interface from address)*/
309         rc = sock_addr_inet_pton(&addr, b->ptr+1, AF_INET6, 0);
310         if (percent) *percent = '%'; /*(restore %interface)*/
311         *bracket = ']'; /*(restore bracket)*/
312         if (1 != rc) return -1;
313 
314         sock_addr_inet_ntop(&addr, buf, sizeof(buf));
315         len = strlen(buf);
316         if (percent) {
317             if (percent > bracket) return -1;
318             if (len + (size_t)(bracket - percent) >= sizeof(buf)) return -1;
319             if (len < sizeof(laddr.s)) memcpy(laddr.s, buf, (laddr.n = len));
320             memcpy(buf+len, percent, (size_t)(bracket - percent));
321             len += (size_t)(bracket - percent);
322         }
323         buffer_string_set_length(b, 1); /* truncate after '[' */
324         buffer_append_string_len(b, buf, len);
325         buffer_append_string_len(b, CONST_STR_LEN("]"));
326 
327       #else
328 
329         return -1;
330 
331       #endif
332     } while (0);
333 
334     if (0 != port && port != scheme_port) {
335         buffer_append_string_len(b, CONST_STR_LEN(":"));
336         buffer_append_int(b, (int)port);
337     }
338 
339     return 0;
340 }
341 
342 int http_request_host_policy (buffer * const b, const unsigned int http_parseopts, const int scheme_port) {
343     return (((http_parseopts & HTTP_PARSEOPT_HOST_STRICT)
344              && 0 != request_check_hostname(b))
345             || ((http_parseopts & HTTP_PARSEOPT_HOST_NORMALIZE)
346                 && 0 != http_request_host_normalize(b, scheme_port)));
347 }
348 
349 __attribute_pure__ /*(could be even more strict and use __attribute_const__)*/
350 static int request_uri_is_valid_char(const unsigned char c) {
351 	return (c > 32 && c != 127 && c != 255);
352 }
353 
354 __attribute_cold__
355 __attribute_noinline__
356 static int http_request_header_line_invalid(request_st * const restrict r, const int status, const char * const restrict msg) {
357     if (r->conf.log_request_header_on_error) {
358         if (msg) log_error(r->conf.errh, __FILE__, __LINE__, "%s", msg);
359     }
360     return status;
361 }
362 
363 __attribute_cold__
364 __attribute_noinline__
365 static int http_request_header_char_invalid(request_st * const restrict r, const char ch, const char * const restrict msg) {
366     if (r->conf.log_request_header_on_error) {
367         if ((unsigned char)ch > 32 && ch != 127) {
368             log_error(r->conf.errh, __FILE__, __LINE__, "%s ('%c')", msg, ch);
369         }
370         else {
371             log_error(r->conf.errh, __FILE__, __LINE__, "%s (0x%x)", msg, ch);
372         }
373     }
374     return 400;
375 }
376 
377 /* add header to list of headers
378  * certain headers are also parsed
379  * might drop a header if deemed unnecessary/broken
380  *
381  * returns 0 on success, HTTP status on error
382  */
383 static int http_request_parse_single_header(request_st * const restrict r, const enum http_header_e id, const char * const restrict k, const size_t klen, const char * const restrict v, const size_t vlen) {
384     buffer **saveb = NULL;
385 
386     /*
387      * Note: k might not be '\0'-terminated
388      * Note: v is not '\0'-terminated, and ends with whitespace
389      *   (one of '\r' '\n' ' ' '\t')
390      */
391 
392     switch (id) {
393       /*case HTTP_HEADER_OTHER:*/
394       default:
395         break;
396       case HTTP_HEADER_HOST:
397         if (!(r->rqst_htags & HTTP_HEADER_HOST)) {
398             saveb = &r->http_host;
399             if (vlen >= 1024) { /*(expecting < 256)*/
400                 return http_request_header_line_invalid(r, 400, "uri-authority too long -> 400");
401             }
402         }
403         else if (NULL != r->http_host
404                  && buffer_is_equal_string(r->http_host, v, vlen)) {
405             /* ignore all Host: headers if match authority in request line */
406             return 0; /* ignore header */
407         }
408         else {
409             return http_request_header_line_invalid(r, 400, "duplicate Host header -> 400");
410         }
411         break;
412       case HTTP_HEADER_CONNECTION:
413         /* "Connection: close" is common case if header is present */
414         if ((vlen == 5 && buffer_eq_icase_ssn(v, CONST_STR_LEN("close")))
415             || http_header_str_contains_token(v,vlen,CONST_STR_LEN("close"))) {
416             r->keep_alive = 0;
417             break;
418         }
419         if (http_header_str_contains_token(v,vlen,CONST_STR_LEN("keep-alive"))){
420             r->keep_alive = 1;
421             break;
422         }
423         break;
424       case HTTP_HEADER_CONTENT_TYPE:
425         if (r->rqst_htags & HTTP_HEADER_CONTENT_TYPE) {
426             return http_request_header_line_invalid(r, 400, "duplicate Content-Type header -> 400");
427         }
428         break;
429       case HTTP_HEADER_IF_NONE_MATCH:
430         /* if dup, only the first one will survive */
431         if (r->rqst_htags & HTTP_HEADER_IF_NONE_MATCH) {
432             return 0; /* ignore header */
433         }
434         break;
435       case HTTP_HEADER_CONTENT_LENGTH:
436         if (!(r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH)) {
437             /*(trailing whitespace was removed from vlen)*/
438             char *err;
439             off_t clen = strtoll(v, &err, 10);
440             if (clen >= 0 && err == v+vlen && light_isdigit(v[0])) {
441                 /* (set only if not set to -1 by Transfer-Encoding: chunked) */
442                 if (0 == r->reqbody_length) r->reqbody_length = clen;
443             }
444             else {
445                 return http_request_header_line_invalid(r, 400, "invalid Content-Length header -> 400");
446             }
447         }
448         else {
449             return http_request_header_line_invalid(r, 400, "duplicate Content-Length header -> 400");
450         }
451         break;
452       case HTTP_HEADER_IF_MODIFIED_SINCE:
453         if (r->rqst_htags & HTTP_HEADER_IF_MODIFIED_SINCE) {
454             /* Proxies sometimes send dup headers
455              * if they are the same we ignore the second
456              * if not, we raise an error */
457             const buffer *vb =
458               http_header_request_get(r, HTTP_HEADER_IF_MODIFIED_SINCE,
459                                       CONST_STR_LEN("If-Modified-Since"));
460             if (vb && buffer_is_equal_caseless_string(vb, v, vlen)) {
461                 /* ignore it if they are the same */
462                 return 0; /* ignore header */
463             }
464             else {
465                 return http_request_header_line_invalid(r, 400, "duplicate If-Modified-Since header -> 400");
466             }
467         }
468         break;
469       case HTTP_HEADER_TRANSFER_ENCODING:
470         if (HTTP_VERSION_1_0 == r->http_version) {
471             return http_request_header_line_invalid(r, 400, "HTTP/1.0 with Transfer-Encoding (bad HTTP/1.0 proxy?) -> 400");
472         }
473 
474         if (!buffer_eq_icase_ss(v, vlen, CONST_STR_LEN("chunked"))) {
475             /* Transfer-Encoding might contain additional encodings,
476              * which are not currently supported by lighttpd */
477             return http_request_header_line_invalid(r, 501, NULL); /* Not Implemented */
478         }
479         r->reqbody_length = -1;
480 
481         /* Transfer-Encoding is a hop-by-hop header,
482          * which must not be blindly forwarded to backends */
483         return 0; /* skip header */
484     }
485 
486     http_header_request_append(r, id, k, klen, v, vlen);
487 
488     if (saveb) {
489         *saveb = http_header_request_get(r, id, k, klen);
490     }
491 
492     return 0;
493 }
494 
495 __attribute_cold__
496 static int http_request_parse_proto_loose(request_st * const restrict r, const char * const restrict ptr, const size_t len, const unsigned int http_parseopts) {
497     const char * proto = memchr(ptr, ' ', len);
498     if (NULL == proto)
499         return http_request_header_line_invalid(r, 400, "incomplete request line -> 400");
500     proto = memchr(proto+1, ' ', len - (proto+1 - ptr));
501     if (NULL == proto)
502         return http_request_header_line_invalid(r, 400, "incomplete request line -> 400");
503     ++proto;
504 
505     if (proto[0]=='H' && proto[1]=='T' && proto[2]=='T' && proto[3]=='P' && proto[4] == '/') {
506         if (proto[5] == '1' && proto[6] == '.' && (proto[7] == '1' || proto[7] == '0')) {
507             /* length already checked before calling this routine */
508             /* (len != (size_t)(proto - ptr + 8)) */
509             if (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT) /*(http_header_strict)*/
510                 return http_request_header_line_invalid(r, 400, "incomplete request line -> 400");
511             r->http_version = (proto[7] == '1') ? HTTP_VERSION_1_1 : HTTP_VERSION_1_0;
512         }
513         else
514             return http_request_header_line_invalid(r, 505, "unknown HTTP version -> 505");
515     }
516     else
517         return http_request_header_line_invalid(r, 400, "unknown protocol -> 400");
518 
519     /* keep-alive default: HTTP/1.1 -> true; HTTP/1.0 -> false */
520     r->keep_alive = (HTTP_VERSION_1_0 != r->http_version);
521 
522     return 0;
523 }
524 
525 __attribute_cold__
526 static const char * http_request_parse_reqline_uri(request_st * const restrict r, const char * const restrict uri, const size_t len, const unsigned int http_parseopts) {
527     const char *nuri;
528     if ((len > 7 && buffer_eq_icase_ssn(uri, "http://", 7)
529         && NULL != (nuri = memchr(uri + 7, '/', len-7)))
530        ||
531        (len > 8 && buffer_eq_icase_ssn(uri, "https://", 8)
532         && NULL != (nuri = memchr(uri + 8, '/', len-8)))) {
533         const char * const host = uri + (uri[4] == ':' ? 7 : 8);
534         const size_t hostlen = nuri - host;
535         if (0 == hostlen || hostlen >= 1024) { /*(expecting < 256)*/
536             http_request_header_line_invalid(r, 400, "uri-authority empty or too long -> 400");
537             return NULL;
538         }
539         /* Insert as host header */
540         http_header_request_set(r, HTTP_HEADER_HOST, CONST_STR_LEN("Host"), host, hostlen);
541         r->http_host = http_header_request_get(r, HTTP_HEADER_HOST, CONST_STR_LEN("Host"));
542         return nuri;
543     } else if (!(http_parseopts & HTTP_PARSEOPT_HEADER_STRICT) /*(!http_header_strict)*/
544            || (HTTP_METHOD_CONNECT == r->http_method && (uri[0] == ':' || light_isdigit(uri[0])))
545            || (HTTP_METHOD_OPTIONS == r->http_method && uri[0] == '*' && 1 == len)) {
546         /* (permitted) */
547         return uri;
548     } else {
549         http_request_header_line_invalid(r, 400, "request-URI parse error -> 400");
550         return NULL;
551     }
552 }
553 
554 static int http_request_parse_reqline(request_st * const restrict r, const char * const restrict ptr, const unsigned short * const restrict hoff, const unsigned int http_parseopts) {
555     size_t len = hoff[2];
556 
557     /* parse the first line of the request
558      * <method> <uri> <protocol>\r\n
559      * */
560     if (len < 13) /* minimum len with (!http_header_strict): "x x HTTP/1.0\n" */
561         return http_request_header_line_invalid(r, 400, "invalid request line (too short) -> 400");
562     if (ptr[len-2] == '\r')
563         len-=2;
564     else if (!(http_parseopts & HTTP_PARSEOPT_HEADER_STRICT)) /*(!http_header_strict)*/
565         len-=1;
566     else
567         return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400");
568 
569     /*
570      * RFC7230:
571      *   HTTP-version  = HTTP-name "/" DIGIT "." DIGIT
572      *   HTTP-name     = %x48.54.54.50 ; "HTTP", case-sensitive
573      */
574 
575     /* protocol is expected to be " HTTP/1.1" or " HTTP/1.0" at end of line */
576     union proto_un {
577       char c[8];
578       uint64_t u;
579     };
580     static const union proto_un http_1_1 = {{'H','T','T','P','/','1','.','1'}};
581     static const union proto_un http_1_0 = {{'H','T','T','P','/','1','.','0'}};
582     const char *p = ptr + len - 8;
583     union proto_un proto8;
584     proto8.c[0]=p[0]; proto8.c[1]=p[1]; proto8.c[2]=p[2]; proto8.c[3]=p[3];
585     proto8.c[4]=p[4]; proto8.c[5]=p[5]; proto8.c[6]=p[6]; proto8.c[7]=p[7];
586     if (p[-1] == ' ' && http_1_1.u == proto8.u) {
587         r->http_version = HTTP_VERSION_1_1;
588         r->keep_alive = 1; /* keep-alive default: HTTP/1.1 -> true */
589     }
590     else if (p[-1] == ' ' && http_1_0.u == proto8.u) {
591         r->http_version = HTTP_VERSION_1_0;
592         r->keep_alive = 0; /* keep-alive default: HTTP/1.0 -> false */
593     }
594     else {
595         int status = http_request_parse_proto_loose(r,ptr,len,http_parseopts);
596         if (0 != status) return status;
597         /*(space char must exist if http_request_parse_proto_loose() succeeds)*/
598         for (p = ptr + len - 9; p[-1] != ' '; --p) ;
599     }
600 
601     /* method is expected to be a short string in the general case */
602     size_t i = 0;
603     while (ptr[i] != ' ') ++i;
604   #if 0 /*(space must exist if protocol was parsed successfully)*/
605     while (i < len && ptr[i] != ' ') ++i;
606     if (ptr[i] != ' ')
607         return http_request_header_line_invalid(r, 400, "incomplete request line -> 400");
608   #endif
609 
610     r->http_method = get_http_method_key(ptr, i);
611     if (HTTP_METHOD_UNSET == r->http_method)
612         return http_request_header_line_invalid(r, 501, "unknown http-method -> 501");
613 
614     const char *uri = ptr + i + 1;
615 
616     if (uri == p)
617         return http_request_header_line_invalid(r, 400, "no uri specified -> 400");
618     len = (size_t)(p - uri - 1);
619 
620     if (*uri != '/') { /* (common case: (*uri == '/')) */
621         uri = http_request_parse_reqline_uri(r, uri, len, http_parseopts);
622         if (NULL == uri) return 400;
623         len = (size_t)(p - uri - 1);
624     }
625 
626     if (0 == len)
627         return http_request_header_line_invalid(r, 400, "no uri specified -> 400");
628 
629     /* check uri for invalid characters */
630     if (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT) { /* http_header_strict */
631         if ((http_parseopts & HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT)) {
632             /* URI will be checked in http_response_prepare() */
633         }
634         else {
635             for (i = 0; i < len; ++i) {
636                 if (!request_uri_is_valid_char(uri[i]))
637                     return http_request_header_char_invalid(r, uri[i], "invalid character in URI -> 400");
638             }
639         }
640     }
641     else {
642         /* check entire set of request headers for '\0' */
643         if (NULL != memchr(ptr, '\0', hoff[hoff[0]]))
644             return http_request_header_char_invalid(r, '\0', "invalid character in header -> 400");
645     }
646 
647     buffer_copy_string_len(&r->target, uri, len);
648     buffer_copy_string_len(&r->target_orig, uri, len);
649     return 0;
650 }
651 
652 int http_request_parse_target(request_st * const r, int scheme_port) {
653     /* URI is parsed into components at start of request and may
654      * also be re-parsed upon HANDLER_COMEBACK during the request
655      * r->target is expected to be a "/url-part?query-part"
656      *   (and *not* a fully-qualified URI starting https://...)
657      * r->uri.authority is expected to be parsed elsewhere into r->http_host
658      */
659 
660     /**
661      * prepare strings
662      *
663      * - uri.path
664      * - uri.query
665      *
666      */
667 
668     /**
669      * Name according to RFC 2396
670      *
671      * - scheme
672      * - authority
673      * - path
674      * - query
675      *
676      * (scheme)://(authority)(path)?(query)#fragment
677      *
678      */
679 
680     /* take initial scheme value from connection-level state
681      * (request r->uri.scheme can be overwritten for later,
682      *  for example by mod_extforward or mod_magnet) */
683     if (scheme_port == 443)
684         buffer_copy_string_len(&r->uri.scheme, CONST_STR_LEN("https"));
685     else
686         buffer_copy_string_len(&r->uri.scheme, CONST_STR_LEN("http"));
687 
688     buffer * const target = &r->target;
689     if (r->http_method == HTTP_METHOD_CONNECT
690         || (r->http_method == HTTP_METHOD_OPTIONS
691             && target->ptr[0] == '*'
692             && target->ptr[1] == '\0')) {
693         /* CONNECT ... (or) OPTIONS * ... */
694         buffer_copy_buffer(&r->uri.path, target);
695         buffer_clear(&r->uri.query);
696         return 0;
697     }
698 
699     char *qstr;
700     if (r->conf.http_parseopts & HTTP_PARSEOPT_URL_NORMALIZE) {
701         /*uint32_t len = (uint32_t)buffer_string_length(target);*/
702         int qs = burl_normalize(target, r->tmp_buf, r->conf.http_parseopts);
703         if (-2 == qs) {
704             log_error(r->conf.errh, __FILE__, __LINE__,
705               "invalid character in URI -> 400 %s",
706               target->ptr);
707             return 400; /* Bad Request */
708         }
709         qstr = (-1 == qs) ? NULL : target->ptr+qs;
710       #if 0  /* future: might enable here, or below for all requests */
711         /* (Note: total header size not recalculated on HANDLER_COMEBACK
712          *  even if other request headers changed during processing)
713          * (If (0 != r->loops_per_request), then the generated
714          *  request is too large.  Should a different error be returned?) */
715         r->rqst_header_len -= len;
716         len = buffer_string_length(target);
717         r->rqst_header_len += len;
718         if (len > MAX_HTTP_REQUEST_URI) {
719             return 414; /* 414 Request-URI Too Long */
720         }
721         if (r->rqst_header_len > MAX_HTTP_REQUEST_HEADER) {
722             log_error(r->conf.errh, __FILE__, __LINE__,
723               "request header fields too large: %u -> 431",
724               r->rqst_header_len);
725             return 431; /* Request Header Fields Too Large */
726         }
727       #endif
728     }
729     else {
730         size_t rlen = buffer_string_length(target);
731         qstr = memchr(target->ptr, '#', rlen);/* discard fragment */
732         if (qstr) {
733             rlen = (size_t)(qstr - target->ptr);
734             buffer_string_set_length(target, rlen);
735         }
736         qstr = memchr(target->ptr, '?', rlen);
737     }
738 
739     /** extract query string from target */
740     const char * const pstr = target->ptr;
741     const uint32_t rlen = buffer_string_length(target);
742     uint32_t plen;
743     if (NULL != qstr) {
744         plen = (uint32_t)(qstr - pstr);
745         buffer_copy_string_len(&r->uri.query, qstr + 1, rlen - plen - 1);
746     }
747     else {
748         plen = rlen;
749         buffer_clear(&r->uri.query);
750     }
751     buffer_copy_string_len(&r->uri.path, pstr, plen);
752 
753     /* decode url to path
754      *
755      * - decode url-encodings  (e.g. %20 -> ' ')
756      * - remove path-modifiers (e.g. /../)
757      */
758 
759     buffer_urldecode_path(&r->uri.path);
760     buffer_path_simplify(&r->uri.path, &r->uri.path);
761     if (r->uri.path.ptr[0] != '/') {
762         log_error(r->conf.errh, __FILE__, __LINE__,
763           "uri-path does not begin with '/': %s -> 400", r->uri.path.ptr);
764         return 400; /* Bad Request */
765     }
766 
767     return 0;
768 }
769 
770 __attribute_cold__
771 __attribute_noinline__
772 static int http_request_parse_header_other(request_st * const restrict r, const char * const restrict k, const int klen, const unsigned int http_header_strict) {
773     for (int i = 0; i < klen; ++i) {
774         if (light_isalpha(k[i]) || k[i] == '-') continue; /*(common cases)*/
775         /**
776          * 1*<any CHAR except CTLs or separators>
777          * CTLs == 0-31 + 127, CHAR = 7-bit ascii (0..127)
778          *
779          */
780         switch(k[i]) {
781         case ' ':
782         case '\t':
783             return http_request_header_line_invalid(r, 400, "WS character in key -> 400");
784         case '(':
785         case ')':
786         case '<':
787         case '>':
788         case '@':
789         case ',':
790         case ';':
791         case '\\':
792         case '\"':
793         case '/':
794         case '[':
795         case ']':
796         case '?':
797         case '=':
798         case '{':
799         case '}':
800             return http_request_header_char_invalid(r, k[i], "invalid character in header key -> 400");
801         default:
802             if (http_header_strict ? (k[i] < 32 || ((unsigned char *)k)[i] >= 127) : k[i] == '\0')
803                 return http_request_header_char_invalid(r, k[i], "invalid character in header key -> 400");
804             break; /* ok */
805         }
806     }
807     return 0;
808 }
809 
810 static int http_request_parse_headers(request_st * const restrict r, char * const restrict ptr, const unsigned short * const restrict hoff, const unsigned int http_parseopts) {
811     const unsigned int http_header_strict = (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT);
812 
813   #if 0 /*(not checked here; will later result in invalid label for HTTP header)*/
814     int i = hoff[2];
815 
816     if (ptr[i] == ' ' || ptr[i] == '\t') {
817         return http_request_header_line_invalid(r, 400, "WS at the start of first line -> 400");
818     }
819   #endif
820 
821     for (int i = 2; i < hoff[0]; ++i) {
822         const char *k = ptr + hoff[i];
823         /* one past last line hoff[hoff[0]] is to final "\r\n" */
824         char *end = ptr + hoff[i+1];
825 
826         const char *colon = memchr(k, ':', end - k);
827         if (NULL == colon)
828             return http_request_header_line_invalid(r, 400, "invalid header missing ':' -> 400");
829 
830         const char *v = colon + 1;
831 
832         /* RFC7230 Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing
833          * 3.2.4.  Field Parsing
834          * [...]
835          * No whitespace is allowed between the header field-name and colon.  In
836          * the past, differences in the handling of such whitespace have led to
837          * security vulnerabilities in request routing and response handling.  A
838          * server MUST reject any received request message that contains
839          * whitespace between a header field-name and colon with a response code
840          * of 400 (Bad Request).  A proxy MUST remove any such whitespace from a
841          * response message before forwarding the message downstream.
842          */
843         /* (line k[-1] is always preceded by a '\n',
844          *  including first header after request-line,
845          *  so no need to check colon != k) */
846         if (colon[-1] == ' ' || colon[-1] == '\t') {
847             if (http_header_strict) {
848                 return http_request_header_line_invalid(r, 400, "invalid whitespace between field-name and colon -> 400");
849             }
850             else {
851                 /* remove trailing whitespace from key(if !http_header_strict)*/
852                 do { --colon; } while (colon[-1] == ' ' || colon[-1] == '\t');
853             }
854         }
855 
856         const int klen = (int)(colon - k);
857         if (0 == klen)
858             return http_request_header_line_invalid(r, 400, "invalid header key -> 400");
859         const enum http_header_e id = http_header_hkey_get(k, klen);
860 
861         if (id == HTTP_HEADER_OTHER) {
862             for (int j = 0; j < klen; ++j) {
863                 if (light_isalpha(k[j]) || k[j] == '-') continue; /*(common cases)*/
864                 if (0 != http_request_parse_header_other(r, k+j, klen-j, http_header_strict))
865                     return 400;
866                 break;
867             }
868         }
869 
870         /* remove leading whitespace from value */
871         while (*v == ' ' || *v == '\t') ++v;
872 
873         for (; i+1 <= hoff[0]; ++i) {
874             end = ptr + hoff[i+1];
875             if (end[0] != ' ' && end[0] != '\t') break;
876 
877             /* line folding */
878           #ifdef __COVERITY__
879             force_assert(end - k >= 2);
880           #endif
881             if (end[-2] == '\r')
882                 end[-2] = ' ';
883             else if (http_header_strict)
884                 return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400");
885             end[-1] = ' ';
886         }
887       #ifdef __COVERITY__
888         /*(buf holding k has non-zero request-line, so end[-2] valid)*/
889         force_assert(end >= k + 2);
890       #endif
891         if (end[-2] == '\r')
892             --end;
893         else if (http_header_strict)
894             return http_request_header_line_invalid(r, 400, "missing CR before LF in header -> 400");
895         /* remove trailing whitespace from value (+ remove '\r\n') */
896         /* (line k[-1] is always preceded by a '\n',
897          *  including first header after request-line,
898          *  so no need to check (end != k)) */
899         do { --end; } while (end[-1] == ' ' || end[-1] == '\t');
900 
901         const int vlen = (int)(end - v);
902         /* empty header-fields are not allowed by HTTP-RFC, we just ignore them */
903         if (vlen <= 0) continue; /* ignore header */
904 
905         if (http_header_strict) {
906             for (int j = 0; j < vlen; ++j) {
907                 if ((((unsigned char *)v)[j] < 32 && v[j] != '\t') || v[j]==127)
908                     return http_request_header_char_invalid(r, v[j], "invalid character in header -> 400");
909             }
910         } /* else URI already checked in http_request_parse_reqline() for any '\0' */
911 
912         int status = http_request_parse_single_header(r, id, k, (size_t)klen, v, (size_t)vlen);
913         if (0 != status) return status;
914     }
915 
916     return 0;
917 }
918 
919 int http_request_parse(request_st * const restrict r, char * const restrict hdrs, const unsigned short * const restrict hoff, const int scheme_port) {
920     /*
921      * Request: "^(GET|POST|HEAD|...) ([^ ]+(\\?[^ ]+|)) (HTTP/1\\.[01])$"
922      * Header : "^([-a-zA-Z]+): (.+)$"
923      * End    : "^$"
924      */
925 
926     int status;
927     const unsigned int http_parseopts = r->conf.http_parseopts;
928 
929     status = http_request_parse_reqline(r, hdrs, hoff, http_parseopts);
930     if (0 != status) return status;
931 
932     status = http_request_parse_target(r, scheme_port);
933     if (0 != status) return status;
934 
935     status = http_request_parse_headers(r, hdrs, hoff, http_parseopts);
936     if (0 != status) return status;
937 
938     /*(r->http_host might not be set until after parsing request headers)*/
939     buffer_copy_buffer(&r->uri.authority, r->http_host);/*(copy even if empty)*/
940     buffer_to_lower(&r->uri.authority);
941 
942     /* post-processing */
943 
944     /* check hostname field if it is set */
945     if (r->http_host) {
946         if (0 != http_request_host_policy(r->http_host,
947                                           http_parseopts, scheme_port))
948             return http_request_header_line_invalid(r, 400, "Invalid Hostname -> 400");
949     }
950     else {
951         if (r->http_version == HTTP_VERSION_1_1)
952             return http_request_header_line_invalid(r, 400, "HTTP/1.1 but Host missing -> 400");
953     }
954 
955     if (0 == r->reqbody_length) {
956         /* POST requires Content-Length (or Transfer-Encoding)
957          * (-1 == r->reqbody_length when Transfer-Encoding: chunked)*/
958         if (HTTP_METHOD_POST == r->http_method
959             && !(r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH)) {
960             return http_request_header_line_invalid(r, 411, "POST-request, but content-length missing -> 411");
961         }
962     }
963     else {
964         /* (-1 == r->reqbody_length when Transfer-Encoding: chunked)*/
965         if (-1 == r->reqbody_length
966             && (r->rqst_htags & HTTP_HEADER_CONTENT_LENGTH)) {
967             /* RFC7230 Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing
968              * 3.3.3.  Message Body Length
969              * [...]
970              * If a message is received with both a Transfer-Encoding and a
971              * Content-Length header field, the Transfer-Encoding overrides the
972              * Content-Length.  Such a message might indicate an attempt to
973              * perform request smuggling (Section 9.5) or response splitting
974              * (Section 9.4) and ought to be handled as an error.  A sender MUST
975              * remove the received Content-Length field prior to forwarding such
976              * a message downstream.
977              */
978             const unsigned int http_header_strict =
979               (http_parseopts & HTTP_PARSEOPT_HEADER_STRICT);
980             if (http_header_strict) {
981                 return http_request_header_line_invalid(r, 400, "invalid Transfer-Encoding + Content-Length -> 400");
982             }
983             else {
984                 /* ignore Content-Length */
985                 http_header_request_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length"));
986             }
987         }
988         if (http_method_get_or_head(r->http_method)
989             && !(http_parseopts & HTTP_PARSEOPT_METHOD_GET_BODY)) {
990             return http_request_header_line_invalid(r, 400, "GET/HEAD with content-length -> 400");
991         }
992     }
993 
994     return 0;
995 }
996