Bug Summary

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