Bug Summary

File:lwan-thread.c
Warning:line 1243, column 53
The left operand of '==' is a garbage value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name lwan-thread.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 -fno-rounding-math -mconstructor-aliases -fno-plt -munwind-tables -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/13.0.0 -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.0 -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/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../x86_64-pc-linux-gnu/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-unused-parameter -Wno-free-nonheap-object -std=gnu99 -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/2021-12-16-045847-1643655-1 -x c /home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c
1/*
2 * lwan - simple web server
3 * Copyright (c) 2012, 2013 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,
18 * USA.
19 */
20
21#define _GNU_SOURCE
22#include <assert.h>
23#include <errno(*__errno_location ()).h>
24#include <fcntl.h>
25#include <pthread.h>
26#include <sched.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/epoll.h>
30#include <sys/ioctl.h>
31#include <sys/socket.h>
32#include <unistd.h>
33
34#if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF)
35#include <linux1/filter.h>
36#endif
37
38#if defined(HAVE_MBEDTLS)
39#include <mbedtls/entropy.h>
40#include <mbedtls/error.h>
41#include <mbedtls/gcm.h>
42#include <mbedtls/net_sockets.h>
43#include <mbedtls/ssl_internal.h>
44
45#include <linux1/tls.h>
46#include <netinet/tcp.h>
47#endif
48
49#include "list.h"
50#include "murmur3.h"
51#include "lwan-private.h"
52#include "lwan-tq.h"
53
54static void lwan_strbuf_free_defer(void *data)
55{
56 return lwan_strbuf_free((struct lwan_strbuf *)data);
57}
58
59static void graceful_close(struct lwan *l,
60 struct lwan_connection *conn,
61 char buffer[static DEFAULT_BUFFER_SIZE4096])
62{
63 int fd = lwan_connection_get_fd(l, conn);
64
65 while (TIOCOUTQ0x5411) {
66 /* This ioctl isn't probably doing what it says on the tin; the details
67 * are subtle, but it seems to do the trick to allow gracefully closing
68 * the connection in some cases with minimal system calls. */
69 int bytes_waiting;
70 int r = ioctl(fd, TIOCOUTQ0x5411, &bytes_waiting);
71
72 if (!r && !bytes_waiting) /* See note about close(2) below. */
73 return;
74 if (r < 0 && errno(*__errno_location ()) == EINTR4)
75 continue;
76
77 break;
78 }
79
80 if (UNLIKELY(shutdown(fd, SHUT_WR) < 0)__builtin_expect(((shutdown(fd, SHUT_WR) < 0)), (0))) {
81 if (UNLIKELY(errno == ENOTCONN)__builtin_expect((((*__errno_location ()) == 107)), (0)))
82 return;
83 }
84
85 for (int tries = 0; tries < 20; tries++) {
86 ssize_t r = recv(fd, buffer, DEFAULT_BUFFER_SIZE4096, 0);
87
88 if (!r)
89 break;
90
91 if (r < 0) {
92 switch (errno(*__errno_location ())) {
93 case EAGAIN11:
94 break;
95 case EINTR4:
96 continue;
97 default:
98 return;
99 }
100 }
101
102 coro_yield(conn->coro, CONN_CORO_WANT_READ);
103 }
104
105 /* close(2) will be called when the coroutine yields with CONN_CORO_ABORT */
106}
107
108#if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
109static void lwan_random_seed_prng_for_thread(const struct lwan_thread *t)
110{
111 (void)t;
112}
113
114uint64_t lwan_random_uint64()
115{
116 static uint64_t value;
117
118 return ATOMIC_INC(value)(__sync_add_and_fetch(((&(value))), ((1))));
119}
120#else
121static __thread __uint128_t lehmer64_state;
122
123static void lwan_random_seed_prng_for_thread(const struct lwan_thread *t)
124{
125 if (lwan_getentropy(&lehmer64_state, sizeof(lehmer64_state), 0) < 0) {
126 lwan_status_warning("Couldn't get proper entropy for PRNG, using fallback seed")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 126, __FUNCTION__, "Couldn't get proper entropy for PRNG, using fallback seed"
)
;
127 lehmer64_state |= murmur3_fmix64((uint64_t)(uintptr_t)t);
128 lehmer64_state <<= 64;
129 lehmer64_state |= murmur3_fmix64((uint64_t)t->epoll_fd);
130 }
131}
132
133uint64_t lwan_random_uint64()
134{
135 /* https://lemire.me/blog/2019/03/19/the-fastest-conventional-random-number-generator-that-can-pass-big-crush/ */
136 lehmer64_state *= 0xda942042e4dd58b5ull;
137 return (uint64_t)(lehmer64_state >> 64);
138}
139#endif
140
141uint64_t lwan_request_get_id(struct lwan_request *request)
142{
143 struct lwan_request_parser_helper *helper = request->helper;
144
145 if (helper->request_id == 0)
146 helper->request_id = lwan_random_uint64();
147
148 return helper->request_id;
149}
150
151#if defined(HAVE_MBEDTLS)
152static bool_Bool
153lwan_setup_tls_keys(int fd, const mbedtls_ssl_context *ssl, int rx_or_tx)
154{
155 struct tls12_crypto_info_aes_gcm_128 info = {
156 .info = {.version = TLS_1_2_VERSION((((0x3) & 0xFF) << 8) | ((0x3) & 0xFF)),
157 .cipher_type = TLS_CIPHER_AES_GCM_12851},
158 };
159 const unsigned char *salt, *iv, *rec_seq;
160 mbedtls_gcm_context *gcm_ctx;
161 mbedtls_aes_context *aes_ctx;
162
163 switch (rx_or_tx) {
164 case TLS_RX2:
165 salt = ssl->transform->iv_dec;
166 rec_seq = ssl->in_ctr;
167 gcm_ctx = ssl->transform->cipher_ctx_dec.cipher_ctx;
168 break;
169 case TLS_TX1:
170 salt = ssl->transform->iv_enc;
171 rec_seq = ssl->cur_out_ctr;
172 gcm_ctx = ssl->transform->cipher_ctx_enc.cipher_ctx;
173 break;
174 default:
175 __builtin_unreachable();
176 }
177
178 iv = salt + 4;
179 aes_ctx = gcm_ctx->cipher_ctx.cipher_ctx;
180
181 memcpy(info.iv, iv, TLS_CIPHER_AES_GCM_128_IV_SIZE8);
182 memcpy(info.rec_seq, rec_seq, TLS_CIPHER_AES_GCM_128_REC_SEQ_SIZE8);
183 memcpy(info.key, aes_ctx->rk, TLS_CIPHER_AES_GCM_128_KEY_SIZE16);
184 memcpy(info.salt, salt, TLS_CIPHER_AES_GCM_128_SALT_SIZE4);
185
186 if (UNLIKELY(setsockopt(fd, SOL_TLS, rx_or_tx, &info, sizeof(info)) < 0)__builtin_expect(((setsockopt(fd, 282, rx_or_tx, &info, sizeof
(info)) < 0)), (0))
) {
187 lwan_status_perror("Could not set kTLS keys for fd %d", fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 187, __FUNCTION__, "Could not set kTLS keys for fd %d", fd)
;
188 lwan_always_bzero(&info, sizeof(info));
189 return false0;
190 }
191
192 lwan_always_bzero(&info, sizeof(info));
193 return true1;
194}
195
196__attribute__((format(printf, 2, 3)))
197__attribute__((noinline, cold))
198static void lwan_status_mbedtls_error(int error_code, const char *fmt, ...)
199{
200 char *formatted;
201 va_list ap;
202 int r;
203
204 va_start(ap, fmt)__builtin_va_start(ap, fmt);
205 r = vasprintf(&formatted, fmt, ap);
206 if (r >= 0) {
207 char mbedtls_errbuf[128];
208
209 mbedtls_strerror(error_code, mbedtls_errbuf, sizeof(mbedtls_errbuf));
210 lwan_status_error("%s: %s", formatted, mbedtls_errbuf)lwan_status_error_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 210, __FUNCTION__, "%s: %s", formatted, mbedtls_errbuf)
;
211 free(formatted);
212 }
213 va_end(ap)__builtin_va_end(ap);
214}
215
216static void lwan_setup_tls_free_ssl_context(void *data1, void *data2)
217{
218 struct lwan_connection *conn = data1;
219
220 if (UNLIKELY(conn->flags & CONN_NEEDS_TLS_SETUP)__builtin_expect(((conn->flags & CONN_NEEDS_TLS_SETUP)
), (0))
) {
221 mbedtls_ssl_context *ssl = data2;
222
223 mbedtls_ssl_free(ssl);
224 conn->flags &= ~CONN_NEEDS_TLS_SETUP;
225 }
226}
227
228static bool_Bool lwan_setup_tls(const struct lwan *l, struct lwan_connection *conn)
229{
230 mbedtls_ssl_context ssl;
231 bool_Bool retval = false0;
232 int r;
233
234 mbedtls_ssl_init(&ssl);
235
236 r = mbedtls_ssl_setup(&ssl, &l->tls->config);
237 if (UNLIKELY(r != 0)__builtin_expect(((r != 0)), (0))) {
238 lwan_status_mbedtls_error(r, "Could not setup TLS context");
239 return false0;
240 }
241
242 /* Yielding the coroutine during the handshake enables the I/O loop to
243 * destroy this coro (e.g. on connection hangup) before we have the
244 * opportunity to free the SSL context. Defer this call for these
245 * cases. */
246 coro_defer2(conn->coro, lwan_setup_tls_free_ssl_context, conn, &ssl);
247
248 int fd = lwan_connection_get_fd(l, conn);
249 /* FIXME: This is only required for the handshake; this uses read() and
250 * write() under the hood but maybe we can use something like recv() and
251 * send() instead to force MSG_MORE et al? (strace shows a few
252 * consecutive calls to write(); this might be sent in separate TCP
253 * fragments.) */
254 mbedtls_ssl_set_bio(&ssl, &fd, mbedtls_net_send, mbedtls_net_recv, NULL((void*)0));
255
256 while (true1) {
257 switch (mbedtls_ssl_handshake(&ssl)) {
258 case 0:
259 goto enable_tls_ulp;
260 case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS-0x6500:
261 case MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS-0x7000:
262 case MBEDTLS_ERR_SSL_WANT_READ-0x6900:
263 coro_yield(conn->coro, CONN_CORO_WANT_READ);
264 break;
265 case MBEDTLS_ERR_SSL_WANT_WRITE-0x6880:
266 coro_yield(conn->coro, CONN_CORO_WANT_WRITE);
267 break;
268 default:
269 goto fail;
270 }
271 }
272
273enable_tls_ulp:
274 if (UNLIKELY(setsockopt(fd, SOL_TCP, TCP_ULP, "tls", sizeof("tls")) < 0)__builtin_expect(((setsockopt(fd, 6, 31, "tls", sizeof("tls")
) < 0)), (0))
)
275 goto fail;
276 if (UNLIKELY(!lwan_setup_tls_keys(fd, &ssl, TLS_RX))__builtin_expect(((!lwan_setup_tls_keys(fd, &ssl, 2))), (
0))
)
277 goto fail;
278 if (UNLIKELY(!lwan_setup_tls_keys(fd, &ssl, TLS_TX))__builtin_expect(((!lwan_setup_tls_keys(fd, &ssl, 1))), (
0))
)
279 goto fail;
280
281 retval = true1;
282
283fail:
284 mbedtls_ssl_free(&ssl);
285
286 conn->flags &= ~CONN_NEEDS_TLS_SETUP;
287 return retval;
288}
289#endif
290
291__attribute__((noreturn)) static int process_request_coro(struct coro *coro,
292 void *data)
293{
294 /* NOTE: This function should not return; coro_yield should be used
295 * instead. This ensures the storage for `strbuf` is alive when the
296 * coroutine ends and lwan_strbuf_free() is called. */
297 struct lwan_connection *conn = data;
298 struct lwan *lwan = conn->thread->lwan;
299 int fd = lwan_connection_get_fd(lwan, conn);
300 enum lwan_request_flags flags = lwan->config.request_flags;
301 struct lwan_strbuf strbuf = LWAN_STRBUF_STATIC_INIT(struct lwan_strbuf) { .buffer = "" };
302 char request_buffer[DEFAULT_BUFFER_SIZE4096];
303 struct lwan_value buffer = {.value = request_buffer, .len = 0};
304 char *next_request = NULL((void*)0);
305 char *header_start[N_HEADER_START64];
306 struct lwan_proxy proxy;
307 const int error_when_n_packets = lwan_calculate_n_packets(DEFAULT_BUFFER_SIZE4096);
308
309 coro_defer(coro, lwan_strbuf_free_defer, &strbuf);
310
311 const size_t init_gen = 1; /* 1 call to coro_defer() */
312 assert(init_gen == coro_deferred_get_generation(coro))((void) sizeof ((init_gen == coro_deferred_get_generation(coro
)) ? 1 : 0), __extension__ ({ if (init_gen == coro_deferred_get_generation
(coro)) ; else __assert_fail ("init_gen == coro_deferred_get_generation(coro)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 312, __extension__ __PRETTY_FUNCTION__); }))
;
313
314#if defined(HAVE_MBEDTLS)
315 if (conn->flags & CONN_NEEDS_TLS_SETUP) {
316 /* Sometimes this flag is unset when it *should* be set! Need to
317 * figure out why. This causes the TLS handshake to not happen,
318 * making the normal HTTP request reading code to try and read
319 * the handshake as if it were a HTTP request. */
320 if (UNLIKELY(!lwan_setup_tls(lwan, conn))__builtin_expect(((!lwan_setup_tls(lwan, conn))), (0))) {
321 coro_yield(coro, CONN_CORO_ABORT);
322 __builtin_unreachable();
323 }
324
325 conn->flags |= CONN_TLS;
326 }
327#endif
328 assert(!(conn->flags & CONN_NEEDS_TLS_SETUP))((void) sizeof ((!(conn->flags & CONN_NEEDS_TLS_SETUP)
) ? 1 : 0), __extension__ ({ if (!(conn->flags & CONN_NEEDS_TLS_SETUP
)) ; else __assert_fail ("!(conn->flags & CONN_NEEDS_TLS_SETUP)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 328, __extension__ __PRETTY_FUNCTION__); }))
;
329
330 while (true1) {
331 struct lwan_request_parser_helper helper = {
332 .buffer = &buffer,
333 .next_request = next_request,
334 .error_when_n_packets = error_when_n_packets,
335 .header_start = header_start,
336 };
337 struct lwan_request request = {.conn = conn,
338 .global_response_headers = &lwan->headers,
339 .fd = fd,
340 .response = {.buffer = &strbuf},
341 .flags = flags,
342 .proxy = &proxy,
343 .helper = &helper};
344
345 lwan_process_request(lwan, &request);
346
347 /* Run the deferred instructions now (except those used to initialize
348 * the coroutine), so that if the connection is gracefully closed,
349 * the storage for ``helper'' is still there. */
350 coro_deferred_run(coro, init_gen);
351
352 if (UNLIKELY(!(conn->flags & CONN_IS_KEEP_ALIVE))__builtin_expect(((!(conn->flags & CONN_IS_KEEP_ALIVE)
)), (0))
) {
353 graceful_close(lwan, conn, request_buffer);
354 break;
355 }
356
357 if (next_request && *next_request) {
358 conn->flags |= CONN_CORK;
359
360 if (!(conn->flags & CONN_EVENTS_WRITE))
361 coro_yield(coro, CONN_CORO_WANT_WRITE);
362 } else {
363 conn->flags &= ~CONN_CORK;
364 coro_yield(coro, CONN_CORO_WANT_READ);
365 }
366
367 /* Ensure string buffer is reset between requests, and that the backing
368 * store isn't over 2KB. */
369 lwan_strbuf_reset_trim(&strbuf, 2048);
370
371 /* Only allow flags from config. */
372 flags = request.flags & (REQUEST_PROXIED | REQUEST_ALLOW_CORS);
373 next_request = helper.next_request;
374 }
375
376 coro_yield(coro, CONN_CORO_ABORT);
377 __builtin_unreachable();
378}
379
380static ALWAYS_INLINEinline __attribute__((always_inline)) uint32_t
381conn_flags_to_epoll_events(enum lwan_connection_flags flags)
382{
383 static const uint32_t map[CONN_EVENTS_MASK + 1] = {
384 [0 /* Suspended (timer or await) */] = EPOLLRDHUPEPOLLRDHUP,
385 [CONN_EVENTS_WRITE] = EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP,
386 [CONN_EVENTS_READ] = EPOLLINEPOLLIN | EPOLLRDHUPEPOLLRDHUP,
387 [CONN_EVENTS_READ_WRITE] = EPOLLINEPOLLIN | EPOLLOUTEPOLLOUT | EPOLLRDHUPEPOLLRDHUP,
388 };
389
390 return map[flags & CONN_EVENTS_MASK];
391}
392
393static void update_epoll_flags(int fd,
394 struct lwan_connection *conn,
395 int epoll_fd,
396 enum lwan_connection_coro_yield yield_result)
397{
398 static const enum lwan_connection_flags or_mask[CONN_CORO_MAX] = {
399 [CONN_CORO_YIELD] = 0,
400
401 [CONN_CORO_WANT_READ_WRITE] = CONN_EVENTS_READ_WRITE,
402 [CONN_CORO_WANT_READ] = CONN_EVENTS_READ,
403 [CONN_CORO_WANT_WRITE] = CONN_EVENTS_WRITE,
404
405 /* While the coro is suspended, we're not interested in either EPOLLIN
406 * or EPOLLOUT events. We still want to track this fd in epoll, though,
407 * so unset both so that only EPOLLRDHUP (plus the implicitly-set ones)
408 * are set. */
409 [CONN_CORO_SUSPEND] = CONN_SUSPENDED,
410
411 /* Ideally, when suspending a coroutine, the current flags&CONN_EVENTS_MASK
412 * would have to be stored and restored -- however, resuming as if the
413 * client coroutine is interested in a write event always guarantees that
414 * they'll be resumed as they're TCP sockets. There's a good chance that
415 * trying to read from a socket after resuming a coroutine will succeed,
416 * but if it doesn't because read() returns -EAGAIN, the I/O wrappers will
417 * yield with CONN_CORO_WANT_READ anyway. */
418 [CONN_CORO_RESUME] = CONN_EVENTS_WRITE,
419 };
420 static const enum lwan_connection_flags and_mask[CONN_CORO_MAX] = {
421 [CONN_CORO_YIELD] = ~0,
422
423 [CONN_CORO_WANT_READ_WRITE] = ~0,
424 [CONN_CORO_WANT_READ] = ~CONN_EVENTS_WRITE,
425 [CONN_CORO_WANT_WRITE] = ~CONN_EVENTS_READ,
426
427 [CONN_CORO_SUSPEND] = ~CONN_EVENTS_READ_WRITE,
428 [CONN_CORO_RESUME] = ~CONN_SUSPENDED,
429 };
430 enum lwan_connection_flags prev_flags = conn->flags;
431
432 conn->flags |= or_mask[yield_result];
433 conn->flags &= and_mask[yield_result];
434
435 assert(!(conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)))((void) sizeof ((!(conn->flags & (CONN_LISTENER_HTTP |
CONN_LISTENER_HTTPS))) ? 1 : 0), __extension__ ({ if (!(conn
->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)))
; else __assert_fail ("!(conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS))"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 435, __extension__ __PRETTY_FUNCTION__); }))
;
436 assert((conn->flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP)) ==((void) sizeof (((conn->flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP
)) == (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP))) ?
1 : 0), __extension__ ({ if ((conn->flags & (CONN_TLS
| CONN_NEEDS_TLS_SETUP)) == (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP
))) ; else __assert_fail ("(conn->flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP)) == (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP))"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 437, __extension__ __PRETTY_FUNCTION__); }))
437 (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP)))((void) sizeof (((conn->flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP
)) == (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP))) ?
1 : 0), __extension__ ({ if ((conn->flags & (CONN_TLS
| CONN_NEEDS_TLS_SETUP)) == (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP
))) ; else __assert_fail ("(conn->flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP)) == (prev_flags & (CONN_TLS | CONN_NEEDS_TLS_SETUP))"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 437, __extension__ __PRETTY_FUNCTION__); }))
;
438
439 if (conn->flags == prev_flags)
440 return;
441
442 struct epoll_event event = {
443 .events = conn_flags_to_epoll_events(conn->flags),
444 .data.ptr = conn,
445 };
446
447 if (UNLIKELY(epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, &event) < 0)__builtin_expect(((epoll_ctl(epoll_fd, 3, fd, &event) <
0)), (0))
)
448 lwan_status_perror("epoll_ctl")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 448, __FUNCTION__, "epoll_ctl")
;
449}
450
451static void clear_async_await_flag(void *data)
452{
453 struct lwan_connection *async_fd_conn = data;
454
455 async_fd_conn->flags &= ~CONN_ASYNC_AWAIT;
456}
457
458static enum lwan_connection_coro_yield
459resume_async(struct timeout_queue *tq,
460 enum lwan_connection_coro_yield yield_result,
461 int64_t from_coro,
462 struct lwan_connection *conn,
463 int epoll_fd)
464{
465 static const enum lwan_connection_flags to_connection_flags[] = {
466 [CONN_CORO_ASYNC_AWAIT_READ] = CONN_EVENTS_READ,
467 [CONN_CORO_ASYNC_AWAIT_WRITE] = CONN_EVENTS_WRITE,
468 [CONN_CORO_ASYNC_AWAIT_READ_WRITE] = CONN_EVENTS_READ_WRITE,
469 };
470 int await_fd = (int)((uint64_t)from_coro >> 32);
471 enum lwan_connection_flags flags;
472 int op;
473
474 assert(await_fd >= 0)((void) sizeof ((await_fd >= 0) ? 1 : 0), __extension__ ({
if (await_fd >= 0) ; else __assert_fail ("await_fd >= 0"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 474, __extension__ __PRETTY_FUNCTION__); }))
;
475 assert(yield_result >= CONN_CORO_ASYNC_AWAIT_READ &&((void) sizeof ((yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ? 1 : 0), __extension__ ({ if (yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ; else __assert_fail ("yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 476, __extension__ __PRETTY_FUNCTION__); }))
476 yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE)((void) sizeof ((yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ? 1 : 0), __extension__ ({ if (yield_result >= CONN_CORO_ASYNC_AWAIT_READ
&& yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE
) ; else __assert_fail ("yield_result >= CONN_CORO_ASYNC_AWAIT_READ && yield_result <= CONN_CORO_ASYNC_AWAIT_READ_WRITE"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 476, __extension__ __PRETTY_FUNCTION__); }))
;
477
478 flags = to_connection_flags[yield_result];
479
480 struct lwan_connection *await_fd_conn = &tq->lwan->conns[await_fd];
481 if (LIKELY(await_fd_conn->flags & CONN_ASYNC_AWAIT)__builtin_expect((!!(await_fd_conn->flags & CONN_ASYNC_AWAIT
)), (1))
) {
482 if (LIKELY((await_fd_conn->flags & CONN_EVENTS_MASK) == flags)__builtin_expect((!!((await_fd_conn->flags & CONN_EVENTS_MASK
) == flags)), (1))
)
483 return CONN_CORO_SUSPEND;
484
485 op = EPOLL_CTL_MOD3;
486 } else {
487 op = EPOLL_CTL_ADD1;
488 flags |= CONN_ASYNC_AWAIT;
489 coro_defer(conn->coro, clear_async_await_flag, await_fd_conn);
490 }
491
492 struct epoll_event event = {.events = conn_flags_to_epoll_events(flags),
493 .data.ptr = conn};
494 if (LIKELY(!epoll_ctl(epoll_fd, op, await_fd, &event))__builtin_expect((!!(!epoll_ctl(epoll_fd, op, await_fd, &
event))), (1))
) {
495 await_fd_conn->flags &= ~CONN_EVENTS_MASK;
496 await_fd_conn->flags |= flags;
497 return CONN_CORO_SUSPEND;
498 }
499
500 return CONN_CORO_ABORT;
501}
502
503static ALWAYS_INLINEinline __attribute__((always_inline)) void resume_coro(struct timeout_queue *tq,
504 struct lwan_connection *conn,
505 int epoll_fd)
506{
507 assert(conn->coro)((void) sizeof ((conn->coro) ? 1 : 0), __extension__ ({ if
(conn->coro) ; else __assert_fail ("conn->coro", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 507, __extension__ __PRETTY_FUNCTION__); }))
;
508
509 int64_t from_coro = coro_resume(conn->coro);
510 enum lwan_connection_coro_yield yield_result = from_coro & 0xffffffff;
511
512 if (UNLIKELY(yield_result >= CONN_CORO_ASYNC)__builtin_expect(((yield_result >= CONN_CORO_ASYNC)), (0)))
513 yield_result = resume_async(tq, yield_result, from_coro, conn, epoll_fd);
514
515 if (UNLIKELY(yield_result == CONN_CORO_ABORT)__builtin_expect(((yield_result == CONN_CORO_ABORT)), (0)))
516 return timeout_queue_expire(tq, conn);
517
518 return update_epoll_flags(lwan_connection_get_fd(tq->lwan, conn), conn,
519 epoll_fd, yield_result);
520}
521
522static void update_date_cache(struct lwan_thread *thread)
523{
524 time_t now = time(NULL((void*)0));
525
526 lwan_format_rfc_time(now, thread->date.date);
527 lwan_format_rfc_time(now + (time_t)thread->lwan->config.expires,
528 thread->date.expires);
529}
530
531__attribute__((cold))
532static bool_Bool send_buffer_without_coro(int fd, const char *buf, size_t buf_len, int flags)
533{
534 size_t total_sent = 0;
535
536 for (int try = 0; try < 10; try++) {
537 size_t to_send = buf_len - total_sent;
538 if (!to_send)
539 return true1;
540
541 ssize_t sent = send(fd, buf + total_sent, to_send, flags);
542 if (sent <= 0) {
543 if (errno(*__errno_location ()) == EINTR4)
544 continue;
545 if (errno(*__errno_location ()) == EAGAIN11)
546 continue;
547 break;
548 }
549
550 total_sent += (size_t)sent;
551 }
552
553 return false0;
554}
555
556__attribute__((cold))
557static bool_Bool send_string_without_coro(int fd, const char *str, int flags)
558{
559 return send_buffer_without_coro(fd, str, strlen(str), flags);
560}
561
562__attribute__((cold)) static void
563send_last_response_without_coro(const struct lwan *l,
564 const struct lwan_connection *conn,
565 enum lwan_http_status status)
566{
567 int fd = lwan_connection_get_fd(l, conn);
568
569 if (conn->flags & CONN_NEEDS_TLS_SETUP) {
570 /* There's nothing that can be done here if a client is expecting a
571 * TLS connection: the TLS handshake requires a coroutine as it
572 * might yield. (In addition, the TLS handshake might allocate
573 * memory, and if you couldn't create a coroutine at this point,
574 * it's unlikely you'd be able to allocate memory for the TLS
575 * context anyway.) */
576 goto shutdown_and_close;
577 }
578
579 if (!send_string_without_coro(fd, "HTTP/1.0 ", MSG_MOREMSG_MORE))
580 goto shutdown_and_close;
581
582 if (!send_string_without_coro(
583 fd, lwan_http_status_as_string_with_code(status), MSG_MOREMSG_MORE))
584 goto shutdown_and_close;
585
586 if (!send_string_without_coro(fd, "\r\nConnection: close", MSG_MOREMSG_MORE))
587 goto shutdown_and_close;
588
589 if (!send_string_without_coro(fd, "\r\nContent-Type: text/html", MSG_MOREMSG_MORE))
590 goto shutdown_and_close;
591
592 if (send_buffer_without_coro(fd, l->headers.value, l->headers.len,
593 MSG_MOREMSG_MORE)) {
594 struct lwan_strbuf buffer;
595
596 lwan_strbuf_init(&buffer);
597 lwan_fill_default_response(&buffer, status);
598
599 send_buffer_without_coro(fd, lwan_strbuf_get_buffer(&buffer),
600 lwan_strbuf_get_length(&buffer), 0);
601
602 lwan_strbuf_free(&buffer);
603 }
604
605shutdown_and_close:
606 shutdown(fd, SHUT_RDWRSHUT_RDWR);
607 close(fd);
608}
609
610static ALWAYS_INLINEinline __attribute__((always_inline)) bool_Bool spawn_coro(struct lwan_connection *conn,
611 struct coro_switcher *switcher,
612 struct timeout_queue *tq)
613{
614 struct lwan_thread *t = conn->thread;
615#if defined(HAVE_MBEDTLS)
616 const enum lwan_connection_flags flags_to_keep = conn->flags & CONN_NEEDS_TLS_SETUP;
617#else
618 const enum lwan_connection_flags flags_to_keep = 0;
619#endif
620
621 assert(!conn->coro)((void) sizeof ((!conn->coro) ? 1 : 0), __extension__ ({ if
(!conn->coro) ; else __assert_fail ("!conn->coro", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 621, __extension__ __PRETTY_FUNCTION__); }))
;
622 assert(!(conn->flags & CONN_ASYNC_AWAIT))((void) sizeof ((!(conn->flags & CONN_ASYNC_AWAIT)) ? 1
: 0), __extension__ ({ if (!(conn->flags & CONN_ASYNC_AWAIT
)) ; else __assert_fail ("!(conn->flags & CONN_ASYNC_AWAIT)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 622, __extension__ __PRETTY_FUNCTION__); }))
;
623 assert(t)((void) sizeof ((t) ? 1 : 0), __extension__ ({ if (t) ; else __assert_fail
("t", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 623, __extension__ __PRETTY_FUNCTION__); }))
;
624 assert((uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads)((void) sizeof (((uintptr_t)t >= (uintptr_t)tq->lwan->
thread.threads) ? 1 : 0), __extension__ ({ if ((uintptr_t)t >=
(uintptr_t)tq->lwan->thread.threads) ; else __assert_fail
("(uintptr_t)t >= (uintptr_t)tq->lwan->thread.threads"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 624, __extension__ __PRETTY_FUNCTION__); }))
;
625 assert((uintptr_t)t <((void) sizeof (((uintptr_t)t < (uintptr_t)(tq->lwan->
thread.threads + tq->lwan->thread.count)) ? 1 : 0), __extension__
({ if ((uintptr_t)t < (uintptr_t)(tq->lwan->thread.
threads + tq->lwan->thread.count)) ; else __assert_fail
("(uintptr_t)t < (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 626, __extension__ __PRETTY_FUNCTION__); }))
626 (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count))((void) sizeof (((uintptr_t)t < (uintptr_t)(tq->lwan->
thread.threads + tq->lwan->thread.count)) ? 1 : 0), __extension__
({ if ((uintptr_t)t < (uintptr_t)(tq->lwan->thread.
threads + tq->lwan->thread.count)) ; else __assert_fail
("(uintptr_t)t < (uintptr_t)(tq->lwan->thread.threads + tq->lwan->thread.count)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 626, __extension__ __PRETTY_FUNCTION__); }))
;
627
628 *conn = (struct lwan_connection){
629 .coro = coro_new(switcher, process_request_coro, conn),
630 .flags = CONN_EVENTS_READ | flags_to_keep,
631 .time_to_expire = tq->current_time + tq->move_to_last_bump,
632 .thread = t,
633 };
634 if (LIKELY(conn->coro)__builtin_expect((!!(conn->coro)), (1))) {
635 timeout_queue_insert(tq, conn);
636 return true1;
637 }
638
639 conn->flags = 0;
640
641 int fd = lwan_connection_get_fd(tq->lwan, conn);
642
643 lwan_status_error("Couldn't spawn coroutine for file descriptor %d", fd)lwan_status_error_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 643, __FUNCTION__, "Couldn't spawn coroutine for file descriptor %d"
, fd)
;
644
645 send_last_response_without_coro(tq->lwan, conn, HTTP_UNAVAILABLE);
646 return false0;
647}
648
649static bool_Bool process_pending_timers(struct timeout_queue *tq,
650 struct lwan_thread *t,
651 int epoll_fd)
652{
653 struct timeout *timeout;
654 bool_Bool should_expire_timers = false0;
655
656 while ((timeout = timeouts_get(t->wheel))) {
657 struct lwan_request *request;
658
659 if (timeout == &tq->timeout) {
660 should_expire_timers = true1;
661 continue;
662 }
663
664 request = 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))
;
665
666 update_epoll_flags(request->fd, request->conn, epoll_fd,
667 CONN_CORO_RESUME);
668 }
669
670 if (should_expire_timers) {
671 timeout_queue_expire_waiting(tq);
672
673 /* tq timeout expires every 1000ms if there are connections, so
674 * update the date cache at this point as well. */
675 update_date_cache(t);
676
677 if (!timeout_queue_empty(tq)) {
678 timeouts_add(t->wheel, &tq->timeout, 1000);
679 return true1;
680 }
681
682 timeouts_del(t->wheel, &tq->timeout);
683 }
684
685 return false0;
686}
687
688static int
689turn_timer_wheel(struct timeout_queue *tq, struct lwan_thread *t, int epoll_fd)
690{
691 const int infinite_timeout = -1;
692 timeout_t wheel_timeout;
693 struct timespec now;
694
695 if (UNLIKELY(clock_gettime(monotonic_clock_id, &now) < 0)__builtin_expect(((clock_gettime(monotonic_clock_id, &now
) < 0)), (0))
)
696 lwan_status_critical("Could not get monotonic time")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 696, __FUNCTION__, "Could not get monotonic time")
;
697
698 timeouts_update(t->wheel,
699 (timeout_t)(now.tv_sec * 1000 + now.tv_nsec / 1000000));
700
701 /* Check if there's an expired timer. */
702 wheel_timeout = timeouts_timeout(t->wheel);
703 if (wheel_timeout > 0) {
704 return (int)wheel_timeout; /* No, but will soon. Wake us up in
705 wheel_timeout ms. */
706 }
707
708 if (UNLIKELY((int64_t)wheel_timeout < 0)__builtin_expect((((int64_t)wheel_timeout < 0)), (0)))
709 return infinite_timeout; /* None found. */
710
711 if (!process_pending_timers(tq, t, epoll_fd))
712 return infinite_timeout; /* No more timers to process. */
713
714 /* After processing pending timers, determine when to wake up. */
715 return (int)timeouts_timeout(t->wheel);
716}
717
718static bool_Bool accept_waiting_clients(const struct lwan_thread *t,
719 const struct lwan_connection *listen_socket)
720{
721 const uint32_t read_events = conn_flags_to_epoll_events(CONN_EVENTS_READ);
722 struct lwan_connection *conns = t->lwan->conns;
723 int listen_fd = (int)(intptr_t)(listen_socket - conns);
724
725 while (true1) {
726 int fd = accept4(listen_fd, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC);
727
728 if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) {
729 struct lwan_connection *conn = &conns[fd];
730 struct epoll_event ev = {.data.ptr = conn, .events = read_events};
731 int r = epoll_ctl(conn->thread->epoll_fd, EPOLL_CTL_ADD1, fd, &ev);
732
733 if (UNLIKELY(r < 0)__builtin_expect(((r < 0)), (0))) {
734 lwan_status_perror("Could not add file descriptor %d to epoll "lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 736, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
735 "set %d. Dropping connection",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 736, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
736 fd, conn->thread->epoll_fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 736, __FUNCTION__, "Could not add file descriptor %d to epoll "
"set %d. Dropping connection", fd, conn->thread->epoll_fd
)
;
737
738 send_last_response_without_coro(t->lwan, conn, HTTP_UNAVAILABLE);
739#if defined(HAVE_MBEDTLS)
740 } else if (listen_socket->flags & CONN_LISTENER_HTTPS) {
741 assert(listen_fd == t->tls_listen_fd)((void) sizeof ((listen_fd == t->tls_listen_fd) ? 1 : 0), __extension__
({ if (listen_fd == t->tls_listen_fd) ; else __assert_fail
("listen_fd == t->tls_listen_fd", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 741, __extension__ __PRETTY_FUNCTION__); }))
;
742 assert(!(listen_socket->flags & CONN_LISTENER_HTTP))((void) sizeof ((!(listen_socket->flags & CONN_LISTENER_HTTP
)) ? 1 : 0), __extension__ ({ if (!(listen_socket->flags &
CONN_LISTENER_HTTP)) ; else __assert_fail ("!(listen_socket->flags & CONN_LISTENER_HTTP)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 742, __extension__ __PRETTY_FUNCTION__); }))
;
743 conn->flags = CONN_NEEDS_TLS_SETUP;
744 } else {
745 assert(listen_fd == t->listen_fd)((void) sizeof ((listen_fd == t->listen_fd) ? 1 : 0), __extension__
({ if (listen_fd == t->listen_fd) ; else __assert_fail ("listen_fd == t->listen_fd"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 745, __extension__ __PRETTY_FUNCTION__); }))
;
746 assert(listen_socket->flags & CONN_LISTENER_HTTP)((void) sizeof ((listen_socket->flags & CONN_LISTENER_HTTP
) ? 1 : 0), __extension__ ({ if (listen_socket->flags &
CONN_LISTENER_HTTP) ; else __assert_fail ("listen_socket->flags & CONN_LISTENER_HTTP"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 746, __extension__ __PRETTY_FUNCTION__); }))
;
747#endif
748 }
749 continue;
750 }
751
752 switch (errno(*__errno_location ())) {
753 default:
754 lwan_status_perror("Unexpected error while accepting connections")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 754, __FUNCTION__, "Unexpected error while accepting connections"
)
;
755 /* fallthrough */
756
757 case EAGAIN11:
758 return true1;
759
760 case EBADF9:
761 case ECONNABORTED103:
762 case EINVAL22:
763 lwan_status_info("Listening socket closed")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 763, __FUNCTION__, "Listening socket closed")
;
764 return false0;
765 }
766 }
767
768 __builtin_unreachable();
769}
770
771static int create_listen_socket(struct lwan_thread *t,
772 unsigned int num,
773 bool_Bool tls)
774{
775 const struct lwan *lwan = t->lwan;
776 int listen_fd;
777
778 listen_fd = lwan_create_listen_socket(lwan, num == 0, tls);
779 if (listen_fd < 0)
780 lwan_status_critical("Could not create listen_fd")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 780, __FUNCTION__, "Could not create listen_fd")
;
781
782 /* Ignore errors here, as this is just a hint */
783#if defined(HAVE_SO_ATTACH_REUSEPORT_CBPF)
784 /* From socket(7): "These options may be set repeatedly at any time on
785 * any socket in the group to replace the current BPF program used by
786 * all sockets in the group." */
787 if (num == 0) {
788 /* From socket(7): "The BPF program must return an index between 0 and
789 * N-1 representing the socket which should receive the packet (where N
790 * is the number of sockets in the group)." */
791 const uint32_t cpu_ad_off = (uint32_t)SKF_AD_OFF(-0x1000) + SKF_AD_CPU36;
792 struct sock_filter filter[] = {
793 {BPF_LD0x00 | BPF_W0x00 | BPF_ABS0x20, 0, 0, cpu_ad_off}, /* A = curr_cpu_index */
794 {BPF_RET0x06 | BPF_A0x10, 0, 0, 0}, /* return A */
795 };
796 struct sock_fprog fprog = {.filter = filter, .len = N_ELEMENTS(filter)((!sizeof(char[1 - 2 * __builtin_types_compatible_p( __typeof__
(filter), __typeof__(&(filter)[0]))])) | sizeof(filter) /
sizeof(filter[0]))
};
797
798 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_ATTACH_REUSEPORT_CBPF51,
799 &fprog, sizeof(fprog));
800 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_LOCK_FILTER44,
801 (int[]){1}, sizeof(int));
802 }
803#elif defined(HAVE_SO_INCOMING_CPU) && defined(__x86_64__1)
804 (void)setsockopt(listen_fd, SOL_SOCKET1, SO_INCOMING_CPU49, &t->cpu,
805 sizeof(t->cpu));
806#endif
807
808 struct epoll_event event = {
809 .events = EPOLLINEPOLLIN | EPOLLETEPOLLET | EPOLLERREPOLLERR,
810 .data.ptr = &t->lwan->conns[listen_fd],
811 };
812 if (epoll_ctl(t->epoll_fd, EPOLL_CTL_ADD1, listen_fd, &event) < 0)
813 lwan_status_critical_perror("Could not add socket to epoll")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 813, __FUNCTION__, "Could not add socket to epoll")
;
814
815 return listen_fd;
816}
817
818static void *thread_io_loop(void *data)
819{
820 struct lwan_thread *t = data;
821 int epoll_fd = t->epoll_fd;
822 const int max_events = LWAN_MIN((int)t->lwan->thread.max_fd, 1024)({ const __typeof__(((int)t->lwan->thread.max_fd) + 0) lwan_tmp_id6
= ((int)t->lwan->thread.max_fd); const __typeof__((1024
) + 0) lwan_tmp_id7 = (1024); lwan_tmp_id6 > lwan_tmp_id7 ?
lwan_tmp_id7 : lwan_tmp_id6; })
;
823 struct lwan *lwan = t->lwan;
824 struct epoll_event *events;
825 struct coro_switcher switcher;
826 struct timeout_queue tq;
827
828 lwan_status_debug("Worker thread #%zd starting",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 829, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
829 t - t->lwan->thread.threads + 1)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 829, __FUNCTION__, "Worker thread #%zd starting", t - t->
lwan->thread.threads + 1)
;
830 lwan_set_thread_name("worker");
831
832 events = calloc((size_t)max_events, sizeof(*events));
833 if (UNLIKELY(!events)__builtin_expect(((!events)), (0)))
834 lwan_status_critical("Could not allocate memory for events")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 834, __FUNCTION__, "Could not allocate memory for events")
;
835
836 update_date_cache(t);
837
838 timeout_queue_init(&tq, lwan);
839
840 lwan_random_seed_prng_for_thread(t);
841
842 pthread_barrier_wait(&lwan->thread.barrier);
843
844 for (;;) {
845 int timeout = turn_timer_wheel(&tq, t, epoll_fd);
846 int n_fds = epoll_wait(epoll_fd, events, max_events, timeout);
847 bool_Bool accepted_connections = false0;
848
849 if (UNLIKELY(n_fds < 0)__builtin_expect(((n_fds < 0)), (0))) {
850 if (errno(*__errno_location ()) == EBADF9 || errno(*__errno_location ()) == EINVAL22)
851 break;
852 continue;
853 }
854
855 for (struct epoll_event *event = events; n_fds--; event++) {
856 struct lwan_connection *conn = event->data.ptr;
857
858 if (UNLIKELY(event->events & (EPOLLRDHUP | EPOLLHUP))__builtin_expect(((event->events & (EPOLLRDHUP | EPOLLHUP
))), (0))
) {
859 timeout_queue_expire(&tq, conn);
860 continue;
861 }
862
863 if (conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)) {
864 if (LIKELY(accept_waiting_clients(t, conn))__builtin_expect((!!(accept_waiting_clients(t, conn))), (1))) {
865 accepted_connections = true1;
866 continue;
867 }
868 close(epoll_fd);
869 epoll_fd = -1;
870 break;
871 }
872
873 if (!conn->coro) {
874 if (UNLIKELY(!spawn_coro(conn, &switcher, &tq))__builtin_expect(((!spawn_coro(conn, &switcher, &tq))
), (0))
) {
875 send_last_response_without_coro(t->lwan, conn, HTTP_INTERNAL_ERROR);
876 continue;
877 }
878 }
879
880 resume_coro(&tq, conn, epoll_fd);
881 timeout_queue_move_to_last(&tq, conn);
882 }
883
884 if (accepted_connections)
885 timeouts_add(t->wheel, &tq.timeout, 1000);
886 }
887
888 pthread_barrier_wait(&lwan->thread.barrier);
889
890 timeout_queue_expire_all(&tq);
891 free(events);
892
893 return NULL((void*)0);
894}
895
896static void create_thread(struct lwan *l, struct lwan_thread *thread)
897{
898 int ignore;
899 pthread_attr_t attr;
900
901 thread->lwan = l;
902
903 thread->wheel = timeouts_open(&ignore);
904 if (!thread->wheel)
905 lwan_status_critical("Could not create timer wheel")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 905, __FUNCTION__, "Could not create timer wheel")
;
906
907 if ((thread->epoll_fd = epoll_create1(EPOLL_CLOEXECEPOLL_CLOEXEC)) < 0)
908 lwan_status_critical_perror("epoll_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 908, __FUNCTION__, "epoll_create")
;
909
910 if (pthread_attr_init(&attr))
911 lwan_status_critical_perror("pthread_attr_init")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 911, __FUNCTION__, "pthread_attr_init")
;
912
913 if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEMPTHREAD_SCOPE_SYSTEM))
914 lwan_status_critical_perror("pthread_attr_setscope")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 914, __FUNCTION__, "pthread_attr_setscope")
;
915
916 if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLEPTHREAD_CREATE_JOINABLE))
917 lwan_status_critical_perror("pthread_attr_setdetachstate")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 917, __FUNCTION__, "pthread_attr_setdetachstate")
;
918
919 if (pthread_create(&thread->self, &attr, thread_io_loop, thread))
920 lwan_status_critical_perror("pthread_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 920, __FUNCTION__, "pthread_create")
;
921
922 if (pthread_attr_destroy(&attr))
923 lwan_status_critical_perror("pthread_attr_destroy")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 923, __FUNCTION__, "pthread_attr_destroy")
;
924}
925
926#if defined(__linux__1) && defined(__x86_64__1)
927static bool_Bool read_cpu_topology(struct lwan *l, uint32_t siblings[])
928{
929 char path[PATH_MAX4096];
930
931 for (uint32_t i = 0; i < l->available_cpus; i++)
932 siblings[i] = 0xbebacafe;
933
934 for (unsigned int i = 0; i < l->available_cpus; i++) {
935 FILE *sib;
936 uint32_t id, sibling;
937 char separator;
938
939 snprintf(path, sizeof(path),
940 "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list",
941 i);
942
943 sib = fopen(path, "re");
944 if (!sib) {
945 lwan_status_warning("Could not open `%s` to determine CPU topology",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 946, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
946 path)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 946, __FUNCTION__, "Could not open `%s` to determine CPU topology"
, path)
;
947 return false0;
948 }
949
950 switch (fscanf(sib, "%u%c%u", &id, &separator, &sibling)) {
951 case 2: /* No SMT */
952 siblings[i] = id;
953 break;
954 case 3: /* SMT */
955 if (!(separator == ',' || separator == '-')) {
956 lwan_status_critical("Expecting either ',' or '-' for sibling separator")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 956, __FUNCTION__, "Expecting either ',' or '-' for sibling separator"
)
;
957 __builtin_unreachable();
958 }
959
960 siblings[i] = sibling;
961 break;
962 default:
963 lwan_status_critical("%s has invalid format", path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 963, __FUNCTION__, "%s has invalid format", path)
;
964 __builtin_unreachable();
965 }
966
967 fclose(sib);
968 }
969
970 /* Perform a sanity check here, as some systems seem to filter out the
971 * result of sysconf() to obtain the number of configured and online
972 * CPUs but don't bother changing what's available through sysfs as far
973 * as the CPU topology information goes. It's better to fall back to a
974 * possibly non-optimal setup than just crash during startup while
975 * trying to perform an out-of-bounds array access. */
976 for (unsigned int i = 0; i < l->available_cpus; i++) {
977 if (siblings[i] == 0xbebacafe) {
978 lwan_status_warning("Could not determine sibling for CPU %d", i)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 978, __FUNCTION__, "Could not determine sibling for CPU %d"
, i)
;
979 return false0;
980 }
981
982 if (siblings[i] >= l->available_cpus) {
983 lwan_status_warning("CPU information topology says CPU %d exists, "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 986, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
984 "but max available CPUs is %d (online CPUs: %d). "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 986, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
985 "Is Lwan running in a (broken) container?",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 986, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
986 siblings[i], l->available_cpus, l->online_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 986, __FUNCTION__, "CPU information topology says CPU %d exists, "
"but max available CPUs is %d (online CPUs: %d). " "Is Lwan running in a (broken) container?"
, siblings[i], l->available_cpus, l->online_cpus)
;
987 return false0;
988 }
989 }
990
991 return true1;
992}
993
994static void
995siblings_to_schedtbl(struct lwan *l, uint32_t siblings[], uint32_t schedtbl[])
996{
997 int *seen = alloca(l->available_cpus * sizeof(int))__builtin_alloca (l->available_cpus * sizeof(int));
998 unsigned int n_schedtbl = 0;
999
1000 for (uint32_t i = 0; i < l->available_cpus; i++)
1001 seen[i] = -1;
1002
1003 for (uint32_t i = 0; i < l->available_cpus; i++) {
1004 if (seen[siblings[i]] < 0) {
1005 seen[siblings[i]] = (int)i;
1006 } else {
1007 schedtbl[n_schedtbl++] = (uint32_t)seen[siblings[i]];
1008 schedtbl[n_schedtbl++] = i;
1009 }
1010 }
1011
1012 if (n_schedtbl != l->available_cpus)
1013 memcpy(schedtbl, seen, l->available_cpus * sizeof(int));
1014}
1015
1016static bool_Bool
1017topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads)
1018{
1019 uint32_t *siblings = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
1020
1021 if (read_cpu_topology(l, siblings)) {
8
Assuming the condition is false
9
Taking false branch
1022 uint32_t *affinity = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t));
1023
1024 siblings_to_schedtbl(l, siblings, affinity);
1025
1026 for (uint32_t i = 0; i < n_threads; i++)
1027 schedtbl[i] = affinity[i % l->available_cpus];
1028 return true1;
1029 }
1030
1031 for (uint32_t i = 0; i < n_threads; i++)
10
Assuming 'i' is >= 'n_threads'
11
Loop condition is false. Execution continues on line 1033
1032 schedtbl[i] = (i / 2) % l->thread.count;
1033 return false0;
12
Returning without writing to '*schedtbl'
1034}
1035
1036static void
1037adjust_thread_affinity(const struct lwan_thread *thread)
1038{
1039 cpu_set_t set;
1040
1041 CPU_ZERO(&set)do __builtin_memset (&set, '\0', sizeof (cpu_set_t)); while
(0)
;
1042 CPU_SET(thread->cpu, &set)(__extension__ ({ size_t __cpu = (thread->cpu); __cpu / 8 <
(sizeof (cpu_set_t)) ? (((__cpu_mask *) ((&set)->__bits
))[((__cpu) / (8 * sizeof (__cpu_mask)))] |= ((__cpu_mask) 1 <<
((__cpu) % (8 * sizeof (__cpu_mask))))) : 0; }))
;
1043
1044 if (pthread_setaffinity_np(thread->self, sizeof(set), &set))
1045 lwan_status_warning("Could not set thread affinity")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1045, __FUNCTION__, "Could not set thread affinity")
;
1046}
1047#endif
1048
1049#if defined(HAVE_MBEDTLS)
1050static bool_Bool is_tls_ulp_supported(void)
1051{
1052 FILE *available_ulp = fopen("/proc/sys/net/ipv4/tcp_available_ulp", "re");
1053 char buffer[512];
1054 bool_Bool available = false0;
1055
1056 if (!available_ulp)
1057 return false0;
1058
1059 if (fgets(buffer, 512, available_ulp)) {
1060 if (strstr(buffer, "tls"))
1061 available = true1;
1062 }
1063
1064 fclose(available_ulp);
1065 return available;
1066}
1067
1068static bool_Bool lwan_init_tls(struct lwan *l)
1069{
1070 static const int aes128_ciphers[] = {
1071 /* Only allow Ephemeral Diffie-Hellman key exchange, so Perfect
1072 * Forward Secrecy is possible. */
1073 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA2560xC02F,
1074 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA2560xC02B,
1075 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA2560x9E,
1076 MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA2560xAA,
1077
1078 /* FIXME: Other ciphers are supported by kTLS, notably AES256 and
1079 * ChaCha20-Poly1305. Add those here and patch
1080 * lwan_setup_tls_keys() to match. */
1081
1082 /* FIXME: Maybe allow this to be user-tunable like other servers do? */
1083 0,
1084 };
1085 int r;
1086
1087 if (!l->config.ssl.cert || !l->config.ssl.key)
1088 return false0;
1089
1090 if (!is_tls_ulp_supported())
1091 lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1092, __FUNCTION__, "TLS ULP not loaded. Try running `modprobe tls` as root."
)
1092 "TLS ULP not loaded. Try running `modprobe tls` as root.")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1092, __FUNCTION__, "TLS ULP not loaded. Try running `modprobe tls` as root."
)
;
1093
1094 l->tls = calloc(1, sizeof(*l->tls));
1095 if (!l->tls)
1096 lwan_status_critical("Could not allocate memory for SSL context")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1096, __FUNCTION__, "Could not allocate memory for SSL context"
)
;
1097
1098 lwan_status_debug("Initializing mbedTLS")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1098, __FUNCTION__, "Initializing mbedTLS")
;
1099
1100 mbedtls_ssl_config_init(&l->tls->config);
1101 mbedtls_x509_crt_init(&l->tls->server_cert);
1102 mbedtls_pk_init(&l->tls->server_key);
1103 mbedtls_entropy_init(&l->tls->entropy);
1104 mbedtls_ctr_drbg_init(&l->tls->ctr_drbg);
1105
1106 r = mbedtls_x509_crt_parse_file(&l->tls->server_cert, l->config.ssl.cert);
1107 if (r) {
1108 lwan_status_mbedtls_error(r, "Could not parse certificate at %s",
1109 l->config.ssl.cert);
1110 abort();
1111 }
1112
1113 r = mbedtls_pk_parse_keyfile(&l->tls->server_key, l->config.ssl.key, NULL((void*)0));
1114 if (r) {
1115 lwan_status_mbedtls_error(r, "Could not parse key file at %s",
1116 l->config.ssl.key);
1117 abort();
1118 }
1119
1120 /* Even though this points to files that will probably be outside
1121 * the reach of the server (if straightjackets are used), wipe this
1122 * struct to get rid of the paths to these files. */
1123 lwan_always_bzero(l->config.ssl.cert, strlen(l->config.ssl.cert));
1124 free(l->config.ssl.cert);
1125 lwan_always_bzero(l->config.ssl.key, strlen(l->config.ssl.key));
1126 free(l->config.ssl.key);
1127 lwan_always_bzero(&l->config.ssl, sizeof(l->config.ssl));
1128
1129 mbedtls_ssl_conf_ca_chain(&l->tls->config, l->tls->server_cert.next, NULL((void*)0));
1130 r = mbedtls_ssl_conf_own_cert(&l->tls->config, &l->tls->server_cert,
1131 &l->tls->server_key);
1132 if (r) {
1133 lwan_status_mbedtls_error(r, "Could not set cert/key");
1134 abort();
1135 }
1136
1137 r = mbedtls_ctr_drbg_seed(&l->tls->ctr_drbg, mbedtls_entropy_func,
1138 &l->tls->entropy, NULL((void*)0), 0);
1139 if (r) {
1140 lwan_status_mbedtls_error(r, "Could not seed ctr_drbg");
1141 abort();
1142 }
1143
1144 r = mbedtls_ssl_config_defaults(&l->tls->config, MBEDTLS_SSL_IS_SERVER1,
1145 MBEDTLS_SSL_TRANSPORT_STREAM0,
1146 MBEDTLS_SSL_PRESET_DEFAULT0);
1147 if (r) {
1148 lwan_status_mbedtls_error(r, "Could not set mbedTLS default config");
1149 abort();
1150 }
1151
1152 mbedtls_ssl_conf_rng(&l->tls->config, mbedtls_ctr_drbg_random,
1153 &l->tls->ctr_drbg);
1154 mbedtls_ssl_conf_ciphersuites(&l->tls->config, aes128_ciphers);
1155
1156 mbedtls_ssl_conf_renegotiation(&l->tls->config,
1157 MBEDTLS_SSL_RENEGOTIATION_DISABLED0);
1158 mbedtls_ssl_conf_legacy_renegotiation(&l->tls->config,
1159 MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION0);
1160
1161#if defined(MBEDTLS_SSL_ALPN)
1162 static const char *alpn_protos[] = {"http/1.1", NULL((void*)0)};
1163 mbedtls_ssl_conf_alpn_protocols(&l->tls->config, alpn_protos);
1164#endif
1165
1166 return true1;
1167}
1168#endif
1169
1170void lwan_thread_init(struct lwan *l)
1171{
1172 const unsigned int total_conns = l->thread.max_fd * l->thread.count;
1173#if defined(HAVE_MBEDTLS)
1174 const bool_Bool tls_initialized = lwan_init_tls(l);
1175#else
1176 const bool_Bool tls_initialized = false0;
1177#endif
1178
1179 lwan_status_debug("Initializing threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1179, __FUNCTION__, "Initializing threads")
;
1180
1181 l->thread.threads =
1182 calloc((size_t)l->thread.count, sizeof(struct lwan_thread));
1183 if (!l->thread.threads)
1
Assuming field 'threads' is non-null
2
Taking false branch
1184 lwan_status_critical("Could not allocate memory for threads")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1184, __FUNCTION__, "Could not allocate memory for threads"
)
;
1185
1186 uint32_t *schedtbl;
1187 uint32_t n_threads;
1188 bool_Bool adj_affinity;
1189
1190#if defined(__x86_64__1) && defined(__linux__1)
1191 if (l->online_cpus > 1) {
3
Assuming field 'online_cpus' is > 1
4
Taking true branch
1192 static_assert(sizeof(struct lwan_connection) == 32,extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(struct lwan_connection) ==
32) ? 2 : -1; })]
1193 "Two connections per cache line")extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(struct lwan_connection) ==
32) ? 2 : -1; })]
;
1194#ifdef _SC_LEVEL1_DCACHE_LINESIZE_SC_LEVEL1_DCACHE_LINESIZE
1195 assert(sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64)((void) sizeof ((sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64) ?
1 : 0), __extension__ ({ if (sysconf(_SC_LEVEL1_DCACHE_LINESIZE
) == 64) ; else __assert_fail ("sysconf(_SC_LEVEL1_DCACHE_LINESIZE) == 64"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1195, __extension__ __PRETTY_FUNCTION__); }))
;
5
Assuming the condition is true
6
Taking true branch
1196#endif
1197 lwan_status_debug("%d CPUs of %d are online. "lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1199, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
1198 "Reading topology to pre-schedule clients",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1199, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
1199 l->online_cpus, l->available_cpus)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1199, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients"
, l->online_cpus, l->available_cpus)
;
1200 /*
1201 * Pre-schedule each file descriptor, to reduce some operations in the
1202 * fast path.
1203 *
1204 * Since struct lwan_connection is guaranteed to be 32-byte long, two of
1205 * them can fill up a cache line. Assume siblings share cache lines and
1206 * use the CPU topology to group two connections per cache line in such
1207 * a way that false sharing is avoided.
1208 */
1209 n_threads = (uint32_t)lwan_nextpow2((size_t)((l->thread.count - 1) * 2));
1210 schedtbl = alloca(n_threads * sizeof(uint32_t))__builtin_alloca (n_threads * sizeof(uint32_t));
1211
1212 adj_affinity = topology_to_schedtbl(l, schedtbl, n_threads);
7
Calling 'topology_to_schedtbl'
13
Returning from 'topology_to_schedtbl'
1213
1214 n_threads--; /* Transform count into mask for AND below */
1215
1216 for (unsigned int i = 0; i < total_conns; i++)
14
Assuming 'i' is >= 'total_conns'
15
Loop condition is false. Execution continues on line 1233
1217 l->conns[i].thread = &l->thread.threads[schedtbl[i & n_threads]];
1218 } else
1219#endif /* __x86_64__ && __linux__ */
1220 {
1221 lwan_status_debug("Using round-robin to preschedule clients")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1221, __FUNCTION__, "Using round-robin to preschedule clients"
)
;
1222
1223 for (unsigned int i = 0; i < l->thread.count; i++)
1224 l->thread.threads[i].cpu = i % l->online_cpus;
1225 for (unsigned int i = 0; i < total_conns; i++)
1226 l->conns[i].thread = &l->thread.threads[i % l->thread.count];
1227
1228 schedtbl = NULL((void*)0);
1229 adj_affinity = false0;
1230 n_threads = l->thread.count;
1231 }
1232
1233 for (unsigned int i = 0; i < l->thread.count; i++) {
16
Assuming 'i' is < field 'count'
17
Loop condition is true. Entering loop body
1234 struct lwan_thread *thread = NULL((void*)0);
1235
1236 if (schedtbl
17.1
'schedtbl' is non-null
) {
18
Taking true branch
1237 /* This is not the most elegant thing, but this assures that the
1238 * listening sockets are added to the SO_REUSEPORT group in a
1239 * specific order, because that's what the CBPF program to direct
1240 * the incoming connection to the right CPU will use. */
1241 for (uint32_t thread_id = 0; thread_id
18.1
'thread_id' is < field 'count'
< l->thread.count;
19
Loop condition is true. Entering loop body
1242 thread_id++) {
1243 if (schedtbl[thread_id & n_threads] == i) {
20
The left operand of '==' is a garbage value
1244 thread = &l->thread.threads[thread_id];
1245 break;
1246 }
1247 }
1248 if (!thread) {
1249 /* FIXME: can this happen when we have a offline CPU? */
1250 lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1251, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
1251 "Could not figure out which CPU thread %d should go to", i)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1251, __FUNCTION__, "Could not figure out which CPU thread %d should go to"
, i)
;
1252 }
1253 } else {
1254 thread = &l->thread.threads[i % l->thread.count];
1255 }
1256
1257 if (pthread_barrier_init(&l->thread.barrier, NULL((void*)0), 2))
1258 lwan_status_critical("Could not create barrier")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1258, __FUNCTION__, "Could not create barrier")
;
1259
1260 create_thread(l, thread);
1261
1262 if ((thread->listen_fd = create_listen_socket(thread, i, false0)) < 0)
1263 lwan_status_critical_perror("Could not create listening socket")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1263, __FUNCTION__, "Could not create listening socket")
;
1264 l->conns[thread->listen_fd].flags |= CONN_LISTENER_HTTP;
1265
1266 if (tls_initialized) {
1267 if ((thread->tls_listen_fd = create_listen_socket(thread, i, true1)) < 0)
1268 lwan_status_critical_perror("Could not create TLS listening socket")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1268, __FUNCTION__, "Could not create TLS listening socket"
)
;
1269 l->conns[thread->tls_listen_fd].flags |= CONN_LISTENER_HTTPS;
1270 } else {
1271 thread->tls_listen_fd = -1;
1272 }
1273
1274 if (adj_affinity) {
1275 l->thread.threads[i].cpu = schedtbl[i & n_threads];
1276 adjust_thread_affinity(thread);
1277 }
1278
1279 pthread_barrier_wait(&l->thread.barrier);
1280 }
1281
1282 lwan_status_debug("Worker threads created and ready to serve")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1282, __FUNCTION__, "Worker threads created and ready to serve"
)
;
1283}
1284
1285void lwan_thread_shutdown(struct lwan *l)
1286{
1287 lwan_status_debug("Shutting down threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c"
, 1287, __FUNCTION__, "Shutting down threads")
;
1288
1289 for (unsigned int i = 0; i < l->thread.count; i++) {
1290 struct lwan_thread *t = &l->thread.threads[i];
1291 int epoll_fd = t->epoll_fd;
1292 int listen_fd = t->listen_fd;
1293
1294 t->listen_fd = -1;
1295 t->epoll_fd = -1;
1296 close(epoll_fd);
1297 close(listen_fd);
1298 }
1299
1300 pthread_barrier_wait(&l->thread.barrier);
1301 pthread_barrier_destroy(&l->thread.barrier);
1302
1303 for (unsigned int i = 0; i < l->thread.count; i++) {
1304 struct lwan_thread *t = &l->thread.threads[i];
1305
1306 pthread_join(l->thread.threads[i].self, NULL((void*)0));
1307 timeouts_close(t->wheel);
1308 }
1309
1310 free(l->thread.threads);
1311
1312#if defined(HAVE_MBEDTLS)
1313 if (l->tls) {
1314 mbedtls_ssl_config_free(&l->tls->config);
1315 mbedtls_x509_crt_free(&l->tls->server_cert);
1316 mbedtls_pk_free(&l->tls->server_key);
1317 mbedtls_entropy_free(&l->tls->entropy);
1318 mbedtls_ctr_drbg_free(&l->tls->ctr_drbg);
1319 free(l->tls);
1320 }
1321#endif
1322}