2 # dns based ad/abuse domain blocking
3 # Copyright (c) 2015-2021 Dirk Brenken (dev@brenken.org)
4 # This is free software, licensed under the GNU General Public License v3.
6 # set (s)hellcheck exceptions
7 # shellcheck disable=1091,2010,2016,2034,2039,2059,2086,2091,2129,2143,2154,2181,2183,2188
12 export PATH
="/usr/sbin:/usr/bin:/sbin:/bin"
32 adb_dnsprefix
="adb_list"
33 adb_locallist
="blacklist whitelist iplist"
35 adb_backupdir
="${adb_tmpbase}/adblock-Backup"
36 adb_reportdir
="${adb_tmpbase}/adblock-Report"
38 adb_pidfile
="/var/run/adblock.pid"
39 adb_blacklist
="/etc/adblock/adblock.blacklist"
40 adb_whitelist
="/etc/adblock/adblock.whitelist"
41 adb_mailservice
="/etc/adblock/adblock.mail"
42 adb_dnsfile
="${adb_dnsprefix}.overall"
43 adb_dnsjail
="${adb_dnsprefix}.jail"
44 adb_srcarc
="/etc/adblock/adblock.sources.gz"
45 adb_srcfile
="${adb_tmpbase}/adb_sources.json"
46 adb_rtfile
="${adb_tmpbase}/adb_runtime.json"
47 adb_loggercmd
="$(command -v logger)"
48 adb_dumpcmd
="$(command -v tcpdump)"
49 adb_lookupcmd
="$(command -v nslookup)"
58 adb_lookupdomain
="example.com"
59 adb_action
="${1:-"start"}"
64 # load & check adblock environment
68 local bg_pid iface port ports
70 adb_sysver
="$(ubus -S call system board 2>/dev/null | jsonfilter -e '@.model' -e '@.release.description' | \
71 "${adb_awk}" 'BEGIN{ORS=", "}{print $0}' | "${adb_awk}" '{print substr($0,1,length($0)-2)}')"
73 if [ "${adb_action}" != "report" ]
79 if [ "${adb_enabled}" = "0" ]
85 f_log "info" "adblock is currently disabled, please set the config option 'adb_enabled
' to '1' to use this service"
89 if [ "${adb_report}" = "1" ] && [ ! -x "${adb_dumpcmd}" ]
91 f_log "info" "Please install the package 'tcpdump
' or 'tcpdump-mini
' to use the reporting feature"
92 elif [ "${adb_report}" = "0" ] && [ "${adb_action}" = "report" ]
94 f_log "info" "Please enable the 'DNS Report
' option to use the reporting feature"
98 bg_pid="$(pgrep -f "^${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
99 if [ -x "${adb_dumpcmd}" ] && { [ "${adb_report}" = "0" ] || { [ -n "${bg_pid}" ] && { [ "${adb_action}" = "stop" ] || [ "${adb_action}" = "restart" ]; }; }; }
101 if [ -n "${bg_pid}" ]
103 kill -HUP "${bg_pid}" 2>/dev
/null
104 while $
(kill -0 "${bg_pid}" 2>/dev
/null
)
112 if [ -x "${adb_dumpcmd}" ] && [ "${adb_report}" = "1" ] && [ -z "${bg_pid}" ] && [ "${adb_action}" != "report" ] && [ "${adb_action}" != "stop" ]
114 for port
in ${adb_replisten}
120 ports
="${ports} or port ${port}"
123 if [ -z "${adb_repiface}" ]
125 network_get_device iface
"lan"
128 adb_repiface
="${iface}"
130 network_get_physdev iface
"lan"
133 adb_repiface
="${iface}"
136 if [ -n "${adb_repiface}" ]
138 uci_set adblock global adb_repiface
"${adb_repiface}"
142 if [ -n "${adb_reportdir}" ] && [ ! -d "${adb_reportdir}" ]
144 mkdir
-p "${adb_reportdir}"
145 f_log
"info" "report directory '${adb_reportdir}' created"
147 if [ -n "${adb_repiface}" ] && [ -d "${adb_reportdir}" ]
149 ( "${adb_dumpcmd}" -nn -p -s0 -l -i ${adb_repiface} ${ports} -C${adb_repchunksize} -W${adb_repchunkcnt} -w "${adb_reportdir}/adb_report.pcap" >/dev
/null
2>&1 & )
150 bg_pid
="$(pgrep -f "^
${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
152 f_log "info" "Please set the name of the reporting network device 'adb_repiface
' manually"
157 # check & set environment
161 adb_starttime="$(date "+%s")"
162 f_log "info" "adblock instance started ::: action: ${adb_action}, priority: ${adb_nice:-"0"}, pid: ${$}"
167 if [ "${adb_dnsflush}" = "1" ]
169 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
173 if [ ! -r "${adb_srcfile}" ]
175 if [ -r "${adb_srcarc}" ]
177 zcat "${adb_srcarc}" > "${adb_srcfile}"
179 f_log "err" "adblock source archive not found"
182 if [ -r "${adb_srcfile}" ] && [ "${adb_action}" != "report" ]
185 json_load_file "${adb_srcfile}"
187 f_log "err" "adblock source file not found"
191 # load adblock config
195 local cnt=0 cnt_max=10
197 if [ ! -r "/etc/config/adblock" ] || [ -z "$(uci -q show adblock.global.adb_safesearch)" ]
199 f_log "err" "no valid adblock config found, please re-install the package via opkg with the '--force-reinstall --force-maintainer' options"
208 eval "${option}=\"${value}\""
214 if [ "${option}" = "adb_sources" ]
216 eval "${option}=\"$(printf "%s" "${adb_sources}") ${value}\""
217 elif [ "${option}" = "adb_eng_sources" ]
219 eval "${option}=\"$(printf "%s" "${adb_eng_sources}") ${value}\""
220 elif [ "${option}" = "adb_sha_sources" ]
222 eval "${option}=\"$(printf "%s" "${adb_sha_sources}") ${value}\""
223 elif [ "${option}" = "adb_stb_sources" ]
225 eval "${option}=\"$(printf "%s" "${adb_stb_sources}") ${value}\""
226 elif [ "${option}" = "adb_utc_sources" ]
228 eval "${option}=\"$(printf "%s" "${adb_utc_sources}") ${value}\""
229 elif [ "${option}" = "adb_denyip" ]
231 eval "${option}=\"$(printf "%s" "${adb_denyip}") ${value}\""
232 elif [ "${option}" = "adb_allowip" ]
234 eval "${option}=\"$(printf "%s" "${adb_allowip}") ${value}\""
235 elif [ "${option}" = "adb_safesearchlist" ]
237 eval "${option}=\"$(printf "%s" "${adb_safesearchlist}") ${value}\""
238 elif [ "${option}" = "adb_zonelist" ]
240 eval "${option}=\"$(printf "%s" "${adb_zonelist}") ${value}\""
241 elif [ "${option}" = "adb_portlist" ]
243 eval "${option}=\"$(printf "%s" "${adb_portlist}") ${value}\""
249 if [ -z "${adb_fetchutil}" ] || [ -z "${adb_dns}" ]
251 while [ -z "${adb_packages}" ] && [ "${cnt}" -le "${cnt_max}" ]
253 adb_packages="$(opkg list-installed 2>/dev/null)"
257 if [ -z "${adb_packages}" ]
259 f_log "err" "local opkg package repository is not available, please set 'adb_fetchutil
' and 'adb_dns
' manually"
264 # status helper function
268 local result input="${1}"
270 if [ "${input}" = "1" ]
276 printf "%s" "${result}"
279 # load dns backend config
283 local util utils dns_up cnt=0
285 if [ -z "${adb_dns}" ]
287 utils="knot-resolver bind unbound dnsmasq raw"
290 if [ "${util}" = "raw" ] || [ -n "$(printf "%s" "${adb_packages}" | grep "^${util}")" ]
292 if [ "${util}" = "knot-resolver" ]
295 elif [ "${util}" = "bind" ]
299 if [ "${util}" = "raw" ] || [ -x "$(command -v "${util}")" ]
302 uci_set adblock global adb_dns "${util}"
308 elif [ "${adb_dns}" != "raw" ] && [ ! -x "$(command -v "${adb_dns}")" ]
313 if [ -n "${adb_dns}" ]
318 adb_dnsinotify="${adb_dnsinotify:-"0"}"
319 adb_dnsinstance="${adb_dnsinstance:-"0"}"
320 adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
321 adb_dnsdir="${adb_dnsdir:-"/tmp/dnsmasq.d"}"
322 adb_dnsheader="${adb_dnsheader}"
323 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"address=/\"\$0\"/\"}'"}"
324 adb_dnsallow
="${adb_dnsallow:-"${adb_awk} '{print \"local=/\"\$0\"/#\"}'"}"
325 adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"address=/\"\$0\"/\"item\"\"}'"}"
326 adb_dnsstop="${adb_dnsstop:-"address=/#/"}"
329 adb_dnscachecmd="$(command -v unbound-control || printf "%s" "-")"
330 adb_dnsinotify="${adb_dnsinotify:-"0"}"
331 adb_dnsinstance="${adb_dnsinstance:-"0"}"
332 adb_dnsuser="${adb_dnsuser:-"unbound"}"
333 adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
334 adb_dnsheader="${adb_dnsheader}"
335 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 static\"}'"}"
336 adb_dnsallow
="${adb_dnsallow:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 transparent\"}'"}"
337 adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{type=\"AAAA\";if(match(item,/^([0-9]{1,3}\.
){3}[0-9]{1,3}$
/)){type=\"A
\"}}{print
\"local-data
: \\042\"\
$0\" \"type\" \"item
\"\\042\"}'"}"
338 adb_dnsstop="${adb_dnsstop:-"local-zone: \".\" static"}"
341 adb_dnscachecmd="$(command -v rndc || printf "%s" "-")"
342 adb_dnsinotify="${adb_dnsinotify:-"0"}"
343 adb_dnsinstance="${adb_dnsinstance:-"0"}"
344 adb_dnsuser="${adb_dnsuser:-"bind"}"
345 adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
346 adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n IN NS localhost.\n"}"
347 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
348 adb_dnsallow
="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
349 adb_dnsdenyip="${adb_dnsdenyip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME .\"}'"}"
350 adb_dnsallowip="${adb_dnsallowip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME rpz-passthru.\"}'"}"
351 adb_dnssafesearch
="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"\"\$0\" CNAME \"item\".\\n*.\"\$0\" CNAME \"item\".\"}'"}"
352 adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
356 adb_dnsinotify="${adb_dnsinotify:-"0"}"
357 adb_dnsinstance="${adb_dnsinstance:-"0"}"
358 adb_dnsuser="${adb_dnsuser:-"root"}"
359 adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
360 adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n"}"
361 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
362 adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
363 adb_dnssafesearch
="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{type=\"AAAA\";if(match(item,/^([0-9]{1,3}\.){3}[0-9]{1,3}$/)){type=\"A\"}}{print \"\"\$0\" \"type\" \"item\"\"}'"}"
364 adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
368 adb_dnsinotify="${adb_dnsinotify:-"0"}"
369 adb_dnsinstance="${adb_dnsinstance:-"0"}"
370 adb_dnsuser="${adb_dnsuser:-"root"}"
371 adb_dnsdir="${adb_dnsdir:-"/tmp"}"
372 adb_dnsheader="${adb_dnsheader}"
373 adb_dnsdeny="${adb_dnsdeny:-"0"}"
374 adb_dnsallow="${adb_dnsallow:-"1"}"
375 adb_dnssafesearch="${adb_dnssafesearch:-"0"}"
376 adb_dnsstop="${adb_dnsstop:-"0"}"
381 if [ "${adb_dns}" != "raw" ] && { [ -z "${adb_dns}" ] || [ ! -x "$(command -v "${adb_dns}")" ]; }
383 f_log
"err" "dns backend not found, please set 'adb_dns' manually"
386 if [ "${adb_dns}" != "raw" ] && { [ "${adb_dnsdir}" = "${adb_tmpbase}" ] || [ "${adb_dnsdir}" = "${adb_backupdir}" ] || [ "${adb_dnsdir}" = "${adb_reportdir}" ]; }
388 f_log "err
" "dns directory
'${adb_dnsdir}' has been misconfigured
, it must not point to the
'adb_tmpbase', 'adb_backupdir', 'adb_reportdir'"
391 if [ "${adb_action}" = "start
" ] && [ -z "${adb_trigger}" ]
393 sleep ${adb_triggerdelay}
396 if [ "${adb_dns}" != "raw
" ] && [ "${adb_action}" != "stop
" ]
398 while [ "${cnt}" -le 30 ]
400 dns_up="$
(ubus
-S call service list
"{\"name\":\"${adb_dns}\"}" 2>/dev
/null | jsonfilter
-l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev
/null
)"
401 if [ "${dns_up}" = "true
" ]
409 if [ -n "${adb_dnsdir}" ] && [ ! -d "${adb_dnsdir}" ]
411 mkdir -p "${adb_dnsdir}"
414 f_log "info
" "dns backend directory
'${adb_dnsdir}' created
"
416 f_log "err
" "dns backend directory
'${adb_dnsdir}' could not be created
"
420 if [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
422 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
425 if [ "${dns_up}" != "true
" ]
430 f_log "err
" "dns backend
'${adb_dns}' not running or executable
"
434 if [ "${adb_backup}" = "1" ] && [ -n "${adb_backupdir}" ] && [ ! -d "${adb_backupdir}" ]
436 mkdir -p "${adb_backupdir}"
439 f_log "info
" "backup directory
'${adb_backupdir}' created
"
441 f_log "err
" "backup directory
'${adb_backupdir}' could not be created
"
445 if [ -n "${adb_jaildir}" ] && [ ! -d "${adb_jaildir}" ]
447 mkdir -p "${adb_jaildir}"
450 f_log "info
" "jail directory
'${adb_jaildir}' created
"
452 f_log "err
" "jail directory
'${adb_jaildir}' could not be created
"
456 f_log "debug
" "f_dns
::: dns
: ${adb_dns}, dns_dir: ${adb_dnsdir}, dns_file: ${adb_dnsfile}, dns_user: ${adb_dnsuser}, dns_inotify: ${adb_dnsinotify}, dns_instance: ${adb_dnsinstance}, backup: ${adb_backup}, backup_dir: ${adb_backupdir}, jail_dir: ${adb_jaildir}"
463 local util utils insecure cnt=0
465 if [ -z "${adb_fetchutil}" ]
467 utils="aria2c curl wget uclient-fetch
"
470 if { [ "${util}" = "uclient-fetch" ] && [ -n "$(printf "%s" "${adb_packages}" | grep "^libustream-")" ]; } || \
471 { [ "${util}" = "wget" ] && [ -n "$(printf "%s" "${adb_packages}" | grep "^wget -")" ]; } || \
472 [ "${util}" = "curl
" ] || [ "${util}" = "aria2c
" ]
474 if [ -x "$
(command -v "${util}")" ]
476 adb_fetchutil="${util}"
477 uci_set adblock global adb_fetchutil "${util}"
483 elif [ ! -x "$
(command -v "${adb_fetchutil}")" ]
487 case "${adb_fetchutil}" in
489 if [ "${adb_fetchinsecure}" = "1" ]
491 insecure="--check-certificate=false
"
493 adb_fetchparm="${adb_fetchparm:-"${insecure} --timeout=20 --allow-overwrite=true --auto-file-renaming=false --log-level=warn --dir=/ -o"}"
496 if [ "${adb_fetchinsecure}" = "1" ]
498 insecure="--insecure"
500 adb_fetchparm="${adb_fetchparm:-"${insecure} --connect-timeout 20 --silent --show-error --location -o"}"
503 if [ "${adb_fetchinsecure}" = "1" ]
505 insecure="--no-check-certificate"
507 adb_fetchparm="${adb_fetchparm:-"${insecure} --timeout=20 -O"}"
510 if [ "${adb_fetchinsecure}" = "1" ]
512 insecure="--no-check-certificate"
514 adb_fetchparm="${adb_fetchparm:-"${insecure} --no-cache --no-cookies --max-redirect=0 --timeout=20 -O"}"
517 if [ -n "${adb_fetchutil}" ] && [ -n "${adb_fetchparm}" ]
519 adb_fetchutil="$
(command -v "${adb_fetchutil}")"
521 f_log "err
" "download utility with SSL support not found
, please
install 'uclient-fetch' with a
'libustream-*' variant or another download utility like
'wget', 'curl' or
'aria2'"
523 f_log "debug
" "f_fetch
::: fetch_util
: ${adb_fetchutil:-"-"}, fetch_parm
: ${adb_fetchparm:-"-"}"
526 # create temporary files, directories and set dependent options
532 cpu="$
(grep -c '^processor' /proc
/cpuinfo
2>/dev
/null
)"
533 core="$
(grep -cm1 '^core id' /proc
/cpuinfo
2>/dev
/null
)"
534 if [ "${cpu}" = "0" ]
538 if [ "${core}" = "0" ]
544 if [ -d "${adb_tmpbase}" ]
546 adb_tmpdir="$
(mktemp
-p "${adb_tmpbase}" -d)"
547 adb_tmpload="$
(mktemp
-p "${adb_tmpdir}" -tu)"
548 adb_tmpfile="$
(mktemp
-p "${adb_tmpdir}" -tu)"
549 adb_srtopts="--temporary-directory=${adb_tmpdir} --compress-program=gzip --batch-size=32 --parallel=${cores}"
551 f_log "err
" "the temp base directory
'${adb_tmpbase}' does not exist
/is not mounted yet
, please create the directory or raise the
'adb_triggerdelay' to defer the adblock start
"
553 if [ ! -s "${adb_pidfile}" ]
555 printf "%s
" "${$}" > "${adb_pidfile}"
557 f_log "debug
" "f_temp
::: tmp_base
: ${adb_tmpbase:-"-"}, tmp_dir: ${adb_tmpdir:-"-"}, cores: ${cores:-"-"}, sort_options: ${adb_srtopts}, pid_file: ${adb_pidfile:-"-"}"
560 # remove temporary files and directories
564 if [ -d "${adb_tmpdir}" ]
566 rm -rf "${adb_tmpdir}"
568 rm -f "${adb_srcfile}"
570 f_log "debug
" "f_rmtemp
::: tmp_dir
: ${adb_tmpdir:-"-"}, src_file: ${adb_srcfile:-"-"}, pid_file: ${adb_pidfile:-"-"}"
573 # remove dns related files
579 status="$
(ubus
-S call service list
'{"name":"adblock"}' 2>/dev
/null | jsonfilter
-l1 -e '@["adblock"].instances.*.running' 2>/dev
/null
)"
580 if [ "${adb_dns}" = "raw" ] || { [ -n "${adb_dns}" ] && [ -n "${status}" ]; }
583 if [ "${adb_backup}" = "1" ]
585 rm -f "${adb_backupdir}/${adb_dnsprefix}".
*.gz
587 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
591 f_log
"debug" "f_rmdns ::: dns: ${adb_dns}, status: ${status:-"-"}, dns_dir: ${adb_dnsdir}, dns_file: ${adb_dnsfile}, rt_file: ${adb_rtfile}, backup_dir: ${adb_backupdir:-"-"}"
598 local change config
="${1}"
600 if [ -n "${config}" ]
602 change
="$(uci -q changes "${config}" | "${adb_awk}" '{ORS=" "; print $0}')"
603 if [ -n "${change}" ]
605 uci_commit "${config}"
608 "/etc/init.d/firewall" reload >/dev/null 2>&1
611 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
614 "/etc/init.d/${adb_dns}" reload >/dev/null 2>&1
618 f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
626 local file mode="${1}" name="${2}"
631 if [ -s "${adb_tmpdir}/tmp.add.${name}" ]
633 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add.${name}")"
637 if [ -s "${adb_tmpfile}.${name}" ]
639 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpfile}.${name}")"
643 if [ -s "${adb_tmpdir}/tmp.raw.${name}" ]
645 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.raw.${name}")"
646 rm -f "${adb_tmpdir}/tmp.raw.${name}"
650 if [ -s "${adb_tmpdir}/tmp.safesearch.${name}" ]
652 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.safesearch.${name}")"
656 if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
658 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/${adb_dnsfile}")"
661 "download"|"backup"|"restore")
662 if [ -s "${src_tmpfile}" ]
664 adb_cnt="$(wc -l 2>/dev/null < "${src_tmpfile}")"
668 if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
670 adb_cnt="$(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}")"
671 if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]
673 adb_cnt=$((adb_cnt-$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add.whitelist")))
675 for file in "${adb_tmpdir}/tmp.safesearch".*
679 adb_cnt=$((adb_cnt-$(wc -l 2>/dev/null < "${file}")))
682 if [ -n "${adb_dnsheader}" ]
684 adb_cnt=$(((adb_cnt-$(printf "${adb_dnsheader}" | grep -c "^"))/2))
691 # set external config options
695 local config config_dir config_file section zone port fwcfg
700 config_dir="$(uci_get dhcp "@dnsmasq[${adb_dnsinstance}]" confdir | grep -Fo "${adb_dnsdir}")"
701 if [ "${adb_enabled}" = "1" ] && [ -z "${config_dir}" ]
703 uci_set dhcp "@dnsmasq[${adb_dnsinstance}]" confdir "${adb_dnsdir}" 2>/dev/null
708 config_file="$(uci_get resolver kresd rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
709 if [ "${adb_enabled}" = "1" ] && [ -z "${config_file}" ]
711 uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
712 elif [ "${adb_enabled}" = "0" ] && [ -n "${config_file}" ]
714 uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
721 fwcfg="$(uci -qNX show "${config}" | "${adb_awk}" 'BEGIN{FS="[.=]"};/adblock_/{if(zone==$2){next}else{ORS=" ";zone=$2;print zone}}')"
722 if [ "${adb_enabled}" = "1" ] && [ "${adb_forcedns}" = "1" ] && \
723 [ "$
(/etc
/init.d
/firewall enabled
; printf "%u" ${?})" = "0" ]
725 for zone in ${adb_zonelist}
727 for port in ${adb_portlist}
729 if [ -z "$
(printf "%s" "${fwcfg}" | grep -o -m1 "adblock_${zone}${port}[ |\$]")" ]
732 set firewall."adblock_
${zone}${port}"="redirect
"
733 set firewall."adblock_
${zone}${port}".name="Adblock DNS (${zone}, ${port})"
734 set firewall."adblock_
${zone}${port}".src="${zone}"
735 set firewall."adblock_
${zone}${port}".proto="tcp udp
"
736 set firewall."adblock_
${zone}${port}".src_dport="${port}"
737 set firewall."adblock_
${zone}${port}".dest_port="${port}"
738 set firewall."adblock_
${zone}${port}".target="DNAT
"
741 fwcfg="${fwcfg/adblock_${zone}${port}[ |\$]/}"
744 fwcfg="${fwcfg#"${fwcfg%%[![:space:]]*}"}"
745 fwcfg="${fwcfg%"${fwcfg##*[![:space:]]}"}"
747 if [ "${adb_enabled}" = "0" ] || [ "${adb_forcedns}" = "0" ] || [ -n "${fwcfg}" ]
749 for section in ${fwcfg}
751 uci_remove firewall "${section}"
757 # restart dns backend
761 local dns_service dns_up dns_pid dns_procfile restart_rc cnt=0 out_rc=4 in_rc="${1:-0}"
763 if [ "${adb_dns}" = "raw" ] || { [ "${in_rc}" = "0" ] && [ "${adb_dnsinotify}" = "1" ]; }
767 if [ "${in_rc}" = "0" ] && [ "${adb_dnsflush}" = "0" ]
771 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}/unbound.conf" ]
773 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" dump_cache > "${adb_tmpdir}/adb_cache.dump" 2>/dev
/null
775 "/etc/init.d/${adb_dns}" restart
>/dev
/null
2>&1
779 if [ -x "${adb_dnscachecmd}" ] && [ -f "/etc/bind/rndc.conf" ]
781 "${adb_dnscachecmd}" -c "/etc/bind/rndc.conf" reload
>/dev
/null
2>&1
784 if [ -z "${restart_rc}" ] || { [ -n "${restart_rc}" ] && [ "${restart_rc}" != "0" ]; }
786 "/etc
/init.d
/${adb_dns}" restart >/dev/null 2>&1
791 "/etc
/init.d
/${adb_dns}" restart >/dev/null 2>&1
796 if [ -z "${restart_rc}" ]
798 "/etc
/init.d
/${adb_dns}" restart >/dev/null 2>&1
802 if [ "${restart_rc}" = "0" ]
804 while [ "${cnt}" -le "${adb_dnstimeout}" ]
806 dns_service="$
(ubus
-S call service list
"{\"name\":\"${adb_dns}\"}")"
807 dns_up="$
(printf "%s" "${dns_service}" | jsonfilter
-l1 -e "@[\"${adb_dns}\"].instances.*.running")"
808 dns_pid="$
(printf "%s" "${dns_service}" | jsonfilter
-l1 -e "@[\"${adb_dns}\"].instances.*.pid")"
809 dns_procfile="$
(ls -l "/proc/${dns_pid}/fd" 2>/dev/null | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
810 if [ "${dns_up}" = "true" ] && [ -n "${dns_pid}" ] && [ -z "${dns_procfile}" ]
812 if [ -x "${adb_lookupcmd}" ] && [ "${adb_lookupdomain}" != "false
" ]
814 "${adb_lookupcmd}" "${adb_lookupdomain}" >/dev/null 2>&1
821 sleep ${adb_dnstimeout}
822 cnt=${adb_dnstimeout}
830 if [ "${out_rc}" = "0" ] && [ "${adb_dns}" = "unbound
" ]
832 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}/adb_cache.dump
" ]
834 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" load_cache < "${adb_tmpdir}/adb_cache.dump
" >/dev/null 2>&1
839 f_log "debug
" "f_dnsup
::: dns
: ${adb_dns}, cache_cmd: ${adb_dnscachecmd:-"-"}, lookup_cmd: ${adb_lookupcmd:-"-"}, lookup_domain: ${adb_lookupdomain:-"-"}, restart_rc: ${restart_rc:-"-"}, dns_flush: ${adb_dnsflush}, dns_inotify: ${adb_dnsinotify}, dns_timeout: ${adb_dnstimeout}, dns_cnt: ${cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
843 # backup/restore/remove blocklists
847 local hold file rset item array safe_url safe_ips safe_cname safe_domains ip out_rc mode="${1}" src_name="${2:-"${src_name}"}" in_rc="${src_rc:-0}" cnt="1" ffiles="-maxdepth 1 -name ${adb_dnsprefix}.
*.gz
"
852 if [ "${adb_dns}" = "named
" ]
854 rset="BEGIN
{FS
=\"[.
:]\";pfx
=\"32\"}{if(match
(\
$0,/:/))pfx
=\"128\"}{printf \"%s.
\",pfx
;for(seg
=NF
;seg
>=1;seg--
)if(seg
==1)printf \"%s
\n\",\
$seg;else if(\
$seg>=0)printf \"%s.
\",\
$seg; else printf \"%s.
\",\"zz
\"}"
855 if [ -n "${adb_allowip}" ]
857 > "${adb_tmpdir}/tmp.raw.
${src_name}"
858 for ip in ${adb_allowip}
860 printf "%s
" "${ip}" | "${adb_awk}" "${rset}" >> "${adb_tmpdir}/tmp.raw.${src_name}"
862 eval "${adb_dnsallowip}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.add.${src_name}"
865 if [ -n "${adb_denyip}" ] && { [ -z "${out_rc}" ] || [ "${out_rc}" = "0" ]; }
867 > "${adb_tmpdir}/tmp.raw.${src_name}"
868 for ip
in ${adb_denyip}
870 printf "%s" "${ip}" | "${adb_awk}" "${rset}" >> "${adb_tmpdir}/tmp.raw.${src_name}"
872 eval "${adb_dnsdenyip}" "${adb_tmpdir}/tmp.raw.${src_name}" >> "${adb_tmpdir}/tmp.add.${src_name}"
875 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
878 "blacklist"|
"whitelist")
880 if [ "${src_name}" = "blacklist" ] && [ -f "${adb_blacklist}" ]
882 rset
="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
883 "${adb_awk}" "${rset}" "${adb_blacklist}" | \
884 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${adb_tmpdir}/tmp.raw.${src_name}"
885 "${adb_sort}" ${adb_srtopts} -u "${adb_tmpdir}/tmp.raw.${src_name}" 2>/dev/null > "${adb_tmpfile}.${src_name}"
887 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
888 elif [ "${src_name}" = "whitelist" ] && [ -f "${adb_whitelist}" ]
890 rset
="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
891 "${adb_awk}" "${rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.raw.${src_name}"
893 if [ "${out_rc}" = "0" ]
895 rset
="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\\.\",\"\\\\.\",\$1);print tolower(\"^(|.*\\\\.)\"\$1\"$\")}"
896 "${adb_awk}" "${rset}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.rem.${src_name}"
898 if [ "${out_rc}" = "0" ] && [ "${adb_dnsallow}" != "1" ]
900 eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.add.${src_name}"
902 if [ "${out_rc}" = "0" ] && [ "${adb_jail}" = "1" ] && [ "${adb_dnsstop}" != "0" ]
904 > "${adb_jaildir}/${adb_dnsjail}"
905 if [ -n "${adb_dnsheader}" ]
907 printf "${adb_dnsheader}" >> "${adb_jaildir}/${adb_dnsjail}"
909 cat "${adb_tmpdir}/tmp.add.${src_name}" >> "${adb_jaildir}/${adb_dnsjail}"
910 printf "%s\n" "${adb_dnsstop}" >> "${adb_jaildir}/${adb_dnsjail}"
917 case "${src_name}" in
919 rset
="/^\\.([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{printf \"%s\n%s\n\",tolower(\"www\"\$1),tolower(substr(\$1,2,length(\$1)))}"
920 safe_url
="https://www.google.com/supported_domains"
921 safe_cname
="forcesafesearch.google.com"
922 safe_domains
="${adb_tmpdir}/tmp.load.safesearch.${src_name}"
923 if [ "${adb_backup}" = "1" ] && [ -s "${adb_backupdir}/safesearch.${src_name}.gz" ]
925 zcat
"${adb_backupdir}/safesearch.${src_name}.gz" > "${safe_domains}"
928 "${adb_fetchutil}" ${adb_fetchparm} "${safe_domains}" "${safe_url}" 2>/dev
/null
930 if [ "${adb_backup}" = "1" ] && [ "${out_rc}" = "0" ]
932 gzip -cf "${safe_domains}" > "${adb_backupdir}/safesearch.${src_name}.gz"
935 if [ "${out_rc}" = "0" ]
937 if [ -x "${adb_lookupcmd}" ]
939 safe_ips
="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
940 if [ -n "${safe_ips}" ]
942 "${adb_awk}" "${rset}" "${safe_domains}" > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
949 safe_cname="strict.bing.com"
950 safe_domains="www.bing.com"
951 if [ -x "${adb_lookupcmd}" ]
953 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
954 if [ -n "${safe_ips}" ]
956 printf "%s
\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
962 safe_cname
="safe.duckduckgo.com"
963 safe_domains
="duckduckgo.com"
964 if [ -x "${adb_lookupcmd}" ]
966 safe_ips
="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
967 if [ -n "${safe_ips}" ]
969 printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
975 safe_cname="safesearch.pixabay.com"
976 safe_domains="pixabay.com"
977 if [ -x "${adb_lookupcmd}" ]
979 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
980 if [ -n "${safe_ips}" ]
982 printf "%s
\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
988 safe_cname
="familysearch.yandex.ru"
989 safe_domains
="ya.ru yandex.ru yandex.com yandex.com.tr yandex.ua yandex.by yandex.ee yandex.lt yandex.lv yandex.md yandex.uz yandex.tm yandex.tj yandex.az yandex.kz"
990 if [ -x "${adb_lookupcmd}" ]
992 safe_ips
="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
993 if [ -n "${safe_ips}" ]
995 printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
1001 if [ "${adb_safesearchmod}" = "0" ]
1003 safe_cname="restrict.youtube.com"
1005 safe_cname="restrictmoderate.youtube.com"
1007 safe_domains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
1008 if [ -x "${adb_lookupcmd}" ]
1010 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
1011 if [ -n "${safe_ips}" ]
1013 printf "%s
\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
1019 if [ "${out_rc}" = "0" ] && [ -s "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" ]
1021 > "${adb_tmpdir}/tmp.safesearch.${src_name}"
1022 if [ "${adb_dns}" = "named" ]
1024 array
="${safe_cname}"
1028 for item
in ${array}
1030 eval "${adb_dnssafesearch}" "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" >> "${adb_tmpdir}/tmp.safesearch.${src_name}"
1031 if [ "${?}" != "0" ]
1033 rm -f "${adb_tmpdir}/tmp.safesearch.${src_name}"
1038 rm -f "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
1043 gzip -cf "${src_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
1048 if [ -n "${src_name}" ] && [ -s "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
1050 zcat
"${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${src_tmpfile}"
1052 elif [ -z "${src_name}" ]
1054 for file in "${adb_backupdir}/${adb_dnsprefix}".
*.gz
1060 zcat
"${file}" > "${adb_tmpfile}.${name}" &
1061 hold
=$
((cnt
%adb_maxqueue
))
1062 if [ "${hold}" = "0" ]
1074 if [ "${adb_action}" != "start" ] && [ "${adb_action}" != "resume" ] && [ -n "${src_name}" ] && [ "${out_rc}" != "0" ]
1076 adb_sources
="${adb_sources/${src_name}}"
1080 if [ "${adb_backup}" = "1" ]
1082 rm "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev
/null
1085 adb_sources
="${adb_sources/${src_name}}"
1088 if [ "${adb_backup}" = "1" ]
1090 for src_name
in ${adb_sources}
1092 ffiles
="${ffiles} -a ! -name ${adb_dnsprefix}.${src_name}.gz"
1094 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]
1096 ffiles
="${ffiles} -a ! -name safesearch.google.gz"
1098 find "${adb_backupdir}" ${ffiles} -print0 2>/dev
/null |
xargs -0 rm 2>/dev
/null
1101 "${adb_sort}" ${adb_srtopts} -mu "${adb_tmpfile}".* 2>/dev/null > "${adb_tmpdir}/${adb_dnsfile}"
1103 rm -f "${adb_tmpfile}".
*
1107 if [ -n "${adb_dnsheader}" ]
1109 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1111 > "${adb_dnsdir}/${adb_dnsfile}"
1113 if [ -s "${adb_tmpdir}/tmp.add.iplist" ]
1115 cat "${adb_tmpdir}/tmp.add.iplist" >> "${adb_dnsdir}/${adb_dnsfile}"
1117 if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]
1119 cat "${adb_tmpdir}/tmp.add.whitelist" >> "${adb_dnsdir}/${adb_dnsfile}"
1121 for file in "${adb_tmpdir}/tmp.safesearch".
*
1125 cat "${file}" >> "${adb_dnsdir}/${adb_dnsfile}"
1128 if [ "${adb_dnsdeny}" != "0" ]
1130 eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >> "${adb_dnsdir}/${adb_dnsfile}"
1132 mv "${adb_tmpdir}/${adb_dnsfile}" "${adb_dnsdir}/${adb_dnsfile}"
1137 f_count
"${mode}" "${src_name}"
1138 out_rc
="${out_rc:-"${in_rc}"}"
1139 f_log
"debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
1143 # top level domain compression
1147 local cnt cnt_tld
source="${1}" temp_tld
="${1}.tld"
1149 "${adb_awk}" '{if(NR==1){tld=$NF};while(getline){if(index($NF,tld".")==0){print tld;tld=$NF}}print tld}' "${source}" | \
1150 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${temp_tld}"
1153 mv -f "${temp_tld}" "${source}"
1154 cnt_tld
="$(wc -l 2>/dev/null < "${source}")"
1158 f_log
"debug" "f_tld ::: source: ${source}, cnt: ${adb_cnt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
1161 # suspend/resume adblock processing
1165 local status entry
done="false" mode
="${1}"
1168 json_load_file
"${adb_rtfile}" >/dev
/null
2>&1
1169 json_select
"data" >/dev
/null
2>&1
1170 json_get_var status
"adblock_status"
1171 if [ "${mode}" = "suspend" ] && [ "${status}" = "enabled" ]
1174 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1175 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]
1177 printf "${adb_dnsheader}" > "${adb_jaildir}/${adb_dnsjail}"
1178 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]
1180 rm -f "${adb_dnsdir}/${adb_dnsjail}"
1184 elif [ "${mode}" = "resume" ] && [ "${status}" = "paused" ]
1190 if [ "${done}" = "true" ]
1192 if [ "${mode}" = "suspend" ]
1197 f_log
"info" "${mode} adblock processing"
1202 # query blocklist for certain (sub-)domains
1206 local search result prefix suffix field query_start query_end query_timeout
=30 domain
="${1}" tld
="${1#*.}"
1208 if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
1210 printf "%s\n" "::: invalid input, please submit a single (sub-)domain :::"
1212 case "${adb_dns}" in
1224 prefix
="[^\\*].*[\\.]"
1229 prefix
="[^\\*].*[\\.]"
1239 query_start
="$(date "+%s
")"
1240 while [ "${domain}" != "${tld}" ]
1242 search
="${domain//[+*~%\$&\"\']/}"
1243 search
="${search//./\\.}"
1244 result
="$("${adb_awk}" -F '/|\"|\t| ' "/^(${search}|${prefix}+${search}.*${suffix})$/{i++;if(i<=9){printf \" + %s\n\",\$${field}}else if(i==10){printf \" + %s\n\",\"[...]\";exit}}" "${adb_dnsdir}/${adb_dnsfile}")"
1245 printf "%s\n%s\n%s\n" ":::" "::: domain '${domain}' in active blocklist" ":::"
1246 printf "%s\n\n" "${result:-" - no match"}"
1250 if [ "${adb_backup}" = "1" ] && [ -d "${adb_backupdir}" ]
1252 search
="${1//[+*~%\$&\"\']/}"
1253 search
="${search//./\\.}"
1254 printf "%s\n%s\n%s\n" ":::" "::: domain '${1}' in backups and black-/whitelist" ":::"
1255 for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz "${adb_blacklist}" "${adb_whitelist}"
1257 suffix
="${file##*.}"
1258 if [ "${suffix}" = "gz" ]
1260 zcat
"${file}" 2>/dev
/null | \
1261 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' | "${adb_awk}" -v f="${file##*/}" "BEGIN{rc=1};/^($search|.*\\.${search})$/{i++;if(i<=3){printf \" + %-30s%s\n\",f,\$1;rc=0}else if(i==4){printf \" + %-30s%s\n\",f,\"[...]\"}};END{exit rc}"
1263 "${adb_awk}" -v f="${file##*/}" "BEGIN{rc=1};/^($search|.*\\.${search})$/{i++;if(i<=3){printf \" + %-30s%s\n\",f,\$1;rc=0}else if(i==4){printf \" + %-30s%s\n\",f,\"[...]\"}};END{exit rc}" "${file}"
1268 query_end
="$(date "+%s
")"
1269 if [ "$((query_end-query_start))" -gt "${query_timeout}" ]
1271 printf "%s\n\n" " - [...]"
1276 if [ "${result}" != "true" ]
1278 printf "%s\n\n" " - no match"
1284 # update runtime information
1288 local entry sources runtime utils memory bg_pid status
="${1:-"enabled"}"
1292 adb_endtime
="$(date "+%s
")"
1293 memory
="$("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null | "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
1294 if [ "$(( (adb_endtime-adb_starttime)/60 ))" -lt 60 ]
1296 runtime="${adb_action}, $(( (adb_endtime-adb_starttime)/60 ))m $(( (adb_endtime-adb_starttime)%60 ))s, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
1298 runtime="${adb_action}, n/a, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
1300 if [ "${status}" = "error" ]
1313 json_load_file "${adb_rtfile}" >/dev/null 2>&1
1316 utils="download: $(readlink -fn "${adb_fetchutil}"), sort: $(readlink -fn "${adb_sort}"), awk: $(readlink -fn "${adb_awk}")"
1317 if [ -z "${adb_cnt}" ]
1319 json_get_var adb_cnt "blocked_domains"
1320 adb_cnt="${adb_cnt%% *}"
1322 if [ -z "${runtime}" ]
1324 json_get_var runtime "last_run"
1327 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]
1330 sources="restrictive_jail"
1332 sources="$(printf "%s\n" ${adb_sources} | "${adb_sort}" | "${adb_awk}" '{ORS=" ";print $0}')"
1337 json_load_file "${adb_rtfile}" >/dev/null 2>&1
1339 json_add_string "adblock_status
" "${status:-"enabled"}"
1340 json_add_string "adblock_version
" "${adb_ver}"
1341 json_add_string "blocked_domains
" "${adb_cnt:-0}"
1342 json_add_array "active_sources
"
1343 for entry in ${sources}
1346 json_add_string "source" "${entry}"
1350 json_add_string "dns_backend
" "${adb_dns:-"-"} (${adb_dnscachecmd##*/}), ${adb_dnsdir:-"-"}"
1351 json_add_string "run_utils
" "${utils:-"-"}"
1352 json_add_string "run_ifaces
" "trigger
: ${adb_trigger:-"-"}, report
: ${adb_repiface:-"-"}"
1353 json_add_string "run_directories
" "base
: ${adb_tmpbase}, backup: ${adb_backupdir}, report: ${adb_reportdir}, jail: ${adb_jaildir}"
1354 json_add_string "run_flags
" "backup
: $
(f_char
${adb_backup}), flush: $(f_char ${adb_dnsflush}), force: $(f_char ${adb_forcedns}), search: $(f_char ${adb_safesearch}), report: $(f_char ${adb_report}), mail: $(f_char ${adb_mail}), jail: $(f_char ${adb_jail})"
1355 json_add_string "last_run
" "${runtime:-"-"}"
1356 json_add_string "system
" "${adb_sysver}"
1357 json_dump > "${adb_rtfile}"
1359 if [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ] && \
1360 { [ "${status}" = "error" ] || { [ "${status}" = "enabled" ] && [ "${adb_cnt}" -le "${adb_mailcnt}" ]; } }
1362 ( "${adb_mailservice}" "${adb_ver}" >/dev
/null
2>&1 )&
1365 f_log
"debug" "f_jsnup ::: status: ${status:-"-"}, cnt: ${adb_cnt}, mail: ${adb_mail}, mail_service: ${adb_mailservice}, mail_cnt: ${adb_mailcnt}, mail_pid: ${bg_pid:-"-"}"
1372 local class
="${1}" log_msg
="${2}"
1374 if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${adb_debug}" = "1" ]; }
1376 if [ -x "${adb_loggercmd}" ]
1378 "${adb_loggercmd}" -p "${class}" -t "adblock-${adb_ver}[${$}]" "${log_msg}"
1380 printf "%s
%s
%s
\n" "${class}" "adblock-${adb_ver}[${$}]" "${log_msg}"
1382 if [ "${class}" = "err
" ]
1391 # main function for blocklist processing
1395 local src_tmpload src_tmpfile src_name src_rset src_url src_log src_arc src_cat src_item src_list src_entries src_suffix src_rc entry memory cnt=1
1397 memory="$
("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null | "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
1398 f_log
"debug" "f_main ::: memory: ${memory:-0}, max_queue: ${adb_maxqueue}, safe_search: ${adb_safesearch}, force_dns: ${adb_forcedns}, awk: ${adb_awk}"
1400 # white- and blacklist preparation
1402 for entry
in ${adb_locallist}
1404 ( f_list
"${entry}" "${entry}" )&
1407 if [ "${adb_dns}" != "raw" ] && [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]
1409 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1410 chown
"${adb_dnsuser}" "${adb_jaildir}/${adb_dnsjail}" 2>/dev
/null
1414 if [ "${adb_action}" != "resume" ]
1418 f_log
"info" "restrictive jail mode enabled successfully (${adb_sysver})"
1420 f_log
"err" "dns backend restart in jail mode failed"
1424 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]
1426 rm -f "${adb_dnsdir}/${adb_dnsjail}"
1430 # safe search preparation
1432 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]
1434 if [ -z "${adb_safesearchlist}" ]
1436 adb_safesearchlist
="google bing duckduckgo pixabay yandex youtube"
1438 for entry
in ${adb_safesearchlist}
1440 ( f_list safesearch
"${entry}" )&
1447 for src_name
in ${adb_sources}
1449 json_select
"${src_name}" >/dev
/null
2>&1
1450 if [ "${?}" != "0" ]
1452 adb_sources
="${adb_sources/${src_name}}"
1455 json_get_var src_url
"url" >/dev
/null
2>&1
1456 json_get_var src_rset
"rule" >/dev
/null
2>&1
1458 src_tmpcat
="${adb_tmpload}.${src_name}.cat"
1459 src_tmpload
="${adb_tmpload}.${src_name}.load"
1460 src_tmpsort
="${adb_tmpload}.${src_name}.sort"
1461 src_tmpfile
="${adb_tmpfile}.${src_name}"
1466 if [ -z "${src_url}" ] ||
[ -z "${src_rset}" ]
1474 if [ "${adb_backup}" = "1" ] && { [ "${adb_action}" = "start" ] || [ "${adb_action}" = "resume" ]; }
1477 if [ "${?}" = "0" ] && [ -s "${src_tmpfile}" ]
1483 # download queue processing
1485 unset src_cat src_entries
1486 if [ "${src_name}" = "shallalist
" ] || [ "${src_name}" = "utcapitole
" ]
1488 if [ "${src_name}" = "shallalist
" ] && [ -n "${adb_sha_sources}" ]
1490 src_cat="${adb_sha_sources}"
1491 elif [ "${src_name}" = "utcapitole
" ] && [ -n "${adb_utc_sources}" ]
1493 src_cat="${adb_utc_sources}"
1495 if [ -n "${src_cat}" ]
1498 src_arc="${adb_tmpdir}/${src_url##*/}"
1499 src_log="$
("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
1501 if [ "${src_rc}" = "0" ] && [ -s "${src_arc}" ]
1503 src_suffix="$
(eval printf "%s" \"\$\
{adb_src_suffix_
${src_name}:-\"domains
\"\
}\")"
1504 src_list="$
(tar -tzf "${src_arc}" 2>/dev
/null
)"
1505 for src_item in ${src_cat}
1507 src_entries="${src_entries} $(printf "%s" "${src_list}" | grep -E "${src_item}/${src_suffix}$
")"
1509 if [ -n "${src_entries}" ]
1511 tar -xOzf "${src_arc}" ${src_entries} 2>/dev/null > "${src_tmpload}"
1516 src_log
="$(printf "%s
" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1517 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1519 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]
1521 if [ -s "${adb_tmpdir}/tmp.rem.whitelist
" ]
1523 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s
/\r//g
" | \
1524 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f
=NF
;f
>1;f--
)printf "%s.",$f;print
$1}' > "${src_tmpsort}"
1526 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
1527 "${adb_awk}" 'BEGIN
{FS
="."}{for(f
=NF
;f
>1;f--
)printf "%s.",$f;print
$1}' > "${src_tmpsort}"
1530 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
1533 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]
1536 if [ "${adb_backup}" = "1" ]
1540 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
1542 f_log "info" "archive preparation of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1544 rm -f "${src_tmpfile}"
1546 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start
" ]
1548 f_log "info
" "archive extraction of
'${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1554 if [ "${src_name}" = "energized" ] && [ -n "${adb_eng_sources}" ]
1556 src_cat="${adb_eng_sources}"
1557 elif [ "${src_name}" = "stevenblack" ] && [ -n "${adb_stb_sources}" ]
1559 src_cat="${adb_stb_sources}"
1560 elif { [ "${src_name}" = "energized" ] && [ -z "${adb_eng_sources}" ]; } || \
1561 { [ "${src_name}" = "stevenblack" ] && [ -z "${adb_stb_sources}" ]; }
1566 for suffix in ${src_cat:-${src_url}}
1568 if [ "${src_url}" != "${suffix}" ]
1570 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpcat}" "${src_url}${suffix}" 2>&1)"
1572 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpcat}" ]
1574 cat "${src_tmpcat}" >> "${src_tmpload}"
1578 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpload}" "${src_url}" 2>&1)"
1582 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]
1584 if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]
1586 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
1587 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
1589 "${adb_awk}" "${src_rset}" "${src_tmpload}" |
sed "s/\r//g" | \
1590 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
1593 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
1596 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]
1599 if [ "${adb_backup}" = "1" ]
1603 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
1605 f_log
"info" "preparation of '${src_name}' failed, rc: ${src_rc}"
1607 rm -f "${src_tmpfile}"
1610 src_log
="$(printf "%s
" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1611 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1612 if [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start
" ]
1619 hold=$((cnt%adb_maxqueue))
1620 if [ "${hold}" = "0" ]
1629 # tld compression and dns restart
1631 if [ "${?}" = "0" ] && [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
1633 f_tld "${adb_tmpdir}/${adb_dnsfile}"
1636 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1638 chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
1642 if [ "${adb_action}" != "resume
" ]
1646 f_log "info
" "blocklist with overall
${adb_cnt} blocked domains loaded successfully
(${adb_sysver})"
1648 f_log "err
" "dns backend restart with adblock blocklist failed
"
1653 # trace dns queries via tcpdump and prepare a report
1657 local report_raw report_json report_txt content status total start end blocked percent top_list top array item index hold ports value key key_list cnt=0 resolve="-nn" action="${1}" count="${2:-"50"}" search="${3:-"+"}"
1659 report_raw="${adb_reportdir}/adb_report.raw
"
1660 report_srt="${adb_reportdir}/adb_report.srt
"
1661 report_jsn="${adb_reportdir}/adb_report.json
"
1662 report_txt="${adb_reportdir}/adb_mailreport.txt
"
1666 if [ "${action}" != "json
" ]
1672 if [ "${adb_represolve}" = "1" ]
1676 for file in "${adb_reportdir}/adb_report.pcap
"*
1679 "${adb_dumpcmd}" "${resolve}" -tttt -r "${file}" 2>/dev/null | \
1680 "${adb_awk}" -v cnt="${cnt}" '!/\.lan\. |PTR\? | SOA\? /&&/ A[\? ]+|NXDomain|0\.0\.0\.0/{a=$1;b=substr($2,0,8);c=$4;sub(/\.[0-9]+$/,"",c);gsub(/[^[:alnum:]\.:-]/,"",c);d=cnt $7;sub(/\*$/,"",d);
1681 e=$(NF-1);sub(/[0-9]\/[0-9]\/[0-9]|0\.0\.0\.0/,"NX
",e);sub(/\.$/,"",e);sub(/([0-9]{1,3}\.){3}[0-9]{1,3}/,"OK
",e);gsub(/[^[:alnum:]\.-]/,"",e);if(e==""){e="err
"};printf "%s
\t%s
\t%s
\t%s
\t%s
\n",d,e,a,b,c}' >> "${report_raw}"
1683 hold=$((cnt%adb_maxqueue))
1684 if [ "${hold}" = "0" ]
1691 if [ -s "${report_raw}" ]
1693 "${adb_sort}" ${adb_srtopts} -k1 -k3 -k4 -k5 -k1 -ur "${report_raw}" | \
1694 "${adb_awk}" '{currA=($1+0);currB=$1;currC=substr($1,length($1),1);if(reqA==currB){reqA=0;printf "%s
\t%s
\n",d,$2}else if(currC=="+"){reqA=currA;d=$3"\t"$4"\t"$5"\t"$2}}' | \
1695 "${adb_sort}" ${adb_srtopts} -k1 -k2 -k3 -k4 -ur > "${report_srt}"
1696 rm -f "${report_raw}"
1699 if [ -s "${report_srt}" ]
1701 start="$
("${adb_awk}" 'END{printf "%s_%s",$1,$2}' "${report_srt}")"
1702 end="$
("${adb_awk}" 'NR==1{printf "%s_%s",$1,$2}' "${report_srt}")"
1703 total="$
(wc -l < "${report_srt}")"
1704 blocked="$
("${adb_awk}" '{if($5=="NX")cnt++}END{printf "%s",cnt}' "${report_srt}")"
1705 percent="$
("${adb_awk}" -v t="${total}" -v b="${blocked}" 'BEGIN{printf "%.2f%s",b/t*100,"%"}')"
1707 printf "%s\n" "{ " >> "${report_jsn}"
1708 printf "\t%s\n" "\"start_date\": \"${start%_*}\", " >> "${report_jsn}"
1709 printf "\t%s\n" "\"start_time\": \"${start#*_}\", " >> "${report_jsn}"
1710 printf "\t%s\n" "\"end_date\": \"${end%_*}\", " >> "${report_jsn}"
1711 printf "\t%s\n" "\"end_time\": \"${end#*_}\", " >> "${report_jsn}"
1712 printf "\t%s\n" "\"total\": \"${total}\", " >> "${report_jsn}"
1713 printf "\t%s\n" "\"blocked\": \"${blocked}\", " >> "${report_jsn}"
1714 printf "\t%s\n" "\"percent\": \"${percent}\", " >> "${report_jsn}"
1715 top_list
="top_clients top_domains top_blocked"
1716 for top
in ${top_list}
1718 printf "\t%s" "\"${top}\": [ " >> "${report_jsn}"
1721 "${adb_awk}" '{print $3}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c | \
1722 "${adb_sort}" ${adb_srtopts} -nr | \
1723 "${adb_awk}" '{ORS=" ";if(NR==1)printf "\n\t\t{\n\t\t\t\"count
\": \"%s
\",\n\t\t\t\"address
\": \"%s
\"\n\t\t}",$1,$2; else if(NR<10)printf ",\n\t\t{\n\t\t\t\"count
\": \"%s
\",\n\t\t\t\"address
\": \"%s
\"\n\t\t}",$1,$2}' >> "${report_jsn}"
1726 "${adb_awk}" '{if($5!="NX")print $4}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} |
uniq -c | \
1727 "${adb_sort}" ${adb_srtopts} -nr | \
1728 "${adb_awk}" '{ORS=" ";if(NR==1)printf "\n\t\t{\n\t\t\t\"count\": \"%s\",\n\t\t\t\"address\": \"%s\"\n\t\t}",$1,$2; else if(NR<10)printf ",\n\t\t{\n\t\t\t\"count\": \"%s\",\n\t\t\t\"address\": \"%s\"\n\t\t}",$1,$2}' >> "${report_jsn}"
1731 "${adb_awk}" '{if($5=="NX")print $4}' "${report_srt}" | \
1732 "${adb_sort}" ${adb_srtopts} | uniq -c | "${adb_sort}" ${adb_srtopts} -nr | \
1733 "${adb_awk}" '{ORS=" ";if(NR==1)printf "\n\t\t{\n\t\t\t\"count
\": \"%s
\",\n\t\t\t\"address
\": \"%s
\"\n\t\t}",$1,$2; else if(NR<10)printf ",\n\t\t{\n\t\t\t\"count
\": \"%s
\",\n\t\t\t\"address
\": \"%s
\"\n\t\t}",$1,$2}' >> "${report_jsn}"
1736 printf "\n\t%s
\n" "]," >> "${report_jsn}"
1738 search="${search//./\\.}"
1739 search="${search//[+*~%\$&\"\' ]/}"
1740 "${adb_awk}" "BEGIN{i=0;printf \"\t\\\"requests\\\": [\n\"}/(${search})/{i++;if(i==1)printf \"\n\t\t{\n\t\t\t\\\"date\\\": \\\"%s\\\",\n\t\t\t\\\"time\\\": \\\"%s\\\",\n\t\t\t\\\"client\\\": \\\"%s\\\",\n\t\t\t\\\"domain\\\": \\\"%s\\\",\n\t\t\t\\\"rc\\\": \\\"%s\\\"\n\t\t}\",\$1,\$2,\$3,\$4,\$5;else if(i<=${count})printf \",\n\t\t{\n\t\t\t\\\"date\\\": \\\"%s\\\",\n\t\t\t\\\"time\\\": \\\"%s\\\",\n\t\t\t\\\"client\\\": \\\"%s\\\",\n\t\t\t\\\"domain\\\": \\\"%s\\\",\n\t\t\t\\\"rc\\\": \\\"%s\\\"\n\t\t}\",\$1,\$2,\$3,\$4,\$5}END{printf \"\n\t]\n}\n\"}" "${adb_reportdir}/adb_report.srt" >> "${report_jsn}"
1741 rm -f "${report_srt}"
1745 # output preparation
1747 if [ -s "${report_jsn}" ] && { [ "${action}" = "cli" ] || [ "${action}" = "mail" ]; }
1749 printf "%s\n%s\n%s\n" ":::" "::: Adblock DNS-Query Report" ":::" >> "${report_txt}"
1751 json_load_file
"${report_jsn}"
1752 json_get_keys key_list
1753 for key
in ${key_list}
1755 json_get_var value
"${key}"
1756 eval "${key}=\"${value}\""
1758 printf " + %s\n + %s\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}" >> "${report_txt}"
1759 printf " + %s\n + %s %s\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})" >> "${report_txt}"
1760 top_list
="top_clients top_domains top_blocked requests"
1761 for top
in ${top_list}
1765 item
="::: Top 10 Clients"
1768 item
="::: Top 10 Domains"
1771 item
="::: Top 10 Blocked Domains"
1774 if json_get_type status
"${top}" && [ "${top}" != "requests" ] && [ "${status}" = "array" ]
1776 printf "%s\n%s\n%s\n" ":::" "${item}" ":::" >> "${report_txt}"
1777 json_select
"${top}"
1780 while json_get_type status
"${index}" && [ "${status}" = "object" ]
1782 json_get_values item
"${index}"
1783 printf " + %-9s::: %s\n" ${item} >> "${report_txt}"
1786 elif json_get_type status
"${top}" && [ "${top}" = "requests" ] && [ "${status}" = "array" ]
1788 printf "%s\n%s\n%s\n" ":::" "::: Latest DNS Queries" ":::" >> "${report_txt}"
1789 printf "%-15s%-15s%-45s%-80s%s\n" "Date" "Time" "Client" "Domain" "Answer" >> "${report_txt}"
1790 json_select
"${top}"
1792 while json_get_type status
"${index}" && [ "${status}" = "object" ]
1794 json_get_values item
"${index}"
1795 printf "%-15s%-15s%-45s%-80s%s\n" ${item} >> "${report_txt}"
1801 content
="$(cat "${report_txt}" 2>/dev/null)"
1802 rm -f "${report_txt}"
1807 if [ "${action}" = "cli" ]
1809 printf "%s\n" "${content}"
1810 elif [ "${action}" = "json" ]
1813 elif [ "${action}" = "mail" ] && [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ]
1815 ( "${adb_mailservice}" "${adb_ver}" "${content}" >/dev
/null
2>&1 )&
1818 f_log
"debug" "f_report ::: action: ${action}, count: ${count}, search: ${search}, dump_util: ${adb_dumpcmd}, rep_dir: ${adb_reportdir}, rep_iface: ${adb_repiface:-"-"}, rep_listen: ${adb_replisten}, rep_chunksize: ${adb_repchunksize}, rep_chunkcnt: ${adb_repchunkcnt}, rep_resolve: ${adb_represolve}"
1821 # source required system libraries
1823 if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
1825 .
"/lib/functions.sh"
1826 .
"/lib/functions/network.sh"
1827 .
"/usr/share/libubox/jshn.sh"
1829 f_log
"err" "system libraries not found"
1832 # version information
1834 if [ "${adb_action}" = "version" ]
1836 printf "%s\n" "${adb_ver}"
1842 adb_awk
="$(command -v gawk)"
1843 if [ ! -x "${adb_awk}" ]
1845 adb_awk
="$(command -v awk)"
1846 if [ ! -x "${adb_awk}" ]
1848 f_log
"err" "awk not found or not executable"
1854 adb_sort
="$(command -v sort)"
1855 if [ ! -x "${adb_sort}" ] ||
[ "$("${adb_sort}" --version 2>/dev/null | grep -c "coreutils
")" = "0" ]
1857 f_log
"err" "coreutils sort not found or not executable"
1860 # handle different adblock actions
1863 case "${adb_action}" in
1873 if [ "${adb_dns}" != "raw" ]
1879 if [ "${adb_dns}" != "raw" ]
1885 f_report
"${2}" "${3}" "${4}"