Bug Summary

File:lib/lwan-request.c
Warning:line 1747, column 13
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name lwan-request.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -fno-plt -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/home/buildbot/lwan-worker/clang-analyze/build/src/lib -resource-dir /usr/lib/clang/14.0.6 -include /home/buildbot/lwan-worker/clang-analyze/build/lwan-build-config.h -D _FILE_OFFSET_BITS=64 -D _TIME_BITS=64 -I /home/buildbot/lwan-worker/clang-analyze/build/src/lib/missing -I /usr/include/luajit-2.1 -I /usr/include/valgrind -I /home/buildbot/lwan-worker/clang-analyze/build/src/lib -I /home/buildbot/lwan-worker/clang-analyze/build -internal-isystem /usr/lib/clang/14.0.6/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/12.2.0/../../../../x86_64-pc-linux-gnu/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-unused-parameter -Wno-override-init -Wno-free-nonheap-object -std=gnu11 -fdebug-compilation-dir=/home/buildbot/lwan-worker/clang-analyze/build/src/lib -ferror-limit 19 -stack-protector 2 -fgnuc-version=4.2.1 -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/buildbot/lwan-worker/clang-analyze/CLANG/2023-01-05-025445-1097561-1 -x c /home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c
1/*
2 * lwan - web server
3 * Copyright (c) 2012-2014 L. A. F. Pereira <l@tia.mat.br>
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 */
19
20#define _GNU_SOURCE
21#include <arpa/inet.h>
22#include <assert.h>
23#include <ctype.h>
24#include <errno(*__errno_location ()).h>
25#include <fcntl.h>
26#include <inttypes.h>
27#include <limits.h>
28#include <stddef.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32#include <strings.h>
33#include <sys/mman.h>
34#include <sys/socket.h>
35#include <sys/stat.h>
36#include <sys/types.h>
37#include <sys/vfs.h>
38#include <unistd.h>
39
40#include "lwan-private.h"
41
42#include "base64.h"
43#include "list.h"
44#include "lwan-config.h"
45#include "lwan-http-authorize.h"
46#include "lwan-io-wrappers.h"
47#include "sha1.h"
48
49#define HEADER_VALUE_SEPARATOR_LEN(sizeof(": ") - 1) (sizeof(": ") - 1)
50#define HEADER_TERMINATOR_LEN(sizeof("\r\n") - 1) (sizeof("\r\n") - 1)
51#define MIN_REQUEST_SIZE(sizeof("GET / HTTP/1.1\r\n\r\n") - 1) (sizeof("GET / HTTP/1.1\r\n\r\n") - 1)
52
53enum lwan_read_finalizer {
54 FINALIZER_DONE,
55 FINALIZER_TRY_AGAIN,
56 FINALIZER_TIMEOUT,
57};
58
59struct proxy_header_v2 {
60 uint8_t sig[12];
61 uint8_t cmd_ver;
62 uint8_t fam;
63 uint16_t len;
64 union {
65 struct {
66 in_addr_t src_addr;
67 in_addr_t dst_addr;
68 uint16_t src_port;
69 uint16_t dst_port;
70 } ip4;
71 struct {
72 struct in6_addr src_addr;
73 struct in6_addr dst_addr;
74 uint16_t src_port;
75 uint16_t dst_port;
76 } ip6;
77 } addr;
78};
79
80static char *ignore_leading_whitespace(char *buffer) __attribute__((pure));
81
82
83static bool_Bool
84parse_ascii_port(char *port, unsigned short *out)
85{
86 unsigned long parsed;
87 char *end_ptr;
88
89 errno(*__errno_location ()) = 0;
90 parsed = strtoul(port, &end_ptr, 10);
91
92 if (UNLIKELY(errno != 0)__builtin_expect((((*__errno_location ()) != 0)), (0)))
93 return false0;
94
95 if (UNLIKELY(*end_ptr != '\0')__builtin_expect(((*end_ptr != '\0')), (0)))
96 return false0;
97
98 if (UNLIKELY((unsigned long)(unsigned short)parsed != parsed)__builtin_expect((((unsigned long)(unsigned short)parsed != parsed
)), (0))
)
99 return false0;
100
101 *out = htons((unsigned short)parsed);
102 return true1;
103}
104
105static char *
106strsep_char(char *strp, const char *end, char delim)
107{
108 char *ptr;
109
110 if (UNLIKELY(!strp)__builtin_expect(((!strp)), (0)))
111 return NULL((void*)0);
112
113 if (UNLIKELY(strp > end)__builtin_expect(((strp > end)), (0)))
114 return NULL((void*)0);
115
116 ptr = strchr(strp, delim);
117 if (UNLIKELY(!ptr)__builtin_expect(((!ptr)), (0)))
118 return NULL((void*)0);
119
120 *ptr = '\0';
121 return ptr + 1;
122}
123
124static char *
125parse_proxy_protocol_v1(struct lwan_request *request, char *buffer)
126{
127 static const size_t line_size = 108;
128 char *end, *protocol, *src_addr, *dst_addr, *src_port, *dst_port;
129 unsigned int size;
130 struct lwan_proxy *const proxy = request->proxy;
131
132 end = memchr(buffer, '\r', line_size);
133 if (UNLIKELY(!end || end[1] != '\n')__builtin_expect(((!end || end[1] != '\n')), (0)))
134 return NULL((void*)0);
135 *end = '\0';
136 size = (unsigned int) (end + 2 - buffer);
137
138 protocol = buffer + sizeof("PROXY ") - 1;
139 src_addr = strsep_char(protocol, end, ' ');
140 dst_addr = strsep_char(src_addr, end, ' ');
141 src_port = strsep_char(dst_addr, end, ' ');
142 dst_port = strsep_char(src_port, end, ' ');
143
144 if (UNLIKELY(!dst_port)__builtin_expect(((!dst_port)), (0)))
145 return NULL((void*)0);
146
147 STRING_SWITCH(protocol)switch (string_as_uint32(protocol)) {
148 case STR4_INT('T', 'C', 'P', '4')((uint32_t)(('T') | ('C') << 8 | ('P') << 16 | ('4'
) << 24))
: {
149 struct sockaddr_in *from = &proxy->from.ipv4;
150 struct sockaddr_in *to = &proxy->to.ipv4;
151
152 from->sin_family = to->sin_family = AF_INET2;
153
154 if (UNLIKELY(inet_pton(AF_INET, src_addr, &from->sin_addr) <= 0)__builtin_expect(((inet_pton(2, src_addr, &from->sin_addr
) <= 0)), (0))
)
155 return NULL((void*)0);
156 if (UNLIKELY(inet_pton(AF_INET, dst_addr, &to->sin_addr) <= 0)__builtin_expect(((inet_pton(2, dst_addr, &to->sin_addr
) <= 0)), (0))
)
157 return NULL((void*)0);
158 if (UNLIKELY(!parse_ascii_port(src_port, &from->sin_port))__builtin_expect(((!parse_ascii_port(src_port, &from->
sin_port))), (0))
)
159 return NULL((void*)0);
160 if (UNLIKELY(!parse_ascii_port(dst_port, &to->sin_port))__builtin_expect(((!parse_ascii_port(dst_port, &to->sin_port
))), (0))
)
161 return NULL((void*)0);
162
163 break;
164 }
165 case STR4_INT('T', 'C', 'P', '6')((uint32_t)(('T') | ('C') << 8 | ('P') << 16 | ('6'
) << 24))
: {
166 struct sockaddr_in6 *from = &proxy->from.ipv6;
167 struct sockaddr_in6 *to = &proxy->to.ipv6;
168
169 from->sin6_family = to->sin6_family = AF_INET610;
170
171 if (UNLIKELY(inet_pton(AF_INET6, src_addr, &from->sin6_addr) <= 0)__builtin_expect(((inet_pton(10, src_addr, &from->sin6_addr
) <= 0)), (0))
)
172 return NULL((void*)0);
173 if (UNLIKELY(inet_pton(AF_INET6, dst_addr, &to->sin6_addr) <= 0)__builtin_expect(((inet_pton(10, dst_addr, &to->sin6_addr
) <= 0)), (0))
)
174 return NULL((void*)0);
175 if (UNLIKELY(!parse_ascii_port(src_port, &from->sin6_port))__builtin_expect(((!parse_ascii_port(src_port, &from->
sin6_port))), (0))
)
176 return NULL((void*)0);
177 if (UNLIKELY(!parse_ascii_port(dst_port, &to->sin6_port))__builtin_expect(((!parse_ascii_port(dst_port, &to->sin6_port
))), (0))
)
178 return NULL((void*)0);
179
180 break;
181 }
182 default:
183 return NULL((void*)0);
184 }
185
186 request->flags |= REQUEST_PROXIED;
187 return buffer + size;
188}
189
190static char *parse_proxy_protocol_v2(struct lwan_request *request, char *buffer)
191{
192 struct proxy_header_v2 *hdr = (struct proxy_header_v2 *)buffer;
193 struct lwan_request_parser_helper *helper = request->helper;
194 const unsigned int proto_signature_length = 16;
195 unsigned int size;
196 struct lwan_proxy *const proxy = request->proxy;
197
198 enum { LOCAL = 0x20, PROXY = 0x21, TCP4 = 0x11, TCP6 = 0x21 };
199
200 size = proto_signature_length + (unsigned int)ntohs(hdr->len);
201 if (UNLIKELY(size > (unsigned int)sizeof(*hdr))__builtin_expect(((size > (unsigned int)sizeof(*hdr))), (0
))
)
202 return NULL((void*)0);
203 if (UNLIKELY(size >= helper->buffer->len)__builtin_expect(((size >= helper->buffer->len)), (0
))
)
204 return NULL((void*)0);
205
206 if (LIKELY(hdr->cmd_ver == PROXY)__builtin_expect((!!(hdr->cmd_ver == PROXY)), (1))) {
207 if (hdr->fam == TCP4) {
208 struct sockaddr_in *from = &proxy->from.ipv4;
209 struct sockaddr_in *to = &proxy->to.ipv4;
210
211 to->sin_family = from->sin_family = AF_INET2;
212
213 from->sin_addr.s_addr = hdr->addr.ip4.src_addr;
214 from->sin_port = hdr->addr.ip4.src_port;
215
216 to->sin_addr.s_addr = hdr->addr.ip4.dst_addr;
217 to->sin_port = hdr->addr.ip4.dst_port;
218 } else if (hdr->fam == TCP6) {
219 struct sockaddr_in6 *from = &proxy->from.ipv6;
220 struct sockaddr_in6 *to = &proxy->to.ipv6;
221
222 from->sin6_family = to->sin6_family = AF_INET610;
223
224 from->sin6_addr = hdr->addr.ip6.src_addr;
225 from->sin6_port = hdr->addr.ip6.src_port;
226
227 to->sin6_addr = hdr->addr.ip6.dst_addr;
228 to->sin6_port = hdr->addr.ip6.dst_port;
229 } else {
230 return NULL((void*)0);
231 }
232 } else if (hdr->cmd_ver == LOCAL) {
233 struct sockaddr_in *from = &proxy->from.ipv4;
234 struct sockaddr_in *to = &proxy->to.ipv4;
235
236 from->sin_family = to->sin_family = AF_UNSPEC0;
237 } else {
238 return NULL((void*)0);
239 }
240
241 request->flags |= REQUEST_PROXIED;
242 return buffer + size;
243}
244
245#if !defined(LWAN_HAVE_BUILTIN_EXPECT_PROBABILITY)
246#define __builtin_expect_with_probability(value1, value2, probability) \
247 __builtin_expect(value1, value2)
248#endif
249
250static ALWAYS_INLINEinline __attribute__((always_inline)) char *identify_http_method(struct lwan_request *request,
251 char *buffer)
252{
253 const uint32_t first_four = string_as_uint32(buffer);
254
255#define GENERATE_IF(upper, lower, mask, constant, probability) \
256 if (__builtin_expect_with_probability(first_four == (constant), 1, \
257 probability)) { \
258 request->flags |= (mask); \
259 return buffer + sizeof(#upper); \
260 }
261
262 FOR_EACH_REQUEST_METHOD(GENERATE_IF)GENERATE_IF(GET, get, (1 << 0), (((uint32_t)(('G') | ('E'
) << 8 | ('T') << 16 | (' ') << 24))), 0.6)
GENERATE_IF(POST, post, (1 << 3 | 1 << 1 | 1 <<
0), (((uint32_t)(('P') | ('O') << 8 | ('S') << 16
| ('T') << 24))), 0.2) GENERATE_IF(HEAD, head, (1 <<
1), (((uint32_t)(('H') | ('E') << 8 | ('A') << 16
| ('D') << 24))), 0.2) GENERATE_IF(OPTIONS, options, (
1 << 2), (((uint32_t)(('O') | ('P') << 8 | ('T') <<
16 | ('I') << 24))), 0.1) GENERATE_IF(DELETE, delete, (
1 << 1 | 1 << 2), (((uint32_t)(('D') | ('E') <<
8 | ('L') << 16 | ('E') << 24))), 0.1) GENERATE_IF
(PUT, put, (1 << 3 | 1 << 2 | 1 << 0), (((uint32_t
)(('P') | ('U') << 8 | ('T') << 16 | (' ') <<
24))), 0.1)
263
264#undef GENERATE_IF
265
266 return NULL((void*)0);
267}
268
269__attribute__((nonnull(1))) static ssize_t url_decode(char *str)
270{
271 static const unsigned char tbl1[256] = {
272 [0 ... 255] = 255, ['0'] = 0 << 4, ['1'] = 1 << 4, ['2'] = 2 << 4,
273 ['3'] = 3 << 4, ['4'] = 4 << 4, ['5'] = 5 << 4, ['6'] = 6 << 4,
274 ['7'] = 7 << 4, ['8'] = 8 << 4, ['9'] = 9 << 4, ['a'] = 10 << 4,
275 ['b'] = 11 << 4, ['c'] = 12 << 4, ['d'] = 13 << 4, ['e'] = 14 << 4,
276 ['f'] = 15 << 4, ['A'] = 10 << 4, ['B'] = 11 << 4, ['C'] = 12 << 4,
277 ['D'] = 13 << 4, ['E'] = 14 << 4, ['F'] = 15 << 4,
278 };
279 static const char tbl2[256] = {
280 [0 ... 255] = -1, ['0'] = 0, ['1'] = 1, ['2'] = 2, ['3'] = 3,
281 ['4'] = 4, ['5'] = 5, ['6'] = 6, ['7'] = 7, ['8'] = 8,
282 ['9'] = 9, ['a'] = 10, ['b'] = 11, ['c'] = 12, ['d'] = 13,
283 ['e'] = 14, ['f'] = 15, ['A'] = 10, ['B'] = 11, ['C'] = 12,
284 ['D'] = 13, ['E'] = 14, ['F'] = 15,
285 };
286
287 const char *inptr = str;
288 char *outptr = str;
289
290 for (char *ch = strchr(str, '+'); ch; ch = strchr(ch + 1, '+'))
291 *ch = ' ';
292
293 for (const char *pct = strchr(inptr, '%'); pct; pct = strchr(inptr, '%')) {
294 const ptrdiff_t diff = pct - inptr;
295 if (diff)
296 outptr = stpncpy(outptr, inptr, (size_t)diff);
297
298 const char first = (char)tbl1[(unsigned char)pct[1]];
299 const char second = tbl2[(unsigned char)pct[2]];
300 const char decoded = first | second;
301 if (UNLIKELY(decoded <= 0)__builtin_expect(((decoded <= 0)), (0))) {
302 /* This shouldn't happen in normal circumstances, but if %00 is
303 * found in the encoded string, bail here. */
304 if (decoded == '\0')
305 return -1;
306
307 /* OR-ing both lookups will yield a negative number if either
308 * encoded character is not a valid hex digit; check it here so
309 * that other valid-but-negative bytes (e.g. 0xff) are still
310 * written to outptr. */
311 if (first == -1) {
312 /* tbl1 is shifted so a valid nibble might be negative;
313 * check for all the bits here instead. */
314 return -1;
315 }
316 if (second < 0) {
317 /* tbl2 isn't shifted so we can check for the sign bit only. */
318 return -1;
319 }
320 }
321
322 *outptr++ = decoded;
323 inptr = pct + 3;
324 }
325
326 if (inptr > outptr) {
327 outptr = stpcpy(outptr, inptr);
328 return (ssize_t)(outptr - str);
329 }
330
331 return (ssize_t)strlen(str);
332}
333
334static int key_value_compare(const void *a, const void *b)
335{
336 return strcmp(((const struct lwan_key_value *)a)->key,
337 ((const struct lwan_key_value *)b)->key);
338}
339
340static void
341reset_key_value_array(void *data)
342{
343 struct lwan_key_value_array *array = data;
344
345 lwan_key_value_array_reset(array);
346}
347
348static void parse_key_values(struct lwan_request *request,
349 struct lwan_value *helper_value,
350 struct lwan_key_value_array *array,
351 ssize_t (*decode_value)(char *value),
352 const char separator)
353{
354 struct lwan_key_value *kv;
355 char *ptr = helper_value->value;
356 const char *end = helper_value->value + helper_value->len;
357 coro_deferred reset_defer;
358
359 if (!helper_value->len)
360 return;
361
362 lwan_key_value_array_init(array);
363 reset_defer = coro_defer(request->conn->coro, reset_key_value_array, array);
364
365 do {
366 char *key, *value;
367
368 while (*ptr == ' ' || *ptr == separator)
369 ptr++;
370 if (UNLIKELY(*ptr == '\0')__builtin_expect(((*ptr == '\0')), (0)))
371 break;
372
373 key = ptr;
374 ptr = strsep_char(key, end, separator);
375
376 value = strsep_char(key, end, '=');
377 if (UNLIKELY(!value)__builtin_expect(((!value)), (0))) {
378 value = "";
379 } else if (UNLIKELY(decode_value(value) < 0)__builtin_expect(((decode_value(value) < 0)), (0))) {
380 /* Disallow values that failed decoding, but allow empty values */
381 goto error;
382 }
383
384 if (UNLIKELY(decode_value(key) <= 0)__builtin_expect(((decode_value(key) <= 0)), (0))) {
385 /* Disallow keys that failed decoding, or empty keys */
386 goto error;
387 }
388
389 kv = lwan_key_value_array_append(array);
390 if (UNLIKELY(!kv)__builtin_expect(((!kv)), (0)))
391 goto error;
392
393 kv->key = key;
394 kv->value = value;
395 } while (ptr);
396
397 lwan_key_value_array_sort(array, key_value_compare);
398
399 return;
400
401error:
402 coro_defer_fire_and_disarm(request->conn->coro, reset_defer);
403}
404
405static ssize_t
406identity_decode(char *input __attribute__((unused)))
407{
408 return 1;
409}
410
411static void parse_cookies(struct lwan_request *request)
412{
413 const char *cookies = lwan_request_get_header(request, "Cookie");
414
415 if (!cookies)
416 return;
417
418 struct lwan_value header = {.value = (char *)cookies,
419 .len = strlen(cookies)};
420 parse_key_values(request, &header, &request->helper->cookies,
421 identity_decode, ';');
422}
423
424static void parse_query_string(struct lwan_request *request)
425{
426 struct lwan_request_parser_helper *helper = request->helper;
427
428 parse_key_values(request, &helper->query_string, &helper->query_params,
429 url_decode, '&');
430}
431
432static void parse_form_data(struct lwan_request *request)
433{
434 struct lwan_request_parser_helper *helper = request->helper;
435 static const char content_type[] = "application/x-www-form-urlencoded";
436
437 if (helper->content_type.len < sizeof(content_type) - 1)
438 return;
439 if (UNLIKELY(strncmp(helper->content_type.value, content_type,__builtin_expect(((strncmp(helper->content_type.value, content_type
, sizeof(content_type) - 1))), (0))
440 sizeof(content_type) - 1))__builtin_expect(((strncmp(helper->content_type.value, content_type
, sizeof(content_type) - 1))), (0))
)
441 return;
442
443 parse_key_values(request, &helper->body_data, &helper->post_params,
444 url_decode, '&');
445}
446
447static void find_query_string(struct lwan_request *request, const char *space)
448{
449 struct lwan_request_parser_helper *helper = request->helper;
450
451 char *query_string = memchr(request->url.value, '?', request->url.len);
452 if (query_string) {
453 *query_string = '\0';
454 helper->query_string.value = query_string + 1;
455 helper->query_string.len = (size_t)(space - query_string - 1);
456 request->url.len -= helper->query_string.len + 1;
457 request->flags |= REQUEST_HAS_QUERY_STRING;
458 }
459}
460
461static char *
462identify_http_path(struct lwan_request *request, char *buffer)
463{
464 struct lwan_request_parser_helper *helper = request->helper;
465 static const size_t minimal_request_line_len = sizeof("/ HTTP/1.0") - 1;
466 char *space, *end_of_line;
467 ptrdiff_t end_len;
468
469 if (UNLIKELY(*buffer != '/')__builtin_expect(((*buffer != '/')), (0)))
470 return NULL((void*)0);
471
472 end_len = buffer - helper->buffer->value;
473 if (UNLIKELY((size_t)end_len >= helper->buffer->len)__builtin_expect((((size_t)end_len >= helper->buffer->
len)), (0))
)
474 return NULL((void*)0);
475
476 end_of_line = memchr(buffer, '\r', helper->buffer->len - (size_t)end_len);
477 if (UNLIKELY(!end_of_line)__builtin_expect(((!end_of_line)), (0)))
478 return NULL((void*)0);
479 if (UNLIKELY((size_t)(end_of_line - buffer) < minimal_request_line_len)__builtin_expect((((size_t)(end_of_line - buffer) < minimal_request_line_len
)), (0))
)
480 return NULL((void*)0);
481 *end_of_line = '\0';
482
483 space = end_of_line - sizeof("HTTP/X.X");
484
485 request->url.value = buffer;
486 request->url.len = (size_t)(space - buffer);
487 find_query_string(request, space);
488 request->original_url = request->url;
489
490 *space++ = '\0';
491
492 STRING_SWITCH_LARGE(space)switch (string_as_uint64(space)) {
493 case STR8_INT('H','T','T','P','/','1','.','0')((uint64_t)((uint32_t)(('H') | ('T') << 8 | ('T') <<
16 | ('P') << 24)) | (uint64_t)((uint32_t)(('/') | ('1'
) << 8 | ('.') << 16 | ('0') << 24)) <<
32)
:
494 request->flags |= REQUEST_IS_HTTP_1_0;
495 break;
496 case STR8_INT('H','T','T','P','/','1','.','1')((uint64_t)((uint32_t)(('H') | ('T') << 8 | ('T') <<
16 | ('P') << 24)) | (uint64_t)((uint32_t)(('/') | ('1'
) << 8 | ('.') << 16 | ('1') << 24)) <<
32)
:
497 break;
498 default:
499 return NULL((void*)0);
500 }
501
502 return end_of_line + 1;
503}
504
505__attribute__((noinline)) static void set_header_value(
506 struct lwan_value *header, char *end, char *p, size_t header_len)
507{
508 p += header_len;
509
510 if (LIKELY(string_as_uint16(p) == STR2_INT(':', ' '))__builtin_expect((!!(string_as_uint16(p) == ((uint16_t)((':')
| (' ') << 8)))), (1))
) {
511 *end = '\0';
512 char *value = p + sizeof(": ") - 1;
513
514 header->value = value;
515 header->len = (size_t)(end - value);
516 }
517}
518
519#define HEADER_LENGTH(hdr) \
520 ({ \
521 if (UNLIKELY(end - sizeof(hdr) + 1 < p)__builtin_expect(((end - sizeof(hdr) + 1 < p)), (0))) \
522 continue; \
523 sizeof(hdr) - 1; \
524 })
525
526#define SET_HEADER_VALUE(dest, hdr) \
527 do { \
528 const size_t header_len = HEADER_LENGTH(hdr); \
529 set_header_value(&(helper->dest), end, p, header_len); \
530 } while (0)
531
532static ALWAYS_INLINEinline __attribute__((always_inline)) ssize_t find_headers(char **header_start,
533 struct lwan_value *request_buffer,
534 char **next_request)
535{
536 char *buffer = request_buffer->value;
537 char *buffer_end = buffer + request_buffer->len;
538 ssize_t n_headers = 0;
539 char *next_header;
540
541 for (char *next_chr = buffer + 1;;) {
542 next_header = memchr(next_chr, '\r', (size_t)(buffer_end - next_chr));
543
544 if (UNLIKELY(!next_header)__builtin_expect(((!next_header)), (0)))
545 return -1;
546
547 if (next_chr == next_header) {
548 if (buffer_end - next_chr >= (ptrdiff_t)HEADER_TERMINATOR_LEN(sizeof("\r\n") - 1)) {
549 STRING_SWITCH_SMALL (next_header)switch (string_as_uint16(next_header)) {
550 case STR2_INT('\r', '\n')((uint16_t)(('\r') | ('\n') << 8)):
551 *next_request = next_header + HEADER_TERMINATOR_LEN(sizeof("\r\n") - 1);
552 }
553 }
554 goto out;
555 }
556
557 /* Is there at least a space for a minimal (H)eader and a (V)alue? */
558 if (LIKELY(next_header - next_chr >= (ptrdiff_t)(sizeof("H: V") - 1))__builtin_expect((!!(next_header - next_chr >= (ptrdiff_t)
(sizeof("H: V") - 1))), (1))
) {
559 header_start[n_headers++] = next_chr;
560
561 if (UNLIKELY(n_headers >= N_HEADER_START - 1)__builtin_expect(((n_headers >= 64 - 1)), (0)))
562 return -1;
563 } else {
564 /* Better to abort early if there's no space. */
565 return -1;
566 }
567
568 next_chr = next_header + HEADER_TERMINATOR_LEN(sizeof("\r\n") - 1);
569 if (UNLIKELY(next_chr >= buffer_end)__builtin_expect(((next_chr >= buffer_end)), (0)))
570 return -1;
571 }
572
573out:
574 header_start[n_headers] = next_header;
575 return n_headers;
576}
577
578static bool_Bool parse_headers(struct lwan_request_parser_helper *helper,
579 char *buffer)
580{
581 char **header_start = helper->header_start;
582 ssize_t n_headers = 0;
583
584 /* FIXME: is there a better way to do this? */
585 struct lwan_value header_start_buffer = {
586 .value = buffer,
587 .len = helper->buffer->len - (size_t)(buffer - helper->buffer->value)
588 };
589 n_headers = find_headers(header_start, &header_start_buffer,
590 &helper->next_request);
591 if (UNLIKELY(n_headers < 0)__builtin_expect(((n_headers < 0)), (0)))
592 return false0;
593
594 for (ssize_t i = 0; i < n_headers; i++) {
595 char *p = header_start[i];
596 char *end = header_start[i + 1] - HEADER_TERMINATOR_LEN(sizeof("\r\n") - 1);
597
598 STRING_SWITCH_L (p)switch (((string_as_uint32(p)) | (uint32_t)0x20202020)) {
599 case STR4_INT_L('A', 'c', 'c', 'e')((((uint32_t)(('A') | ('c') << 8 | ('c') << 16 | (
'e') << 24))) | (uint32_t)0x20202020)
:
600 p += HEADER_LENGTH("Accept");
601
602 STRING_SWITCH_L (p)switch (((string_as_uint32(p)) | (uint32_t)0x20202020)) {
603 case STR4_INT_L('-', 'E', 'n', 'c')((((uint32_t)(('-') | ('E') << 8 | ('n') << 16 | (
'c') << 24))) | (uint32_t)0x20202020)
:
604 SET_HEADER_VALUE(accept_encoding, "-Encoding");
605 break;
606 }
607 break;
608 case STR4_INT_L('C', 'o', 'n', 'n')((((uint32_t)(('C') | ('o') << 8 | ('n') << 16 | (
'n') << 24))) | (uint32_t)0x20202020)
:
609 SET_HEADER_VALUE(connection, "Connection");
610 break;
611 case STR4_INT_L('C', 'o', 'n', 't')((((uint32_t)(('C') | ('o') << 8 | ('n') << 16 | (
't') << 24))) | (uint32_t)0x20202020)
:
612 p += HEADER_LENGTH("Content");
613
614 STRING_SWITCH_L (p)switch (((string_as_uint32(p)) | (uint32_t)0x20202020)) {
615 case STR4_INT_L('-', 'T', 'y', 'p')((((uint32_t)(('-') | ('T') << 8 | ('y') << 16 | (
'p') << 24))) | (uint32_t)0x20202020)
:
616 SET_HEADER_VALUE(content_type, "-Type");
617 break;
618 case STR4_INT_L('-', 'L', 'e', 'n')((((uint32_t)(('-') | ('L') << 8 | ('e') << 16 | (
'n') << 24))) | (uint32_t)0x20202020)
:
619 SET_HEADER_VALUE(content_length, "-Length");
620 break;
621 }
622 break;
623 case STR4_INT_L('I', 'f', '-', 'M')((((uint32_t)(('I') | ('f') << 8 | ('-') << 16 | (
'M') << 24))) | (uint32_t)0x20202020)
:
624 SET_HEADER_VALUE(if_modified_since.raw, "If-Modified-Since");
625 break;
626 case STR4_INT_L('H', 'o', 's', 't')((((uint32_t)(('H') | ('o') << 8 | ('s') << 16 | (
't') << 24))) | (uint32_t)0x20202020)
:
627 SET_HEADER_VALUE(host, "Host");
628 break;
629 case STR4_INT_L('R', 'a', 'n', 'g')((((uint32_t)(('R') | ('a') << 8 | ('n') << 16 | (
'g') << 24))) | (uint32_t)0x20202020)
:
630 SET_HEADER_VALUE(range.raw, "Range");
631 break;
632 }
633 }
634
635 helper->n_header_start = (size_t)n_headers;
636 return true1;
637}
638#undef HEADER_LENGTH
639#undef SET_HEADER_VALUE
640
641ssize_t lwan_find_headers(char **header_start, struct lwan_value *buffer,
642 char **next_request)
643{
644 return find_headers(header_start, buffer, next_request);
645}
646
647static void parse_if_modified_since(struct lwan_request_parser_helper *helper)
648{
649 static const size_t header_len =
650 sizeof("Wed, 17 Apr 2019 13:59:27 GMT") - 1;
651 time_t parsed;
652
653 if (UNLIKELY(helper->if_modified_since.raw.len != header_len)__builtin_expect(((helper->if_modified_since.raw.len != header_len
)), (0))
)
654 return;
655
656 if (UNLIKELY(lwan_parse_rfc_time(helper->if_modified_since.raw.value,__builtin_expect(((lwan_parse_rfc_time(helper->if_modified_since
.raw.value, &parsed) < 0)), (0))
657 &parsed) < 0)__builtin_expect(((lwan_parse_rfc_time(helper->if_modified_since
.raw.value, &parsed) < 0)), (0))
)
658 return;
659
660 helper->if_modified_since.parsed = parsed;
661}
662
663static bool_Bool
664parse_off_without_sign(const char *ptr, char **end, off_t *off)
665{
666 unsigned long long val;
667
668 static_assert_Static_assert(sizeof(val) >= sizeof(off_t),
669 "off_t fits in a long long");
670
671 errno(*__errno_location ()) = 0;
672
673 val = strtoull(ptr, end, 10);
674 if (UNLIKELY(val == 0 && *end == ptr)__builtin_expect(((val == 0 && *end == ptr)), (0)))
675 return false0;
676 if (UNLIKELY(errno != 0)__builtin_expect((((*__errno_location ()) != 0)), (0)))
677 return false0;
678 if (UNLIKELY(val > OFF_MAX)__builtin_expect(((val > 9223372036854775807LL)), (0)))
679 return false0;
680
681 *off = (off_t)val;
682 return true1;
683}
684
685static void
686parse_range(struct lwan_request_parser_helper *helper)
687{
688 if (UNLIKELY(helper->range.raw.len <= (sizeof("bytes=") - 1))__builtin_expect(((helper->range.raw.len <= (sizeof("bytes="
) - 1))), (0))
)
689 return;
690
691 char *range = helper->range.raw.value;
692 if (UNLIKELY(strncmp(range, "bytes=", sizeof("bytes=") - 1))__builtin_expect(((strncmp(range, "bytes=", sizeof("bytes=") -
1))), (0))
)
693 return;
694
695 range += sizeof("bytes=") - 1;
696
697 off_t from, to;
698 char *end;
699
700 if (*range == '-') {
701 from = 0;
702
703 if (!parse_off_without_sign(range + 1, &end, &to))
704 goto invalid_range;
705 if (*end != '\0')
706 goto invalid_range;
707 } else if (lwan_char_isdigit(*range)) {
708 if (!parse_off_without_sign(range, &end, &from))
709 goto invalid_range;
710 if (*end != '-')
711 goto invalid_range;
712
713 range = end + 1;
714 if (*range == '\0') {
715 to = -1;
716 } else {
717 if (!parse_off_without_sign(range, &end, &to))
718 goto invalid_range;
719 if (*end != '\0')
720 goto invalid_range;
721 }
722 } else {
723invalid_range:
724 to = from = -1;
725 }
726
727 helper->range.from = from;
728 helper->range.to = to;
729}
730
731static void
732parse_accept_encoding(struct lwan_request *request)
733{
734 struct lwan_request_parser_helper *helper = request->helper;
735
736 if (!helper->accept_encoding.len)
737 return;
738
739 for (const char *p = helper->accept_encoding.value; *p; p++) {
740 STRING_SWITCH(p)switch (string_as_uint32(p)) {
741 case STR4_INT('d','e','f','l')((uint32_t)(('d') | ('e') << 8 | ('f') << 16 | ('l'
) << 24))
:
742 case STR4_INT(' ','d','e','f')((uint32_t)((' ') | ('d') << 8 | ('e') << 16 | ('f'
) << 24))
:
743 request->flags |= REQUEST_ACCEPT_DEFLATE;
744 break;
745 case STR4_INT('g','z','i','p')((uint32_t)(('g') | ('z') << 8 | ('i') << 16 | ('p'
) << 24))
:
746 case STR4_INT(' ','g','z','i')((uint32_t)((' ') | ('g') << 8 | ('z') << 16 | ('i'
) << 24))
:
747 request->flags |= REQUEST_ACCEPT_GZIP;
748 break;
749#if defined(LWAN_HAVE_ZSTD)
750 case STR4_INT('z','s','t','d')((uint32_t)(('z') | ('s') << 8 | ('t') << 16 | ('d'
) << 24))
:
751 case STR4_INT(' ','z','s','t')((uint32_t)((' ') | ('z') << 8 | ('s') << 16 | ('t'
) << 24))
:
752 request->flags |= REQUEST_ACCEPT_ZSTD;
753 break;
754#endif
755#if defined(LWAN_HAVE_BROTLI)
756 default:
757 while (lwan_char_isspace(*p))
758 p++;
759
760 STRING_SWITCH_SMALL(p)switch (string_as_uint16(p)) {
761 case STR2_INT('b', 'r')((uint16_t)(('b') | ('r') << 8)):
762 request->flags |= REQUEST_ACCEPT_BROTLI;
763 break;
764 }
765#endif
766 }
767
768 if (!(p = strchr(p, ',')))
769 break;
770 }
771}
772
773static ALWAYS_INLINEinline __attribute__((always_inline)) char *
774ignore_leading_whitespace(char *buffer)
775{
776 while (lwan_char_isspace(*buffer))
777 buffer++;
778 return buffer;
779}
780
781static ALWAYS_INLINEinline __attribute__((always_inline)) void parse_connection_header(struct lwan_request *request)
782{
783 struct lwan_request_parser_helper *helper = request->helper;
784 bool_Bool has_keep_alive = false0;
785 bool_Bool has_close = false0;
786
787 if (!helper->connection.len)
788 goto out;
789
790 for (const char *p = helper->connection.value; *p; p++) {
791 STRING_SWITCH_L(p)switch (((string_as_uint32(p)) | (uint32_t)0x20202020)) {
792 case STR4_INT_L('k','e','e','p')((((uint32_t)(('k') | ('e') << 8 | ('e') << 16 | (
'p') << 24))) | (uint32_t)0x20202020)
:
793 case STR4_INT_L(' ', 'k','e','e')((((uint32_t)((' ') | ('k') << 8 | ('e') << 16 | (
'e') << 24))) | (uint32_t)0x20202020)
:
794 has_keep_alive = true1;
795 break;
796 case STR4_INT_L('c','l','o','s')((((uint32_t)(('c') | ('l') << 8 | ('o') << 16 | (
's') << 24))) | (uint32_t)0x20202020)
:
797 case STR4_INT_L(' ', 'c','l','o')((((uint32_t)((' ') | ('c') << 8 | ('l') << 16 | (
'o') << 24))) | (uint32_t)0x20202020)
:
798 has_close = true1;
799 break;
800 case STR4_INT_L('u','p','g','r')((((uint32_t)(('u') | ('p') << 8 | ('g') << 16 | (
'r') << 24))) | (uint32_t)0x20202020)
:
801 case STR4_INT_L(' ', 'u','p','g')((((uint32_t)((' ') | ('u') << 8 | ('p') << 16 | (
'g') << 24))) | (uint32_t)0x20202020)
:
802 request->conn->flags |= CONN_IS_UPGRADE;
803 break;
804 }
805
806 if (!(p = strchr(p, ',')))
807 break;
808 }
809
810out:
811 if (LIKELY(!(request->flags & REQUEST_IS_HTTP_1_0))__builtin_expect((!!(!(request->flags & REQUEST_IS_HTTP_1_0
))), (1))
)
812 has_keep_alive = !has_close;
813
814 if (has_keep_alive) {
815 request->conn->flags |= CONN_IS_KEEP_ALIVE;
816 } else {
817 request->conn->flags &=
818 ~(CONN_IS_KEEP_ALIVE | CONN_SENT_CONNECTION_HEADER);
819 }
820}
821
822#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
823static void save_to_corpus_for_fuzzing(struct lwan_value buffer)
824{
825 struct lwan_value buffer_copy;
826 char corpus_name[PATH_MAX4096];
827 const char *crlfcrlf;
828 int fd;
829
830 if (!(crlfcrlf = memmem(buffer.value, buffer.len, "\r\n\r\n", 4)))
831 return;
832 buffer.len = (size_t)(crlfcrlf - buffer.value + 4);
833
834try_another_file_name:
835 buffer_copy = buffer;
836
837 snprintf(corpus_name, sizeof(corpus_name), "corpus-request-%d", rand());
838
839 fd = open(corpus_name, O_WRONLY01 | O_CLOEXEC02000000 | O_CREAT0100 | O_EXCL0200, 0644);
840 if (fd < 0)
841 goto try_another_file_name;
842
843 while (buffer_copy.len) {
844 ssize_t r = write(fd, buffer_copy.value, buffer_copy.len);
845
846 if (r < 0) {
847 if (errno(*__errno_location ()) == EAGAIN11 || errno(*__errno_location ()) == EINTR4)
848 continue;
849
850 close(fd);
851 unlink(corpus_name);
852 goto try_another_file_name;
853 }
854
855 buffer_copy.value += r;
856 buffer_copy.len -= r;
857 }
858
859 close(fd);
860 lwan_status_debug("Request saved to %s", corpus_name)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 860, __FUNCTION__, "Request saved to %s", corpus_name)
;
861}
862#endif
863
864static enum lwan_http_status
865client_read(struct lwan_request *request,
866 struct lwan_value *buffer,
867 const size_t want_to_read,
868 enum lwan_read_finalizer (*finalizer)(const struct lwan_value *buffer,
869 size_t want_to_read,
870 const struct lwan_request *request,
871 int n_packets))
872{
873 struct lwan_request_parser_helper *helper = request->helper;
874 int n_packets = 0;
875
876 if (helper->next_request) {
877 const size_t next_request_len = (size_t)(helper->next_request - buffer->value);
878 size_t new_len;
879
880 if (__builtin_sub_overflow(buffer->len, next_request_len, &new_len)) {
881 helper->next_request = NULL((void*)0);
882 } else if (new_len) {
883 /* FIXME: This memmove() could be eventually removed if a better
884 * stucture (maybe a ringbuffer, reading with readv(), and each
885 * pointer is coro_strdup() if they wrap around?) were used for
886 * the request buffer. */
887 buffer->len = new_len;
888 memmove(buffer->value, helper->next_request, new_len);
889 goto try_to_finalize;
890 }
891 }
892
893 for (buffer->len = 0;; n_packets++) {
894 size_t to_read = (size_t)(want_to_read - buffer->len);
895
896 if (UNLIKELY(to_read == 0)__builtin_expect(((to_read == 0)), (0)))
897 return HTTP_TOO_LARGE;
898
899 ssize_t n = recv(request->fd, buffer->value + buffer->len, to_read, 0);
900 if (UNLIKELY(n <= 0)__builtin_expect(((n <= 0)), (0))) {
901 if (n < 0) {
902 switch (errno(*__errno_location ())) {
903 case EINTR4:
904 case EAGAIN11:
905yield_and_read_again:
906 coro_yield(request->conn->coro, CONN_CORO_WANT_READ);
907 continue;
908 }
909
910 /* Unexpected error before reading anything */
911 if (UNLIKELY(!buffer->len)__builtin_expect(((!buffer->len)), (0)))
912 return HTTP_BAD_REQUEST;
913 }
914
915 /* Client shut down orderly (n = 0), or unrecoverable error (n < 0);
916 * shut down coro. */
917 break;
918 }
919
920 buffer->len += (size_t)n;
921
922try_to_finalize:
923 switch (finalizer(buffer, want_to_read, request, n_packets)) {
924 case FINALIZER_DONE:
925 buffer->value[buffer->len] = '\0';
926#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
927 save_to_corpus_for_fuzzing(*buffer);
928#endif
929 return HTTP_OK;
930
931 case FINALIZER_TRY_AGAIN:
932 goto yield_and_read_again;
933
934 case FINALIZER_TIMEOUT:
935 return HTTP_TIMEOUT;
936 }
937 }
938
939 coro_yield(request->conn->coro, CONN_CORO_ABORT);
940 __builtin_unreachable();
941 return HTTP_INTERNAL_ERROR;
942}
943
944static enum lwan_read_finalizer
945read_request_finalizer_from_helper(const struct lwan_value *buffer,
946 struct lwan_request_parser_helper *helper,
947 int n_packets,
948 bool_Bool allow_proxy_reqs)
949{
950 static const size_t min_proxied_request_size =
951 MIN_REQUEST_SIZE(sizeof("GET / HTTP/1.1\r\n\r\n") - 1) + sizeof(struct proxy_header_v2);
952
953 if (LIKELY(buffer->len >= MIN_REQUEST_SIZE)__builtin_expect((!!(buffer->len >= (sizeof("GET / HTTP/1.1\r\n\r\n"
) - 1))), (1))
) {
954 STRING_SWITCH (buffer->value + buffer->len - 4)switch (string_as_uint32(buffer->value + buffer->len - 4
))
{
955 case STR4_INT('\r', '\n', '\r', '\n')((uint32_t)(('\r') | ('\n') << 8 | ('\r') << 16 |
('\n') << 24))
:
956 return FINALIZER_DONE;
957 }
958 }
959
960 char *crlfcrlf = memmem(buffer->value, buffer->len, "\r\n\r\n", 4);
961 if (LIKELY(crlfcrlf)__builtin_expect((!!(crlfcrlf)), (1))) {
962 if (LIKELY(helper->next_request)__builtin_expect((!!(helper->next_request)), (1))) {
963 helper->next_request = NULL((void*)0);
964 return FINALIZER_DONE;
965 }
966
967 const size_t crlfcrlf_to_base = (size_t)(crlfcrlf - buffer->value);
968 if (crlfcrlf_to_base >= MIN_REQUEST_SIZE(sizeof("GET / HTTP/1.1\r\n\r\n") - 1) - 4)
969 return FINALIZER_DONE;
970
971 if (buffer->len > min_proxied_request_size && allow_proxy_reqs) {
972 /* FIXME: Checking for PROXYv2 protocol header here is a layering
973 * violation. */
974 STRING_SWITCH_LARGE (crlfcrlf + 4)switch (string_as_uint64(crlfcrlf + 4)) {
975 case STR8_INT(0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a)((uint64_t)((uint32_t)((0x00) | (0x0d) << 8 | (0x0a) <<
16 | (0x51) << 24)) | (uint64_t)((uint32_t)((0x55) | (
0x49) << 8 | (0x54) << 16 | (0x0a) << 24)) <<
32)
:
976 return FINALIZER_DONE;
977 }
978 }
979 }
980
981 /* Yield a timeout error to avoid clients being intentionally slow and
982 * hogging the server. (Clients can't only connect and do nothing, they
983 * need to send data, otherwise the timeout queue timer will kick in and
984 * close the connection. Limit the number of packets to avoid them sending
985 * just a byte at a time.) See lwan_calculate_n_packets() to see how this is
986 * calculated. */
987 if (UNLIKELY(n_packets > helper->error_when_n_packets)__builtin_expect(((n_packets > helper->error_when_n_packets
)), (0))
)
988 return FINALIZER_TIMEOUT;
989
990 return FINALIZER_TRY_AGAIN;
991}
992
993static inline enum lwan_read_finalizer
994read_request_finalizer(const struct lwan_value *buffer,
995 size_t want_to_read __attribute__((unused)),
996 const struct lwan_request *request,
997 int n_packets)
998{
999 return read_request_finalizer_from_helper(
1000 buffer, request->helper, n_packets,
1001 request->flags & REQUEST_ALLOW_PROXY_REQS);
1002}
1003
1004static ALWAYS_INLINEinline __attribute__((always_inline)) enum lwan_http_status
1005read_request(struct lwan_request *request)
1006{
1007 return client_read(request, request->helper->buffer,
1008 DEFAULT_BUFFER_SIZE4096 - 1 /* -1 for NUL byte */,
1009 read_request_finalizer);
1010}
1011
1012static enum lwan_read_finalizer
1013body_data_finalizer(const struct lwan_value *buffer,
1014 size_t want_to_read,
1015 const struct lwan_request *request,
1016 int n_packets)
1017{
1018 const struct lwan_request_parser_helper *helper = request->helper;
1019
1020 if (want_to_read == buffer->len)
1021 return FINALIZER_DONE;
1022
1023 /* For POST requests, the body can be larger, and due to small MTUs on
1024 * most ethernet connections, responding with a timeout solely based on
1025 * number of packets doesn't work. Use keepalive timeout instead. */
1026 if (UNLIKELY(time(NULL) > helper->error_when_time)__builtin_expect(((time(((void*)0)) > helper->error_when_time
)), (0))
)
1027 return FINALIZER_TIMEOUT;
1028
1029 /* In addition to time, also estimate the number of packets based on an
1030 * usual MTU value and the request body size. */
1031 if (UNLIKELY(n_packets > helper->error_when_n_packets)__builtin_expect(((n_packets > helper->error_when_n_packets
)), (0))
)
1032 return FINALIZER_TIMEOUT;
1033
1034 return FINALIZER_TRY_AGAIN;
1035}
1036
1037static const char *is_dir(const char *v)
1038{
1039 struct stat st;
1040
1041 if (!v)
1042 return NULL((void*)0);
1043
1044 if (*v != '/')
1045 return NULL((void*)0);
1046
1047 if (stat(v, &st) < 0)
1048 return NULL((void*)0);
1049
1050 if (!S_ISDIR(st.st_mode)((((st.st_mode)) & 0170000) == (0040000)))
1051 return NULL((void*)0);
1052
1053 if (!(st.st_mode & S_ISVTX01000)) {
1054 lwan_status_warning(lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1057, __FUNCTION__, "Using %s as temporary directory, but it doesn't have "
"the sticky bit set.", v)
1055 "Using %s as temporary directory, but it doesn't have "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1057, __FUNCTION__, "Using %s as temporary directory, but it doesn't have "
"the sticky bit set.", v)
1056 "the sticky bit set.",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1057, __FUNCTION__, "Using %s as temporary directory, but it doesn't have "
"the sticky bit set.", v)
1057 v)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1057, __FUNCTION__, "Using %s as temporary directory, but it doesn't have "
"the sticky bit set.", v)
;
1058 }
1059
1060 return v;
1061}
1062
1063static const char *is_dir_good_for_tmp(const char *v)
1064{
1065 struct statfs sb;
1066
1067 v = is_dir(v);
1068 if (!v)
1069 return NULL((void*)0);
1070
1071 if (!statfs(v, &sb) && sb.f_type == TMPFS_MAGIC0x01021994) {
1072 lwan_status_warning("%s is a tmpfs filesystem, "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1073, __FUNCTION__, "%s is a tmpfs filesystem, " "not considering it"
, v)
1073 "not considering it", v)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1073, __FUNCTION__, "%s is a tmpfs filesystem, " "not considering it"
, v)
;
1074 return NULL((void*)0);
1075 }
1076
1077 return v;
1078}
1079
1080static const char *temp_dir;
1081static const size_t body_buffer_temp_file_thresh = 1<<20;
1082
1083static const char *
1084get_temp_dir(void)
1085{
1086 const char *tmpdir;
1087
1088 tmpdir = is_dir_good_for_tmp(secure_getenv("TMPDIR"));
1089 if (tmpdir)
1090 return tmpdir;
1091
1092 tmpdir = is_dir_good_for_tmp(secure_getenv("TMP"));
1093 if (tmpdir)
1094 return tmpdir;
1095
1096 tmpdir = is_dir_good_for_tmp(secure_getenv("TEMP"));
1097 if (tmpdir)
1098 return tmpdir;
1099
1100 tmpdir = is_dir_good_for_tmp("/var/tmp");
1101 if (tmpdir)
1102 return tmpdir;
1103
1104 tmpdir = is_dir_good_for_tmp(P_tmpdir"/tmp");
1105 if (tmpdir)
1106 return tmpdir;
1107
1108 lwan_status_warning("Temporary directory could not be determined. POST "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1110, __FUNCTION__, "Temporary directory could not be determined. POST "
"or PUT requests over %zu bytes bytes will fail.", body_buffer_temp_file_thresh
)
1109 "or PUT requests over %zu bytes bytes will fail.",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1110, __FUNCTION__, "Temporary directory could not be determined. POST "
"or PUT requests over %zu bytes bytes will fail.", body_buffer_temp_file_thresh
)
1110 body_buffer_temp_file_thresh)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1110, __FUNCTION__, "Temporary directory could not be determined. POST "
"or PUT requests over %zu bytes bytes will fail.", body_buffer_temp_file_thresh
)
;
1111 return NULL((void*)0);
1112}
1113
1114__attribute__((constructor)) static void initialize_temp_dir(void)
1115{
1116 temp_dir = get_temp_dir();
1117}
1118
1119static int create_temp_file(void)
1120{
1121 char template[PATH_MAX4096];
1122 mode_t prev_mask;
1123 int ret;
1124
1125 if (UNLIKELY(!temp_dir)__builtin_expect(((!temp_dir)), (0)))
1126 return -ENOENT2;
1127
1128#if defined(O_TMPFILE(020000000 | 0200000))
1129 int fd = open(temp_dir,
1130 O_TMPFILE(020000000 | 0200000) | O_CREAT0100 | O_RDWR02 | O_EXCL0200 | O_CLOEXEC02000000 |
1131 O_NOFOLLOW0400000 | O_NOATIME01000000,
1132 S_IRUSR0400 | S_IWUSR0200);
1133 if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1)))
1134 return fd;
1135#endif
1136
1137 ret = snprintf(template, sizeof(template), "%s/lwanXXXXXX", temp_dir);
1138 if (UNLIKELY(ret < 0 || ret >= (int)sizeof(template))__builtin_expect(((ret < 0 || ret >= (int)sizeof(template
))), (0))
)
1139 return -EOVERFLOW75;
1140
1141 prev_mask = umask_for_tmpfile(S_IRUSR | S_IWUSR)({ (void)(0400 | 0200); 0U; });
1142 ret = mkostemp(template, O_CLOEXEC02000000);
1143 umask_for_tmpfile(prev_mask)({ (void)(prev_mask); 0U; });
1144
1145 if (LIKELY(ret >= 0)__builtin_expect((!!(ret >= 0)), (1)))
1146 unlink(template);
1147
1148 return ret;
1149}
1150
1151struct file_backed_buffer {
1152 void *ptr;
1153 size_t size;
1154};
1155
1156static void
1157free_body_buffer(void *data)
1158{
1159 struct file_backed_buffer *buf = data;
1160
1161 munmap(buf->ptr, buf->size);
1162 free(buf);
1163}
1164
1165static void*
1166alloc_body_buffer(struct coro *coro, size_t size, bool_Bool allow_file)
1167{
1168 struct file_backed_buffer *buf;
1169 void *ptr = (void *)MAP_FAILED((void *) -1);
1170 int fd;
1171
1172 if (LIKELY(size < body_buffer_temp_file_thresh)__builtin_expect((!!(size < body_buffer_temp_file_thresh))
, (1))
) {
1173 ptr = coro_malloc(coro, size);
1174
1175 if (LIKELY(ptr)__builtin_expect((!!(ptr)), (1)))
1176 return ptr;
1177 }
1178
1179 if (UNLIKELY(!allow_file)__builtin_expect(((!allow_file)), (0)))
1180 return NULL((void*)0);
1181
1182 fd = create_temp_file();
1183 if (UNLIKELY(fd < 0)__builtin_expect(((fd < 0)), (0)))
1184 return NULL((void*)0);
1185
1186 if (UNLIKELY(ftruncate(fd, (off_t)size) < 0)__builtin_expect(((ftruncate(fd, (off_t)size) < 0)), (0))) {
1187 close(fd);
1188 return NULL((void*)0);
1189 }
1190
1191 if (MAP_HUGETLB0x40000) {
1192 ptr = mmap(NULL((void*)0), size, PROT_READ0x1 | PROT_WRITE0x2,
1193 MAP_SHARED0x01 | MAP_HUGETLB0x40000, fd, 0);
1194 }
1195 if (UNLIKELY(ptr == MAP_FAILED)__builtin_expect(((ptr == ((void *) -1))), (0)))
1196 ptr = mmap(NULL((void*)0), size, PROT_READ0x1 | PROT_WRITE0x2, MAP_SHARED0x01, fd, 0);
1197 close(fd);
1198 if (UNLIKELY(ptr == MAP_FAILED)__builtin_expect(((ptr == ((void *) -1))), (0)))
1199 return NULL((void*)0);
1200
1201 buf = coro_malloc_full(coro, sizeof(*buf), free_body_buffer);
1202 if (UNLIKELY(!buf)__builtin_expect(((!buf)), (0))) {
1203 munmap(ptr, size);
1204 return NULL((void*)0);
1205 }
1206
1207 buf->ptr = ptr;
1208 buf->size = size;
1209 return ptr;
1210}
1211
1212static enum lwan_http_status
1213get_remaining_body_data_length(struct lwan_request *request,
1214 const size_t max_size,
1215 size_t *total,
1216 size_t *have)
1217{
1218 struct lwan_request_parser_helper *helper = request->helper;
1219 long long parsed_size;
1220
1221 if (UNLIKELY(!helper->content_length.value)__builtin_expect(((!helper->content_length.value)), (0)))
1222 return HTTP_BAD_REQUEST;
1223
1224 parsed_size = parse_long_long(helper->content_length.value, -1);
1225 if (UNLIKELY(parsed_size < 0)__builtin_expect(((parsed_size < 0)), (0)))
1226 return HTTP_BAD_REQUEST;
1227 if (UNLIKELY((size_t)parsed_size >= max_size)__builtin_expect((((size_t)parsed_size >= max_size)), (0)))
1228 return HTTP_TOO_LARGE;
1229 if (UNLIKELY(!parsed_size)__builtin_expect(((!parsed_size)), (0)))
1230 return HTTP_OK;
1231
1232 *total = (size_t)parsed_size;
1233
1234 if (!helper->next_request) {
1235 *have = 0;
1236 return HTTP_PARTIAL_CONTENT;
1237 }
1238
1239 char *buffer_end = helper->buffer->value + helper->buffer->len;
1240
1241 *have = (size_t)(buffer_end - helper->next_request);
1242
1243 if (*have < *total)
1244 return HTTP_PARTIAL_CONTENT;
1245
1246 helper->body_data.value = helper->next_request;
1247 helper->body_data.len = *total;
1248 helper->next_request += *total;
1249 return HTTP_OK;
1250}
1251
1252static int read_body_data(struct lwan_request *request)
1253{
1254 /* Holy indirection, Batman! */
1255 const struct lwan_config *config = &request->conn->thread->lwan->config;
1256 struct lwan_request_parser_helper *helper = request->helper;
1257 enum lwan_http_status status;
1258 size_t total, have, max_data_size;
1259 bool_Bool allow_temp_file;
1260 char *new_buffer;
1261
1262 switch (lwan_request_get_method(request)) {
1263 case REQUEST_METHOD_POST:
1264 allow_temp_file = config->allow_post_temp_file;
1265 max_data_size = config->max_post_data_size;
1266 break;
1267 case REQUEST_METHOD_PUT:
1268 allow_temp_file = config->allow_put_temp_file;
1269 max_data_size = config->max_put_data_size;
1270 break;
1271 default:
1272 return -HTTP_NOT_ALLOWED;
1273 }
1274
1275 status =
1276 get_remaining_body_data_length(request, max_data_size, &total, &have);
1277 if (status != HTTP_PARTIAL_CONTENT)
1278 return -(int)status;
1279
1280 new_buffer =
1281 alloc_body_buffer(request->conn->coro, total + 1, allow_temp_file);
1282 if (UNLIKELY(!new_buffer)__builtin_expect(((!new_buffer)), (0)))
1283 return -HTTP_INTERNAL_ERROR;
1284
1285 if (!(request->flags & REQUEST_IS_HTTP_1_0)) {
1286 /* §8.2.3 https://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html */
1287 const char *expect = lwan_request_get_header(request, "Expect");
1288
1289 if (expect && strncmp(expect, "100-", 4) == 0) {
1290 static const char continue_header[] = "HTTP/1.1 100 Continue\r\n\r\n";
1291
1292 lwan_send(request, continue_header, sizeof(continue_header) - 1, 0);
1293 }
1294 }
1295
1296 helper->body_data.value = new_buffer;
1297 helper->body_data.len = total;
1298 if (have) {
1299 new_buffer = mempcpy(new_buffer, helper->next_request, have);
1300 total -= have;
1301 }
1302 helper->next_request = NULL((void*)0);
1303
1304 helper->error_when_time = time(NULL((void*)0)) + config->keep_alive_timeout;
1305 helper->error_when_n_packets = lwan_calculate_n_packets(total);
1306
1307 struct lwan_value buffer = {.value = new_buffer, .len = total};
1308 return (int)client_read(request, &buffer, total, body_data_finalizer);
1309}
1310
1311static char *
1312parse_proxy_protocol(struct lwan_request *request, char *buffer)
1313{
1314 STRING_SWITCH(buffer)switch (string_as_uint32(buffer)) {
1315 case STR4_INT('P','R','O','X')((uint32_t)(('P') | ('R') << 8 | ('O') << 16 | ('X'
) << 24))
:
1316 return parse_proxy_protocol_v1(request, buffer);
1317 case STR4_INT('\x0D','\x0A','\x0D','\x0A')((uint32_t)(('\x0D') | ('\x0A') << 8 | ('\x0D') <<
16 | ('\x0A') << 24))
:
1318 return parse_proxy_protocol_v2(request, buffer);
1319 }
1320
1321 return buffer;
1322}
1323
1324static enum lwan_http_status parse_http_request(struct lwan_request *request)
1325{
1326 struct lwan_request_parser_helper *helper = request->helper;
1327 char *buffer = helper->buffer->value;
1328
1329 if (request->flags & REQUEST_ALLOW_PROXY_REQS) {
1330 /* REQUEST_ALLOW_PROXY_REQS will be cleared in lwan_process_request() */
1331
1332 buffer = parse_proxy_protocol(request, buffer);
1333 if (UNLIKELY(!buffer)__builtin_expect(((!buffer)), (0)))
1334 return HTTP_BAD_REQUEST;
1335 }
1336
1337 buffer = ignore_leading_whitespace(buffer);
1338
1339 if (UNLIKELY(buffer > helper->buffer->value + helper->buffer->len -__builtin_expect(((buffer > helper->buffer->value + helper
->buffer->len - (sizeof("GET / HTTP/1.1\r\n\r\n") - 1))
), (0))
1340 MIN_REQUEST_SIZE)__builtin_expect(((buffer > helper->buffer->value + helper
->buffer->len - (sizeof("GET / HTTP/1.1\r\n\r\n") - 1))
), (0))
)
1341 return HTTP_BAD_REQUEST;
1342
1343 char *path = identify_http_method(request, buffer);
1344 if (UNLIKELY(!path)__builtin_expect(((!path)), (0)))
1345 return HTTP_NOT_ALLOWED;
1346
1347 buffer = identify_http_path(request, path);
1348 if (UNLIKELY(!buffer)__builtin_expect(((!buffer)), (0)))
1349 return HTTP_BAD_REQUEST;
1350
1351 if (UNLIKELY(!parse_headers(helper, buffer))__builtin_expect(((!parse_headers(helper, buffer))), (0)))
1352 return HTTP_BAD_REQUEST;
1353
1354 ssize_t decoded_len = url_decode(request->url.value);
1355 if (UNLIKELY(decoded_len < 0)__builtin_expect(((decoded_len < 0)), (0)))
1356 return HTTP_BAD_REQUEST;
1357 request->original_url.len = request->url.len = (size_t)decoded_len;
1358
1359 parse_connection_header(request);
1360
1361 return HTTP_OK;
1362}
1363
1364static enum lwan_http_status
1365prepare_websocket_handshake(struct lwan_request *request, char **encoded)
1366{
1367 static const unsigned char websocket_uuid[] =
1368 "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1369 unsigned char digest[20];
1370 sha1_context ctx;
1371
1372 if (UNLIKELY(request->flags & RESPONSE_SENT_HEADERS)__builtin_expect(((request->flags & RESPONSE_SENT_HEADERS
)), (0))
)
1373 return HTTP_INTERNAL_ERROR;
1374
1375 if (UNLIKELY(!(request->conn->flags & CONN_IS_UPGRADE))__builtin_expect(((!(request->conn->flags & CONN_IS_UPGRADE
))), (0))
)
1376 return HTTP_BAD_REQUEST;
1377
1378 const char *upgrade = lwan_request_get_header(request, "Upgrade");
1379 if (UNLIKELY(!upgrade || !streq(upgrade, "websocket"))__builtin_expect(((!upgrade || !streq(upgrade, "websocket")))
, (0))
)
1380 return HTTP_BAD_REQUEST;
1381
1382 const char *sec_websocket_key =
1383 lwan_request_get_header(request, "Sec-WebSocket-Key");
1384 if (UNLIKELY(!sec_websocket_key)__builtin_expect(((!sec_websocket_key)), (0)))
1385 return HTTP_BAD_REQUEST;
1386
1387 const size_t sec_websocket_key_len = strlen(sec_websocket_key);
1388 if (base64_encoded_len(16) != sec_websocket_key_len)
1389 return HTTP_BAD_REQUEST;
1390 if (UNLIKELY(!base64_validate((void *)sec_websocket_key, sec_websocket_key_len))__builtin_expect(((!base64_validate((void *)sec_websocket_key
, sec_websocket_key_len))), (0))
)
1391 return HTTP_BAD_REQUEST;
1392
1393 sha1_init(&ctx);
1394 sha1_update(&ctx, (void *)sec_websocket_key, sec_websocket_key_len);
1395 sha1_update(&ctx, websocket_uuid, sizeof(websocket_uuid) - 1);
1396 sha1_finalize(&ctx, digest);
1397
1398 *encoded = (char *)base64_encode(digest, sizeof(digest), NULL((void*)0));
1399 return LIKELY(*encoded)__builtin_expect((!!(*encoded)), (1)) ? HTTP_SWITCHING_PROTOCOLS : HTTP_INTERNAL_ERROR;
1400}
1401
1402enum lwan_http_status
1403lwan_request_websocket_upgrade(struct lwan_request *request)
1404{
1405 char header_buf[DEFAULT_HEADERS_SIZE2048];
1406 size_t header_buf_len;
1407 char *encoded;
1408
1409 enum lwan_http_status r = prepare_websocket_handshake(request, &encoded);
1410 if (r != HTTP_SWITCHING_PROTOCOLS)
1411 return r;
1412
1413 request->flags |= RESPONSE_NO_CONTENT_LENGTH;
1414 header_buf_len = lwan_prepare_response_header_full(
1415 request, HTTP_SWITCHING_PROTOCOLS, header_buf, sizeof(header_buf),
1416 (struct lwan_key_value[]){
1417 /* Connection: Upgrade is implicit if conn->flags & CONN_IS_UPGRADE */
1418 {.key = "Sec-WebSocket-Accept", .value = encoded},
1419 {.key = "Upgrade", .value = "websocket"},
1420 {},
1421 });
1422 free(encoded);
1423 if (UNLIKELY(!header_buf_len)__builtin_expect(((!header_buf_len)), (0)))
1424 return HTTP_INTERNAL_ERROR;
1425
1426 request->conn->flags |= CONN_IS_WEBSOCKET;
1427 lwan_send(request, header_buf, header_buf_len, 0);
1428
1429 return HTTP_SWITCHING_PROTOCOLS;
1430}
1431
1432static inline bool_Bool request_has_body(const struct lwan_request *request)
1433{
1434 /* 3rd bit set in method: request method has body. See lwan.h,
1435 * definition of FOR_EACH_REQUEST_METHOD() for more info. */
1436 return lwan_request_get_method(request) & 1 << 3;
1437}
1438
1439static enum lwan_http_status
1440maybe_read_body_data(const struct lwan_url_map *url_map,
1441 struct lwan_request *request)
1442{
1443 int status = 0;
1444
1445 if (url_map->flags & HANDLER_EXPECTS_BODY_DATA) {
1446 status = read_body_data(request);
1447 if (status > 0)
1448 return (enum lwan_http_status)status;
1449 }
1450
1451 /* Instead of trying to read the body here, which will require
1452 * us to allocate and read potentially a lot of bytes, force
1453 * this connection to be closed as soon as we send a "not allowed"
1454 * response. */
1455 request->conn->flags &= ~CONN_IS_KEEP_ALIVE;
1456
1457 if (status < 0) {
1458 status = -status;
1459 return (enum lwan_http_status)status;
1460 }
1461
1462 return HTTP_NOT_ALLOWED;
1463}
1464
1465static enum lwan_http_status prepare_for_response(const struct lwan_url_map *url_map,
1466 struct lwan_request *request)
1467{
1468 request->url.value += url_map->prefix_len;
1469 request->url.len -= url_map->prefix_len;
1470 while (*request->url.value == '/' && request->url.len > 0) {
1471 request->url.value++;
1472 request->url.len--;
1473 }
1474
1475 if (UNLIKELY(url_map->flags & HANDLER_MUST_AUTHORIZE)__builtin_expect(((url_map->flags & HANDLER_MUST_AUTHORIZE
)), (0))
) {
1476 if (!lwan_http_authorize_urlmap(request, url_map))
1477 return HTTP_NOT_AUTHORIZED;
1478 }
1479
1480 if (UNLIKELY(request_has_body(request))__builtin_expect(((request_has_body(request))), (0)))
1481 return maybe_read_body_data(url_map, request);
1482
1483 return HTTP_OK;
1484}
1485
1486static bool_Bool handle_rewrite(struct lwan_request *request)
1487{
1488 struct lwan_request_parser_helper *helper = request->helper;
1489
1490 request->flags &= ~RESPONSE_URL_REWRITTEN;
1491
1492 find_query_string(request, request->url.value + request->url.len);
1493
1494 helper->urls_rewritten++;
1495 if (UNLIKELY(helper->urls_rewritten > 4)__builtin_expect(((helper->urls_rewritten > 4)), (0))) {
1496 lwan_default_response(request, HTTP_INTERNAL_ERROR);
1497 return false0;
1498 }
1499
1500 return true1;
1501}
1502
1503const char *lwan_request_get_method_str(const struct lwan_request *request)
1504{
1505#define GENERATE_CASE_STMT(upper, lower, mask, constant, probability) \
1506 case REQUEST_METHOD_##upper: \
1507 return #upper;
1508
1509 switch (lwan_request_get_method(request)) {
1510 FOR_EACH_REQUEST_METHOD(GENERATE_CASE_STMT)GENERATE_CASE_STMT(GET, get, (1 << 0), (((uint32_t)(('G'
) | ('E') << 8 | ('T') << 16 | (' ') << 24)
)), 0.6) GENERATE_CASE_STMT(POST, post, (1 << 3 | 1 <<
1 | 1 << 0), (((uint32_t)(('P') | ('O') << 8 | (
'S') << 16 | ('T') << 24))), 0.2) GENERATE_CASE_STMT
(HEAD, head, (1 << 1), (((uint32_t)(('H') | ('E') <<
8 | ('A') << 16 | ('D') << 24))), 0.2) GENERATE_CASE_STMT
(OPTIONS, options, (1 << 2), (((uint32_t)(('O') | ('P')
<< 8 | ('T') << 16 | ('I') << 24))), 0.1) GENERATE_CASE_STMT
(DELETE, delete, (1 << 1 | 1 << 2), (((uint32_t)(
('D') | ('E') << 8 | ('L') << 16 | ('E') <<
24))), 0.1) GENERATE_CASE_STMT(PUT, put, (1 << 3 | 1 <<
2 | 1 << 0), (((uint32_t)(('P') | ('U') << 8 | (
'T') << 16 | (' ') << 24))), 0.1)
1511 default:
1512 return "UNKNOWN";
1513 }
1514#undef GENERATE_CASE_STMT
1515}
1516
1517#ifndef NDEBUG
1518static void log_request(struct lwan_request *request,
1519 enum lwan_http_status status,
1520 double time_to_read_request,
1521 double time_to_process_request)
1522{
1523 char ip_buffer[INET6_ADDRSTRLEN46];
1524
1525 lwan_status_debug(lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
5
Calling 'lwan_request_get_remote_address'
1526 "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
1527 lwan_request_get_remote_address(request, ip_buffer),lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
1528 request->conn->thread->date.date, lwan_request_get_id(request),lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
1529 lwan_request_get_method_str(request), request->original_url.value,lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
1530 request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" : "1.1", status,lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
1531 request->response.mime_type, time_to_read_request,lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
1532 time_to_process_request)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1532, __FUNCTION__, "%s [%s] %016lx \"%s %s HTTP/%s\" %d %s (r:%.3fms p:%.3fms)"
, lwan_request_get_remote_address(request, ip_buffer), request
->conn->thread->date.date, lwan_request_get_id(request
), lwan_request_get_method_str(request), request->original_url
.value, request->flags & REQUEST_IS_HTTP_1_0 ? "1.0" :
"1.1", status, request->response.mime_type, time_to_read_request
, time_to_process_request)
;
1533}
1534#else
1535#define log_request(...)
1536#endif
1537
1538#ifndef NDEBUG
1539static struct timespec current_precise_monotonic_timespec(void)
1540{
1541 struct timespec now;
1542
1543 if (UNLIKELY(clock_gettime(CLOCK_MONOTONIC, &now) < 0)__builtin_expect(((clock_gettime(1, &now) < 0)), (0))) {
1544 lwan_status_perror("clock_gettime")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1544, __FUNCTION__, "clock_gettime")
;
1545 return (struct timespec){};
1546 }
1547
1548 return now;
1549}
1550
1551static double elapsed_time_ms(const struct timespec then)
1552{
1553 const struct timespec now = current_precise_monotonic_timespec();
1554 struct timespec diff = {
1555 .tv_sec = now.tv_sec - then.tv_sec,
1556 .tv_nsec = now.tv_nsec - then.tv_nsec,
1557 };
1558
1559 if (diff.tv_nsec < 0) {
1560 diff.tv_sec--;
1561 diff.tv_nsec += 1000000000l;
1562 }
1563
1564 return (double)diff.tv_sec / 1000.0 + (double)diff.tv_nsec / 1000000.0;
1565}
1566#endif
1567
1568void lwan_process_request(struct lwan *l, struct lwan_request *request)
1569{
1570 enum lwan_http_status status;
1571 struct lwan_url_map *url_map;
1572
1573#ifndef NDEBUG
1574 struct timespec request_read_begin_time = current_precise_monotonic_timespec();
1575#endif
1576 status = read_request(request);
1577
1578#ifndef NDEBUG
1579 double time_to_read_request = elapsed_time_ms(request_read_begin_time);
1580
1581 struct timespec request_begin_time = current_precise_monotonic_timespec();
1582#endif
1583 if (UNLIKELY(status != HTTP_OK)__builtin_expect(((status != HTTP_OK)), (0))) {
1
Taking false branch
1584 /* If read_request() returns any error at this point, it's probably
1585 * better to just send an error response and abort the coroutine and
1586 * let the client handle the error instead: we don't have
1587 * information to even log the request because it has not been
1588 * parsed yet at this stage. Even if there are other requests waiting
1589 * in the pipeline, this seems like the safer thing to do. */
1590 request->conn->flags &= ~CONN_IS_KEEP_ALIVE;
1591 lwan_default_response(request, status);
1592 /* Let process_request_coro() gracefully close the connection. */
1593 return;
1594 }
1595
1596 status = parse_http_request(request);
1597 if (UNLIKELY(status != HTTP_OK)__builtin_expect(((status != HTTP_OK)), (0)))
2
Taking true branch
1598 goto log_and_return;
3
Control jumps to line 1621
1599
1600lookup_again:
1601 url_map = lwan_trie_lookup_prefix(&l->url_map_trie, request->url.value);
1602 if (UNLIKELY(!url_map)__builtin_expect(((!url_map)), (0))) {
1603 status = HTTP_NOT_FOUND;
1604 goto log_and_return;
1605 }
1606
1607 status = prepare_for_response(url_map, request);
1608 if (UNLIKELY(status != HTTP_OK)__builtin_expect(((status != HTTP_OK)), (0)))
1609 goto log_and_return;
1610
1611 status = url_map->handler(request, &request->response, url_map->data);
1612 if (UNLIKELY(url_map->flags & HANDLER_CAN_REWRITE_URL)__builtin_expect(((url_map->flags & HANDLER_CAN_REWRITE_URL
)), (0))
) {
1613 if (request->flags & RESPONSE_URL_REWRITTEN) {
1614 if (LIKELY(handle_rewrite(request))__builtin_expect((!!(handle_rewrite(request))), (1)))
1615 goto lookup_again;
1616 return;
1617 }
1618 }
1619
1620log_and_return:
1621 lwan_response(request, status);
1622
1623 log_request(request, status, time_to_read_request, elapsed_time_ms(request_begin_time));
4
Calling 'log_request'
1624}
1625
1626static inline void *
1627value_lookup(const struct lwan_key_value_array *array, const char *key)
1628{
1629 const struct lwan_array *la = (const struct lwan_array *)array;
1630
1631 if (LIKELY(la->elements)__builtin_expect((!!(la->elements)), (1))) {
1632 struct lwan_key_value k = { .key = (char *)key };
1633 struct lwan_key_value *entry;
1634
1635 entry = bsearch(&k, la->base, la->elements, sizeof(k), key_value_compare);
1636 if (LIKELY(entry)__builtin_expect((!!(entry)), (1)))
1637 return entry->value;
1638 }
1639
1640 return NULL((void*)0);
1641}
1642
1643const char *lwan_request_get_query_param(struct lwan_request *request,
1644 const char *key)
1645{
1646 return value_lookup(lwan_request_get_query_params(request), key);
1647}
1648
1649const char *lwan_request_get_post_param(struct lwan_request *request,
1650 const char *key)
1651{
1652 return value_lookup(lwan_request_get_post_params(request), key);
1653}
1654
1655const char *lwan_request_get_cookie(struct lwan_request *request,
1656 const char *key)
1657{
1658 return value_lookup(lwan_request_get_cookies(request), key);
1659}
1660
1661const char *
1662lwan_request_get_header_from_helper(struct lwan_request_parser_helper *helper,
1663 const char *header)
1664{
1665 const size_t header_len = strlen(header);
1666 const size_t header_len_with_separator =
1667 header_len + HEADER_VALUE_SEPARATOR_LEN(sizeof(": ") - 1);
1668
1669 assert(strchr(header, ':') == NULL)((void) sizeof ((strchr(header, ':') == ((void*)0)) ? 1 : 0),
__extension__ ({ if (strchr(header, ':') == ((void*)0)) ; else
__assert_fail ("strchr(header, ':') == NULL", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1669, __extension__ __PRETTY_FUNCTION__); }))
;
1670
1671 for (size_t i = 0; i < helper->n_header_start; i++) {
1672 const char *start = helper->header_start[i];
1673 char *end = helper->header_start[i + 1] - HEADER_TERMINATOR_LEN(sizeof("\r\n") - 1);
1674
1675 if (UNLIKELY((size_t)(end - start) < header_len_with_separator)__builtin_expect((((size_t)(end - start) < header_len_with_separator
)), (0))
)
1676 continue;
1677
1678 STRING_SWITCH_SMALL (start + header_len)switch (string_as_uint16(start + header_len)) {
1679 case STR2_INT(':', ' ')((uint16_t)((':') | (' ') << 8)):
1680 if (!strncasecmp(start, header, header_len)) {
1681 *end = '\0';
1682 return start + header_len_with_separator;
1683 }
1684 }
1685 }
1686
1687 return NULL((void*)0);
1688}
1689
1690inline const char *lwan_request_get_header(struct lwan_request *request,
1691 const char *header)
1692{
1693 return lwan_request_get_header_from_helper(request->helper, header);
1694}
1695
1696const char *lwan_request_get_host(struct lwan_request *request)
1697{
1698 const struct lwan_request_parser_helper *helper = request->helper;
1699
1700 return helper->host.len ? helper->host.value : NULL((void*)0);
1701}
1702
1703ALWAYS_INLINEinline __attribute__((always_inline)) int
1704lwan_connection_get_fd(const struct lwan *lwan, const struct lwan_connection *conn)
1705{
1706 return (int)(intptr_t)(conn - lwan->conns);
1707}
1708
1709const char *
1710lwan_request_get_remote_address_and_port(struct lwan_request *request,
1711 char buffer[static INET6_ADDRSTRLEN46],
1712 uint16_t *port)
1713{
1714 struct sockaddr_storage non_proxied_addr = {.ss_family = AF_UNSPEC0};
1715 struct sockaddr_storage *sock_addr;
1716
1717 *port = 0;
1718
1719 if (request->flags & REQUEST_PROXIED) {
7
Assuming the condition is false
8
Taking false branch
1720 sock_addr = (struct sockaddr_storage *)&request->proxy->from;
1721
1722 if (UNLIKELY(sock_addr->ss_family == AF_UNSPEC)__builtin_expect(((sock_addr->ss_family == 0)), (0))) {
1723 static const char unspecified[] = "*unspecified*";
1724
1725 static_assert_Static_assert(sizeof(unspecified) <= INET6_ADDRSTRLEN46,
1726 "Enough space for unspecified address family");
1727 return memcpy(buffer, unspecified, sizeof(unspecified));
1728 }
1729 } else {
1730 socklen_t sock_len = sizeof(non_proxied_addr);
1731
1732 sock_addr = &non_proxied_addr;
1733
1734 if (UNLIKELY(getpeername(request->fd, (struct sockaddr *)sock_addr,__builtin_expect(((getpeername(request->fd, (struct sockaddr
*)sock_addr, &sock_len) < 0)), (0))
9
Assuming the condition is false
10
Taking false branch
1735 &sock_len) < 0)__builtin_expect(((getpeername(request->fd, (struct sockaddr
*)sock_addr, &sock_len) < 0)), (0))
) {
1736 return NULL((void*)0);
1737 }
1738 }
1739
1740 if (sock_addr->ss_family
10.1
Field 'ss_family' is not equal to AF_INET
== AF_INET2) {
11
Taking false branch
1741 struct sockaddr_in *sin = (struct sockaddr_in *)sock_addr;
1742 *port = ntohs(sin->sin_port);
1743 return inet_ntop(AF_INET2, &sin->sin_addr, buffer, INET6_ADDRSTRLEN46);
1744 }
1745
1746 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sock_addr;
1747 *port = ntohs(sin6->sin6_port);
12
1st function call argument is an uninitialized value
1748 return inet_ntop(AF_INET610, &sin6->sin6_addr, buffer, INET6_ADDRSTRLEN46);
1749}
1750
1751const char *
1752lwan_request_get_remote_address(struct lwan_request *request,
1753 char buffer[static INET6_ADDRSTRLEN46])
1754{
1755 uint16_t port;
1756 return lwan_request_get_remote_address_and_port(request, buffer, &port);
6
Calling 'lwan_request_get_remote_address_and_port'
1757}
1758
1759static void remove_sleep(void *data1, void *data2)
1760{
1761 static const enum lwan_connection_flags suspended_sleep =
1762 CONN_SUSPENDED | CONN_HAS_REMOVE_SLEEP_DEFER;
1763 struct timeouts *wheel = data1;
1764 struct timeout *timeout = data2;
1765 struct lwan_request *request =
1766 container_of(timeout, struct lwan_request, timeout)((struct lwan_request *) ((char *)(timeout) - __builtin_offsetof
(struct lwan_request, timeout)) + ((typeof(*(timeout)) *)0 !=
(typeof(((struct lwan_request *)0)->timeout) *)0))
;
1767
1768 if ((request->conn->flags & suspended_sleep) == suspended_sleep)
1769 timeouts_del(wheel, timeout);
1770
1771 request->conn->flags &= ~CONN_HAS_REMOVE_SLEEP_DEFER;
1772}
1773
1774void lwan_request_sleep(struct lwan_request *request, uint64_t ms)
1775{
1776 struct lwan_connection *conn = request->conn;
1777 struct timeouts *wheel = conn->thread->wheel;
1778 struct timespec now;
1779 coro_deferred defer = -1;
1780
1781 /* We need to update the timer wheel right now because
1782 * a request might have requested to sleep a long time
1783 * before it was being serviced -- causing the timeout
1784 * to essentially be a no-op. */
1785 if (UNLIKELY(clock_gettime(monotonic_clock_id, &now) < 0)__builtin_expect(((clock_gettime(monotonic_clock_id, &now
) < 0)), (0))
)
1786 lwan_status_critical("Could not get monotonic time")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 1786, __FUNCTION__, "Could not get monotonic time")
;
1787 timeouts_update(wheel, (timeout_t)(now.tv_sec * 1000 + now.tv_nsec / 1000000));
1788
1789 request->timeout = (struct timeout) {};
1790 timeouts_add(wheel, &request->timeout, ms);
1791
1792 if (!(conn->flags & CONN_HAS_REMOVE_SLEEP_DEFER)) {
1793 defer = coro_defer2(conn->coro, remove_sleep, wheel, &request->timeout);
1794 conn->flags |= CONN_HAS_REMOVE_SLEEP_DEFER;
1795 }
1796
1797 coro_yield(conn->coro, CONN_CORO_SUSPEND);
1798
1799 if (defer > 0)
1800 coro_defer_fire_and_disarm(conn->coro, defer);
1801}
1802
1803ALWAYS_INLINEinline __attribute__((always_inline)) int
1804lwan_request_get_range(struct lwan_request *request, off_t *from, off_t *to)
1805{
1806 struct lwan_request_parser_helper *helper = request->helper;
1807
1808 if (!(request->flags & REQUEST_PARSED_RANGE)) {
1809 parse_range(helper);
1810 request->flags |= REQUEST_PARSED_RANGE;
1811 }
1812
1813 if (LIKELY(helper->range.raw.len)__builtin_expect((!!(helper->range.raw.len)), (1))) {
1814 *from = helper->range.from;
1815 *to = helper->range.to;
1816 return 0;
1817 }
1818
1819 return -ENOENT2;
1820}
1821
1822ALWAYS_INLINEinline __attribute__((always_inline)) int
1823lwan_request_get_if_modified_since(struct lwan_request *request, time_t *value)
1824{
1825 struct lwan_request_parser_helper *helper = request->helper;
1826
1827 if (!(request->flags & REQUEST_PARSED_IF_MODIFIED_SINCE)) {
1828 parse_if_modified_since(helper);
1829 request->flags |= REQUEST_PARSED_IF_MODIFIED_SINCE;
1830 }
1831
1832 if (LIKELY(helper->if_modified_since.raw.len)__builtin_expect((!!(helper->if_modified_since.raw.len)), (
1))
) {
1833 *value = helper->if_modified_since.parsed;
1834 return 0;
1835 }
1836
1837 return -ENOENT2;
1838}
1839
1840ALWAYS_INLINEinline __attribute__((always_inline)) const struct lwan_value *
1841lwan_request_get_request_body(struct lwan_request *request)
1842{
1843 return &request->helper->body_data;
1844}
1845
1846ALWAYS_INLINEinline __attribute__((always_inline)) const struct lwan_value *
1847lwan_request_get_content_type(struct lwan_request *request)
1848{
1849 return &request->helper->content_type;
1850}
1851
1852ALWAYS_INLINEinline __attribute__((always_inline)) const struct lwan_key_value_array *
1853lwan_request_get_cookies(struct lwan_request *request)
1854{
1855 if (!(request->flags & REQUEST_PARSED_COOKIES)) {
1856 parse_cookies(request);
1857 request->flags |= REQUEST_PARSED_COOKIES;
1858 }
1859
1860 return &request->helper->cookies;
1861}
1862
1863ALWAYS_INLINEinline __attribute__((always_inline)) const struct lwan_key_value_array *
1864lwan_request_get_query_params(struct lwan_request *request)
1865{
1866 if (!(request->flags & REQUEST_PARSED_QUERY_STRING)) {
1867 parse_query_string(request);
1868 request->flags |= REQUEST_PARSED_QUERY_STRING;
1869 }
1870
1871 return &request->helper->query_params;
1872}
1873
1874ALWAYS_INLINEinline __attribute__((always_inline)) const struct lwan_key_value_array *
1875lwan_request_get_post_params(struct lwan_request *request)
1876{
1877 if (!(request->flags & REQUEST_PARSED_FORM_DATA)) {
1878 parse_form_data(request);
1879 request->flags |= REQUEST_PARSED_FORM_DATA;
1880 }
1881
1882 return &request->helper->post_params;
1883}
1884
1885ALWAYS_INLINEinline __attribute__((always_inline)) enum lwan_request_flags
1886lwan_request_get_accept_encoding(struct lwan_request *request)
1887{
1888 if (!(request->flags & REQUEST_PARSED_ACCEPT_ENCODING)) {
1889 parse_accept_encoding(request);
1890 request->flags |= REQUEST_PARSED_ACCEPT_ENCODING;
1891 }
1892
1893 return request->flags & REQUEST_ACCEPT_MASK;
1894}
1895
1896#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1897static int useless_coro_for_fuzzing(struct coro *c __attribute__((unused)),
1898 void *data __attribute__((unused)))
1899{
1900 return 0;
1901}
1902
1903static bool_Bool request_seems_complete(struct lwan_request_parser_helper *helper)
1904{
1905 return read_request_finalizer_from_helper(helper->buffer, helper, 1,
1906 false0) == FINALIZER_DONE;
1907}
1908
1909__attribute__((used)) int fuzz_parse_http_request(const uint8_t *data,
1910 size_t length)
1911{
1912 static struct coro_switcher switcher;
1913 static struct coro *coro;
1914 static char *header_start[N_HEADER_START64];
1915 static char data_copy[32767] = {0};
1916
1917 if (length > sizeof(data_copy))
1918 length = sizeof(data_copy);
1919 memcpy(data_copy, data, length);
1920
1921 if (!coro) {
1922 coro = coro_new(&switcher, useless_coro_for_fuzzing, NULL((void*)0));
1923
1924 lwan_job_thread_init();
1925 lwan_http_authorize_init();
1926 }
1927
1928 struct lwan_request_parser_helper helper = {
1929 .buffer = &(struct lwan_value){.value = data_copy, .len = length},
1930 .header_start = header_start,
1931 .error_when_n_packets = 2,
1932 };
1933 struct lwan_connection conn = {.coro = coro};
1934 struct lwan_proxy proxy = {};
1935 struct lwan_request request = {
1936 .helper = &helper,
1937 .conn = &conn,
1938 .flags = REQUEST_ALLOW_PROXY_REQS,
1939 .proxy = &proxy,
1940 };
1941
1942 /* If the finalizer isn't happy with a request, there's no point in
1943 * going any further with parsing it. */
1944 if (!request_seems_complete(&helper))
1945 return 0;
1946
1947 /* client_read() NUL-terminates the string */
1948 data_copy[length - 1] = '\0';
1949
1950 if (parse_http_request(&request) != HTTP_OK)
1951 return 0;
1952
1953 off_t trash1;
1954 time_t trash2;
1955 char *trash3;
1956 size_t gen = coro_deferred_get_generation(coro);
1957
1958 /* Only pointers were set in helper struct; actually parse them here. */
1959 parse_accept_encoding(&request);
1960
1961 /* Requesting these items will force them to be parsed, and also
1962 * exercise the lookup function. */
1963 LWAN_NO_DISCARD(lwan_request_get_header(&request, "Non-Existing-Header"))do { __typeof__(lwan_request_get_header(&request, "Non-Existing-Header"
)) no_discard_ = lwan_request_get_header(&request, "Non-Existing-Header"
); __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
;
1964
1965 /* Usually existing short header */
1966 LWAN_NO_DISCARD(lwan_request_get_header(&request, "Host"))do { __typeof__(lwan_request_get_header(&request, "Host")
) no_discard_ = lwan_request_get_header(&request, "Host")
; __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
;
1967
1968 LWAN_NO_DISCARD(lwan_request_get_cookie(&request, "Non-Existing-Cookie"))do { __typeof__(lwan_request_get_cookie(&request, "Non-Existing-Cookie"
)) no_discard_ = lwan_request_get_cookie(&request, "Non-Existing-Cookie"
); __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
;
1969 /* Set by some tests */
1970 LWAN_NO_DISCARD(lwan_request_get_cookie(&request, "FOO"))do { __typeof__(lwan_request_get_cookie(&request, "FOO"))
no_discard_ = lwan_request_get_cookie(&request, "FOO"); __asm__
__volatile__("" ::"g"(no_discard_) : "memory"); } while (0)
;
1971
1972 LWAN_NO_DISCARD(do { __typeof__(lwan_request_get_query_param(&request, "Non-Existing-Query-Param"
)) no_discard_ = lwan_request_get_query_param(&request, "Non-Existing-Query-Param"
); __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
1973 lwan_request_get_query_param(&request, "Non-Existing-Query-Param"))do { __typeof__(lwan_request_get_query_param(&request, "Non-Existing-Query-Param"
)) no_discard_ = lwan_request_get_query_param(&request, "Non-Existing-Query-Param"
); __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
;
1974
1975 LWAN_NO_DISCARD(do { __typeof__(lwan_request_get_post_param(&request, "Non-Existing-Post-Param"
)) no_discard_ = lwan_request_get_post_param(&request, "Non-Existing-Post-Param"
); __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
1976 lwan_request_get_post_param(&request, "Non-Existing-Post-Param"))do { __typeof__(lwan_request_get_post_param(&request, "Non-Existing-Post-Param"
)) no_discard_ = lwan_request_get_post_param(&request, "Non-Existing-Post-Param"
); __asm__ __volatile__("" ::"g"(no_discard_) : "memory"); } while
(0)
;
1977
1978 lwan_request_get_range(&request, &trash1, &trash1);
1979 LWAN_NO_DISCARD(trash1)do { __typeof__(trash1) no_discard_ = trash1; __asm__ __volatile__
("" ::"g"(no_discard_) : "memory"); } while (0)
;
1980
1981 lwan_request_get_if_modified_since(&request, &trash2);
1982 LWAN_NO_DISCARD(trash2)do { __typeof__(trash2) no_discard_ = trash2; __asm__ __volatile__
("" ::"g"(no_discard_) : "memory"); } while (0)
;
1983
1984 enum lwan_http_status handshake =
1985 prepare_websocket_handshake(&request, &trash3);
1986 LWAN_NO_DISCARD(trash3)do { __typeof__(trash3) no_discard_ = trash3; __asm__ __volatile__
("" ::"g"(no_discard_) : "memory"); } while (0)
;
1987 if (handshake == HTTP_SWITCHING_PROTOCOLS)
1988 free(trash3);
1989
1990 LWAN_NO_DISCARD(lwan_http_authorize(&request, "Fuzzy Realm", "/dev/null"))do { __typeof__(lwan_http_authorize(&request, "Fuzzy Realm"
, "/dev/null")) no_discard_ = lwan_http_authorize(&request
, "Fuzzy Realm", "/dev/null"); __asm__ __volatile__("" ::"g"(
no_discard_) : "memory"); } while (0)
;
1991
1992 coro_deferred_run(coro, gen);
1993
1994 return 0;
1995}
1996#endif
1997
1998static inline int64_t
1999make_async_yield_value(int fd, enum lwan_connection_coro_yield event)
2000{
2001 return (int64_t)(((uint64_t)fd << 32 | event));
2002}
2003
2004static inline void async_await_fd(struct coro *coro,
2005 int fd,
2006 enum lwan_connection_coro_yield events)
2007{
2008 assert(events >= CONN_CORO_ASYNC_AWAIT_READ &&((void) sizeof ((events >= CONN_CORO_ASYNC_AWAIT_READ &&
events <= CONN_CORO_ASYNC_AWAIT_READ_WRITE) ? 1 : 0), __extension__
({ if (events >= CONN_CORO_ASYNC_AWAIT_READ && events
<= CONN_CORO_ASYNC_AWAIT_READ_WRITE) ; else __assert_fail
("events >= CONN_CORO_ASYNC_AWAIT_READ && events <= CONN_CORO_ASYNC_AWAIT_READ_WRITE"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 2009, __extension__ __PRETTY_FUNCTION__); }))
2009 events <= CONN_CORO_ASYNC_AWAIT_READ_WRITE)((void) sizeof ((events >= CONN_CORO_ASYNC_AWAIT_READ &&
events <= CONN_CORO_ASYNC_AWAIT_READ_WRITE) ? 1 : 0), __extension__
({ if (events >= CONN_CORO_ASYNC_AWAIT_READ && events
<= CONN_CORO_ASYNC_AWAIT_READ_WRITE) ; else __assert_fail
("events >= CONN_CORO_ASYNC_AWAIT_READ && events <= CONN_CORO_ASYNC_AWAIT_READ_WRITE"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-request.c"
, 2009, __extension__ __PRETTY_FUNCTION__); }))
;
2010
2011 return (void)coro_yield(coro, make_async_yield_value(fd, events));
2012}
2013
2014void lwan_request_await_read(struct lwan_request *r, int fd)
2015{
2016 return async_await_fd(r->conn->coro, fd, CONN_CORO_ASYNC_AWAIT_READ);
2017}
2018
2019void lwan_request_await_write(struct lwan_request *r, int fd)
2020{
2021 return async_await_fd(r->conn->coro, fd, CONN_CORO_ASYNC_AWAIT_WRITE);
2022}
2023
2024void lwan_request_await_read_write(struct lwan_request *r, int fd)
2025{
2026 return async_await_fd(r->conn->coro, fd, CONN_CORO_ASYNC_AWAIT_READ_WRITE);
2027}
2028
2029ssize_t lwan_request_async_read_flags(
2030 struct lwan_request *request, int fd, void *buf, size_t len, int flags)
2031{
2032 while (true1) {
2033 ssize_t r = recv(fd, buf, len, MSG_DONTWAITMSG_DONTWAIT | MSG_NOSIGNALMSG_NOSIGNAL | flags);
2034
2035 if (r < 0) {
2036 switch (errno(*__errno_location ())) {
2037 case EWOULDBLOCK11:
2038 lwan_request_await_read(request, fd);
2039 /* Fallthrough */
2040 case EINTR4:
2041 continue;
2042 case EPIPE32:
2043 return -errno(*__errno_location ());
2044 }
2045 }
2046
2047 return r;
2048 }
2049}
2050
2051ssize_t lwan_request_async_read(struct lwan_request *request,
2052 int fd,
2053 void *buf,
2054 size_t len)
2055{
2056 return lwan_request_async_read_flags(request, fd, buf, len, 0);
2057}
2058
2059ssize_t lwan_request_async_write(struct lwan_request *request,
2060 int fd,
2061 const void *buf,
2062 size_t len)
2063{
2064 while (true1) {
2065 ssize_t r = send(fd, buf, len, MSG_DONTWAITMSG_DONTWAIT|MSG_NOSIGNALMSG_NOSIGNAL);
2066
2067 if (r < 0) {
2068 switch (errno(*__errno_location ())) {
2069 case EWOULDBLOCK11:
2070 lwan_request_await_write(request, fd);
2071 /* Fallthrough */
2072 case EINTR4:
2073 continue;
2074 case EPIPE32:
2075 return -errno(*__errno_location ());
2076 }
2077 }
2078
2079 return r;
2080 }
2081}
2082
2083ssize_t lwan_request_async_writev(struct lwan_request *request,
2084 int fd,
2085 struct iovec *iov,
2086 int iov_count)
2087{
2088 ssize_t total_written = 0;
2089 int curr_iov = 0;
2090
2091 for (int tries = 10; tries;) {
2092 const int remaining_len = (int)(iov_count - curr_iov);
2093 ssize_t written;
2094
2095 if (remaining_len == 1) {
2096 const struct iovec *vec = &iov[curr_iov];
2097 return lwan_request_async_write(request, fd, vec->iov_base,
2098 vec->iov_len);
2099 }
2100
2101 written = writev(fd, iov + curr_iov, (size_t)remaining_len);
2102 if (UNLIKELY(written < 0)__builtin_expect(((written < 0)), (0))) {
2103 /* FIXME: Consider short writes as another try as well? */
2104 tries--;
2105
2106 switch (errno(*__errno_location ())) {
2107 case EAGAIN11:
2108 case EINTR4:
2109 goto try_again;
2110 default:
2111 goto out;
2112 }
2113 }
2114
2115 total_written += written;
2116
2117 while (curr_iov < iov_count &&
2118 written >= (ssize_t)iov[curr_iov].iov_len) {
2119 written -= (ssize_t)iov[curr_iov].iov_len;
2120 curr_iov++;
2121 }
2122
2123 if (curr_iov == iov_count)
2124 return total_written;
2125
2126 iov[curr_iov].iov_base = (char *)iov[curr_iov].iov_base + written;
2127 iov[curr_iov].iov_len -= (size_t)written;
2128
2129 try_again:
2130 lwan_request_await_write(request, fd);
2131 }
2132
2133out:
2134 coro_yield(request->conn->coro, CONN_CORO_ABORT);
2135 __builtin_unreachable();
2136}
2137
2138void lwan_request_foreach_header_for_cgi(struct lwan_request *request,
2139 void (*cb)(const char *header_name,
2140 size_t header_len,
2141 const char *value,
2142 size_t value_len,
2143 void *user_data),
2144 void *user_data)
2145{
2146 struct lwan_request_parser_helper *helper = request->helper;
2147 char **header_start = helper->header_start;
2148 size_t n_header_start = helper->n_header_start;
2149
2150 for (size_t i = 0; i < n_header_start; i++) {
2151 const char *header = header_start[i];
2152 const char *next_header = header_start[i + 1];
2153 const char *colon = memchr(header, ':', 127 - sizeof("HTTP_: ") - 1);
2154 char header_name[128];
2155 int r;
2156
2157 if (!colon)
2158 continue;
2159
2160 const size_t header_len = (size_t)(colon - header);
2161 const size_t value_len = (size_t)(next_header - colon - 4);
2162
2163 r = snprintf(header_name, sizeof(header_name), "HTTP_%.*s",
2164 (int)header_len, header);
2165 if (r < 0 || r >= (int)sizeof(header_name))
2166 continue;
2167
2168 /* FIXME: RFC7230/RFC3875 compliance */
2169 for (char *p = header_name; *p; p++) {
2170 if (isalpha(*p)((*__ctype_b_loc ())[(int) ((*p))] & (unsigned short int)
_ISalpha)
)
2171 *p &= ~0x20;
2172 else if (!isdigit(*p)((*__ctype_b_loc ())[(int) ((*p))] & (unsigned short int)
_ISdigit)
)
2173 *p = '_';
2174 }
2175
2176 if (streq(header_name, "HTTP_PROXY")) {
2177 /* Mitigation for https://httpoxy.org */
2178 continue;
2179 }
2180
2181 cb(header_name, header_len + sizeof("HTTP_") - 1, colon + 2, value_len,
2182 user_data);
2183 }
2184}