File: | lib/lwan-thread.c |
Warning: | line 1294, column 35 Array subscript is undefined |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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(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 | ||||
54 | static void lwan_strbuf_free_defer(void *data) | |||
55 | { | |||
56 | return lwan_strbuf_free((struct lwan_strbuf *)data); | |||
57 | } | |||
58 | ||||
59 | static 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) | |||
109 | static void lwan_random_seed_prng_for_thread(const struct lwan_thread *t) | |||
110 | { | |||
111 | (void)t; | |||
112 | } | |||
113 | ||||
114 | uint64_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 | |||
121 | static __thread __uint128_t lehmer64_state; | |||
122 | ||||
123 | static 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 | ||||
133 | uint64_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 | ||||
141 | uint64_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) | |||
152 | static bool_Bool | |||
153 | lwan_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)) | |||
200 | static 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 | ||||
218 | static void lwan_setup_tls_free_ssl_context(void *data) | |||
219 | { | |||
220 | mbedtls_ssl_context *ssl = data; | |||
221 | ||||
222 | mbedtls_ssl_free(ssl); | |||
223 | } | |||
224 | ||||
225 | struct lwan_mbedtls_handshake_ctx { | |||
226 | int fd; | |||
227 | bool_Bool last_was_send; | |||
228 | }; | |||
229 | ||||
230 | static 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 | ||||
262 | static void flush_pending_output(int fd) | |||
263 | { | |||
264 | int zero = 0; | |||
265 | setsockopt(fd, SOL_TCP6, TCP_CORK3, &zero, sizeof(zero)); | |||
266 | } | |||
267 | ||||
268 | static 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 | ||||
296 | static 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 | struct coro_defer *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 | ||||
346 | enable_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 | ||||
356 | fail: | |||
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 | ||||
447 | static ALWAYS_INLINEinline __attribute__((always_inline)) uint32_t | |||
448 | conn_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 | ||||
460 | static 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 | ||||
516 | static 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 | ||||
523 | static enum lwan_connection_coro_yield | |||
524 | resume_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 | ||||
568 | static 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 | ||||
590 | static 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)) | |||
600 | static 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)) | |||
625 | static 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 | |||
631 | send_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 | ||||
673 | shutdown_and_close: | |||
674 | shutdown(fd, SHUT_RDWRSHUT_RDWR); | |||
675 | close(fd); | |||
676 | } | |||
677 | ||||
678 | static 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(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" , 691, __extension__ __PRETTY_FUNCTION__); })); | |||
692 | 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" , 692, __extension__ __PRETTY_FUNCTION__); })); | |||
693 | 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" , 694, __extension__ __PRETTY_FUNCTION__); })) | |||
694 | (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" , 694, __extension__ __PRETTY_FUNCTION__); })); | |||
695 | ||||
696 | *conn = (struct lwan_connection){ | |||
697 | .coro = coro_new(switcher, process_request_coro, conn), | |||
698 | .flags = CONN_EVENTS_READ | flags_to_keep, | |||
699 | .time_to_expire = tq->current_time + tq->move_to_last_bump, | |||
700 | .thread = t, | |||
701 | }; | |||
702 | if (LIKELY(conn->coro)__builtin_expect((!!(conn->coro)), (1))) { | |||
703 | timeout_queue_insert(tq, conn); | |||
704 | return true1; | |||
705 | } | |||
706 | ||||
707 | conn->flags = 0; | |||
708 | ||||
709 | int fd = lwan_connection_get_fd(tq->lwan, conn); | |||
710 | ||||
711 | 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" , 711, __FUNCTION__, "Couldn't spawn coroutine for file descriptor %d" , fd); | |||
712 | ||||
713 | send_last_response_without_coro(tq->lwan, conn, HTTP_UNAVAILABLE); | |||
714 | return false0; | |||
715 | } | |||
716 | ||||
717 | static bool_Bool process_pending_timers(struct timeout_queue *tq, | |||
718 | struct lwan_thread *t, | |||
719 | int epoll_fd) | |||
720 | { | |||
721 | struct timeout *timeout; | |||
722 | bool_Bool should_expire_timers = false0; | |||
723 | ||||
724 | while ((timeout = timeouts_get(t->wheel))) { | |||
725 | struct lwan_request *request; | |||
726 | ||||
727 | if (timeout == &tq->timeout) { | |||
728 | should_expire_timers = true1; | |||
729 | continue; | |||
730 | } | |||
731 | ||||
732 | 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)); | |||
733 | update_epoll_flags(tq, request->conn, epoll_fd, CONN_CORO_RESUME); | |||
734 | } | |||
735 | ||||
736 | if (should_expire_timers) { | |||
737 | timeout_queue_expire_waiting(tq); | |||
738 | ||||
739 | /* tq timeout expires every 1000ms if there are connections, so | |||
740 | * update the date cache at this point as well. */ | |||
741 | update_date_cache(t); | |||
742 | ||||
743 | if (!timeout_queue_empty(tq)) { | |||
744 | timeouts_add(t->wheel, &tq->timeout, 1000); | |||
745 | return true1; | |||
746 | } | |||
747 | ||||
748 | timeouts_del(t->wheel, &tq->timeout); | |||
749 | } | |||
750 | ||||
751 | return false0; | |||
752 | } | |||
753 | ||||
754 | static int | |||
755 | turn_timer_wheel(struct timeout_queue *tq, struct lwan_thread *t, int epoll_fd) | |||
756 | { | |||
757 | const int infinite_timeout = -1; | |||
758 | timeout_t wheel_timeout; | |||
759 | struct timespec now; | |||
760 | ||||
761 | if (UNLIKELY(clock_gettime(monotonic_clock_id, &now) < 0)__builtin_expect(((clock_gettime(monotonic_clock_id, &now ) < 0)), (0))) | |||
762 | lwan_status_critical("Could not get monotonic time")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 762, __FUNCTION__, "Could not get monotonic time"); | |||
763 | ||||
764 | timeouts_update(t->wheel, | |||
765 | (timeout_t)(now.tv_sec * 1000 + now.tv_nsec / 1000000)); | |||
766 | ||||
767 | /* Check if there's an expired timer. */ | |||
768 | wheel_timeout = timeouts_timeout(t->wheel); | |||
769 | if (wheel_timeout > 0) { | |||
770 | return (int)wheel_timeout; /* No, but will soon. Wake us up in | |||
771 | wheel_timeout ms. */ | |||
772 | } | |||
773 | ||||
774 | if (UNLIKELY((int64_t)wheel_timeout < 0)__builtin_expect((((int64_t)wheel_timeout < 0)), (0))) | |||
775 | return infinite_timeout; /* None found. */ | |||
776 | ||||
777 | if (!process_pending_timers(tq, t, epoll_fd)) | |||
778 | return infinite_timeout; /* No more timers to process. */ | |||
779 | ||||
780 | /* After processing pending timers, determine when to wake up. */ | |||
781 | return (int)timeouts_timeout(t->wheel); | |||
782 | } | |||
783 | ||||
784 | static bool_Bool accept_waiting_clients(const struct lwan_thread *t, | |||
785 | const struct lwan_connection *listen_socket) | |||
786 | { | |||
787 | const uint32_t read_events = conn_flags_to_epoll_events(CONN_EVENTS_READ); | |||
788 | struct lwan_connection *conns = t->lwan->conns; | |||
789 | int listen_fd = (int)(intptr_t)(listen_socket - conns); | |||
790 | enum lwan_connection_flags new_conn_flags = 0; | |||
791 | ||||
792 | #if defined(LWAN_HAVE_MBEDTLS) | |||
793 | if (listen_socket->flags & CONN_LISTENER_HTTPS) { | |||
794 | 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" , 794, __extension__ __PRETTY_FUNCTION__); })); | |||
795 | 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" , 795, __extension__ __PRETTY_FUNCTION__); })); | |||
796 | new_conn_flags = CONN_TLS; | |||
797 | } else { | |||
798 | 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" , 798, __extension__ __PRETTY_FUNCTION__); })); | |||
799 | 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" , 799, __extension__ __PRETTY_FUNCTION__); })); | |||
800 | } | |||
801 | #endif | |||
802 | ||||
803 | while (true1) { | |||
804 | int fd = accept4(listen_fd, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC); | |||
805 | ||||
806 | if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) { | |||
807 | struct lwan_connection *conn = &conns[fd]; | |||
808 | struct epoll_event ev = {.data.ptr = conn, .events = read_events}; | |||
809 | int r; | |||
810 | ||||
811 | conn->flags = new_conn_flags; | |||
812 | ||||
813 | r = epoll_ctl(conn->thread->epoll_fd, EPOLL_CTL_ADD1, fd, &ev); | |||
814 | if (UNLIKELY(r < 0)__builtin_expect(((r < 0)), (0))) { | |||
815 | 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" , 817, __FUNCTION__, "Could not add file descriptor %d to epoll " "set %d. Dropping connection", fd, conn->thread->epoll_fd ) | |||
816 | "set %d. Dropping connection",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 817, __FUNCTION__, "Could not add file descriptor %d to epoll " "set %d. Dropping connection", fd, conn->thread->epoll_fd ) | |||
817 | fd, conn->thread->epoll_fd)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 817, __FUNCTION__, "Could not add file descriptor %d to epoll " "set %d. Dropping connection", fd, conn->thread->epoll_fd ); | |||
818 | send_last_response_without_coro(t->lwan, conn, HTTP_UNAVAILABLE); | |||
819 | conn->flags = 0; | |||
820 | } | |||
821 | ||||
822 | continue; | |||
823 | } | |||
824 | ||||
825 | switch (errno(*__errno_location ())) { | |||
826 | default: | |||
827 | lwan_status_perror("Unexpected error while accepting connections")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 827, __FUNCTION__, "Unexpected error while accepting connections" ); | |||
828 | /* fallthrough */ | |||
829 | ||||
830 | case EAGAIN11: | |||
831 | return true1; | |||
832 | ||||
833 | case EBADF9: | |||
834 | case ECONNABORTED103: | |||
835 | case EINVAL22: | |||
836 | lwan_status_info("Listening socket closed")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 836, __FUNCTION__, "Listening socket closed"); | |||
837 | return false0; | |||
838 | } | |||
839 | } | |||
840 | ||||
841 | __builtin_unreachable(); | |||
842 | } | |||
843 | ||||
844 | static int create_listen_socket(struct lwan_thread *t, | |||
845 | unsigned int num, | |||
846 | bool_Bool tls) | |||
847 | { | |||
848 | const struct lwan *lwan = t->lwan; | |||
849 | int listen_fd; | |||
850 | ||||
851 | listen_fd = lwan_create_listen_socket(lwan, num == 0, tls); | |||
852 | if (listen_fd < 0) | |||
853 | lwan_status_critical("Could not create listen_fd")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 853, __FUNCTION__, "Could not create listen_fd"); | |||
854 | ||||
855 | /* Ignore errors here, as this is just a hint */ | |||
856 | #if defined(LWAN_HAVE_SO_ATTACH_REUSEPORT_CBPF) | |||
857 | /* From socket(7): "These options may be set repeatedly at any time on | |||
858 | * any socket in the group to replace the current BPF program used by | |||
859 | * all sockets in the group." */ | |||
860 | if (num == 0) { | |||
861 | /* From socket(7): "The BPF program must return an index between 0 and | |||
862 | * N-1 representing the socket which should receive the packet (where N | |||
863 | * is the number of sockets in the group)." */ | |||
864 | const uint32_t cpu_ad_off = (uint32_t)SKF_AD_OFF(-0x1000) + SKF_AD_CPU36; | |||
865 | struct sock_filter filter[] = { | |||
866 | {BPF_LD0x00 | BPF_W0x00 | BPF_ABS0x20, 0, 0, cpu_ad_off}, /* A = curr_cpu_index */ | |||
867 | {BPF_RET0x06 | BPF_A0x10, 0, 0, 0}, /* return A */ | |||
868 | }; | |||
869 | 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]))}; | |||
870 | ||||
871 | (void)setsockopt(listen_fd, SOL_SOCKET1, SO_ATTACH_REUSEPORT_CBPF51, | |||
872 | &fprog, sizeof(fprog)); | |||
873 | (void)setsockopt(listen_fd, SOL_SOCKET1, SO_LOCK_FILTER44, | |||
874 | (int[]){1}, sizeof(int)); | |||
875 | } | |||
876 | #elif defined(LWAN_HAVE_SO_INCOMING_CPU) && defined(__x86_64__1) | |||
877 | (void)setsockopt(listen_fd, SOL_SOCKET1, SO_INCOMING_CPU49, &t->cpu, | |||
878 | sizeof(t->cpu)); | |||
879 | #endif | |||
880 | ||||
881 | struct epoll_event event = { | |||
882 | .events = EPOLLINEPOLLIN | EPOLLETEPOLLET | EPOLLERREPOLLERR, | |||
883 | .data.ptr = &t->lwan->conns[listen_fd], | |||
884 | }; | |||
885 | if (epoll_ctl(t->epoll_fd, EPOLL_CTL_ADD1, listen_fd, &event) < 0) | |||
886 | 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" , 886, __FUNCTION__, "Could not add socket to epoll"); | |||
887 | ||||
888 | return listen_fd; | |||
889 | } | |||
890 | ||||
891 | static void *thread_io_loop(void *data) | |||
892 | { | |||
893 | struct lwan_thread *t = data; | |||
894 | int epoll_fd = t->epoll_fd; | |||
895 | 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; }); | |||
896 | struct lwan *lwan = t->lwan; | |||
897 | struct epoll_event *events; | |||
898 | struct coro_switcher switcher; | |||
899 | struct timeout_queue tq; | |||
900 | ||||
901 | lwan_status_debug("Worker thread #%zd starting",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 902, __FUNCTION__, "Worker thread #%zd starting", t - t-> lwan->thread.threads + 1) | |||
902 | t - t->lwan->thread.threads + 1)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 902, __FUNCTION__, "Worker thread #%zd starting", t - t-> lwan->thread.threads + 1); | |||
903 | lwan_set_thread_name("worker"); | |||
904 | ||||
905 | events = calloc((size_t)max_events, sizeof(*events)); | |||
906 | if (UNLIKELY(!events)__builtin_expect(((!events)), (0))) | |||
907 | 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" , 907, __FUNCTION__, "Could not allocate memory for events"); | |||
908 | ||||
909 | update_date_cache(t); | |||
910 | ||||
911 | timeout_queue_init(&tq, lwan); | |||
912 | ||||
913 | lwan_random_seed_prng_for_thread(t); | |||
914 | ||||
915 | pthread_barrier_wait(&lwan->thread.barrier); | |||
916 | ||||
917 | for (;;) { | |||
918 | int timeout = turn_timer_wheel(&tq, t, epoll_fd); | |||
919 | int n_fds = epoll_wait(epoll_fd, events, max_events, timeout); | |||
920 | bool_Bool created_coros = false0; | |||
921 | ||||
922 | if (UNLIKELY(n_fds < 0)__builtin_expect(((n_fds < 0)), (0))) { | |||
923 | if (errno(*__errno_location ()) == EBADF9 || errno(*__errno_location ()) == EINVAL22) | |||
924 | break; | |||
925 | continue; | |||
926 | } | |||
927 | ||||
928 | for (struct epoll_event *event = events; n_fds--; event++) { | |||
929 | struct lwan_connection *conn = event->data.ptr; | |||
930 | ||||
931 | 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" , 931, __extension__ __PRETTY_FUNCTION__); })); | |||
932 | ||||
933 | if (conn->flags & (CONN_LISTENER_HTTP | CONN_LISTENER_HTTPS)) { | |||
934 | if (LIKELY(accept_waiting_clients(t, conn))__builtin_expect((!!(accept_waiting_clients(t, conn))), (1))) | |||
935 | continue; | |||
936 | close(epoll_fd); | |||
937 | epoll_fd = -1; | |||
938 | break; | |||
939 | } | |||
940 | ||||
941 | if (UNLIKELY(event->events & (EPOLLRDHUP | EPOLLHUP))__builtin_expect(((event->events & (EPOLLRDHUP | EPOLLHUP ))), (0))) { | |||
942 | if ((conn->flags & CONN_AWAITED_FD) != CONN_SUSPENDED) { | |||
943 | timeout_queue_expire(&tq, conn); | |||
944 | continue; | |||
945 | } | |||
946 | } | |||
947 | ||||
948 | if (!conn->coro) { | |||
949 | if (UNLIKELY(!spawn_coro(conn, &switcher, &tq))__builtin_expect(((!spawn_coro(conn, &switcher, &tq)) ), (0))) { | |||
950 | send_last_response_without_coro(t->lwan, conn, HTTP_UNAVAILABLE); | |||
951 | continue; | |||
952 | } | |||
953 | ||||
954 | created_coros = true1; | |||
955 | } | |||
956 | ||||
957 | resume_coro(&tq, conn, epoll_fd); | |||
958 | } | |||
959 | ||||
960 | if (created_coros) | |||
961 | timeouts_add(t->wheel, &tq.timeout, 1000); | |||
962 | } | |||
963 | ||||
964 | pthread_barrier_wait(&lwan->thread.barrier); | |||
965 | ||||
966 | timeout_queue_expire_all(&tq); | |||
967 | free(events); | |||
968 | ||||
969 | return NULL((void*)0); | |||
970 | } | |||
971 | ||||
972 | static void create_thread(struct lwan *l, struct lwan_thread *thread) | |||
973 | { | |||
974 | int ignore; | |||
975 | pthread_attr_t attr; | |||
976 | ||||
977 | thread->lwan = l; | |||
978 | ||||
979 | thread->wheel = timeouts_open(&ignore); | |||
980 | if (!thread->wheel) | |||
981 | lwan_status_critical("Could not create timer wheel")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 981, __FUNCTION__, "Could not create timer wheel"); | |||
982 | ||||
983 | if ((thread->epoll_fd = epoll_create1(EPOLL_CLOEXECEPOLL_CLOEXEC)) < 0) | |||
984 | lwan_status_critical_perror("epoll_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 984, __FUNCTION__, "epoll_create"); | |||
985 | ||||
986 | if (pthread_attr_init(&attr)) | |||
987 | lwan_status_critical_perror("pthread_attr_init")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 987, __FUNCTION__, "pthread_attr_init"); | |||
988 | ||||
989 | if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEMPTHREAD_SCOPE_SYSTEM)) | |||
990 | lwan_status_critical_perror("pthread_attr_setscope")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 990, __FUNCTION__, "pthread_attr_setscope"); | |||
991 | ||||
992 | if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLEPTHREAD_CREATE_JOINABLE)) | |||
993 | lwan_status_critical_perror("pthread_attr_setdetachstate")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 993, __FUNCTION__, "pthread_attr_setdetachstate"); | |||
994 | ||||
995 | if (pthread_create(&thread->self, &attr, thread_io_loop, thread)) | |||
996 | lwan_status_critical_perror("pthread_create")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 996, __FUNCTION__, "pthread_create"); | |||
997 | ||||
998 | if (pthread_attr_destroy(&attr)) | |||
999 | lwan_status_critical_perror("pthread_attr_destroy")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 999, __FUNCTION__, "pthread_attr_destroy"); | |||
1000 | } | |||
1001 | ||||
1002 | #if defined(__linux__1) && defined(__x86_64__1) | |||
1003 | static bool_Bool read_cpu_topology(struct lwan *l, uint32_t siblings[]) | |||
1004 | { | |||
1005 | char path[PATH_MAX4096]; | |||
1006 | ||||
1007 | for (uint32_t i = 0; i < l->available_cpus; i++) | |||
1008 | siblings[i] = 0xbebacafe; | |||
1009 | ||||
1010 | for (unsigned int i = 0; i < l->available_cpus; i++) { | |||
1011 | FILE *sib; | |||
1012 | uint32_t id, sibling; | |||
1013 | char separator; | |||
1014 | ||||
1015 | snprintf(path, sizeof(path), | |||
1016 | "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", | |||
1017 | i); | |||
1018 | ||||
1019 | sib = fopen(path, "re"); | |||
1020 | if (!sib) { | |||
1021 | 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" , 1022, __FUNCTION__, "Could not open `%s` to determine CPU topology" , path) | |||
1022 | path)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1022, __FUNCTION__, "Could not open `%s` to determine CPU topology" , path); | |||
1023 | return false0; | |||
1024 | } | |||
1025 | ||||
1026 | switch (fscanf(sib, "%u%c%u", &id, &separator, &sibling)) { | |||
1027 | case 2: /* No SMT */ | |||
1028 | siblings[i] = id; | |||
1029 | break; | |||
1030 | case 3: /* SMT */ | |||
1031 | if (!(separator == ',' || separator == '-')) { | |||
1032 | 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" , 1032, __FUNCTION__, "Expecting either ',' or '-' for sibling separator" ); | |||
1033 | __builtin_unreachable(); | |||
1034 | } | |||
1035 | ||||
1036 | siblings[i] = sibling; | |||
1037 | break; | |||
1038 | default: | |||
1039 | lwan_status_critical("%s has invalid format", path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1039, __FUNCTION__, "%s has invalid format", path); | |||
1040 | __builtin_unreachable(); | |||
1041 | } | |||
1042 | ||||
1043 | fclose(sib); | |||
1044 | } | |||
1045 | ||||
1046 | /* Perform a sanity check here, as some systems seem to filter out the | |||
1047 | * result of sysconf() to obtain the number of configured and online | |||
1048 | * CPUs but don't bother changing what's available through sysfs as far | |||
1049 | * as the CPU topology information goes. It's better to fall back to a | |||
1050 | * possibly non-optimal setup than just crash during startup while | |||
1051 | * trying to perform an out-of-bounds array access. */ | |||
1052 | for (unsigned int i = 0; i < l->available_cpus; i++) { | |||
1053 | if (siblings[i] == 0xbebacafe) { | |||
1054 | 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" , 1054, __FUNCTION__, "Could not determine sibling for CPU %d" , i); | |||
1055 | return false0; | |||
1056 | } | |||
1057 | ||||
1058 | if (siblings[i] >= l->available_cpus) { | |||
1059 | 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" , 1062, __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) | |||
1060 | "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" , 1062, __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) | |||
1061 | "Is Lwan running in a (broken) container?",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1062, __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 | siblings[i], l->available_cpus, l->online_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1062, __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 | return false0; | |||
1064 | } | |||
1065 | } | |||
1066 | ||||
1067 | return true1; | |||
1068 | } | |||
1069 | ||||
1070 | static void | |||
1071 | siblings_to_schedtbl(struct lwan *l, uint32_t siblings[], uint32_t schedtbl[]) | |||
1072 | { | |||
1073 | int *seen = alloca(l->available_cpus * sizeof(int))__builtin_alloca (l->available_cpus * sizeof(int)); | |||
1074 | unsigned int n_schedtbl = 0; | |||
1075 | ||||
1076 | for (uint32_t i = 0; i < l->available_cpus; i++) | |||
1077 | seen[i] = -1; | |||
1078 | ||||
1079 | for (uint32_t i = 0; i < l->available_cpus; i++) { | |||
1080 | if (seen[siblings[i]] < 0) { | |||
1081 | seen[siblings[i]] = (int)i; | |||
1082 | } else { | |||
1083 | schedtbl[n_schedtbl++] = (uint32_t)seen[siblings[i]]; | |||
1084 | schedtbl[n_schedtbl++] = i; | |||
1085 | } | |||
1086 | } | |||
1087 | ||||
1088 | if (n_schedtbl != l->available_cpus) | |||
1089 | memcpy(schedtbl, seen, l->available_cpus * sizeof(int)); | |||
1090 | } | |||
1091 | ||||
1092 | static bool_Bool | |||
1093 | topology_to_schedtbl(struct lwan *l, uint32_t schedtbl[], uint32_t n_threads) | |||
1094 | { | |||
1095 | uint32_t *siblings = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t)); | |||
1096 | ||||
1097 | if (read_cpu_topology(l, siblings)) { | |||
1098 | uint32_t *affinity = alloca(l->available_cpus * sizeof(uint32_t))__builtin_alloca (l->available_cpus * sizeof(uint32_t)); | |||
1099 | ||||
1100 | siblings_to_schedtbl(l, siblings, affinity); | |||
1101 | ||||
1102 | for (uint32_t i = 0; i < n_threads; i++) | |||
1103 | schedtbl[i] = affinity[i % l->available_cpus]; | |||
1104 | return true1; | |||
1105 | } | |||
1106 | ||||
1107 | for (uint32_t i = 0; i < n_threads; i++) | |||
1108 | schedtbl[i] = (i / 2) % l->thread.count; | |||
1109 | return false0; | |||
1110 | } | |||
1111 | ||||
1112 | static void | |||
1113 | adjust_thread_affinity(const struct lwan_thread *thread) | |||
1114 | { | |||
1115 | cpu_set_t set; | |||
1116 | ||||
1117 | CPU_ZERO(&set)do __builtin_memset (&set, '\0', sizeof (cpu_set_t)); while (0); | |||
1118 | 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; })); | |||
1119 | ||||
1120 | if (pthread_setaffinity_np(thread->self, sizeof(set), &set)) | |||
1121 | lwan_status_warning("Could not set thread affinity")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1121, __FUNCTION__, "Could not set thread affinity"); | |||
1122 | } | |||
1123 | #endif | |||
1124 | ||||
1125 | #if defined(LWAN_HAVE_MBEDTLS) | |||
1126 | static bool_Bool is_tls_ulp_supported(void) | |||
1127 | { | |||
1128 | FILE *available_ulp = fopen("/proc/sys/net/ipv4/tcp_available_ulp", "re"); | |||
1129 | char buffer[512]; | |||
1130 | bool_Bool available = false0; | |||
1131 | ||||
1132 | if (!available_ulp) | |||
1133 | return false0; | |||
1134 | ||||
1135 | if (fgets(buffer, 512, available_ulp)) { | |||
1136 | if (strstr(buffer, "tls")) | |||
1137 | available = true1; | |||
1138 | } | |||
1139 | ||||
1140 | fclose(available_ulp); | |||
1141 | return available; | |||
1142 | } | |||
1143 | ||||
1144 | static bool_Bool lwan_init_tls(struct lwan *l) | |||
1145 | { | |||
1146 | static const int aes128_ciphers[] = { | |||
1147 | /* Only allow Ephemeral Diffie-Hellman key exchange, so Perfect | |||
1148 | * Forward Secrecy is possible. */ | |||
1149 | MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA2560xC02F, | |||
1150 | MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA2560xC02B, | |||
1151 | MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA2560x9E, | |||
1152 | MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA2560xAA, | |||
1153 | ||||
1154 | /* FIXME: Other ciphers are supported by kTLS, notably AES256 and | |||
1155 | * ChaCha20-Poly1305. Add those here and patch | |||
1156 | * lwan_setup_tls_keys() to match. */ | |||
1157 | ||||
1158 | /* FIXME: Maybe allow this to be user-tunable like other servers do? */ | |||
1159 | 0, | |||
1160 | }; | |||
1161 | int r; | |||
1162 | ||||
1163 | if (!l->config.ssl.cert || !l->config.ssl.key) | |||
1164 | return false0; | |||
1165 | ||||
1166 | if (!is_tls_ulp_supported()) { | |||
1167 | lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1168, __FUNCTION__, "TLS ULP not loaded. Try running `modprobe tls` as root." ) | |||
1168 | "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" , 1168, __FUNCTION__, "TLS ULP not loaded. Try running `modprobe tls` as root." ); | |||
1169 | } | |||
1170 | ||||
1171 | l->tls = calloc(1, sizeof(*l->tls)); | |||
1172 | if (!l->tls) | |||
1173 | 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" , 1173, __FUNCTION__, "Could not allocate memory for SSL context" ); | |||
1174 | ||||
1175 | lwan_status_debug("Initializing mbedTLS")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1175, __FUNCTION__, "Initializing mbedTLS"); | |||
1176 | ||||
1177 | mbedtls_ssl_config_init(&l->tls->config); | |||
1178 | mbedtls_x509_crt_init(&l->tls->server_cert); | |||
1179 | mbedtls_pk_init(&l->tls->server_key); | |||
1180 | mbedtls_entropy_init(&l->tls->entropy); | |||
1181 | mbedtls_ctr_drbg_init(&l->tls->ctr_drbg); | |||
1182 | ||||
1183 | r = mbedtls_x509_crt_parse_file(&l->tls->server_cert, l->config.ssl.cert); | |||
1184 | if (r) { | |||
1185 | lwan_status_mbedtls_error(r, "Could not parse certificate at %s", | |||
1186 | l->config.ssl.cert); | |||
1187 | abort(); | |||
1188 | } | |||
1189 | ||||
1190 | r = mbedtls_pk_parse_keyfile(&l->tls->server_key, l->config.ssl.key, NULL((void*)0)); | |||
1191 | if (r) { | |||
1192 | lwan_status_mbedtls_error(r, "Could not parse key file at %s", | |||
1193 | l->config.ssl.key); | |||
1194 | abort(); | |||
1195 | } | |||
1196 | ||||
1197 | /* Even though this points to files that will probably be outside | |||
1198 | * the reach of the server (if straightjackets are used), wipe this | |||
1199 | * struct to get rid of the paths to these files. */ | |||
1200 | lwan_always_bzero(l->config.ssl.cert, strlen(l->config.ssl.cert)); | |||
1201 | free(l->config.ssl.cert); | |||
1202 | lwan_always_bzero(l->config.ssl.key, strlen(l->config.ssl.key)); | |||
1203 | free(l->config.ssl.key); | |||
1204 | lwan_always_bzero(&l->config.ssl, sizeof(l->config.ssl)); | |||
1205 | ||||
1206 | mbedtls_ssl_conf_ca_chain(&l->tls->config, l->tls->server_cert.next, NULL((void*)0)); | |||
1207 | r = mbedtls_ssl_conf_own_cert(&l->tls->config, &l->tls->server_cert, | |||
1208 | &l->tls->server_key); | |||
1209 | if (r) { | |||
1210 | lwan_status_mbedtls_error(r, "Could not set cert/key"); | |||
1211 | abort(); | |||
1212 | } | |||
1213 | ||||
1214 | r = mbedtls_ctr_drbg_seed(&l->tls->ctr_drbg, mbedtls_entropy_func, | |||
1215 | &l->tls->entropy, NULL((void*)0), 0); | |||
1216 | if (r) { | |||
1217 | lwan_status_mbedtls_error(r, "Could not seed ctr_drbg"); | |||
1218 | abort(); | |||
1219 | } | |||
1220 | ||||
1221 | r = mbedtls_ssl_config_defaults(&l->tls->config, MBEDTLS_SSL_IS_SERVER1, | |||
1222 | MBEDTLS_SSL_TRANSPORT_STREAM0, | |||
1223 | MBEDTLS_SSL_PRESET_DEFAULT0); | |||
1224 | if (r) { | |||
1225 | lwan_status_mbedtls_error(r, "Could not set mbedTLS default config"); | |||
1226 | abort(); | |||
1227 | } | |||
1228 | ||||
1229 | mbedtls_ssl_conf_rng(&l->tls->config, mbedtls_ctr_drbg_random, | |||
1230 | &l->tls->ctr_drbg); | |||
1231 | mbedtls_ssl_conf_ciphersuites(&l->tls->config, aes128_ciphers); | |||
1232 | ||||
1233 | mbedtls_ssl_conf_renegotiation(&l->tls->config, | |||
1234 | MBEDTLS_SSL_RENEGOTIATION_DISABLED0); | |||
1235 | mbedtls_ssl_conf_legacy_renegotiation(&l->tls->config, | |||
1236 | MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION0); | |||
1237 | ||||
1238 | #if defined(MBEDTLS_SSL_ALPN) | |||
1239 | static const char *alpn_protos[] = {"http/1.1", NULL((void*)0)}; | |||
1240 | mbedtls_ssl_conf_alpn_protocols(&l->tls->config, alpn_protos); | |||
1241 | #endif | |||
1242 | ||||
1243 | return true1; | |||
1244 | } | |||
1245 | #endif | |||
1246 | ||||
1247 | void lwan_thread_init(struct lwan *l) | |||
1248 | { | |||
1249 | const unsigned int total_conns = l->thread.max_fd * l->thread.count; | |||
1250 | #if defined(LWAN_HAVE_MBEDTLS) | |||
1251 | const bool_Bool tls_initialized = lwan_init_tls(l); | |||
1252 | #else | |||
1253 | const bool_Bool tls_initialized = false0; | |||
1254 | #endif | |||
1255 | ||||
1256 | lwan_status_debug("Initializing threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1256, __FUNCTION__, "Initializing threads"); | |||
1257 | ||||
1258 | l->thread.threads = | |||
1259 | calloc((size_t)l->thread.count, sizeof(struct lwan_thread)); | |||
1260 | if (!l->thread.threads) | |||
| ||||
1261 | 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" , 1261, __FUNCTION__, "Could not allocate memory for threads" ); | |||
1262 | ||||
1263 | uint32_t *schedtbl; | |||
1264 | uint32_t n_threads; | |||
1265 | bool_Bool adj_affinity; | |||
1266 | ||||
1267 | #if defined(__x86_64__1) && defined(__linux__1) | |||
1268 | if (l->online_cpus > 1) { | |||
1269 | static_assert_Static_assert(sizeof(struct lwan_connection) == 32, | |||
1270 | "Two connections per cache line"); | |||
1271 | #ifdef _SC_LEVEL1_DCACHE_LINESIZE_SC_LEVEL1_DCACHE_LINESIZE | |||
1272 | 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" , 1272, __extension__ __PRETTY_FUNCTION__); })); | |||
1273 | #endif | |||
1274 | 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" , 1276, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients" , l->online_cpus, l->available_cpus) | |||
1275 | "Reading topology to pre-schedule clients",lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1276, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients" , l->online_cpus, l->available_cpus) | |||
1276 | l->online_cpus, l->available_cpus)lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1276, __FUNCTION__, "%d CPUs of %d are online. " "Reading topology to pre-schedule clients" , l->online_cpus, l->available_cpus); | |||
1277 | /* | |||
1278 | * Pre-schedule each file descriptor, to reduce some operations in the | |||
1279 | * fast path. | |||
1280 | * | |||
1281 | * Since struct lwan_connection is guaranteed to be 32-byte long, two of | |||
1282 | * them can fill up a cache line. Assume siblings share cache lines and | |||
1283 | * use the CPU topology to group two connections per cache line in such | |||
1284 | * a way that false sharing is avoided. | |||
1285 | */ | |||
1286 | n_threads = (uint32_t)lwan_nextpow2((size_t)((l->thread.count - 1) * 2)); | |||
1287 | schedtbl = alloca(n_threads * sizeof(uint32_t))__builtin_alloca (n_threads * sizeof(uint32_t)); | |||
1288 | ||||
1289 | adj_affinity = topology_to_schedtbl(l, schedtbl, n_threads); | |||
1290 | ||||
1291 | n_threads--; /* Transform count into mask for AND below */ | |||
1292 | ||||
1293 | for (unsigned int i = 0; i < total_conns; i++) | |||
1294 | l->conns[i].thread = &l->thread.threads[schedtbl[i & n_threads]]; | |||
| ||||
1295 | } else | |||
1296 | #endif /* __x86_64__ && __linux__ */ | |||
1297 | { | |||
1298 | 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" , 1298, __FUNCTION__, "Using round-robin to preschedule clients" ); | |||
1299 | ||||
1300 | for (unsigned int i = 0; i < l->thread.count; i++) | |||
1301 | l->thread.threads[i].cpu = i % l->online_cpus; | |||
1302 | for (unsigned int i = 0; i < total_conns; i++) | |||
1303 | l->conns[i].thread = &l->thread.threads[i % l->thread.count]; | |||
1304 | ||||
1305 | schedtbl = NULL((void*)0); | |||
1306 | adj_affinity = false0; | |||
1307 | n_threads = l->thread.count; | |||
1308 | } | |||
1309 | ||||
1310 | for (unsigned int i = 0; i < l->thread.count; i++) { | |||
1311 | struct lwan_thread *thread = NULL((void*)0); | |||
1312 | ||||
1313 | if (schedtbl) { | |||
1314 | /* This is not the most elegant thing, but this assures that the | |||
1315 | * listening sockets are added to the SO_REUSEPORT group in a | |||
1316 | * specific order, because that's what the CBPF program to direct | |||
1317 | * the incoming connection to the right CPU will use. */ | |||
1318 | for (uint32_t thread_id = 0; thread_id < l->thread.count; | |||
1319 | thread_id++) { | |||
1320 | if (schedtbl[thread_id & n_threads] == i) { | |||
1321 | thread = &l->thread.threads[thread_id]; | |||
1322 | break; | |||
1323 | } | |||
1324 | } | |||
1325 | if (!thread) { | |||
1326 | /* FIXME: can this happen when we have a offline CPU? */ | |||
1327 | lwan_status_critical(lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1328, __FUNCTION__, "Could not figure out which CPU thread %d should go to" , i) | |||
1328 | "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" , 1328, __FUNCTION__, "Could not figure out which CPU thread %d should go to" , i); | |||
1329 | } | |||
1330 | } else { | |||
1331 | thread = &l->thread.threads[i % l->thread.count]; | |||
1332 | } | |||
1333 | ||||
1334 | if (pthread_barrier_init(&l->thread.barrier, NULL((void*)0), 2)) | |||
1335 | lwan_status_critical("Could not create barrier")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1335, __FUNCTION__, "Could not create barrier"); | |||
1336 | ||||
1337 | create_thread(l, thread); | |||
1338 | ||||
1339 | if ((thread->listen_fd = create_listen_socket(thread, i, false0)) < 0) | |||
1340 | 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" , 1340, __FUNCTION__, "Could not create listening socket"); | |||
1341 | l->conns[thread->listen_fd].flags |= CONN_LISTENER_HTTP; | |||
1342 | ||||
1343 | if (tls_initialized) { | |||
1344 | if ((thread->tls_listen_fd = create_listen_socket(thread, i, true1)) < 0) | |||
1345 | 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" , 1345, __FUNCTION__, "Could not create TLS listening socket" ); | |||
1346 | l->conns[thread->tls_listen_fd].flags |= CONN_LISTENER_HTTPS; | |||
1347 | } else { | |||
1348 | thread->tls_listen_fd = -1; | |||
1349 | } | |||
1350 | ||||
1351 | if (adj_affinity) { | |||
1352 | l->thread.threads[i].cpu = schedtbl[i & n_threads]; | |||
1353 | adjust_thread_affinity(thread); | |||
1354 | } | |||
1355 | ||||
1356 | pthread_barrier_wait(&l->thread.barrier); | |||
1357 | } | |||
1358 | ||||
1359 | 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" , 1359, __FUNCTION__, "Worker threads created and ready to serve" ); | |||
1360 | } | |||
1361 | ||||
1362 | void lwan_thread_shutdown(struct lwan *l) | |||
1363 | { | |||
1364 | lwan_status_debug("Shutting down threads")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan-thread.c" , 1364, __FUNCTION__, "Shutting down threads"); | |||
1365 | ||||
1366 | for (unsigned int i = 0; i < l->thread.count; i++) { | |||
1367 | struct lwan_thread *t = &l->thread.threads[i]; | |||
1368 | int epoll_fd = t->epoll_fd; | |||
1369 | int listen_fd = t->listen_fd; | |||
1370 | ||||
1371 | t->listen_fd = -1; | |||
1372 | t->epoll_fd = -1; | |||
1373 | close(epoll_fd); | |||
1374 | close(listen_fd); | |||
1375 | } | |||
1376 | ||||
1377 | pthread_barrier_wait(&l->thread.barrier); | |||
1378 | pthread_barrier_destroy(&l->thread.barrier); | |||
1379 | ||||
1380 | for (unsigned int i = 0; i < l->thread.count; i++) { | |||
1381 | struct lwan_thread *t = &l->thread.threads[i]; | |||
1382 | ||||
1383 | pthread_join(l->thread.threads[i].self, NULL((void*)0)); | |||
1384 | timeouts_close(t->wheel); | |||
1385 | } | |||
1386 | ||||
1387 | free(l->thread.threads); | |||
1388 | ||||
1389 | #if defined(LWAN_HAVE_MBEDTLS) | |||
1390 | if (l->tls) { | |||
1391 | mbedtls_ssl_config_free(&l->tls->config); | |||
1392 | mbedtls_x509_crt_free(&l->tls->server_cert); | |||
1393 | mbedtls_pk_free(&l->tls->server_key); | |||
1394 | mbedtls_entropy_free(&l->tls->entropy); | |||
1395 | mbedtls_ctr_drbg_free(&l->tls->ctr_drbg); | |||
1396 | free(l->tls); | |||
1397 | } | |||
1398 | #endif | |||
1399 | } |