Bug Summary

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