Add more compiler warnings and fix a few things they pointed out worth improving/being more explicit about. This adds GCC-12 compatibility out of the box.

Signed-off-by: DL6ER <dl6er@dl6er.de>
This commit is contained in:
DL6ER
2023-01-29 14:45:38 +01:00
parent 5f593bfb3b
commit 8753a8d69b
41 changed files with 420 additions and 257 deletions
+4 -4
View File
@@ -1,11 +1,11 @@
{
"name": "FTL x86_64 Build Env",
"image": "ghcr.io/pi-hole/ftl-build:x86_64-musl",
"name": "FTL x86_64 Build Env",
"image": "ghcr.io/pi-hole/ftl-build:x86_64-musl",
"runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ],
"extensions": [
"jetmartin.bats",
"ms-vscode.cpptools",
"ms-vscode.cmake-tools",
"eamodio.gitlens"
],
}
]
}
+96 -27
View File
@@ -57,39 +57,108 @@ set(DEBUG_FLAGS "-rdynamic -fno-omit-frame-pointer")
set(WARN_FLAGS "-Wall -Wextra -Wno-unused-parameter")
# Extra warning flags we apply only to the FTL part of the code (used not for foreign code such as dnsmasq and SQLite3)
# -Werror: Halt on any warnings, useful for enforcing clean code without any warnings (we use it only for our code part)
# -Waddress: Warn about suspicious uses of memory addresses
# -Wlogical-op: Warn about suspicious uses of logical operators in expressions
# -Wmissing-field-initializers: Warn if a structure's initializer has some fields missing
# -Woverlength-strings: Warn about string constants that are longer than the "minimum maximum length specified in the C standard
# -Wformat: Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
# -Wformat-nonliteral: If -Wformat is specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as a va_list.
# -Wuninitialized: Warn if an automatic variable is used without first being initialized
# -Wswitch-enum: Warn whenever a switch statement has an index of enumerated type and lacks a case for one or more of the named codes of that enumeration.
# -Wshadow: Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member, or whenever a built-in function is shadowed.
# -Wfloat-equal: Warn if floating-point values are used in equality comparisons
# -Wpointer-arith: Warn about anything that depends on the "size of" a function type or of "void". GNU C assigns these types a size of 1
# -Wundef: Warn if an undefined identifier is evaluated in an "#if" directive
# -Wbad-function-cast: Warn when a function call is cast to a non-matching type
# -Wwrite-strings: When compiling C, give string constants the type "const char[length]" so that copying the address of one into a non-"const" "char *" pointer produces a warning
# -Wparentheses: Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about
# -Wlogical-op: Warn about suspicious uses of logical operators in expressions
# -Wstrict-prototypes: Warn if a function is declared or defined without specifying the argument types
# -Wmissing-prototypes: Warn if a global function is defined without a previous prototype declaration
# -Wredundant-decls: Warn if anything is declared more than once in the same scope
# -Winline: Warn if a function that is declared as inline cannot be inlined
set(EXTRAWARN_GCC6 "-Werror \
-Waddress \
-Wlogical-op \
-Wmissing-field-initializers \
-Woverlength-strings \
-Wformat=2 \
-Wformat-signedness \
-Wuninitialized \
-Wnull-dereference \
-Wshift-overflow=2 \
-Wunused-const-variable=2 \
-Wstrict-aliasing \
-Warray-bounds=2 \
-Wno-aggressive-loop-optimizations \
-Wswitch-enum \
-Wshadow \
-Wfloat-equal \
-Wbad-function-cast \
-Wwrite-strings \
-Wparentheses \
-Wlogical-op \
-Wstrict-prototypes \
-Wmissing-prototypes \
-Wredundant-decls \
-Wmissing-field-initializers \
-Wnormalized=nfkc \
-Woverride-init \
-Wpacked \
-Winline \
-Wpacked \
-Wredundant-decls \
-Wnested-externs \
-Wvla \
-Wvector-operation-performance \
-Wvolatile-register-var \
-Wdisabled-optimization \
-Wpointer-sign \
-Wstack-protector \
-Woverlength-strings")
# Extra warnings flags available only in GCC 7 and higher
if(CMAKE_C_COMPILER_VERSION VERSION_EQUAL 7 OR CMAKE_C_COMPILER_VERSION VERSION_GREATER 7)
set(EXTRAWARN_GCC7 "-Wformat-overflow=2 \
-Wformat-truncation=2 \
-Wstringop-overflow=4 \
-Walloc-zero \
-Wint-in-bool-context")
else()
set(EXTRAWARN_GCC7 "")
endif()
# Extra warnings flags available only in GCC 8 and higher
if(CMAKE_C_COMPILER_VERSION VERSION_EQUAL 8 OR CMAKE_C_COMPILER_VERSION VERSION_GREATER 8)
# -Wduplicated-cond: Warn about duplicated conditions in an if-else-if chain
# -Wduplicated-branches: Warn when an if-else has identical branches
# -Wcast-align=strict: Warn whenever a pointer is cast such that the required alignment of the target is increased. For example, warn if a "char *" is cast to an "int *" regardless of the target machine.
# -Wlogical-not-parentheses: Warn about logical not used on the left hand side operand of a comparison
set(EXTRAWARN_GCC8 "-Wduplicated-cond -Wduplicated-branches -Wcast-align=strict -Wlogical-not-parentheses -Wsuggest-attribute=pure -Wsuggest-attribute=const -Wsuggest-attribute=malloc -Wsuggest-attribute=format -Wsuggest-attribute=cold")
set(EXTRAWARN_GCC8 "-Wduplicated-cond \
-Wduplicated-branches \
-Wcast-align=strict \
-Wlogical-not-parentheses \
-Wmultistatement-macros \
-Wmissing-attributes \
-Wsuggest-attribute=pure \
-Wsuggest-attribute=const \
-Wsuggest-attribute=malloc \
-Wsuggest-attribute=format \
-Wsuggest-attribute=cold")
else()
set(EXTRAWARN_GCC8 "")
endif()
set(EXTRAWARN "-Werror -Waddress -Wlogical-op -Wmissing-field-initializers -Woverlength-strings -Wformat -Wformat-nonliteral -Wuninitialized -Wswitch-enum -Wshadow -Wfloat-equal -Wbad-function-cast -Wwrite-strings -Wparentheses -Wlogical-op -Wstrict-prototypes -Wmissing-prototypes -Wredundant-decls -Winline ${EXTRAWARN_GCC8}")
# Extra warnings flags available only in GCC 9 and higher
# The only new warning -Wabsolute-value is implied by -Wextra
# Extra warnings flags available only in GCC 10 and higher
# The new option -Wstring-compare is implied by -Wextra
# The new option -Wzero-length-bounds is implied by -Warray-bounds
# Extra warnings flags available only in GCC 11 and higher
# All new options are implied by either -Wall or -Wextra \
# Extra warnings flags available only in GCC 12 and higher
if(CMAKE_C_COMPILER_VERSION VERSION_EQUAL 12 OR CMAKE_C_COMPILER_VERSION VERSION_GREATER 12)
set(EXTRAWARN_GCC12 "-Wbidi-chars \
-Warray-compare")
else()
set(EXTRAWARN_GCC12 "")
endif()
# Extra warnings flags available only in GCC 13 and higher
if(CMAKE_C_COMPILER_VERSION VERSION_EQUAL 13 OR CMAKE_C_COMPILER_VERSION VERSION_GREATER 13)
set(EXTRAWARN_GCC13 "-Wenum-int-mismatch")
else()
set(EXTRAWARN_GCC13 "")
endif()
set(EXTRAWARN "${EXTRAWARN_GCC6} \
${EXTRAWARN_GCC7} \
${EXTRAWARN_GCC8} \
${EXTRAWARN_GCC12} \
${EXTRAWARN_GCC13}")
separate_arguments(EXTRAWARN)
# -Wxor-used-as-pow
# Do we want to compile a statically linked musl executable?
if(STATIC STREQUAL "true")
SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
+1 -1
View File
@@ -105,7 +105,7 @@
// After how much time does a valid API session expire? [seconds]
// Default: 300 (five minutes)
#define API_SESSION_EXPIRE 300
#define API_SESSION_EXPIRE 300u
// How many authenticated API clients are allowed simultaneously? [.]
#define API_MAX_CLIENTS 16
+1 -1
View File
@@ -33,7 +33,7 @@ int api_docs(struct ftl_conn *api)
(serve_index && strcmp(docs_files[i].path, "index.html") == 0))
{
// Send the file
mg_send_http_ok(api->conn, docs_files[i].mime_type, docs_files[i].content_size);
mg_send_http_ok(api->conn, docs_files[i].mime_type, (long long)docs_files[i].content_size);
return mg_write(api->conn, docs_files[i].content, docs_files[i].content_size);
}
}
+50 -50
View File
@@ -16,103 +16,103 @@
#include "webserver/json_macros.h"
#include "api/api.h"
static const char index_html[] = {
static const unsigned char index_html[] = {
#include "hex/index.html"
};
static const char index_css[] = {
static const unsigned char index_css[] = {
#include "hex/index.css"
};
static const char pi_hole_js[] = {
static const unsigned char pi_hole_js[] = {
#include "hex/pi-hole.js"
};
static const char rapidoc_min_js[] = {
static const unsigned char rapidoc_min_js[] = {
#include "hex/external/rapidoc-min.js"
};
static const char rapidoc_min_map_js[] = {
static const unsigned char rapidoc_min_map_js[] = {
#include "hex/external/rapidoc-min.js.map"
};
static const char highlight_default_min_css[] = {
static const unsigned char highlight_default_min_css[] = {
#include "hex/external/highlight-default.min.css"
};
static const char geraintluff_sha256_min_js[] = {
static const unsigned char geraintluff_sha256_min_js[] = {
#include "hex/external/geraintluff-sha256.min.js"
};
static const char highlight_min_js[] = {
static const unsigned char highlight_min_js[] = {
#include "hex/external/highlight.min.js"
};
static const char images_logo_svg[] = {
static const unsigned char images_logo_svg[] = {
#include "hex/images/logo.svg"
};
static const char specs_auth_yaml[] = {
static const unsigned char specs_auth_yaml[] = {
#include "hex/specs/auth.yaml"
};
static const char specs_clients_yaml[] = {
static const unsigned char specs_clients_yaml[] = {
#include "hex/specs/clients.yaml"
};
static const char specs_common_yaml[] = {
static const unsigned char specs_common_yaml[] = {
#include "hex/specs/common.yaml"
};
static const char specs_dns_yaml[] = {
static const unsigned char specs_dns_yaml[] = {
#include "hex/specs/dns.yaml"
};
static const char specs_domains_yaml[] = {
static const unsigned char specs_domains_yaml[] = {
#include "hex/specs/domains.yaml"
};
static const char specs_info_yaml[] = {
static const unsigned char specs_info_yaml[] = {
#include "hex/specs/info.yaml"
};
static const char specs_groups_yaml[] = {
static const unsigned char specs_groups_yaml[] = {
#include "hex/specs/groups.yaml"
};
static const char specs_history_yaml[] = {
static const unsigned char specs_history_yaml[] = {
#include "hex/specs/history.yaml"
};
static const char specs_lists_yaml[] = {
static const unsigned char specs_lists_yaml[] = {
#include "hex/specs/lists.yaml"
};
static const char specs_main_yaml[] = {
static const unsigned char specs_main_yaml[] = {
#include "hex/specs/main.yaml"
};
static const char specs_queries_yaml[] = {
static const unsigned char specs_queries_yaml[] = {
#include "hex/specs/queries.yaml"
};
static const char specs_stats_yaml[] = {
static const unsigned char specs_stats_yaml[] = {
#include "hex/specs/stats.yaml"
};
static const char specs_config_yaml[] = {
static const unsigned char specs_config_yaml[] = {
#include "hex/specs/config.yaml"
};
static const char specs_network_yaml[] = {
static const unsigned char specs_network_yaml[] = {
#include "hex/specs/network.yaml"
};
static const char specs_logs_yaml[] = {
static const unsigned char specs_logs_yaml[] = {
#include "hex/specs/logs.yaml"
};
static const char specs_endpoints_yaml[] = {
static const unsigned char specs_endpoints_yaml[] = {
#include "hex/specs/endpoints.yaml"
};
struct {
@@ -122,31 +122,31 @@ struct {
const size_t content_size;
} docs_files[] =
{
{"index.html", "text/html", index_html, sizeof(index_html)},
{"index.css", "text/css", index_css, sizeof(index_css)},
{"pi-hole.js", "application/javascript", pi_hole_js, sizeof(pi_hole_js)},
{"external/rapidoc-min.js", "application/javascript", rapidoc_min_js, sizeof(rapidoc_min_js)},
{"external/rapidoc-min.map.js", "text/plain", rapidoc_min_map_js, sizeof(rapidoc_min_map_js)},
{"external/highlight-default.min.css", "text/css", highlight_default_min_css, sizeof(highlight_default_min_css)},
{"external/highlight.min.js", "application/javascript", highlight_min_js, sizeof(highlight_min_js)},
{"external/geraintluff-sha256.min.js", "application/javascript", geraintluff_sha256_min_js, sizeof(geraintluff_sha256_min_js)},
{"images/logo.svg", "image/svg+xml", images_logo_svg, sizeof(images_logo_svg)},
{"specs/auth.yaml", "text/plain", specs_auth_yaml, sizeof(specs_auth_yaml)},
{"specs/clients.yaml", "text/plain", specs_clients_yaml, sizeof(specs_clients_yaml)},
{"specs/common.yaml", "text/plain", specs_common_yaml, sizeof(specs_common_yaml)},
{"specs/dns.yaml", "text/plain", specs_dns_yaml, sizeof(specs_dns_yaml)},
{"specs/domains.yaml", "text/plain", specs_domains_yaml, sizeof(specs_domains_yaml)},
{"specs/info.yaml", "text/plain", specs_info_yaml, sizeof(specs_info_yaml)},
{"specs/groups.yaml", "text/plain", specs_groups_yaml, sizeof(specs_groups_yaml)},
{"specs/history.yaml", "text/plain", specs_history_yaml, sizeof(specs_history_yaml)},
{"specs/lists.yaml", "text/plain", specs_lists_yaml, sizeof(specs_lists_yaml)},
{"specs/main.yaml", "text/plain", specs_main_yaml, sizeof(specs_main_yaml)},
{"specs/queries.yaml", "text/plain", specs_queries_yaml, sizeof(specs_queries_yaml)},
{"specs/stats.yaml", "text/plain", specs_stats_yaml, sizeof(specs_stats_yaml)},
{"specs/config.yaml", "text/plain", specs_config_yaml, sizeof(specs_config_yaml)},
{"specs/network.yaml", "text/plain", specs_network_yaml, sizeof(specs_network_yaml)},
{"specs/logs.yaml", "text/plain", specs_logs_yaml, sizeof(specs_logs_yaml)},
{"specs/endpoints.yaml", "text/plain", specs_endpoints_yaml, sizeof(specs_endpoints_yaml)},
{"index.html", "text/html", (const char*)index_html, sizeof(index_html)},
{"index.css", "text/css", (const char*)index_css, sizeof(index_css)},
{"pi-hole.js", "application/javascript", (const char*)pi_hole_js, sizeof(pi_hole_js)},
{"external/rapidoc-min.js", "application/javascript", (const char*)rapidoc_min_js, sizeof(rapidoc_min_js)},
{"external/rapidoc-min.map.js", "text/plain", (const char*)rapidoc_min_map_js, sizeof(rapidoc_min_map_js)},
{"external/highlight-default.min.css", "text/css", (const char*)highlight_default_min_css, sizeof(highlight_default_min_css)},
{"external/highlight.min.js", "application/javascript", (const char*)highlight_min_js, sizeof(highlight_min_js)},
{"external/geraintluff-sha256.min.js", "application/javascript", (const char*)geraintluff_sha256_min_js, sizeof(geraintluff_sha256_min_js)},
{"images/logo.svg", "image/svg+xml", (const char*)images_logo_svg, sizeof(images_logo_svg)},
{"specs/auth.yaml", "text/plain", (const char*)specs_auth_yaml, sizeof(specs_auth_yaml)},
{"specs/clients.yaml", "text/plain", (const char*)specs_clients_yaml, sizeof(specs_clients_yaml)},
{"specs/common.yaml", "text/plain", (const char*)specs_common_yaml, sizeof(specs_common_yaml)},
{"specs/dns.yaml", "text/plain", (const char*)specs_dns_yaml, sizeof(specs_dns_yaml)},
{"specs/domains.yaml", "text/plain", (const char*)specs_domains_yaml, sizeof(specs_domains_yaml)},
{"specs/info.yaml", "text/plain", (const char*)specs_info_yaml, sizeof(specs_info_yaml)},
{"specs/groups.yaml", "text/plain", (const char*)specs_groups_yaml, sizeof(specs_groups_yaml)},
{"specs/history.yaml", "text/plain", (const char*)specs_history_yaml, sizeof(specs_history_yaml)},
{"specs/lists.yaml", "text/plain", (const char*)specs_lists_yaml, sizeof(specs_lists_yaml)},
{"specs/main.yaml", "text/plain", (const char*)specs_main_yaml, sizeof(specs_main_yaml)},
{"specs/queries.yaml", "text/plain", (const char*)specs_queries_yaml, sizeof(specs_queries_yaml)},
{"specs/stats.yaml", "text/plain", (const char*)specs_stats_yaml, sizeof(specs_stats_yaml)},
{"specs/config.yaml", "text/plain", (const char*)specs_config_yaml, sizeof(specs_config_yaml)},
{"specs/network.yaml", "text/plain", (const char*)specs_network_yaml, sizeof(specs_network_yaml)},
{"specs/logs.yaml", "text/plain", (const char*)specs_logs_yaml, sizeof(specs_logs_yaml)},
{"specs/endpoints.yaml", "text/plain", (const char*)specs_endpoints_yaml, sizeof(specs_endpoints_yaml)},
};
#endif // API_DOCS_H
+4 -2
View File
@@ -124,8 +124,7 @@ int api_history_clients(struct ftl_conn *api)
// Get clients which the user doesn't want to see
// if skipclient[i] == true then this client should be hidden from
// returned data. We initialize it with false
bool skipclient[counters->clients];
memset(skipclient, false, counters->clients*sizeof(bool));
bool *skipclient = calloc(counters->clients, sizeof(bool));
unsigned int exclude_clients = cJSON_GetArraySize(config.webserver.api.exclude_clients.v.json);
if(exclude_clients > 0)
@@ -211,5 +210,8 @@ int api_history_clients(struct ftl_conn *api)
}
JSON_ADD_ITEM_TO_OBJECT(json, "clients", clients);
// Free memory
free(skipclient);
JSON_SEND_OBJECT_UNLOCK(json);
}
+7 -3
View File
@@ -78,19 +78,23 @@ static int api_list_read(struct ftl_conn *api,
// Groups don't have the groups property
if(listtype != GRAVITY_GROUPS)
{
if(table.group_ids != NULL) {
if(table.group_ids != NULL)
{
// Black magic at work here: We build a JSON array from
// the group_concat result delivered from the database,
// parse it as valid array and append it as row to the
// data
char group_ids_str[strlen(table.group_ids)+3u];
char *group_ids_str = calloc(strlen(table.group_ids)+3u, sizeof(char));
group_ids_str[0] = '[';
strcpy(group_ids_str+1u , table.group_ids);
group_ids_str[sizeof(group_ids_str)-2u] = ']';
group_ids_str[sizeof(group_ids_str)-1u] = '\0';
cJSON * group_ids = cJSON_Parse(group_ids_str);
free(group_ids_str);
JSON_ADD_ITEM_TO_OBJECT(row, "groups", group_ids);
} else {
}
else
{
// Empty group set
cJSON *group_ids = JSON_NEW_ARRAY();
JSON_ADD_ITEM_TO_OBJECT(row, "groups", group_ids);
+9 -6
View File
@@ -24,8 +24,9 @@
static bool getDefaultInterface(char iface[IF_NAMESIZE], in_addr_t *gw)
{
// Get IPv4 default route gateway and associated interface
long dest_r = 0, gw_r = 0;
int flags = 0, metric = 0, minmetric = __INT_MAX__;
unsigned long dest_r = 0, gw_r = 0;
unsigned int flags = 0u;
int metric = 0, minmetric = __INT_MAX__;
char iface_r[IF_NAMESIZE] = { 0 };
char buf[1024] = { 0 };
@@ -55,7 +56,7 @@ static bool getDefaultInterface(char iface[IF_NAMESIZE], in_addr_t *gw)
*gw = gw_r;
strcpy(iface, iface_r);
log_debug(DEBUG_API, "Reading interfaces: flags: %i, addr: %s, iface: %s, metric: %i, minmetric: %i",
log_debug(DEBUG_API, "Reading interfaces: flags: %u, addr: %s, iface: %s, metric: %i, minmetric: %i",
flags, inet_ntoa(*(struct in_addr *) gw), iface, metric, minmetric);
}
}
@@ -119,7 +120,7 @@ int api_network_interfaces(struct ftl_conn *api)
while ((dp = readdir(dfd)) != NULL)
{
// Skip "." and ".."
if(!dp->d_name || strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
continue;
// Create new interface record
@@ -255,8 +256,10 @@ int api_network_interfaces(struct ftl_conn *api)
}
// Sum up transmitted and received bytes
tx_sum += tx_bytes;
rx_sum += rx_bytes;
if(tx_bytes > 0)
tx_sum += tx_bytes;
if(rx_bytes > 0)
rx_sum += rx_bytes;
// Add interface to array
JSON_ADD_ITEM_TO_ARRAY(interfaces, iface);
+39 -14
View File
@@ -113,8 +113,14 @@ int api_stats_summary(struct ftl_conn *api)
int api_stats_top_domains(struct ftl_conn *api)
{
int temparray[counters->domains][2], count = 10;
int count = 10;
bool audit = false;
int *temparray = calloc(2*counters->domains, sizeof(int*));
if(temparray == NULL)
{
log_err("Memory allocation failed in %s()", __FUNCTION__);
return 0;
}
// Exit before processing any data if requested via config setting
if(config.misc.privacylevel.v.privacy_level >= PRIVACY_HIDE_DOMAINS)
@@ -127,6 +133,7 @@ int api_stats_top_domains(struct ftl_conn *api)
cJSON *json = JSON_NEW_OBJECT();
cJSON *top_domains = JSON_NEW_ARRAY();
JSON_ADD_ITEM_TO_OBJECT(json, "top_domains", top_domains);
free(temparray);
JSON_SEND_OBJECT(json);
}
@@ -155,12 +162,12 @@ int api_stats_top_domains(struct ftl_conn *api)
if(domain == NULL)
continue;
temparray[domainID][0] = domainID;
temparray[2*domainID + 0] = domainID;
if(blocked)
temparray[domainID][1] = domain->blockedcount;
temparray[2*domainID + 1] = domain->blockedcount;
else
// Count only permitted queries
temparray[domainID][1] = (domain->count - domain->blockedcount);
temparray[2*domainID + 1] = (domain->count - domain->blockedcount);
}
// Sort temporary array
@@ -191,7 +198,7 @@ int api_stats_top_domains(struct ftl_conn *api)
for(int i = 0; i < counters->domains; i++)
{
// Get sorted index
const int domainID = temparray[i][0];
const int domainID = temparray[2*i + 0];
// Get domain pointer
const domainsData* domain = getDomain(domainID, true);
if(domain == NULL)
@@ -249,6 +256,7 @@ int api_stats_top_domains(struct ftl_conn *api)
if(n == count)
break;
}
free(temparray);
cJSON *json = JSON_NEW_OBJECT();
JSON_ADD_ITEM_TO_OBJECT(json, "domains", top_domains);
@@ -262,8 +270,14 @@ int api_stats_top_domains(struct ftl_conn *api)
int api_stats_top_clients(struct ftl_conn *api)
{
int temparray[counters->clients][2], count = 10;
int count = 10;
bool includezeroclients = false;
int *temparray = calloc(2*counters->clients, sizeof(int*));
if(temparray == NULL)
{
log_err("Memory allocation failed in api_stats_top_clients()");
return 0;
}
// Exit before processing any data if requested via config setting
if(config.misc.privacylevel.v.privacy_level >= PRIVACY_HIDE_DOMAINS_CLIENTS)
@@ -276,6 +290,7 @@ int api_stats_top_clients(struct ftl_conn *api)
cJSON *json = JSON_NEW_OBJECT();
cJSON *top_clients = JSON_NEW_ARRAY();
JSON_ADD_ITEM_TO_OBJECT(json, "top_clients", top_clients);
free(temparray);
JSON_SEND_OBJECT(json);
}
@@ -305,9 +320,9 @@ int api_stats_top_clients(struct ftl_conn *api)
if(client == NULL || (!client->flags.aliasclient && client->aliasclient_id >= 0))
continue;
temparray[clientID][0] = clientID;
temparray[2*clientID + 0] = clientID;
// Use either blocked or total count based on request string
temparray[clientID][1] = blocked ? client->blockedcount : client->count;
temparray[2*clientID + 1] = blocked ? client->blockedcount : client->count;
}
// Sort temporary array
@@ -321,8 +336,8 @@ int api_stats_top_clients(struct ftl_conn *api)
for(int i=0; i < counters->clients; i++)
{
// Get sorted indices and counter values (may be either total or blocked count)
const int clientID = temparray[i][0];
const int client_count = temparray[i][1];
const int clientID = temparray[2*i + 0];
const int client_count = temparray[2*i + 1];
// Get client pointer
const clientsData* client = getClient(clientID, true);
if(client == NULL)
@@ -367,6 +382,8 @@ int api_stats_top_clients(struct ftl_conn *api)
if(n == count)
break;
}
// Free temporary array
free(temparray);
cJSON *json = JSON_NEW_OBJECT();
JSON_ADD_ITEM_TO_OBJECT(json, "clients", top_clients);
@@ -382,7 +399,12 @@ int api_stats_upstreams(struct ftl_conn *api)
{
const int forwarded = get_forwarded_count();
unsigned int totalcount = 0;
int temparray[forwarded][2];
int *temparray = calloc(2*forwarded, sizeof(int*));
if(temparray == NULL)
{
log_err("Memory allocation failed in api_stats_upstreams()");
return 0;
}
// Lock shared memory
lock_shm();
@@ -394,12 +416,12 @@ int api_stats_upstreams(struct ftl_conn *api)
if(upstream == NULL)
continue;
temparray[upstreamID][0] = upstreamID;
temparray[2*upstreamID + 0] = upstreamID;
unsigned int count = 0;
for(unsigned i = 0; i < ArraySize(upstream->overTime); i++)
count += upstream->overTime[i];
temparray[upstreamID][1] = count;
temparray[2*upstreamID + 1] = count;
totalcount += count;
}
@@ -433,7 +455,7 @@ int api_stats_upstreams(struct ftl_conn *api)
{
// Regular upstream destionation
// Get sorted indices
const int upstreamID = temparray[i][0];
const int upstreamID = temparray[2*i + 0];
// Get upstream pointer
const upstreamsData *upstream = getUpstream(upstreamID, true);
@@ -480,6 +502,9 @@ int api_stats_upstreams(struct ftl_conn *api)
}
}
// Free temporary array
free(temparray);
cJSON *json = JSON_NEW_OBJECT();
JSON_ADD_ITEM_TO_OBJECT(json, "upstreams", upstreams);
const int forwarded_queries = get_forwarded_count();
+7 -7
View File
@@ -233,9 +233,9 @@ static int api_teleporter_POST(struct ftl_conn *api)
const char *error = read_teleporter_zip(data.zip_data, data.zip_size, hint, json_files);
if(error != NULL)
{
char msg[strlen(error) + strlen(hint) + 4];
memset(msg, 0, sizeof(msg));
strncpy(msg, error, sizeof(msg));
const size_t msglen = strlen(error) + strlen(hint) + 4;
char *msg = calloc(msglen, sizeof(char));
strncpy(msg, error, msglen);
if(strlen(hint) > 0)
{
// Concatenate error message and hint into a single string
@@ -243,10 +243,10 @@ static int api_teleporter_POST(struct ftl_conn *api)
strcat(msg, hint);
}
free_upload_data(&data);
return send_json_error(api, 400,
"bad_request",
"Invalid ZIP archive",
msg);
return send_json_error_free(api, 400,
"bad_request",
"Invalid ZIP archive",
msg, true);
}
// Free allocated memory
+1 -1
View File
@@ -321,7 +321,7 @@ void parse_args(int argc, char* argv[])
if(argc == 3 && strcmp(argv[1], "dnsmasq-test-file") == 0)
{
const char *arg[3];
char filename[strlen(argv[2])+strlen("--conf-file=")+1];
char *filename = calloc(strlen(argv[2])+strlen("--conf-file=")+1, sizeof(char));
arg[0] = "";
sprintf(filename, "--conf-file=%s", argv[2]);
arg[1] = filename;
+1 -1
View File
@@ -257,7 +257,7 @@ static bool readStringValue(struct conf_item *conf_item, const char *value)
const cJSON *item = cJSON_GetArrayItem(elem, i);
if(!cJSON_IsString(item))
{
log_err("Config setting %s is invalid: element with index %d is not a string", conf_item->k, i);
log_err("Config setting %s is invalid: element with index %u is not a string", conf_item->k, i);
cJSON_Delete(elem);
return false;
}
+1 -1
View File
@@ -152,7 +152,7 @@ struct conf_item *get_debug_item(const enum debug_flag debug)
// Sanity check
if(debug > DEBUG_MAX-1)
{
log_err("Debug config item with index %u requested but we have only %u debug elements", debug, DEBUG_MAX-1);
log_err("Debug config item with index %u requested but we have only %i debug elements", debug, DEBUG_MAX-1);
return NULL;
}
+2 -2
View File
@@ -557,7 +557,7 @@ bool read_legacy_dhcp_static_config(void)
cJSON *item = cJSON_CreateString(value);
cJSON_AddItemToArray(config.dhcp.hosts.v.json, item);
log_debug(DEBUG_CONFIG, DNSMASQ_STATIC_LEASES": Setting %s[%d] = %s\n",
log_debug(DEBUG_CONFIG, DNSMASQ_STATIC_LEASES": Setting %s[%u] = %s\n",
config.dhcp.hosts.k, j++, item->valuestring);
}
@@ -620,7 +620,7 @@ bool read_legacy_cnames_config(void)
cJSON *item = cJSON_CreateString(value);
cJSON_AddItemToArray(config.dns.cnames.v.json, item);
log_debug(DEBUG_CONFIG, DNSMASQ_CNAMES": Setting %s[%d] = %s\n",
log_debug(DEBUG_CONFIG, DNSMASQ_CNAMES": Setting %s[%u] = %s\n",
config.dns.cnames.k, j++, item->valuestring);
}
+8 -7
View File
@@ -156,7 +156,7 @@ const char *readFTLlegacy(struct config *conf)
// - larger than 0.1min (6sec), and
// - smaller than 1440.0min (once a day)
if(fvalue >= 0.1f && fvalue <= 1440.0f)
conf->database.DBinterval.v.ui = (int)(fvalue * 60);
conf->database.DBinterval.v.ui = (unsigned int)(fvalue * 60);
// DBFILE
// defaults to: "/etc/pihole/pihole-FTL.db"
@@ -552,12 +552,13 @@ const char *readFTLlegacy(struct config *conf)
// CHECK_SHMEM
// Limit above which FTL should complain about a shared-memory shortage
// defaults to: 90%
unsigned int uvalue = 0;
conf->misc.check.shmem.v.ui = 90;
buffer = parseFTLconf(fp, "CHECK_SHMEM");
if(buffer != NULL && sscanf(buffer, "%i", &ivalue) &&
ivalue >= 0 && ivalue <= 100)
conf->misc.check.shmem.v.ui = ivalue;
if(buffer != NULL && sscanf(buffer, "%u", &uvalue) &&
uvalue <= 100)
conf->misc.check.shmem.v.ui = uvalue;
// CHECK_DISK
// Limit above which FTL should complain about disk shortage for checked files
@@ -565,9 +566,9 @@ const char *readFTLlegacy(struct config *conf)
conf->misc.check.disk.v.ui = 90;
buffer = parseFTLconf(fp, "CHECK_DISK");
if(buffer != NULL && sscanf(buffer, "%i", &ivalue) &&
ivalue >= 0 && ivalue <= 100)
conf->misc.check.disk.v.ui = ivalue;
if(buffer != NULL && sscanf(buffer, "%u", &uvalue) &&
uvalue <= 100)
conf->misc.check.disk.v.ui = uvalue;
// Read DEBUG_... setting from pihole-FTL.conf
// This option should be the last one as it causes
+9 -4
View File
@@ -88,7 +88,7 @@ static void printTOMLstring(FILE *fp, const char *s)
fprintf(fp, "\"");
for ( ; len; len--, s++)
{
int ch = *s;
unsigned char ch = *s;
if (isprint(ch) && ch != '"' && ch != '\\')
{
putc(ch, fp);
@@ -243,12 +243,17 @@ void print_toml_allowed_values(cJSON *allowed_values, FILE *fp, const unsigned i
{
// Frame item name in "..."
const size_t buflen = strlen(item->valuestring) + 3u;
char itemname[buflen];
char *itemname = calloc(buflen, sizeof(char));
// Leading "
itemname[0] = '"';
strncpy(itemname+1, item->valuestring, buflen);
// Copy string (we already know that the string
// length is buflen - 3u)
strncpy(itemname + 1, item->valuestring, buflen - 3u);
// Trailing "
itemname[buflen-2] = '"';
// Print item name
print_comment(fp, itemname, " - ", 85, indent);
free(itemname);
}
else if(item->valueint < 100)
{
@@ -591,7 +596,7 @@ void readTOMLvalue(struct conf_item *conf_item, const char* key, toml_table_t *t
const toml_datum_t d = toml_string_at(array, i);
if(!d.ok)
{
log_debug(DEBUG_CONFIG, "%s is an invalid array (found at index %d)", conf_item->k, i);
log_debug(DEBUG_CONFIG, "%s is an invalid array (found at index %u)", conf_item->k, i);
break;
}
// Add string to our JSON array
+1 -1
View File
@@ -256,7 +256,7 @@ static void reportDebugConfig(void)
// at 1
debugstr(debug_flag, &name);
// Calculate number of spaces to nicely align output
unsigned int spaces = 20 - strlen(name);
int spaces = 20 - strlen(name);
// Print debug flag
// We skip the first 6 characters of the flags as they are always "DEBUG_"
log_debug(DEBUG_ANY, "* %s:%*s %s *", name+6, spaces, "", debug_flags[debug_flag] ? "YES" : "NO ");
+2 -2
View File
@@ -207,7 +207,7 @@ void delay_startup(void)
}
// Sleep if requested by DELAY_STARTUP
log_info("Sleeping for %d seconds as requested by configuration ...", config.misc.delay_startup.v.ui);
log_info("Sleeping for %u seconds as requested by configuration ...", config.misc.delay_startup.v.ui);
if(sleep(config.misc.delay_startup.v.ui) != 0)
{
log_crit("Sleeping was interrupted by an external signal");
@@ -356,7 +356,7 @@ void calc_cpu_usage(void)
return;
}
// Percentage of CPU time spent executing instructions
cpu_usage = 100.0f * (clk - last_clock) / CLOCKS_PER_SEC;
cpu_usage = 100.0f * ((float)clk - (float)last_clock) / CLOCKS_PER_SEC;
last_clock = clk;
}
+1 -1
View File
@@ -1307,7 +1307,7 @@ bool in_auditlist(const char *domain)
bool gravityDB_get_regex_client_groups(clientsData* client, const unsigned int numregex, const regexData *regex,
const unsigned char type, const char* table)
{
log_debug(DEBUG_REGEX, "Getting regex client groups for client with ID %i", client->id);
log_debug(DEBUG_REGEX, "Getting regex client groups for client with ID %u", client->id);
char *querystr = NULL;
if(!client->flags.found_group && !get_client_groupids(client))
+2 -2
View File
@@ -267,7 +267,7 @@ static bool add_message(const enum message_type type,
// Bind message to prepared statement
if(rc != SQLITE_OK)
{
log_err("add_message(type=%u, message=%s) - Failed to bind argument %u (type %u): %s",
log_err("add_message(type=%u, message=%s) - Failed to bind argument %d (type %u): %s",
type, message, 3 + j, datatype, sqlite3_errstr(rc));
sqlite3_reset(stmt);
sqlite3_finalize(stmt);
@@ -339,7 +339,7 @@ void logg_subnet_warning(const char *ip, const int matching_count, const char *m
void logg_hostname_warning(const char *ip, const char *name, const unsigned int pos)
{
// Log to FTL.log
log_warn("Host name of client \"%s\" => \"%s\" contains (at least) one invalid character at position %d",
log_warn("Host name of client \"%s\" => \"%s\" contains (at least) one invalid character at position %u",
ip, name, pos);
// Log to database
+22 -13
View File
@@ -26,7 +26,7 @@
// Private prototypes
static char *getMACVendor(const char *hwaddr) __attribute__ ((malloc));
enum arp_status { CLIENT_NOT_HANDLED, CLIENT_ARP_COMPLETE, CLIENT_ARP_INCOMPLETE };
enum arp_status { CLIENT_NOT_HANDLED, CLIENT_ARP_COMPLETE, CLIENT_ARP_INCOMPLETE } __attribute__ ((packed));
bool create_network_table(sqlite3 *db)
{
@@ -420,7 +420,7 @@ static int update_netDB_numQueries(sqlite3 *db, const int dbID, const int numQue
return SQLITE_OK;
const int ret = dbquery(db, "UPDATE network "
"SET numQueries = numQueries + %u "
"SET numQueries = numQueries + %i "
"WHERE id = %i;",
numQueries, dbID);
@@ -520,19 +520,19 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if(rc != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\") - SQL error prepare (%i): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
checkFTLDBrc(rc);
return rc;
}
log_debug(DEBUG_DATABASE, "dbquery: \"%s\" with arguments ?1-?5 = (\"%s\",%lu,%lu,%u,\"%s\")",
querystr, hwaddr, now, lastQuery, numQueriesARP, macVendor);
querystr, hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor);
// Bind hwaddr to prepared statement (1st argument)
if((rc = sqlite3_bind_text(query_stmt, 1, hwaddr, -1, SQLITE_STATIC)) != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to bind hwaddr (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -542,7 +542,7 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if((rc = sqlite3_bind_int(query_stmt, 2, now)) != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to bind now (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -552,7 +552,7 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if((rc = sqlite3_bind_int(query_stmt, 3, lastQuery)) != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to bind lastQuery (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -562,7 +562,7 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if((rc = sqlite3_bind_int(query_stmt, 4, numQueriesARP)) != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to bind numQueriesARP (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -572,7 +572,7 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if((rc = sqlite3_bind_text(query_stmt, 5, macVendor, -1, SQLITE_STATIC)) != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to bind macVendor (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -582,7 +582,7 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if ((rc = sqlite3_step(query_stmt)) != SQLITE_DONE)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to step (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -592,7 +592,7 @@ static int insert_netDB_device(sqlite3 *db, const char *hwaddr, time_t now, time
if ((rc = sqlite3_finalize(query_stmt)) != SQLITE_OK)
{
log_err("insert_netDB_device(\"%s\",%lu, %lu, %u, \"%s\"): Failed to finalize (error %d): %s",
hwaddr, now, lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
hwaddr, (unsigned long)now, (unsigned long)lastQuery, numQueriesARP, macVendor, rc, sqlite3_errstr(rc));
sqlite3_reset(query_stmt);
checkFTLDBrc(rc);
return rc;
@@ -1263,7 +1263,7 @@ void parse_neighbor_cache(sqlite3* db)
lock_shm();
const int clients = counters->clients;
unlock_shm();
enum arp_status client_status[clients];
enum arp_status *client_status = calloc(clients, sizeof(enum arp_status));
for(int i = 0; i < clients; i++)
{
client_status[i] = CLIENT_NOT_HANDLED;
@@ -1493,17 +1493,26 @@ void parse_neighbor_cache(sqlite3* db)
if(rc != SQLITE_OK)
{
log_err("Database error in ARP cache processing loop");
free(client_status);
return;
}
// Check thread cancellation
if(killed)
{
free(client_status);
return;
}
// Loop over all clients known to FTL and ensure we add them all to the
// database
if(!add_FTL_clients_to_network_table(db, client_status, now, &additional_entries))
{
free(client_status);
return;
}
free(client_status);
client_status = NULL;
// Check thread cancellation
if(killed)
@@ -1545,7 +1554,7 @@ void parse_neighbor_cache(sqlite3* db)
}
// Debug logging
log_debug(DEBUG_ARP, "ARP table processing (%i entries from ARP, %i from FTL's cache) took %.1f ms",
log_debug(DEBUG_ARP, "ARP table processing (%u entries from ARP, %u from FTL's cache) took %.1f ms",
entries, additional_entries, timer_elapsed_msec(ARP_TIMER));
}
+6 -6
View File
@@ -387,7 +387,7 @@ bool import_queries_from_disk(void)
if(!detach_disk_database(NULL))
return false;
log_info("Imported %d queries from the on-disk database (it has %d rows)", mem_db_num, disk_db_num);
log_info("Imported %u queries from the on-disk database (it has %u rows)", mem_db_num, disk_db_num);
return okay;
}
@@ -446,7 +446,7 @@ bool export_queries_to_disk(bool final)
sqlite3_errstr(rc));
// Get number of queries actually inserted by the INSERT INTO ... SELECT * FROM ...
const int insertions = sqlite3_changes(memdb);
const unsigned int insertions = sqlite3_changes(memdb);
// Finalize statement
sqlite3_reset(stmt);
@@ -502,7 +502,7 @@ bool export_queries_to_disk(bool final)
}
}
log_debug(DEBUG_DATABASE, "Exported %u rows for disk.query_storage (took %.1f ms, last SQLite ID %li)",
log_debug(DEBUG_DATABASE, "Exported %u rows for disk.query_storage (took %.1f ms, last SQLite ID %lu)",
insertions, timer_elapsed_msec(DATABASE_WRITE_TIMER), last_disk_db_idx);
return okay;
@@ -551,7 +551,7 @@ bool add_additional_info_column(sqlite3 *db)
SQL_bool(db, "ALTER TABLE queries ADD COLUMN additional_info TEXT;");
// Update the database version to 7
SQL_bool(db, "INSERT OR REPLACE INTO ftl (id, value) VALUES (%u, 7);", DB_VERSION);
SQL_bool(db, "INSERT OR REPLACE INTO ftl (id, value) VALUES (%d, 7);", DB_VERSION);
return true;
}
@@ -1350,7 +1350,7 @@ bool queries_to_database(void)
{
// Store database index for this query (in case we need to
// update it later on)
query->db = ++last_mem_db_idx;
query->db = (int64_t)++last_mem_db_idx;
// Total counter information (delta computation)
new_total++;
@@ -1379,7 +1379,7 @@ bool queries_to_database(void)
if(config.debug.database.v.b && updated + added > 0)
{
log_debug(DEBUG_DATABASE, "In-memory database: Added %d new, updated %d known queries", added, updated);
log_debug(DEBUG_DATABASE, "In-memory database: Added %u new, updated %u known queries", added, updated);
log_in_memory_usage();
}
+6 -6
View File
@@ -101,7 +101,7 @@ int findUpstreamID(const char * upstreamString, const in_port_t port)
// This upstream server is not known
// Store ID
const int upstreamID = counters->upstreams;
log_debug(DEBUG_ANY, "New upstream server: %s:%u (%i/%u)", upstreamString, port, upstreamID, counters->upstreams_MAX);
log_debug(DEBUG_ANY, "New upstream server: %s:%u (%i/%i)", upstreamString, port, upstreamID, counters->upstreams_MAX);
// Get upstream pointer
upstreamsData* upstream = getUpstream(upstreamID, false);
@@ -698,7 +698,7 @@ const char * __attribute__ ((const)) get_refresh_hostnames_str(const enum refres
}
}
int __attribute__ ((const)) get_refresh_hostnames_val(const char *refresh_hostnames)
int __attribute__ ((pure)) get_refresh_hostnames_val(const char *refresh_hostnames)
{
if(strcasecmp(refresh_hostnames, "ALL") == 0)
return REFRESH_ALL;
@@ -733,7 +733,7 @@ const char * __attribute__ ((const)) get_blocking_mode_str(const enum blocking_m
}
}
int __attribute__ ((const)) get_blocking_mode_val(const char *blocking_mode)
int __attribute__ ((pure)) get_blocking_mode_val(const char *blocking_mode)
{
if(strcasecmp(blocking_mode, "IP") == 0)
return MODE_IP;
@@ -944,7 +944,7 @@ const char * __attribute__ ((const)) get_ptr_type_str(const enum ptr_type pihole
return NULL;
}
int __attribute__ ((const)) get_ptr_type_val(const char *piholePTR)
int __attribute__ ((pure)) get_ptr_type_val(const char *piholePTR)
{
if(strcasecmp(piholePTR, "pi.hole") == 0)
return PTR_PIHOLE;
@@ -976,7 +976,7 @@ const char * __attribute__ ((const)) get_busy_reply_str(const enum busy_reply re
return NULL;
}
int __attribute__ ((const)) get_busy_reply_val(const char *replyWhenBusy)
int __attribute__ ((pure)) get_busy_reply_val(const char *replyWhenBusy)
{
if(strcasecmp(replyWhenBusy, "BLOCK") == 0)
return BUSY_BLOCK;
@@ -1007,7 +1007,7 @@ const char * __attribute__ ((const)) get_listening_mode_str(const enum listening
return NULL;
}
int __attribute__ ((const)) get_listening_mode_val(const char *listening_mode)
int __attribute__ ((pure)) get_listening_mode_val(const char *listening_mode)
{
if(strcasecmp(listening_mode, "LOCAL") == 0)
return LISTEN_LOCAL;
+5 -5
View File
@@ -149,15 +149,15 @@ const char *get_query_status_str(const enum query_status status) __attribute__ (
const char *get_query_dnssec_str(const enum dnssec_status dnssec) __attribute__ ((const));
const char *get_query_reply_str(const enum reply_type query) __attribute__ ((const));
const char *get_refresh_hostnames_str(const enum refresh_hostnames refresh) __attribute__ ((const));
int get_refresh_hostnames_val(const char *refresh_hostnames) __attribute__ ((const));
int get_refresh_hostnames_val(const char *refresh_hostnames) __attribute__ ((pure));
const char *get_blocking_mode_str(const enum blocking_mode mode) __attribute__ ((const));
int get_blocking_mode_val(const char *blocking_mode) __attribute__ ((const));
int get_blocking_mode_val(const char *blocking_mode) __attribute__ ((pure));
const char *get_ptr_type_str(const enum ptr_type piholePTR) __attribute__ ((const));
int get_ptr_type_val(const char *piholePTR) __attribute__ ((const));
int get_ptr_type_val(const char *piholePTR) __attribute__ ((pure));
const char *get_busy_reply_str(const enum busy_reply replyWhenBusy) __attribute__ ((const));
int get_busy_reply_val(const char *replyWhenBusy) __attribute__ ((const));
int get_busy_reply_val(const char *replyWhenBusy) __attribute__ ((pure));
const char * get_listening_mode_str(const enum listening_mode listening_mode) __attribute__ ((const));
int get_listening_mode_val(const char *listening_mode) __attribute__ ((const));
int get_listening_mode_val(const char *listening_mode) __attribute__ ((pure));
// Pointer getter functions
#define getQuery(queryID, checkMagic) _getQuery(queryID, checkMagic, __LINE__, __FUNCTION__, __FILE__)
+14 -10
View File
@@ -324,9 +324,10 @@ static void print_dhcp_offer(struct in_addr source, dhcp_packet_data *offer_pack
// We may need to escape this, buffer size: 4
// chars per control character plus room for
// possible "(empty)"
char buffer[4*optlen + 9];
char *buffer = calloc(4*optlen + 9, sizeof(char));
binbuf_to_escaped_C_literal(&offer_packet->options[x], optlen, buffer, sizeof(buffer));
printf("%s: \"%s\"\n", opttab[i].name, buffer);
free(buffer);
}
else if(opttab[i].size & OT_TIME)
{
@@ -380,8 +381,8 @@ static void print_dhcp_offer(struct in_addr source, dhcp_packet_data *offer_pack
printf("Message type: DHCPINFORM (8)\n");
break;
default:
printf("Message type: UNKNOWN (%u)\n",
offer_packet->options[x]);
printf("Message type: UNKNOWN (%hhu)\n",
(unsigned char)offer_packet->options[x]);
break;
}
}
@@ -411,9 +412,10 @@ static void print_dhcp_offer(struct in_addr source, dhcp_packet_data *offer_pack
// We may need to escape this, buffer size: 4
// chars per control character plus room for
// possible "(empty)"
char buffer[4*optlen + 9];
char *buffer = calloc(4*optlen + 9, sizeof(char));
binbuf_to_escaped_C_literal(&offer_packet->options[x], optlen, buffer, sizeof(buffer));
printf("wpad-server: \"%s\"\n", buffer);
free(buffer);
}
else if(opttype == 158) // DHCPv4 PCP Option (RFC 7291)
{ // https://tools.ietf.org/html/rfc7291#section-4
@@ -462,13 +464,13 @@ static void print_dhcp_offer(struct in_addr source, dhcp_packet_data *offer_pack
if(cidr == 0)
{
// default route (0.0.0.0/0)
printf(" %d: default via %d.%d.%d.%d\n", i,
printf(" %u: uefault via %u.%u.%u.%u\n", i,
router[0], router[1], router[2], router[3]);
}
else
{
// specific route
printf(" %d: %d.%d.%d.%d/%d via %d.%d.%d.%d\n", i,
printf(" %u: %u.%u.%u.%u/%u via %u.%u.%u.%u\n", i,
addr[0], addr[1], addr[2], addr[3], cidr,
router[0], router[1], router[2], router[3]);
}
@@ -612,9 +614,10 @@ static bool get_dhcp_offer(const int sock, const uint32_t xid, const char *iface
if(offer_packet.sname[0] != 0)
{
size_t len = strlen(offer_packet.sname);
char buffer[4*len + 9];
char *buffer = calloc(4*len + 9, sizeof(char));
binbuf_to_escaped_C_literal(offer_packet.sname, len, buffer, sizeof(buffer));
printf("%s\n", buffer);
free(buffer);
}
else
printf("(empty)\n");
@@ -623,9 +626,10 @@ static bool get_dhcp_offer(const int sock, const uint32_t xid, const char *iface
if(offer_packet.file[0] != 0)
{
size_t len = strlen(offer_packet.file);
char buffer[4*len + 9];
char *buffer = calloc(4*len + 9, sizeof(char));
binbuf_to_escaped_C_literal(offer_packet.file, len, buffer, sizeof(buffer));
printf("%s\n", buffer);
free(buffer);
}
else
printf("(empty)\n");
@@ -665,8 +669,8 @@ static void *dhcp_discover_iface(void *args)
get_hardware_address(dhcp_socket, iface, mac);
// Generate pseudo-random transaction ID
srand(time(NULL));
const uint32_t xid = random();
srand((unsigned int)time(NULL));
const uint32_t xid = (uint32_t)random();
if(strcmp(iface, "lo") == 0)
{
+8 -8
View File
@@ -342,9 +342,9 @@ size_t _FTL_make_answer(struct dns_header *header, char *limit, const size_t len
forced_ip)
{
if(hostname && config.dns.reply.host.overwrite_v4.v.b)
memcpy(&addr, &config.dns.reply.host.v4.v.in_addr, sizeof(addr));
memcpy(&addr, &config.dns.reply.host.v4.v.in_addr, sizeof(config.dns.reply.host.v4.v.in_addr));
else if(!hostname && config.dns.reply.blocking.overwrite_v4.v.b)
memcpy(&addr, &config.dns.reply.blocking.v4.v.in_addr, sizeof(addr));
memcpy(&addr, &config.dns.reply.blocking.v4.v.in_addr, sizeof(config.dns.reply.blocking.v4.v.in_addr));
else
memcpy(&addr, &next_iface.addr4, sizeof(addr));
}
@@ -377,9 +377,9 @@ size_t _FTL_make_answer(struct dns_header *header, char *limit, const size_t len
forced_ip)
{
if(hostname && config.dns.reply.host.overwrite_v6.v.b)
memcpy(&addr, &config.dns.reply.host.v6.v.in6_addr, sizeof(addr));
memcpy(&addr, &config.dns.reply.host.v6.v.in6_addr, sizeof(config.dns.reply.host.v6.v.in6_addr));
else if(!hostname && config.dns.reply.blocking.overwrite_v6.v.b)
memcpy(&addr, &config.dns.reply.blocking.v6.v.in6_addr, sizeof(addr));
memcpy(&addr, &config.dns.reply.blocking.v6.v.in6_addr, sizeof(config.dns.reply.blocking.v6.v.in6_addr));
else
memcpy(&addr, &next_iface.addr6, sizeof(addr));
}
@@ -2772,13 +2772,13 @@ void FTL_fork_and_bind_sockets(struct passwd *ent_pw)
// we're actually dropping root (user/group my be set to root)
if(ent_pw != NULL && ent_pw->pw_uid != 0)
{
log_info("FTL is going to drop from root to user %s (UID %d)",
ent_pw->pw_name, (int)ent_pw->pw_uid);
log_info("FTL is going to drop from root to user %s (UID %u)",
ent_pw->pw_name, ent_pw->pw_uid);
if(chown(config.files.log.ftl.v.s, ent_pw->pw_uid, ent_pw->pw_gid) == -1)
log_warn("Setting ownership (%i:%i) of %s failed: %s (%i)",
log_warn("Setting ownership (%u:%u) of %s failed: %s (%i)",
ent_pw->pw_uid, ent_pw->pw_gid, config.files.log.ftl.v.s, strerror(errno), errno);
if(chown(config.files.database.v.s, ent_pw->pw_uid, ent_pw->pw_gid) == -1)
log_warn("Setting ownership (%i:%i) of %s failed: %s (%i)",
log_warn("Setting ownership (%u:%u) of %s failed: %s (%i)",
ent_pw->pw_uid, ent_pw->pw_gid, config.files.database.v.s, strerror(errno), errno);
chown_all_shmem(ent_pw);
}
+19 -15
View File
@@ -54,12 +54,12 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
// Debug logging
if(config.debug.edns0.v.b)
{
char payload[3*plen+1];
memset(payload, 0, sizeof(payload));
char *payload = calloc(3*plen+1, sizeof(char));
for(unsigned int i = 0; i < plen; i++)
sprintf(&payload[3*i], "%02X ", pheader[i]);
log_debug(DEBUG_EDNS0, "EDNS(0) pheader: %s (%lu bytes)",
payload, (long unsigned int)plen);
free(payload);
}
// Working pointer
@@ -222,7 +222,7 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
!(family == 2 && source_netmask == 128))
{
log_debug(DEBUG_EDNS0, "EDNS(0) CLIENT SUBNET: %s/%u found (IPv%u)",
ipaddr, source_netmask, family == 1 ? 4 : 6);
ipaddr, source_netmask, family == 1 ? 4u : 6u);
continue;
}
@@ -236,13 +236,13 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
(family == 2 && IN6_IS_ADDR_LOOPBACK(&addr.addr6)))
{
log_debug(DEBUG_EDNS0, "EDNS(0) CLIENT SUBNET: Skipped %s/%u (IPv%u loopback address)",
ipaddr, source_netmask, family == 1 ? 4 : 6);
ipaddr, source_netmask, family == 1 ? 4u : 6u);
}
else
{
edns->client_set = true;
log_debug(DEBUG_EDNS0, "EDNS(0) CLIENT SUBNET: %s/%u - OK (IPv%u)",
ipaddr, source_netmask, family == 1 ? 4 : 6);
ipaddr, source_netmask, family == 1 ? 4u : 6u);
}
}
else if(code == EDNS0_COOKIE && optlen == 8)
@@ -270,7 +270,7 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
memcpy(client_cookie, p, 8);
unsigned short server_cookie_len = optlen - 8;
unsigned char server_cookie[server_cookie_len];
unsigned char *server_cookie = calloc(server_cookie_len, sizeof(unsigned char));
memcpy(server_cookie, p + 8u, server_cookie_len);
if(config.debug.edns0.v.b)
{
@@ -278,13 +278,15 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
char *pp = pretty_client_cookie;
for(unsigned int j = 0; j < 8; j++)
pp += sprintf(pp, "%02X", client_cookie[j]);
char pretty_server_cookie[server_cookie_len*2 + 1u]; // server: variable length
char *pretty_server_cookie = calloc(server_cookie_len*2 + 1u, sizeof(char)); // server: variable length
pp = pretty_server_cookie;
for(unsigned int j = 0; j < server_cookie_len; j++)
pp += sprintf(pp, "%02X", server_cookie[j]);
log_debug(DEBUG_EDNS0, "EDNS(0) COOKIE (client + server): %s (client), %s (server, %u bytes)",
pretty_client_cookie, pretty_server_cookie, server_cookie_len);
free(pretty_server_cookie);
}
free(server_cookie);
// Advance working pointer
p += optlen;
@@ -306,12 +308,12 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
memcpy(edns->mac_text, p, 17);
edns->mac_text[17] = '\0';
if(sscanf(edns->mac_text, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
&edns->mac_byte[0],
&edns->mac_byte[1],
&edns->mac_byte[2],
&edns->mac_byte[3],
&edns->mac_byte[4],
&edns->mac_byte[5]) == 6)
(unsigned char*)&edns->mac_byte[0],
(unsigned char*)&edns->mac_byte[1],
(unsigned char*)&edns->mac_byte[2],
(unsigned char*)&edns->mac_byte[3],
(unsigned char*)&edns->mac_byte[4],
(unsigned char*)&edns->mac_byte[5]) == 6)
{
edns->mac_set = true;
log_debug(DEBUG_EDNS0, "EDNS(0) MAC address (TEXT format): %s", edns->mac_text);
@@ -335,19 +337,21 @@ void FTL_parse_pseudoheaders(struct dns_header *header, size_t n, union mysockad
else if(code == EDNS0_CPE_ID && optlen < 256)
{
// EDNS(0) CPE-ID, 256 byte arbitrary limit
unsigned char payload[optlen + 1u]; // variable length
unsigned char *payload = calloc(optlen + 1u, sizeof(unsigned char));
memcpy(payload, p, optlen);
payload[optlen] = '\0';
if(config.debug.edns0.v.b)
{
char pretty_payload[optlen*5 + 1u];
char *pretty_payload = calloc(optlen*5 + 1u, sizeof(char));
char *pp = pretty_payload;
for(unsigned int j = 0; j < optlen; j++)
pp += sprintf(pp, "0x%02X ", payload[j]);
pretty_payload[optlen*5 - 1] = '\0'; // Truncate away the trailing whitespace
log_debug(DEBUG_EDNS0, "EDNS(0) CPE-ID (payload size %u): \"%s\" (%s)",
optlen, payload, pretty_payload);
free(pretty_payload);
}
free(payload);
// Advance working pointer
p += optlen;
+27 -14
View File
@@ -38,7 +38,7 @@ bool chmod_file(const char *filename, const mode_t mode)
{
if(chmod(filename, mode) < 0)
{
log_warn("chmod(%s, %d): chmod() failed: %s",
log_warn("chmod(%s, %u): chmod() failed: %s",
filename, mode, strerror(errno));
return false;
}
@@ -46,7 +46,7 @@ bool chmod_file(const char *filename, const mode_t mode)
struct stat st;
if(stat(filename, &st) < 0)
{
log_warn("chmod(%s, %d): stat() failed: %s",
log_warn("chmod(%s, %u): stat() failed: %s",
filename, mode, strerror(errno));
return false;
}
@@ -55,7 +55,7 @@ bool chmod_file(const char *filename, const mode_t mode)
// 0x1FF = 0b111_111_111 corresponding to the three-digit octal mode number
if((st.st_mode & 0x1FF) != mode)
{
log_warn("chmod(%s, %d): Verification failed, %d != %d",
log_warn("chmod(%s, %u): Verification failed, %u != %u",
filename, mode, st.st_mode, mode);
return false;
}
@@ -143,7 +143,8 @@ void ls_dir(const char* path)
}
// Stack space for full path (directory + "/" + filename + terminating \0)
char full_path[strlen(path)+NAME_MAX+2];
const size_t full_path_len = strlen(path) + NAME_MAX + 2;
char *full_path = calloc(full_path_len, sizeof(char));
log_info("------ Listing content of directory %s ------", path);
log_info("File Mode User:Group Size Filename");
@@ -156,7 +157,7 @@ void ls_dir(const char* path)
const char *filename = dircontent->d_name;
// Construct full path
snprintf(full_path, sizeof(full_path), "%s/%s", path, filename);
snprintf(full_path, full_path_len, "%s/%s", path, filename);
struct stat st;
// Use stat to get file size, permissions, and ownership
@@ -172,7 +173,7 @@ void ls_dir(const char* path)
if ((pwd = getpwuid(st.st_uid)) != NULL)
snprintf(user, sizeof(user), "%s", pwd->pw_name);
else
snprintf(user, sizeof(user), "%d", st.st_uid);
snprintf(user, sizeof(user), "%u", st.st_uid);
struct group *grp;
char usergroup[256];
@@ -180,7 +181,7 @@ void ls_dir(const char* path)
if ((grp = getgrgid(st.st_gid)) != NULL)
snprintf(usergroup, sizeof(usergroup), "%s:%s", user, grp->gr_name);
else
snprintf(usergroup, sizeof(usergroup), "%s:%d", user, st.st_gid);
snprintf(usergroup, sizeof(usergroup), "%s:%u", user, st.st_gid);
char permissions[10];
get_permission_string(permissions, &st);
@@ -195,6 +196,10 @@ void ls_dir(const char* path)
log_info("---------------------------------------------------");
// Free memory
free(full_path);
full_path = NULL;
// Close directory stream
closedir(dirp);
}
@@ -295,20 +300,22 @@ void rotate_files(const char *path)
const char *filename = basename(fname);
// extra 6 bytes is enough space for up to 999 rotations ("/", ".", "\0", "999")
const size_t buflen = strlen(filename) + MAX(strlen(BACKUP_DIR), strlen(path)) + 6;
char old_path[buflen];
char *old_path = calloc(buflen, sizeof(char));
if(i == 1)
snprintf(old_path, buflen, "%s", path);
else
snprintf(old_path, buflen, BACKUP_DIR"/%s.%u", filename, i-1);
char new_path[buflen];
char *new_path = calloc(buflen, sizeof(char));
snprintf(new_path, buflen, BACKUP_DIR"/%s.%u", filename, i);
free(fname);
char old_path_compressed[strlen(old_path) + 4];
snprintf(old_path_compressed, sizeof(old_path_compressed), "%s.gz", old_path);
size_t old_path_len = strlen(old_path) + 4;
char *old_path_compressed = calloc(old_path_len, sizeof(char));
snprintf(old_path_compressed, old_path_len, "%s.gz", old_path);
char new_path_compressed[strlen(new_path) + 4];
snprintf(new_path_compressed, sizeof(new_path_compressed), "%s.gz", new_path);
size_t new_path_len = strlen(new_path) + 4;
char *new_path_compressed = calloc(new_path_len, sizeof(char));
snprintf(new_path_compressed, new_path_len, "%s.gz", new_path);
if(file_exists(old_path))
{
@@ -349,9 +356,15 @@ void rotate_files(const char *path)
{
// Log success if debug is enabled
log_debug(DEBUG_CONFIG, "Rotated %s -> %s",
new_path_compressed, new_path);
old_path_compressed, new_path_compressed);
}
}
// Free memory
free(old_path);
free(new_path);
free(old_path_compressed);
free(new_path_compressed);
}
}
+2 -2
View File
@@ -56,7 +56,7 @@ static void reset_rate_limiting(void)
// Check if we want to continue rate limiting
if(client->rate_limit > config.dns.rateLimit.count.v.ui)
{
log_info("Still rate-limiting %s as it made additional %d queries", clientIP, client->rate_limit);
log_info("Still rate-limiting %s as it made additional %u queries", clientIP, client->rate_limit);
}
// or if rate-limiting ends for this client now
else
@@ -186,7 +186,7 @@ void *GC_thread(void *val)
timer_start(GC_TIMER);
char timestring[TIMESTR_SIZE] = "";
get_timestr(timestring, mintime, false, false);
log_info("GC starting, mintime: %s (%llu)", timestring, (long long)mintime);
log_info("GC starting, mintime: %s (%lu)", timestring, (unsigned long)mintime);
}
// Process all queries
+3 -2
View File
@@ -426,7 +426,7 @@ void FTL_log_helper(const unsigned char n, ...)
// Extract all variable arguments
va_list args;
char *arg[n];
char **arg = calloc(n, sizeof(char*));
va_start(args, n);
for(unsigned char i = 0; i < n; i++)
{
@@ -460,6 +460,7 @@ void FTL_log_helper(const unsigned char n, ...)
for(unsigned char i = 0; i < n; i++)
if(arg[i] != NULL)
free(arg[i]);
free(arg);
}
void format_memory_size(char prefix[2], const unsigned long long int bytes,
@@ -669,7 +670,7 @@ int binbuf_to_escaped_C_literal(const char *src_buf, size_t src_sz,
*dst++ = '0';
break;
default:
sprintf(dst, "0x%X", *src);
sprintf(dst, "0x%X", *(unsigned char*)src);
dst += 4;
}
+9 -9
View File
@@ -31,7 +31,7 @@ static void initSlot(const unsigned int index, const time_t timestamp)
{
char timestr[20];
strftime(timestr, 20, "%Y-%m-%d %H:%M:%S", localtime(&timestamp));
log_debug(DEBUG_OVERTIME, "initSlot(%u, %llu): Zeroing overTime slot at %s", index, (long long)timestamp, timestr);
log_debug(DEBUG_OVERTIME, "initSlot(%u, %lu): Zeroing overTime slot at %s", index, (unsigned long)timestamp, timestr);
}
// Initialize overTime entry
@@ -87,8 +87,8 @@ void initOverTime(void)
char first[20], last[20];
strftime(first, 20, "%Y-%m-%d %H:%M:%S", localtime(&oldest));
strftime(last, 20, "%Y-%m-%d %H:%M:%S", localtime(&newest));
log_debug(DEBUG_OVERTIME, "initOverTime(): Initializing %i slots from %s (%llu) to %s (%llu)",
OVERTIME_SLOTS, first, (long long)oldest, last, (long long)newest);
log_debug(DEBUG_OVERTIME, "initOverTime(): Initializing %i slots from %s (%lu) to %s (%lu)",
OVERTIME_SLOTS, first, (unsigned long)oldest, last, (unsigned long)newest);
}
// Iterate over overTime
@@ -138,10 +138,10 @@ unsigned int _getOverTimeID(time_t timestamp, const char *file, const int line)
char lastTimestampStr[TIMESTR_SIZE] = "";
get_timestr(lastTimestampStr, lastTimestamp, false, false);
log_warn("Found database entries in the future (%s (%llu), last timestamp for importing: %s (%llu)). "
log_warn("Found database entries in the future (%s (%lu), last timestamp for importing: %s (%lu)). "
"Your over-time statistics may be incorrect (found in %s:%d)",
timestampStr, (long long)timestamp,
lastTimestampStr, (long long)lastTimestamp,
timestampStr, (unsigned long)timestamp,
lastTimestampStr, (unsigned long)lastTimestamp,
short_path(file), line);
warned_about_hwclock = true;
}
@@ -150,7 +150,7 @@ unsigned int _getOverTimeID(time_t timestamp, const char *file, const int line)
}
// Debug output
log_debug(DEBUG_OVERTIME, "getOverTimeID(%llu): %i", (long long)timestamp, id);
log_debug(DEBUG_OVERTIME, "getOverTimeID(%lu): %i", (unsigned long)timestamp, id);
return (unsigned int) id;
}
@@ -173,8 +173,8 @@ void moveOverTimeMemory(const time_t mintime)
// The number of slots which will be moved (not garbage collected)
const unsigned int remainingSlots = OVERTIME_SLOTS - moveOverTime;
log_debug(DEBUG_OVERTIME, "moveOverTimeMemory(): IS: %llu, SHOULD: %llu, MOVING: %u",
(long long)oldestOverTimeIS, (long long)oldestOverTimeSHOULD, moveOverTime);
log_debug(DEBUG_OVERTIME, "moveOverTimeMemory(): IS: %lu, SHOULD: %lu, MOVING: %u",
(unsigned long)oldestOverTimeIS, (unsigned long)oldestOverTimeSHOULD, moveOverTime);
// Check if the move over amount is valid. This prevents errors if the
// function is called before GC is necessary.
+3 -3
View File
@@ -221,9 +221,9 @@ bool parse_proc_meminfo(struct proc_meminfo *mem)
sscanf(line, "MemTotal: %lu kB", &mem->total);
sscanf(line, "MemFree: %lu kB", &mem->mfree);
sscanf(line, "MemAvailable: %lu kB", &mem->avail);
sscanf(line, "Cached: %lu kB", &page_cached);
sscanf(line, "Buffers: %lu kB", &buffers);
sscanf(line, "SReclaimable: %lu kB", &slab_reclaimable);
sscanf(line, "Cached: %ld kB", &page_cached);
sscanf(line, "Buffers: %ld kB", &buffers);
sscanf(line, "SReclaimable: %ld kB", &slab_reclaimable);
}
fclose(meminfo);
+14 -8
View File
@@ -139,7 +139,7 @@ unsigned int __attribute__((pure)) get_num_regex(const enum regex_type regexid)
bool compile_regex(const char *regexin, regexData *regex, char **message)
{
// Extract possible Pi-hole extensions
char rgxbuf[strlen(regexin) + 1u];
char *rgxbuf = calloc(strlen(regexin) + 1u, sizeof(char));
// Parse special FTL syntax if present
if(strstr(regexin, FTL_REGEX_SEP) != NULL)
{
@@ -147,7 +147,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
// Extract regular expression pattern in front of FTL-specific syntax
char *saveptr = NULL;
char *part = strtok_r(buf, FTL_REGEX_SEP, &saveptr);
strncpy(rgxbuf, part, sizeof(rgxbuf));
strncpy(rgxbuf, part, strlen(regexin));
// Analyze FTL-specific parts
while((part = strtok_r(NULL, FTL_REGEX_SEP, &saveptr)) != NULL)
@@ -161,6 +161,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
{
*message = strdup("Overwriting previous querytype setting (multiple \"querytype=...\" found)");
free(buf);
free(rgxbuf);
return false;
}
@@ -189,6 +190,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
if(asprintf(message, "Unknown querytype \"%s\"", extra) < 1)
log_err("Memory allocation failed in compile_regex()");
free(buf);
free(rgxbuf);
return false;
}
@@ -258,6 +260,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
if(asprintf(message, "Unknown reply type \"%s\"", extra) < 1)
log_err("Memory allocation failed in compile_regex()");
free(buf);
free(rgxbuf);
return false;
}
@@ -270,6 +273,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
if(asprintf(message, "Invalid regex option \"%s\"", part) < 1)
log_err("Memory allocation failed in compile_regex()");
free(buf);
free(rgxbuf);
return false;
}
}
@@ -290,6 +294,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
(void) regerror (errcode, &regex->regex, regex_msg, sizeof(regex_msg));
*message = strdup(regex_msg);
regex->available = false;
free(rgxbuf);
return false;
}
@@ -297,6 +302,7 @@ bool compile_regex(const char *regexin, regexData *regex, char **message)
regex->string = strdup(regexin);
regex->available = true;
free(rgxbuf);
return true;
}
@@ -507,7 +513,7 @@ void free_regex(void)
if(regex == NULL)
continue;
log_debug(DEBUG_DATABASE, "Going to free %i entries in %s regex struct",
log_debug(DEBUG_DATABASE, "Going to free %u entries in %s regex struct",
oldcount, regextype[regexid]);
// Loop over entries with this regex type
@@ -609,7 +615,7 @@ static void read_regex_table(const enum regex_type regexid)
// since we counted its entries
if(num_regex[regexid] >= (unsigned int)count)
{
log_warn("read_regex_table(%s) exiting early to avoid overflow (%d/%d).",
log_warn("read_regex_table(%s) exiting early to avoid overflow (%u/%d).",
regextype[regexid], num_regex[regexid], count);
break;
}
@@ -624,7 +630,7 @@ static void read_regex_table(const enum regex_type regexid)
continue;
// Debug logging
log_debug(DEBUG_REGEX, "Compiling %s regex %i (DB ID %i): %s",
log_debug(DEBUG_REGEX, "Compiling %s regex %u (DB ID %i): %s",
regextype[regexid], num_regex[regexid], rowid, regex_string);
const int index = num_regex[regexid]++;
@@ -649,7 +655,7 @@ static void read_regex_table(const enum regex_type regexid)
gravityDB_finalizeTable();
// Debug logging
log_debug(DEBUG_DATABASE, "Read %i %s regex entries",
log_debug(DEBUG_DATABASE, "Read %u %s regex entries",
num_regex[regexid],
regextype[regexid]);
}
@@ -686,7 +692,7 @@ void read_regex_from_database(void)
}
// Print message to FTL's log after reloading regex filters
log_info("Compiled %i allow and %i deny regex for %i client%s in %.1f msec",
log_info("Compiled %u allow and %u deny regex for %i client%s in %.1f msec",
num_regex[REGEX_ALLOW], num_regex[REGEX_DENY],
counters->clients, counters->clients > 1 ? "s" : "",
timer_elapsed_msec(REGEX_TIMER));
@@ -719,7 +725,7 @@ int regex_test(const bool debug_mode, const bool quiet, const char *domainin, co
read_regex_table(REGEX_DENY);
read_regex_table(REGEX_ALLOW);
log_ctrl(false, !quiet); // Re-apply quiet option after compilation
log_info(" Compiled %i deny and %i allow regex in %.3f msec\n",
log_info(" Compiled %u deny and %u allow regex in %.3f msec\n",
num_regex[REGEX_DENY], num_regex[REGEX_ALLOW],
timer_elapsed_msec(REGEX_TIMER));
+2 -2
View File
@@ -118,8 +118,8 @@ static void print_used_resolvers(const char *message)
char nsname[INET6_ADDRSTRLEN];
inet_ntop(family, addr, nsname, INET6_ADDRSTRLEN);
log_debug(DEBUG_RESOLVER, " %s %u: %s:%d (IPv%i)", i < MAXNS ? " " : "EXT",
j, nsname, port, family == AF_INET ? 4 : 6);
log_debug(DEBUG_RESOLVER, " %s %d: %s:%hu (IPv%u)", i < MAXNS ? " " : "EXT",
j, nsname, port, family == AF_INET ? 4u : 6u);
}
}
+4 -4
View File
@@ -84,7 +84,7 @@ static void get_conf_string_array_from_setupVars(const char *key, struct conf_it
cJSON *item = cJSON_CreateString(setupVarsArray[i]);
cJSON_AddItemToArray(conf_item->v.json, item);
log_debug(DEBUG_CONFIG, "setupVars.conf:%s -> Setting %s[%d] = %s\n",
log_debug(DEBUG_CONFIG, "setupVars.conf:%s -> Setting %s[%u] = %s\n",
key, conf_item->k, i, item->valuestring);
}
}
@@ -100,8 +100,8 @@ static void get_conf_upstream_servers_from_setupVars(struct conf_item *conf_item
for(unsigned int j = 0; j < MAX_SERVERS; j++)
{
// Get clients which the user doesn't want to see
char server_key[strlen("PIHOLE_DNS_XX") + 1];
sprintf(server_key, "PIHOLE_DNS_%d", j);
char server_key[sizeof("PIHOLE_DNS_XX") + 1];
sprintf(server_key, "PIHOLE_DNS_%u", j);
// Get value from setupVars.conf (if present)
const char *value = read_setupVarsconf(server_key);
@@ -112,7 +112,7 @@ static void get_conf_upstream_servers_from_setupVars(struct conf_item *conf_item
cJSON *item = cJSON_CreateString(value);
cJSON_AddItemToArray(conf_item->v.json, item);
log_debug(DEBUG_CONFIG, "setupVars.conf:PIHOLE_DNS_%d -> Setting %s[%d] = %s\n",
log_debug(DEBUG_CONFIG, "setupVars.conf:PIHOLE_DNS_%u -> Setting %s[%u] = %s\n",
j, conf_item->k, j, item->valuestring);
}
+4 -4
View File
@@ -177,7 +177,7 @@ static bool chown_shmem(SharedMemory *sharedMemory, struct passwd *ent_pw)
{
// Open shared memory object
const int fd = shm_open(sharedMemory->name, O_RDWR, S_IRUSR | S_IWUSR);
log_debug(DEBUG_SHMEM, "Changing %s (%d) to %d:%d", sharedMemory->name, fd, ent_pw->pw_uid, ent_pw->pw_gid);
log_debug(DEBUG_SHMEM, "Changing %s (%d) to %u:%u", sharedMemory->name, fd, ent_pw->pw_uid, ent_pw->pw_gid);
if(fd == -1)
{
log_crit("chown_shmem(): Failed to open shared memory object \"%s\": %s",
@@ -186,7 +186,7 @@ static bool chown_shmem(SharedMemory *sharedMemory, struct passwd *ent_pw)
}
if(fchown(fd, ent_pw->pw_uid, ent_pw->pw_gid) == -1)
{
log_warn("chown_shmem(%d, %d, %d): failed for %s: %s (%d)",
log_warn("chown_shmem(%d, %u, %u): failed for %s: %s (%d)",
fd, ent_pw->pw_uid, ent_pw->pw_gid, sharedMemory->name,
strerror(errno), errno);
return false;
@@ -1028,7 +1028,7 @@ bool get_per_client_regex(const int clientID, const int regexID)
const size_t maxval = shm_per_client_regex.size / sizeof(bool);
if(id > maxval)
{
log_err("get_per_client_regex(%d, %d): Out of bounds (%d > %d * %d, shm_per_client_regex.size = %zd)!",
log_err("get_per_client_regex(%d, %d): Out of bounds (%u > %d * %u, shm_per_client_regex.size = %zu)!",
clientID, regexID,
id, counters->clients, num_regex_tot, maxval);
return false;
@@ -1043,7 +1043,7 @@ void set_per_client_regex(const int clientID, const int regexID, const bool valu
const size_t maxval = shm_per_client_regex.size / sizeof(bool);
if(id > maxval)
{
log_err("set_per_client_regex(%d, %d, %s): Out of bounds (%d > %d * %d, shm_per_client_regex.size = %zd)!",
log_err("set_per_client_regex(%d, %d, %s): Out of bounds (%u > %d * %u, shm_per_client_regex.size = %zu)!",
clientID, regexID, value ? "true" : "false",
id, counters->clients, num_regex_tot, maxval);
return;
+10 -1
View File
@@ -77,6 +77,13 @@ int send_json_unauthorized(struct ftl_conn *api)
int send_json_error(struct ftl_conn *api, const int code,
const char *key, const char* message,
const char *hint)
{
return send_json_error_free(api, code, key, message, (char*)hint, false);
}
int send_json_error_free(struct ftl_conn *api, const int code,
const char *key, const char* message,
char *hint, bool free_hint)
{
if(hint)
log_warn("API: %s (%s)", message, hint);
@@ -86,7 +93,9 @@ int send_json_error(struct ftl_conn *api, const int code,
cJSON *error = JSON_NEW_OBJECT();
JSON_REF_STR_IN_OBJECT(error, "key", key);
JSON_REF_STR_IN_OBJECT(error, "message", message);
JSON_REF_STR_IN_OBJECT(error, "hint", hint);
JSON_COPY_STR_TO_OBJECT(error, "hint", hint);
if(free_hint)
free(hint);
cJSON *json = JSON_NEW_OBJECT();
JSON_ADD_ITEM_TO_OBJECT(json, "error", error);
+3
View File
@@ -69,6 +69,9 @@ int send_json_unauthorized(struct ftl_conn *api);
int send_json_error(struct ftl_conn *api, const int code,
const char *key, const char* message,
const char *hint);
int send_json_error_free(struct ftl_conn *api, const int code,
const char *key, const char* message,
char *hint, bool free_hint);
int send_json_success(struct ftl_conn *api);
const char *get_http_method_str(const enum http_method method) __attribute__((const));
+9 -2
View File
@@ -61,7 +61,7 @@ int ph7_handler(struct mg_connection *conn, void *cbdata)
buffer_len += 11; // strlen("/index.php")
}
char full_path[buffer_len];
char *full_path = calloc(buffer_len, sizeof(char));
memcpy(full_path, config.webserver.paths.webroot.v.s, webroot_len);
full_path[webroot_len] = '/';
memcpy(full_path + webroot_len + 1u, local_uri, local_uri_len);
@@ -87,12 +87,14 @@ int ph7_handler(struct mg_connection *conn, void *cbdata)
if( rc == PH7_IO_ERR )
{
logg_web(FIFO_PH7, "%s: IO error while opening the target file", full_path);
free(full_path);
// Fall back to HTTP server to handle the 404 event
return 0;
}
else if( rc == PH7_VM_ERR )
{
logg_web(FIFO_PH7, "%s: VM initialization error", full_path);
free(full_path);
// Mark file as processed - this prevents the HTTP server
// from printing the raw PHP source code to the user
return 1;
@@ -100,6 +102,7 @@ int ph7_handler(struct mg_connection *conn, void *cbdata)
else
{
logg_web(FIFO_PH7, "%s: Compile error (%d)", full_path, rc);
free(full_path);
mg_printf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"
"PHP compilation error, check %s for further details.",
@@ -146,11 +149,15 @@ int ph7_handler(struct mg_connection *conn, void *cbdata)
if( rc != PH7_OK )
{
logg_web(FIFO_PH7, "%s: VM execution error", full_path);
free(full_path);
// Mark file as processed - this prevents the HTTP server
// from printing the raw PHP source code to the user
return 1;
}
free(full_path);
full_path = NULL;
// Extract and send the output (if any)
const void *pOut = NULL;
unsigned int nLen = 0u;
@@ -175,7 +182,7 @@ static int PH7_error_report(const void *pOutput, unsigned int nOutputLen,
// Log error message, strip trailing newline character if any
if(((const char*)pOutput)[nOutputLen-1] == '\n')
nOutputLen--;
logg_web(FIFO_PH7, "%.*s", nOutputLen, (const char*)pOutput);
logg_web(FIFO_PH7, "%.*s", (int)nOutputLen, (const char*)pOutput);
return PH7_OK;
}
-2
View File
@@ -426,7 +426,6 @@ bool deflate_file(const char *infilename, const char *outfilename, bool verbose)
if(!success)
{
log_warn("Failed to compress %s", infilename);
free(buffer_uncompressed);
if(buffer_compressed)
free(buffer_compressed);
fclose(outfile);
@@ -438,7 +437,6 @@ bool deflate_file(const char *infilename, const char *outfilename, bool verbose)
{
log_warn("Failed to write %lu bytes to %s", (unsigned long)size_compressed, outfilename);
fclose(outfile);
free(buffer_uncompressed);
free(buffer_compressed);
return false;
}
+4 -4
View File
@@ -533,7 +533,7 @@ const char *read_teleporter_zip(char *buffer, const size_t buflen, char * const
mz_zip_archive_file_stat file_stat;
if(!mz_zip_reader_file_stat(&zip, i, &file_stat))
{
log_warn("Failed to get file information for file %d in ZIP archive: %s",
log_warn("Failed to get file information for file %u in ZIP archive: %s",
i, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
continue;
}
@@ -555,19 +555,19 @@ const char *read_teleporter_zip(char *buffer, const size_t buflen, char * const
void *ptr = malloc(file_stat.m_uncomp_size);
if(ptr == NULL)
{
log_warn("Failed to allocate memory for file %d (%s) in ZIP archive: %s",
log_warn("Failed to allocate memory for file %u (%s) in ZIP archive: %s",
i, file_stat.m_filename, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
continue;
}
if(!mz_zip_reader_extract_to_mem(&zip, i, ptr, file_stat.m_uncomp_size, 0))
{
log_warn("Failed to read file %d (%s) in ZIP archive: %s",
log_warn("Failed to read file %u (%s) in ZIP archive: %s",
i, file_stat.m_filename, mz_zip_get_error_string(mz_zip_get_last_error(&zip)));
free(ptr);
continue;
}
log_debug(DEBUG_CONFIG, "Processing file %d (%s) in ZIP archive (%zu/%zu bytes, comment: \"%s\", timestamp: %lu)",
log_debug(DEBUG_CONFIG, "Processing file %u (%s) in ZIP archive (%zu/%zu bytes, comment: \"%s\", timestamp: %lu)",
i, file_stat.m_filename, (size_t)file_stat.m_comp_size, (size_t)file_stat.m_uncomp_size,
file_stat.m_comment, (unsigned long)file_stat.m_time);