Skip to content

Commit 125794f

Browse files
committed
FTL SQL query rewrite (cleaner, allow more domains)
1 parent 30e96a2 commit 125794f

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

pihole-checklogs.sh

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -330,23 +330,36 @@ function grep_dns_logs() {
330330
#######################################
331331
function check_domains() {
332332
pinfo "Checking for FQDNs/domains in FTL DB..."
333+
if [[ "${#TAB_FQDN[*]}" -gt 100 ]]; then
334+
pwarn "There are ${#TAB_FQDN[*]} FQDNs to check, query will take a (very) long time"
335+
fi
333336
# Building SQL query for Pi-hole FTL DB
334-
local where_cond=""
337+
local ftl_query=""
338+
local in_list=""
339+
local like_buffer=""
340+
local like_values=""
335341
local a_fqdn=""
342+
local index=0
343+
for a_fqdn in "${TAB_FQDN[@]}"; do
344+
index=$(( index + 1 ))
345+
in_list="${in_list}'${a_fqdn}'"
346+
like_buffer="${like_buffer} OR domain LIKE '%.${a_fqdn}'"
347+
# OR x LIKE y OR x LIKE z chain is packaged in parenthesis group of 100 ORed LIKEs to
348+
# circumvent the default SQL depth limit of 1000 conditions in case the FQDNs search
349+
# is on more than 999 items.
350+
if [[ "${index}" -eq 100 ]]; then
351+
like_values="${like_values} OR (${like_buffer/ OR /})"
352+
like_buffer=""
353+
index=0
354+
fi
355+
done
356+
in_list="${in_list//\'\'/\', \'}"
336357
if [[ "${FQDN_MATCH_SUBDOMAINS}" == true ]]; then
337-
for a_fqdn in "${TAB_FQDN[@]}"; do
338-
where_cond="${where_cond}(domain LIKE '%${a_fqdn}')"
339-
done
340-
where_cond="${where_cond//)(/) OR (}"
358+
ftl_query="SELECT DISTINCT timestamp,domain,client FROM queries WHERE domain IN (${in_list})${like_values}"
341359
else
342360
pinfo "--nosubs flag is set, will look for exact matches only"
343-
for a_fqdn in "${TAB_FQDN[@]}"; do
344-
where_cond="${where_cond}'${a_fqdn}'"
345-
done
346-
where_cond="${where_cond//\'\'/\', \'}"
347-
where_cond="domain IN (${where_cond})"
361+
ftl_query="SELECT DISTINCT timestamp,domain,client FROM queries WHERE domain IN (${in_list})"
348362
fi
349-
local ftl_query="SELECT DISTINCT timestamp,domain,client FROM queries WHERE ( ${where_cond} )"
350363
# Executing sqlite3 command in FTL DB
351364
local sql_results=""
352365
# If results found, print, store results, and then look for details in DNS queries logs

0 commit comments

Comments
 (0)