Bug Summary

File:lwan-thread.c
Warning:line 1366, column 40
Array access (from variable 'schedtbl') results in a null pointer dereference

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