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