Bug Summary

File:lwan.c
Warning:line 284, column 17
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name lwan.c -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=all -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -fno-plt -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -resource-dir /usr/lib/clang/10.0.0 -include /home/buildbot/lwan-worker/clang-analyze/build/lwan-build-config.h -D _FILE_OFFSET_BITS=64 -D _TIME_BITS=64 -I /home/buildbot/lwan-worker/clang-analyze/build/src/lib/missing -I /usr/include/luajit-2.0 -I /usr/include/valgrind -I /home/buildbot/lwan-worker/clang-analyze/build/src/lib -I /home/buildbot/lwan-worker/clang-analyze/build -internal-isystem /usr/local/include -internal-isystem /usr/lib/clang/10.0.0/include -internal-externc-isystem /include -internal-externc-isystem /usr/include -Wno-unused-parameter -Wno-free-nonheap-object -std=gnu99 -fdebug-compilation-dir /home/buildbot/lwan-worker/clang-analyze/build/src/lib -ferror-limit 19 -fmessage-length 0 -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -analyzer-output=html -faddrsig -o /home/buildbot/lwan-worker/clang-analyze/CLANG/2020-06-14-203314-580560-1 -x c /home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c
1/*
2 * lwan - simple web server
3 * Copyright (c) 2012, 2013 Leandro A. F. Pereira <leandro@hardinfo.org>
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 <ctype.h>
24#include <dlfcn.h>
25#include <errno(*__errno_location ()).h>
26#include <fcntl.h>
27#include <libproc.h>
28#include <limits.h>
29#include <signal.h>
30#include <stdlib.h>
31#include <string.h>
32#include <sys/resource.h>
33#include <sys/socket.h>
34#include <sys/types.h>
35#include <unistd.h>
36
37#include "lwan-private.h"
38
39#include "lwan-config.h"
40#include "lwan-http-authorize.h"
41
42#if defined(HAVE_LUA)
43#include "lwan-lua.h"
44#endif
45
46/* See detect_fastest_monotonic_clock() */
47clockid_t monotonic_clock_id = CLOCK_MONOTONIC1;
48
49static const struct lwan_config default_config = {
50 .listener = "localhost:8080",
51 .keep_alive_timeout = 15,
52 .quiet = false0,
53 .reuse_port = false0,
54 .proxy_protocol = false0,
55 .allow_cors = false0,
56 .expires = 1 * ONE_WEEK(((60 * 60) * 24) * 7),
57 .n_threads = 0,
58 .max_post_data_size = 10 * DEFAULT_BUFFER_SIZE4096,
59 .allow_post_temp_file = false0,
60};
61
62LWAN_HANDLER(brew_coffee)static enum lwan_http_status lwan_handler_brew_coffee( struct
lwan_request *, struct lwan_response *, void *); static const
struct lwan_handler_info __attribute__((used, section("lwan_handler"
))) lwan_handler_info_brew_coffee = {.name = "brew_coffee", .
handler = lwan_handler_brew_coffee}; static enum lwan_http_status
lwan_handler_brew_coffee( struct lwan_request *request __attribute__
((unused)), struct lwan_response *response __attribute__((unused
)), void *data __attribute__((unused)))
63{
64 /* Placeholder handler so that __start_lwan_handler and __stop_lwan_handler
65 * symbols will get defined.
66 */
67 return HTTP_I_AM_A_TEAPOT;
68}
69
70__attribute__((no_sanitize_address))
71static void *find_handler(const char *name)
72{
73 const struct lwan_handler_info *handler;
74
75 LWAN_SECTION_FOREACH(lwan_handler, handler)for (handler = ({ extern const typeof(*handler) __start_lwan_handler
[]; __start_lwan_handler; }); handler < ({ extern const typeof
(*handler) __stop_lwan_handler[]; __stop_lwan_handler; }); (handler
)++)
{
76 if (streq(handler->name, name))
77 return handler->handler;
78 }
79
80 return NULL((void*)0);
81}
82
83__attribute__((no_sanitize_address))
84static const struct lwan_module *find_module(const char *name)
85{
86 const struct lwan_module_info *module;
87
88 LWAN_SECTION_FOREACH(lwan_module, module)for (module = ({ extern const typeof(*module) __start_lwan_module
[]; __start_lwan_module; }); module < ({ extern const typeof
(*module) __stop_lwan_module[]; __stop_lwan_module; }); (module
)++)
{
89 if (streq(module->name, name))
90 return module->module;
91 }
92
93 return NULL((void*)0);
94}
95
96static void destroy_urlmap(void *data)
97{
98 struct lwan_url_map *url_map = data;
99
100 if (url_map->module) {
101 const struct lwan_module *module = url_map->module;
102
103 if (module->destroy)
104 module->destroy(url_map->data);
105 } else if (url_map->data && url_map->flags & HANDLER_DATA_IS_HASH_TABLE) {
106 hash_free(url_map->data);
107 }
108
109 free(url_map->authorization.realm);
110 free(url_map->authorization.password_file);
111 free((char *)url_map->prefix);
112 free(url_map);
113}
114
115static struct lwan_url_map *add_url_map(struct lwan_trie *t, const char *prefix,
116 const struct lwan_url_map *map)
117{
118 struct lwan_url_map *copy = malloc(sizeof(*copy));
119
120 if (!copy)
121 lwan_status_critical_perror("Could not copy URL map")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 121, __FUNCTION__, "Could not copy URL map")
;
122
123 memcpy(copy, map, sizeof(*copy));
124
125 copy->prefix = strdup(prefix ? prefix : copy->prefix);
126 if (!copy->prefix)
127 lwan_status_critical_perror("Could not copy URL prefix")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 127, __FUNCTION__, "Could not copy URL prefix")
;
128
129 copy->prefix_len = strlen(copy->prefix);
130 lwan_trie_add(t, copy->prefix, copy);
131
132 return copy;
133}
134
135static void lwan_headers_init(struct lwan *l, struct lwan_key_value *hdrs)
136{
137 assert(l)((void) sizeof ((l) ? 1 : 0), __extension__ ({ if (l) ; else __assert_fail
("l", "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 137, __extension__ __PRETTY_FUNCTION__); }))
;
138
139 struct lwan_strbuf * headers = &l->headers;
140 lwan_strbuf_init(headers);
141 bool_Bool set_server = false0;
142 if (hdrs) {
143 for (struct lwan_key_value *kv = hdrs; kv->key; ++kv) {
144 if (!strcasecmp(kv->key, "server"))
145 set_server = true1;
146
147 if (LIKELY(kv->value)__builtin_expect((!!(kv->value)), (1))) {
148 lwan_strbuf_append_printf(headers, "\r\n%s: %s", kv->key, kv->value);
149 }
150 }
151 }
152
153 if (LIKELY(!set_server)__builtin_expect((!!(!set_server)), (1))) {
154 lwan_strbuf_append_strz(headers, "\r\nServer: lwan");
155 }
156
157 lwan_strbuf_append_strz(headers, "\r\n\r\n");
158}
159
160static void parse_global_headers(struct config *c,
161 const struct config_line *l,
162 struct lwan *lwan)
163{
164 struct lwan_key_value *kv;
165 struct lwan_key_value_array hdrs;
166 lwan_key_value_array_init(&hdrs);
167
168 while ((l = config_read_line(c))) {
169 switch (l->type) {
170 case CONFIG_LINE_TYPE_SECTION:
171 config_error(
172 c, "No sections are supported under the 'headers' section");
173 goto cleanup;
174
175 case CONFIG_LINE_TYPE_LINE:
176 kv = lwan_key_value_array_append(&hdrs);
177 if (!kv) {
178 lwan_status_critical_perror(lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 179, __FUNCTION__, "Could not allocate memory for custom response header"
)
179 "Could not allocate memory for custom response header")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 179, __FUNCTION__, "Could not allocate memory for custom response header"
)
;
180 }
181
182 kv->key = strdup(l->key);
183 if (!kv->key) {
184 lwan_status_critical_perror(lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 185, __FUNCTION__, "Could not allocate memory for custom response header"
)
185 "Could not allocate memory for custom response header")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 185, __FUNCTION__, "Could not allocate memory for custom response header"
)
;
186 }
187
188 kv->value = strdup(l->value);
189 if (!kv->value) {
190 lwan_status_critical_perror(lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 191, __FUNCTION__, "Could not allocate memory for custom response header"
)
191 "Could not allocate memory for custom response header")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 191, __FUNCTION__, "Could not allocate memory for custom response header"
)
;
192 }
193 break;
194
195 case CONFIG_LINE_TYPE_SECTION_END:
196 kv = lwan_key_value_array_append(&hdrs);
197 if (!kv) {
198 lwan_status_critical_perror(lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 199, __FUNCTION__, "Could not allocate memory for custom response header"
)
199 "Could not allocate memory for custom response header")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 199, __FUNCTION__, "Could not allocate memory for custom response header"
)
;
200 }
201
202 kv->key = NULL((void*)0);
203 kv->value = NULL((void*)0);
204
205 lwan_headers_init(lwan, lwan_key_value_array_get_array(&hdrs));
206 goto cleanup;
207 }
208 }
209
210 config_error(c, "EOF while looking for end of 'headers' section");
211
212cleanup:
213 LWAN_ARRAY_FOREACH (&hdrs, kv)for (kv = (&hdrs)->base.base; kv < ((typeof(kv))(&
hdrs)->base.base + (&hdrs)->base.elements); kv++)
{
214 free(kv->key);
215 free(kv->value);
216 }
217 lwan_key_value_array_reset(&hdrs);
218}
219
220static void parse_listener_prefix_authorization(struct config *c,
221 const struct config_line *l,
222 struct lwan_url_map *url_map)
223{
224 if (!streq(l->value, "basic")) {
225 config_error(c, "Only basic authorization supported");
226 return;
227 }
228
229 memset(&url_map->authorization, 0, sizeof(url_map->authorization));
230
231 while ((l = config_read_line(c))) {
232 switch (l->type) {
233 case CONFIG_LINE_TYPE_LINE:
234 if (streq(l->key, "realm")) {
235 free(url_map->authorization.realm);
236 url_map->authorization.realm = strdup(l->value);
237 } else if (streq(l->key, "password_file")) {
238 free(url_map->authorization.password_file);
239 url_map->authorization.password_file = realpath(l->value, NULL((void*)0));
240 if (!url_map->authorization.password_file)
241 config_error(c, "Could not determine full path for password file: %s", l->value);
242 }
243 break;
244
245 case CONFIG_LINE_TYPE_SECTION:
246 config_error(c, "Unexpected section: %s", l->key);
247 goto error;
248
249 case CONFIG_LINE_TYPE_SECTION_END:
250 if (!url_map->authorization.realm)
251 url_map->authorization.realm = strdup("Lwan");
252 if (!url_map->authorization.password_file)
253 url_map->authorization.password_file = strdup("htpasswd");
254
255 url_map->flags |= HANDLER_MUST_AUTHORIZE;
256 return;
257 }
258 }
259
260 config_error(c, "Could not find end of authorization section");
261
262error:
263 free(url_map->authorization.realm);
264 free(url_map->authorization.password_file);
265}
266
267static void parse_listener_prefix(struct config *c,
268 const struct config_line *l,
269 struct lwan *lwan,
270 const struct lwan_module *module,
271 void *handler)
272{
273 struct lwan_url_map url_map = {};
274 struct hash *hash = hash_str_new(free, free);
275 char *prefix = strdupa(l->value)(__extension__ ({ const char *__old = (l->value); size_t __len
= strlen (__old) + 1; char *__new = (char *) __builtin_alloca
(__len); (char *) memcpy (__new, __old, __len); }))
;
276 struct config *isolated;
277
278 isolated = config_isolate_section(c, l);
279 if (!isolated) {
21
Assuming 'isolated' is non-null
22
Taking false branch
280 config_error(c, "Could not isolate configuration file");
281 goto out;
282 }
283
284 while ((l = config_read_line(c))) {
23
Loop condition is true. Entering loop body
27
Potential memory leak
285 switch (l->type) {
24
Control jumps to 'case CONFIG_LINE_TYPE_LINE:' at line 286
286 case CONFIG_LINE_TYPE_LINE:
287 hash_add(hash, strdup(l->key), strdup(l->value));
25
Memory is allocated
288 break;
26
Execution continues on line 284
289
290 case CONFIG_LINE_TYPE_SECTION:
291 if (streq(l->key, "authorization")) {
292 parse_listener_prefix_authorization(c, l, &url_map);
293 } else if (!config_skip_section(c, l)) {
294 config_error(c, "Could not skip section");
295 goto out;
296 }
297 break;
298
299 case CONFIG_LINE_TYPE_SECTION_END:
300 goto add_map;
301 }
302 }
303
304 config_error(c, "Expecting section end while parsing prefix");
305 goto out;
306
307add_map:
308 assert((handler && !module) || (!handler && module))((void) sizeof (((handler && !module) || (!handler &&
module)) ? 1 : 0), __extension__ ({ if ((handler && !
module) || (!handler && module)) ; else __assert_fail
("(handler && !module) || (!handler && module)"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 308, __extension__ __PRETTY_FUNCTION__); }))
;
309
310 if (handler) {
311 url_map.handler = handler;
312 url_map.flags |= HANDLER_PARSE_MASK | HANDLER_DATA_IS_HASH_TABLE;
313 url_map.data = hash;
314 url_map.module = NULL((void*)0);
315
316 hash = NULL((void*)0);
317 } else if (module->create_from_hash && module->handle_request) {
318 url_map.data = module->create_from_hash(prefix, hash);
319 if (!url_map.data) {
320 config_error(c, "Could not create module instance");
321 goto out;
322 }
323
324 if (module->parse_conf && !module->parse_conf(url_map.data, isolated)) {
325 const char *msg = config_last_error(isolated);
326
327 config_error(c, "Error from module: %s", msg ? msg : "Unknown");
328 goto out;
329 }
330
331 url_map.handler = module->handle_request;
332 url_map.flags |= module->flags;
333 url_map.module = module;
334 } else if (UNLIKELY(!module->create_from_hash)__builtin_expect(((!module->create_from_hash)), (0))) {
335 config_error(c, "Module isn't prepared to load settings from a file; "
336 "create_from_hash() method isn't present");
337 goto out;
338 } else if (UNLIKELY(!module->handle_request)__builtin_expect(((!module->handle_request)), (0))) {
339 config_error(c, "Module does not have handle_request() method");
340 goto out;
341 }
342
343 add_url_map(&lwan->url_map_trie, prefix, &url_map);
344
345out:
346 hash_free(hash);
347 config_close(isolated);
348}
349
350void lwan_set_url_map(struct lwan *l, const struct lwan_url_map *map)
351{
352 lwan_trie_destroy(&l->url_map_trie);
353 if (UNLIKELY(!lwan_trie_init(&l->url_map_trie, destroy_urlmap))__builtin_expect(((!lwan_trie_init(&l->url_map_trie, destroy_urlmap
))), (0))
)
354 lwan_status_critical_perror("Could not initialize trie")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 354, __FUNCTION__, "Could not initialize trie")
;
355
356 for (; map->prefix; map++) {
357 struct lwan_url_map *copy = add_url_map(&l->url_map_trie, NULL((void*)0), map);
358
359 if (copy->module && copy->module->create) {
360 copy->data = copy->module->create (map->prefix, copy->args);
361 copy->flags = copy->module->flags;
362 copy->handler = copy->module->handle_request;
363 } else {
364 copy->flags = HANDLER_PARSE_MASK;
365 }
366 }
367}
368
369static void parse_listener(struct config *c,
370 const struct config_line *l,
371 struct lwan *lwan)
372{
373 free(lwan->config.listener);
374 lwan->config.listener = strdup(l->value);
375
376 while ((l = config_read_line(c))) {
14
Loop condition is true. Entering loop body
377 switch (l->type) {
15
Control jumps to 'case CONFIG_LINE_TYPE_SECTION:' at line 381
378 case CONFIG_LINE_TYPE_LINE:
379 config_error(c, "Expecting prefix section");
380 return;
381 case CONFIG_LINE_TYPE_SECTION:
382 if (l->key[0] == '&') {
16
Assuming the condition is false
17
Taking false branch
383 void *handler = find_handler(l->key + 1);
384 if (handler) {
385 parse_listener_prefix(c, l, lwan, NULL((void*)0), handler);
386 continue;
387 }
388
389 config_error(c, "Could not find handler name: %s", l->key + 1);
390 return;
391 }
392
393 const struct lwan_module *module = find_module(l->key);
394 if (module) {
18
Assuming 'module' is non-null
19
Taking true branch
395 parse_listener_prefix(c, l, lwan, module, NULL((void*)0));
20
Calling 'parse_listener_prefix'
396 continue;
397 }
398
399 config_error(c, "Invalid section or module not found: %s", l->key);
400 return;
401 case CONFIG_LINE_TYPE_SECTION_END:
402 return;
403 }
404 }
405
406 config_error(c, "Expecting section end while parsing listener");
407}
408
409const char *lwan_get_config_path(char *path_buf, size_t path_buf_len)
410{
411 char buffer[PATH_MAX4096];
412
413 if (proc_pidpath(getpid(), buffer, sizeof(buffer)) < 0)
414 goto out;
415
416 char *path = strrchr(buffer, '/');
417 if (!path)
418 goto out;
419 int ret = snprintf(path_buf, path_buf_len, "%s.conf", path + 1);
420 if (ret < 0 || ret >= (int)path_buf_len)
421 goto out;
422
423 return path_buf;
424
425out:
426 return "lwan.conf";
427}
428
429static bool_Bool setup_from_config(struct lwan *lwan, const char *path)
430{
431 const struct config_line *line;
432 struct config *conf;
433 bool_Bool has_listener = false0;
434 char path_buf[PATH_MAX4096];
435
436 if (!path
3.1
'path' is null
)
4
Taking true branch
437 path = lwan_get_config_path(path_buf, sizeof(path_buf));
438 lwan_status_info("Loading configuration file: %s", path)lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 438, __FUNCTION__, "Loading configuration file: %s", path)
;
439
440 conf = config_open(path);
441 if (!conf)
5
Assuming 'conf' is non-null
6
Taking false branch
442 return false0;
443
444 if (!lwan_trie_init(&lwan->url_map_trie, destroy_urlmap))
7
Assuming the condition is false
8
Taking false branch
445 return false0;
446
447 while ((line = config_read_line(conf))) {
9
Loop condition is true. Entering loop body
448 switch (line->type) {
10
Control jumps to 'case CONFIG_LINE_TYPE_SECTION:' at line 494
449 case CONFIG_LINE_TYPE_LINE:
450 if (streq(line->key, "keep_alive_timeout")) {
451 lwan->config.keep_alive_timeout = (unsigned int)parse_long(
452 line->value, default_config.keep_alive_timeout);
453 } else if (streq(line->key, "quiet")) {
454 lwan->config.quiet =
455 parse_bool(line->value, default_config.quiet);
456 } else if (streq(line->key, "reuse_port")) {
457 lwan->config.reuse_port =
458 parse_bool(line->value, default_config.reuse_port);
459 } else if (streq(line->key, "proxy_protocol")) {
460 lwan->config.proxy_protocol =
461 parse_bool(line->value, default_config.proxy_protocol);
462 } else if (streq(line->key, "allow_cors")) {
463 lwan->config.allow_cors =
464 parse_bool(line->value, default_config.allow_cors);
465 } else if (streq(line->key, "expires")) {
466 lwan->config.expires =
467 parse_time_period(line->value, default_config.expires);
468 } else if (streq(line->key, "error_template")) {
469 free(lwan->config.error_template);
470 lwan->config.error_template = strdup(line->value);
471 } else if (streq(line->key, "threads")) {
472 long n_threads =
473 parse_long(line->value, default_config.n_threads);
474 if (n_threads < 0)
475 config_error(conf, "Invalid number of threads: %ld",
476 n_threads);
477 lwan->config.n_threads = (unsigned int)n_threads;
478 } else if (streq(line->key, "max_post_data_size")) {
479 long max_post_data_size = parse_long(
480 line->value, (long)default_config.max_post_data_size);
481 if (max_post_data_size < 0)
482 config_error(conf, "Negative maximum post data size");
483 else if (max_post_data_size > 128 * (1 << 20))
484 config_error(conf,
485 "Maximum post data can't be over 128MiB");
486 lwan->config.max_post_data_size = (size_t)max_post_data_size;
487 } else if (streq(line->key, "allow_temp_files")) {
488 lwan->config.allow_post_temp_file =
489 !!strstr(line->value, "post");
490 } else {
491 config_error(conf, "Unknown config key: %s", line->key);
492 }
493 break;
494 case CONFIG_LINE_TYPE_SECTION:
495 if (streq(line->key, "listener")) {
11
Taking true branch
496 if (!has_listener
11.1
'has_listener' is false
) {
12
Taking true branch
497 parse_listener(conf, line, lwan);
13
Calling 'parse_listener'
498 has_listener = true1;
499 } else {
500 config_error(conf, "Only one listener supported");
501 }
502 } else if (streq(line->key, "straitjacket")) {
503 lwan_straitjacket_enforce_from_config(conf);
504 } else if (streq(line->key, "headers")) {
505 parse_global_headers(conf, line, lwan);
506 } else {
507 config_error(conf, "Unknown section type: %s", line->key);
508 }
509 break;
510 case CONFIG_LINE_TYPE_SECTION_END:
511 config_error(conf, "Unexpected section end");
512 }
513 }
514
515 if (config_last_error(conf)) {
516 lwan_status_critical("Error on config file \"%s\", line %d: %s", path,lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 517, __FUNCTION__, "Error on config file \"%s\", line %d: %s"
, path, config_cur_line(conf), config_last_error(conf))
517 config_cur_line(conf), config_last_error(conf))lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 517, __FUNCTION__, "Error on config file \"%s\", line %d: %s"
, path, config_cur_line(conf), config_last_error(conf))
;
518 }
519
520 config_close(conf);
521
522 return true1;
523}
524
525static void try_setup_from_config(struct lwan *l,
526 const struct lwan_config *config)
527{
528 if (!setup_from_config(l, config->config_file_path)) {
3
Calling 'setup_from_config'
529 if (config->config_file_path) {
530 lwan_status_critical("Could not read config file: %s",lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 531, __FUNCTION__, "Could not read config file: %s", config
->config_file_path)
531 config->config_file_path)lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 531, __FUNCTION__, "Could not read config file: %s", config
->config_file_path)
;
532 }
533 }
534
535 lwan_status_init(l); /* `quiet` key might have changed value. */
536
537 l->config.request_flags =
538 (l->config.proxy_protocol ? REQUEST_ALLOW_PROXY_REQS : 0) |
539 (l->config.allow_cors ? REQUEST_ALLOW_CORS : 0);
540}
541
542static rlim_t setup_open_file_count_limits(void)
543{
544 struct rlimit r;
545
546 if (getrlimit(RLIMIT_NOFILERLIMIT_NOFILE, &r) < 0) {
547 lwan_status_perror("Could not obtain maximum number of file "lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 549, __FUNCTION__, "Could not obtain maximum number of file "
"descriptors. Assuming %d", 256)
548 "descriptors. Assuming %d",lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 549, __FUNCTION__, "Could not obtain maximum number of file "
"descriptors. Assuming %d", 256)
549 OPEN_MAX)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 549, __FUNCTION__, "Could not obtain maximum number of file "
"descriptors. Assuming %d", 256)
;
550 return OPEN_MAX256;
551 }
552
553 if (r.rlim_max != r.rlim_cur) {
554 const rlim_t current = r.rlim_cur;
555
556 if (r.rlim_max == RLIM_INFINITY0xffffffffffffffffuLL && r.rlim_cur < OPEN_MAX256) {
557 r.rlim_cur = OPEN_MAX256;
558 } else if (r.rlim_cur < r.rlim_max) {
559 r.rlim_cur = r.rlim_max;
560 } else {
561 /* Shouldn't happen, so just return the current value. */
562 goto out;
563 }
564
565 if (setrlimit(RLIMIT_NOFILERLIMIT_NOFILE, &r) < 0) {
566 lwan_status_perror("Could not raise maximum number of file "lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 568, __FUNCTION__, "Could not raise maximum number of file "
"descriptors to %" "l" "u" ". Leaving at " "%" "l" "u", r.rlim_max
, current)
567 "descriptors to %" PRIu64 ". Leaving at "lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 568, __FUNCTION__, "Could not raise maximum number of file "
"descriptors to %" "l" "u" ". Leaving at " "%" "l" "u", r.rlim_max
, current)
568 "%" PRIu64, r.rlim_max, current)lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 568, __FUNCTION__, "Could not raise maximum number of file "
"descriptors to %" "l" "u" ". Leaving at " "%" "l" "u", r.rlim_max
, current)
;
569 r.rlim_cur = current;
570 }
571 }
572
573out:
574 return r.rlim_cur;
575}
576
577static void allocate_connections(struct lwan *l, size_t max_open_files)
578{
579 const size_t sz = max_open_files * sizeof(struct lwan_connection);
580
581 l->conns = lwan_aligned_alloc(sz, 64);
582 if (UNLIKELY(!l->conns)__builtin_expect(((!l->conns)), (0)))
583 lwan_status_critical_perror("lwan_alloc_aligned")lwan_status_critical_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 583, __FUNCTION__, "lwan_alloc_aligned")
;
584
585 memset(l->conns, 0, sz);
586}
587
588static unsigned int get_number_of_cpus(void)
589{
590 long n_online_cpus = sysconf(_SC_NPROCESSORS_ONLN_SC_NPROCESSORS_ONLN);
591
592 if (UNLIKELY(n_online_cpus < 0)__builtin_expect(((n_online_cpus < 0)), (0))) {
593 lwan_status_warning(lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 594, __FUNCTION__, "Could not get number of online CPUs, assuming 1 CPU"
)
594 "Could not get number of online CPUs, assuming 1 CPU")lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 594, __FUNCTION__, "Could not get number of online CPUs, assuming 1 CPU"
)
;
595 return 1;
596 }
597
598 return (unsigned int)n_online_cpus;
599}
600
601void lwan_init(struct lwan *l) { lwan_init_with_config(l, &default_config); }
1
Calling 'lwan_init_with_config'
602
603const struct lwan_config *lwan_get_default_config(void)
604{
605 return &default_config;
606}
607
608static char *dup_or_null(const char *s)
609{
610 return s ? strdup(s) : NULL((void*)0);
611}
612
613void lwan_init_with_config(struct lwan *l, const struct lwan_config *config)
614{
615 /* Load defaults */
616 memset(l, 0, sizeof(*l));
617 memcpy(&l->config, config, sizeof(*config));
618 l->config.listener = dup_or_null(l->config.listener);
619 l->config.config_file_path = dup_or_null(l->config.config_file_path);
620
621 /* Initialize status first, as it is used by other things during
622 * their initialization. */
623 lwan_status_init(l);
624
625 /* These will only print debugging messages. Debug messages are always
626 * printed if we're on a debug build, so the quiet setting will be
627 * respected. */
628 lwan_job_thread_init();
629 lwan_tables_init();
630
631 try_setup_from_config(l, config);
2
Calling 'try_setup_from_config'
632
633 if (!lwan_strbuf_get_length(&l->headers)) {
634 lwan_headers_init(l, config->global_headers);
635 }
636
637 lwan_response_init(l);
638
639 /* Continue initialization as normal. */
640 lwan_status_debug("Initializing lwan web server")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 640, __FUNCTION__, "Initializing lwan web server")
;
641
642 l->n_cpus = get_number_of_cpus();
643 if (!l->config.n_threads) {
644 l->thread.count = l->n_cpus;
645 if (l->thread.count == 1)
646 l->thread.count = 2;
647 } else if (l->config.n_threads > 3 * l->n_cpus) {
648 l->thread.count = l->n_cpus * 3;
649
650 lwan_status_warning("%d threads requested, but only %d online CPUs; "lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 652, __FUNCTION__, "%d threads requested, but only %d online CPUs; "
"capping to %d threads", l->config.n_threads, l->n_cpus
, 3 * l->n_cpus)
651 "capping to %d threads",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 652, __FUNCTION__, "%d threads requested, but only %d online CPUs; "
"capping to %d threads", l->config.n_threads, l->n_cpus
, 3 * l->n_cpus)
652 l->config.n_threads, l->n_cpus, 3 * l->n_cpus)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 652, __FUNCTION__, "%d threads requested, but only %d online CPUs; "
"capping to %d threads", l->config.n_threads, l->n_cpus
, 3 * l->n_cpus)
;
653 } else if (l->config.n_threads > 255) {
654 l->thread.count = 256;
655
656 lwan_status_warning("%d threads requested, but max 256 supported",lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 657, __FUNCTION__, "%d threads requested, but max 256 supported"
, l->config.n_threads)
657 l->config.n_threads)lwan_status_warning_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 657, __FUNCTION__, "%d threads requested, but max 256 supported"
, l->config.n_threads)
;
658 } else {
659 l->thread.count = l->config.n_threads;
660 }
661
662 rlim_t max_open_files = setup_open_file_count_limits();
663 allocate_connections(l, (size_t)max_open_files);
664
665 l->thread.max_fd = (unsigned)max_open_files / (unsigned)l->thread.count;
666 lwan_status_info("Using %d threads, maximum %d sockets per thread",lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 667, __FUNCTION__, "Using %d threads, maximum %d sockets per thread"
, l->thread.count, l->thread.max_fd)
667 l->thread.count, l->thread.max_fd)lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 667, __FUNCTION__, "Using %d threads, maximum %d sockets per thread"
, l->thread.count, l->thread.max_fd)
;
668
669 signal(SIGPIPE13, SIG_IGN((__sighandler_t) 1));
670
671 lwan_readahead_init();
672 lwan_thread_init(l);
673 lwan_socket_init(l);
674 lwan_http_authorize_init();
675}
676
677void lwan_shutdown(struct lwan *l)
678{
679 lwan_status_info("Shutting down")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 679, __FUNCTION__, "Shutting down")
;
680
681 free(l->config.listener);
682 free(l->config.error_template);
683 free(l->config.config_file_path);
684
685 lwan_job_thread_shutdown();
686 lwan_thread_shutdown(l);
687
688 lwan_status_debug("Shutting down URL handlers")lwan_status_debug_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 688, __FUNCTION__, "Shutting down URL handlers")
;
689 lwan_trie_destroy(&l->url_map_trie);
690
691 lwan_strbuf_free(&l->headers);
692 free(l->conns);
693
694 lwan_response_shutdown(l);
695 lwan_tables_shutdown();
696 lwan_status_shutdown(l);
697 lwan_http_authorize_shutdown();
698 lwan_readahead_shutdown();
699}
700
701static ALWAYS_INLINEinline __attribute__((always_inline)) int schedule_client(struct lwan *l, int fd)
702{
703 struct lwan_thread *thread = l->conns[fd].thread;
704
705 lwan_thread_add_client(thread, fd);
706
707 return (int)(thread - l->thread.threads);
708}
709
710static volatile sig_atomic_t main_socket = -1;
711
712static_assert(sizeof(main_socket) >= sizeof(int),extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(main_socket) >= sizeof
(int)) ? 2 : -1; })]
713 "size of sig_atomic_t > size of int")extern int (*__Static_assert_function (void)) [!!sizeof (struct
{ int __error_if_negative: (sizeof(main_socket) >= sizeof
(int)) ? 2 : -1; })]
;
714
715static void sigint_handler(int signal_number __attribute__((unused)))
716{
717 if (main_socket < 0)
718 return;
719
720 shutdown((int)main_socket, SHUT_RDWRSHUT_RDWR);
721 close((int)main_socket);
722
723 main_socket = -1;
724}
725
726enum herd_accept { HERD_MORE = 0, HERD_GONE = -1, HERD_SHUTDOWN = 1 };
727
728struct core_bitmap {
729 uint64_t bitmap[4];
730};
731
732static ALWAYS_INLINEinline __attribute__((always_inline)) enum herd_accept
733accept_one(struct lwan *l, struct core_bitmap *cores)
734{
735 int fd = accept4((int)main_socket, NULL((void*)0), NULL((void*)0), SOCK_NONBLOCKSOCK_NONBLOCK | SOCK_CLOEXECSOCK_CLOEXEC);
736
737 if (LIKELY(fd >= 0)__builtin_expect((!!(fd >= 0)), (1))) {
738 int core = schedule_client(l, fd);
739
740 cores->bitmap[core / 64] |= UINT64_C(1)1UL<<(core % 64);
741
742 return HERD_MORE;
743 }
744
745 switch (errno(*__errno_location ())) {
746 case EAGAIN11:
747 return HERD_GONE;
748
749 case EBADF9:
750 case ECONNABORTED103:
751 case EINVAL22:
752 if (main_socket < 0) {
753 lwan_status_info("Signal 2 (Interrupt) received")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 753, __FUNCTION__, "Signal 2 (Interrupt) received")
;
754 } else {
755 lwan_status_info("Main socket closed for unknown reasons")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 755, __FUNCTION__, "Main socket closed for unknown reasons"
)
;
756 }
757 return HERD_SHUTDOWN;
758
759 default:
760 lwan_status_perror("accept")lwan_status_perror_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 760, __FUNCTION__, "accept")
;
761 return HERD_MORE;
762 }
763}
764
765void lwan_main_loop(struct lwan *l)
766{
767 struct core_bitmap cores = {};
768
769 assert(main_socket == -1)((void) sizeof ((main_socket == -1) ? 1 : 0), __extension__ (
{ if (main_socket == -1) ; else __assert_fail ("main_socket == -1"
, "/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 769, __extension__ __PRETTY_FUNCTION__); }))
;
770 main_socket = l->main_socket;
771
772 if (signal(SIGINT2, sigint_handler) == SIG_ERR((__sighandler_t) -1))
773 lwan_status_critical("Could not set signal handler")lwan_status_critical_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 773, __FUNCTION__, "Could not set signal handler")
;
774
775 lwan_status_info("Ready to serve")lwan_status_info_debug("/home/buildbot/lwan-worker/clang-analyze/build/src/lib/lwan.c"
, 775, __FUNCTION__, "Ready to serve")
;
776
777 while (true1) {
778 enum herd_accept ha;
779
780 fcntl(l->main_socket, F_SETFL4, 0);
781 ha = accept_one(l, &cores);
782 if (ha == HERD_MORE) {
783 fcntl(l->main_socket, F_SETFL4, O_NONBLOCK04000);
784
785 do {
786 ha = accept_one(l, &cores);
787 } while (ha == HERD_MORE);
788 }
789
790 if (UNLIKELY(ha > HERD_MORE)__builtin_expect(((ha > HERD_MORE)), (0)))
791 break;
792
793 for (size_t i = 0; i < N_ELEMENTS(cores.bitmap)((!sizeof(char[1 - 2 * __builtin_types_compatible_p( __typeof__
(cores.bitmap), __typeof__(&(cores.bitmap)[0]))])) | sizeof
(cores.bitmap) / sizeof(cores.bitmap[0]))
; i++) {
794 for (uint64_t c = cores.bitmap[i]; c; c ^= c & -c) {
795 size_t core = (size_t)__builtin_ctzl(c);
796 lwan_thread_nudge(&l->thread.threads[i * 64 + core]);
797 }
798 }
799 cores = (struct core_bitmap){};
800 }
801}
802
803#ifdef CLOCK_MONOTONIC_COARSE6
804__attribute__((constructor)) static void detect_fastest_monotonic_clock(void)
805{
806 struct timespec ts;
807
808 if (!clock_gettime(CLOCK_MONOTONIC_COARSE6, &ts))
809 monotonic_clock_id = CLOCK_MONOTONIC_COARSE6;
810}
811#endif
812
813void lwan_set_thread_name(const char *name)
814{
815 char thread_name[16];
816 char process_name[PATH_MAX4096];
817 char *tmp;
818 int ret;
819
820 if (proc_pidpath(getpid(), process_name, sizeof(process_name)) < 0)
821 return;
822
823 tmp = strrchr(process_name, '/');
824 if (!tmp)
825 return;
826
827 ret = snprintf(thread_name, sizeof(thread_name), "%s %s", tmp + 1, name);
828 if (ret < 0)
829 return;
830
831 pthread_set_name_np(pthread_self(), thread_name);
832}