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)"
57 adb_lookupdomain
="example.com"
58 adb_action
="${1:-"start"}"
63 # load & check adblock environment
67 local bg_pid iface port ports
69 adb_sysver
="$(ubus -S call system board 2>/dev/null | jsonfilter -e '@.model' -e '@.release.description' | \
70 "${adb_awk}" 'BEGIN{ORS=", "}{print $0}' | "${adb_awk}" '{print substr($0,1,length($0)-2)}')"
72 if [ "${adb_action}" != "report" ]
78 if [ "${adb_enabled}" = "0" ]
84 f_log "info" "adblock is currently disabled, please set the config option 'adb_enabled
' to '1' to use this service"
88 if [ "${adb_report}" = "1" ] && [ ! -x "${adb_dumpcmd}" ]
90 f_log "info" "Please install the package 'tcpdump
' or 'tcpdump-mini
' to use the reporting feature"
91 elif [ "${adb_report}" = "0" ] && [ "${adb_action}" = "report" ]
93 f_log "info" "Please enable the 'DNS Report
' option to use the reporting feature"
97 bg_pid="$(pgrep -f "^${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
98 if [ -x "${adb_dumpcmd}" ] && { [ "${adb_report}" = "0" ] || { [ -n "${bg_pid}" ] && { [ "${adb_action}" = "stop" ] || [ "${adb_action}" = "restart" ]; }; }; }
100 if [ -n "${bg_pid}" ]
102 kill -HUP "${bg_pid}" 2>/dev
/null
103 while $
(kill -0 "${bg_pid}" 2>/dev
/null
)
111 if [ -x "${adb_dumpcmd}" ] && [ "${adb_report}" = "1" ] && [ -z "${bg_pid}" ] && [ "${adb_action}" != "report" ] && [ "${adb_action}" != "stop" ]
113 for port
in ${adb_replisten}
119 ports
="${ports} or port ${port}"
122 if [ -z "${adb_repiface}" ]
124 network_get_device iface
"lan"
127 adb_repiface
="${iface}"
129 network_get_physdev iface
"lan"
132 adb_repiface
="${iface}"
135 if [ -n "${adb_repiface}" ]
137 uci_set adblock global adb_repiface
"${adb_repiface}"
141 if [ -n "${adb_reportdir}" ] && [ ! -d "${adb_reportdir}" ]
143 mkdir
-p "${adb_reportdir}"
144 f_log
"info" "report directory '${adb_reportdir}' created"
146 if [ -n "${adb_repiface}" ] && [ -d "${adb_reportdir}" ]
148 ( "${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 & )
149 bg_pid
="$(pgrep -f "^
${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
151 f_log "info" "Please set the name of the reporting network device 'adb_repiface
' manually"
156 # check & set environment
160 adb_starttime="$(date "+%s")"
161 f_log "info" "adblock instance started ::: action: ${adb_action}, priority: ${adb_nice:-"0"}, pid: ${$}"
166 if [ "${adb_dnsflush}" = "1" ]
168 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
172 if [ ! -r "${adb_srcfile}" ]
174 if [ -r "${adb_srcarc}" ]
176 zcat "${adb_srcarc}" > "${adb_srcfile}"
178 f_log "err" "adblock source archive not found"
181 if [ -r "${adb_srcfile}" ] && [ "${adb_action}" != "report" ]
184 json_load_file "${adb_srcfile}"
186 f_log "err" "adblock source file not found"
190 # load adblock config
194 local cnt=0 cnt_max=10
196 if [ ! -r "/etc/config/adblock" ] || [ -z "$(uci -q show adblock.global.adb_safesearch)" ]
198 f_log "err" "no valid adblock config found, please re-install the package via opkg with the '--force-reinstall --force-maintainer' options"
207 eval "${option}=\"${value}\""
213 if [ "${option}" = "adb_sources" ]
215 eval "${option}=\"$(printf "%s" "${adb_sources}") ${value}\""
216 elif [ "${option}" = "adb_eng_sources" ]
218 eval "${option}=\"$(printf "%s" "${adb_eng_sources}") ${value}\""
219 elif [ "${option}" = "adb_sha_sources" ]
221 eval "${option}=\"$(printf "%s" "${adb_sha_sources}") ${value}\""
222 elif [ "${option}" = "adb_stb_sources" ]
224 eval "${option}=\"$(printf "%s" "${adb_stb_sources}") ${value}\""
225 elif [ "${option}" = "adb_utc_sources" ]
227 eval "${option}=\"$(printf "%s" "${adb_utc_sources}") ${value}\""
228 elif [ "${option}" = "adb_denyip" ]
230 eval "${option}=\"$(printf "%s" "${adb_denyip}") ${value}\""
231 elif [ "${option}" = "adb_allowip" ]
233 eval "${option}=\"$(printf "%s" "${adb_allowip}") ${value}\""
234 elif [ "${option}" = "adb_safesearchlist" ]
236 eval "${option}=\"$(printf "%s" "${adb_safesearchlist}") ${value}\""
237 elif [ "${option}" = "adb_zonelist" ]
239 eval "${option}=\"$(printf "%s" "${adb_zonelist}") ${value}\""
240 elif [ "${option}" = "adb_portlist" ]
242 eval "${option}=\"$(printf "%s" "${adb_portlist}") ${value}\""
248 if [ -z "${adb_fetchutil}" ] || [ -z "${adb_dns}" ]
250 while [ -z "${adb_packages}" ] && [ "${cnt}" -le "${cnt_max}" ]
252 adb_packages="$(opkg list-installed 2>/dev/null)"
256 if [ -z "${adb_packages}" ]
258 f_log "err" "local opkg package repository is not available, please set 'adb_fetchutil
' and 'adb_dns
' manually"
263 # status helper function
267 local result input="${1}"
269 if [ "${input}" = "1" ]
275 printf "%s" "${result}"
278 # load dns backend config
282 local util utils dns_up cnt=0
284 if [ -z "${adb_dns}" ]
286 utils="knot-resolver bind unbound dnsmasq raw"
289 if [ "${util}" = "raw" ] || [ -n "$(printf "%s" "${adb_packages}" | grep "^${util}")" ]
291 if [ "${util}" = "knot-resolver" ]
294 elif [ "${util}" = "bind" ]
298 if [ "${util}" = "raw" ] || [ -x "$(command -v "${util}")" ]
301 uci_set adblock global adb_dns "${util}"
307 elif [ "${adb_dns}" != "raw" ] && [ ! -x "$(command -v "${adb_dns}")" ]
312 if [ -n "${adb_dns}" ]
317 adb_dnsinotify="${adb_dnsinotify:-"0"}"
318 adb_dnsinstance="${adb_dnsinstance:-"0"}"
319 adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
320 adb_dnsdir="${adb_dnsdir:-"/tmp/dnsmasq.d"}"
321 adb_dnsheader="${adb_dnsheader}"
322 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"address=/\"\$0\"/\"}'"}"
323 adb_dnsallow
="${adb_dnsallow:-"${adb_awk} '{print \"local=/\"\$0\"/#\"}'"}"
324 adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"address=/\"\$0\"/\"item\"\"}'"}"
325 adb_dnsstop="${adb_dnsstop:-"address=/#/"}"
328 adb_dnscachecmd="$(command -v unbound-control || printf "%s" "-")"
329 adb_dnsinotify="${adb_dnsinotify:-"0"}"
330 adb_dnsinstance="${adb_dnsinstance:-"0"}"
331 adb_dnsuser="${adb_dnsuser:-"unbound"}"
332 adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
333 adb_dnsheader="${adb_dnsheader}"
334 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 static\"}'"}"
335 adb_dnsallow
="${adb_dnsallow:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 transparent\"}'"}"
336 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\"}'"}"
337 adb_dnsstop="${adb_dnsstop:-"local-zone: \".\" static"}"
340 adb_dnscachecmd="$(command -v rndc || printf "%s" "-")"
341 adb_dnsinotify="${adb_dnsinotify:-"0"}"
342 adb_dnsinstance="${adb_dnsinstance:-"0"}"
343 adb_dnsuser="${adb_dnsuser:-"bind"}"
344 adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
345 adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n IN NS localhost.\n"}"
346 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
347 adb_dnsallow
="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
348 adb_dnsdenyip="${adb_dnsdenyip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME .\"}'"}"
349 adb_dnsallowip="${adb_dnsallowip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME rpz-passthru.\"}'"}"
350 adb_dnssafesearch
="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"\"\$0\" CNAME \"item\".\\n*.\"\$0\" CNAME \"item\".\"}'"}"
351 adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
355 adb_dnsinotify="${adb_dnsinotify:-"0"}"
356 adb_dnsinstance="${adb_dnsinstance:-"0"}"
357 adb_dnsuser="${adb_dnsuser:-"root"}"
358 adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
359 adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n"}"
360 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
361 adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
362 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\"\"}'"}"
363 adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
367 adb_dnsinotify="${adb_dnsinotify:-"0"}"
368 adb_dnsinstance="${adb_dnsinstance:-"0"}"
369 adb_dnsuser="${adb_dnsuser:-"root"}"
370 adb_dnsdir="${adb_dnsdir:-"/tmp"}"
371 adb_dnsheader="${adb_dnsheader}"
372 adb_dnsdeny="${adb_dnsdeny:-"0"}"
373 adb_dnsallow="${adb_dnsallow:-"1"}"
374 adb_dnssafesearch="${adb_dnssafesearch:-"0"}"
375 adb_dnsstop="${adb_dnsstop:-"0"}"
380 if [ "${adb_dns}" != "raw" ] && { [ -z "${adb_dns}" ] || [ ! -x "$(command -v "${adb_dns}")" ]; }
382 f_log
"err" "dns backend not found, please set 'adb_dns' manually"
385 if [ "${adb_dns}" != "raw" ] && { [ "${adb_dnsdir}" = "${adb_tmpbase}" ] || [ "${adb_dnsdir}" = "${adb_backupdir}" ] || [ "${adb_dnsdir}" = "${adb_reportdir}" ]; }
387 f_log "err
" "dns directory
'${adb_dnsdir}' has been misconfigured
, it must not point to the
'adb_tmpbase', 'adb_backupdir', 'adb_reportdir'"
390 if [ "${adb_action}" = "start
" ] && [ -z "${adb_trigger}" ]
392 sleep ${adb_triggerdelay}
395 if [ "${adb_dns}" != "raw
" ] && [ "${adb_action}" != "stop
" ]
397 while [ "${cnt}" -le 30 ]
399 dns_up="$
(ubus
-S call service list
"{\"name\":\"${adb_dns}\"}" 2>/dev
/null | jsonfilter
-l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev
/null
)"
400 if [ "${dns_up}" = "true
" ]
408 if [ -n "${adb_dnsdir}" ] && [ ! -d "${adb_dnsdir}" ]
410 mkdir -p "${adb_dnsdir}"
413 f_log "info
" "dns backend directory
'${adb_dnsdir}' created
"
415 f_log "err
" "dns backend directory
'${adb_dnsdir}' could not be created
"
419 if [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
421 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
424 if [ "${dns_up}" != "true
" ]
429 f_log "err
" "dns backend
'${adb_dns}' not running or executable
"
433 if [ "${adb_backup}" = "1" ] && [ -n "${adb_backupdir}" ] && [ ! -d "${adb_backupdir}" ]
435 mkdir -p "${adb_backupdir}"
438 f_log "info
" "backup directory
'${adb_backupdir}' created
"
440 f_log "err
" "backup directory
'${adb_backupdir}' could not be created
"
444 if [ -n "${adb_jaildir}" ] && [ ! -d "${adb_jaildir}" ]
446 mkdir -p "${adb_jaildir}"
449 f_log "info
" "jail directory
'${adb_jaildir}' created
"
451 f_log "err
" "jail directory
'${adb_jaildir}' could not be created
"
455 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}"
462 local util utils insecure cnt=0
464 if [ -z "${adb_fetchutil}" ]
466 utils="aria2c curl wget uclient-fetch
"
469 if { [ "${util}" = "uclient-fetch" ] && [ -n "$(printf "%s" "${adb_packages}" | grep "^libustream-")" ]; } || \
470 { [ "${util}" = "wget" ] && [ -n "$(printf "%s" "${adb_packages}" | grep "^wget -")" ]; } || \
471 [ "${util}" = "curl
" ] || [ "${util}" = "aria2c
" ]
473 if [ -x "$
(command -v "${util}")" ]
475 adb_fetchutil="${util}"
476 uci_set adblock global adb_fetchutil "${util}"
482 elif [ ! -x "$
(command -v "${adb_fetchutil}")" ]
486 case "${adb_fetchutil}" in
488 if [ "${adb_fetchinsecure}" = "1" ]
490 insecure="--check-certificate=false
"
492 adb_fetchparm="${adb_fetchparm:-"${insecure} --timeout=20 --allow-overwrite=true --auto-file-renaming=false --log-level=warn --dir=/ -o"}"
495 if [ "${adb_fetchinsecure}" = "1" ]
497 insecure="--insecure"
499 adb_fetchparm="${adb_fetchparm:-"${insecure} --connect-timeout 20 --silent --show-error --location -o"}"
502 if [ "${adb_fetchinsecure}" = "1" ]
504 insecure="--no-check-certificate"
506 adb_fetchparm="${adb_fetchparm:-"${insecure} --timeout=20 -O"}"
509 if [ "${adb_fetchinsecure}" = "1" ]
511 insecure="--no-check-certificate"
513 adb_fetchparm="${adb_fetchparm:-"${insecure} --no-cache --no-cookies --max-redirect=0 --timeout=20 -O"}"
516 if [ -n "${adb_fetchutil}" ] && [ -n "${adb_fetchparm}" ]
518 adb_fetchutil="$
(command -v "${adb_fetchutil}")"
520 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'"
522 f_log "debug
" "f_fetch
::: fetch_util
: ${adb_fetchutil:-"-"}, fetch_parm
: ${adb_fetchparm:-"-"}"
525 # create temporary files, directories and set dependent options
531 cpu="$
(grep -c '^processor' /proc
/cpuinfo
2>/dev
/null
)"
532 core="$
(grep -cm1 '^core id' /proc
/cpuinfo
2>/dev
/null
)"
533 if [ "${cpu}" = "0" ]
537 if [ "${core}" = "0" ]
543 if [ -d "${adb_tmpbase}" ]
545 adb_tmpdir="$
(mktemp
-p "${adb_tmpbase}" -d)"
546 adb_tmpload="$
(mktemp
-p "${adb_tmpdir}" -tu)"
547 adb_tmpfile="$
(mktemp
-p "${adb_tmpdir}" -tu)"
548 adb_srtopts="--temporary-directory=${adb_tmpdir} --compress-program=gzip --batch-size=32 --parallel=${cores}"
550 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
"
552 if [ ! -s "${adb_pidfile}" ]
554 printf "%s
" "${$}" > "${adb_pidfile}"
556 f_log "debug
" "f_temp
::: tmp_base
: ${adb_tmpbase:-"-"}, tmp_dir: ${adb_tmpdir:-"-"}, cores: ${cores:-"-"}, sort_options: ${adb_srtopts}, pid_file: ${adb_pidfile:-"-"}"
559 # remove temporary files and directories
563 if [ -d "${adb_tmpdir}" ]
565 rm -rf "${adb_tmpdir}"
567 rm -f "${adb_srcfile}"
569 f_log "debug
" "f_rmtemp
::: tmp_dir
: ${adb_tmpdir:-"-"}, src_file: ${adb_srcfile:-"-"}, pid_file: ${adb_pidfile:-"-"}"
572 # remove dns related files
578 status="$
(ubus
-S call service list
'{"name":"adblock"}' 2>/dev
/null | jsonfilter
-l1 -e '@["adblock"].instances.*.running' 2>/dev
/null
)"
579 if [ "${adb_dns}" = "raw" ] || { [ -n "${adb_dns}" ] && [ -n "${status}" ]; }
582 if [ "${adb_backup}" = "1" ]
584 rm -f "${adb_backupdir}/${adb_dnsprefix}".
*.gz
586 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
590 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:-"-"}"
597 local change config
="${1}"
599 if [ -n "${config}" ]
601 change
="$(uci -q changes "${config}" | "${adb_awk}" '{ORS=" "; print $0}')"
602 if [ -n "${change}" ]
604 uci_commit "${config}"
607 "/etc/init.d/firewall" reload >/dev/null 2>&1
610 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
613 "/etc/init.d/${adb_dns}" reload >/dev/null 2>&1
617 f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
625 local file mode="${1}" name="${2}"
630 if [ -s "${adb_tmpdir}/tmp.add.${name}" ]
632 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add.${name}")"
636 if [ -s "${adb_tmpfile}.${name}" ]
638 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpfile}.${name}")"
642 if [ -s "${adb_tmpdir}/tmp.raw.${name}" ]
644 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.raw.${name}")"
645 rm -f "${adb_tmpdir}/tmp.raw.${name}"
649 if [ -s "${adb_tmpdir}/tmp.safesearch.${name}" ]
651 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.safesearch.${name}")"
655 if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
657 adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/${adb_dnsfile}")"
660 "download"|"backup"|"restore")
661 if [ -s "${src_tmpfile}" ]
663 adb_cnt="$(wc -l 2>/dev/null < "${src_tmpfile}")"
667 if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
669 adb_cnt="$(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}")"
670 if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]
672 adb_cnt=$((adb_cnt-$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add.whitelist")))
674 for file in "${adb_tmpdir}/tmp.safesearch".*
678 adb_cnt=$((adb_cnt-$(wc -l 2>/dev/null < "${file}")))
681 if [ -n "${adb_dnsheader}" ]
683 adb_cnt=$(((adb_cnt-$(printf "${adb_dnsheader}" | grep -c "^"))/2))
690 # set external config options
694 local config config_dir config_file section zone port fwcfg
699 config_dir="$(uci_get dhcp "@dnsmasq[${adb_dnsinstance}]" confdir | grep -Fo "${adb_dnsdir}")"
700 if [ "${adb_enabled}" = "1" ] && [ -z "${config_dir}" ]
702 uci_set dhcp "@dnsmasq[${adb_dnsinstance}]" confdir "${adb_dnsdir}" 2>/dev/null
707 config_file="$(uci_get resolver kresd rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
708 if [ "${adb_enabled}" = "1" ] && [ -z "${config_file}" ]
710 uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
711 elif [ "${adb_enabled}" = "0" ] && [ -n "${config_file}" ]
713 uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
720 fwcfg="$(uci -qNX show "${config}" | "${adb_awk}" 'BEGIN{FS="[.=]"};/adblock_/{if(zone==$2){next}else{ORS=" ";zone=$2;print zone}}')"
721 if [ "${adb_enabled}" = "1" ] && [ "${adb_forcedns}" = "1" ] && \
722 [ "$
(/etc
/init.d
/firewall enabled
; printf "%u" ${?})" = "0" ]
724 for zone in ${adb_zonelist}
726 for port in ${adb_portlist}
728 if [ -z "$
(printf "%s" "${fwcfg}" | grep -o -m1 "adblock_${zone}${port}[ |\$]")" ]
731 set firewall."adblock_
${zone}${port}"="redirect
"
732 set firewall."adblock_
${zone}${port}".name="Adblock DNS (${zone}, ${port})"
733 set firewall."adblock_
${zone}${port}".src="${zone}"
734 set firewall."adblock_
${zone}${port}".proto="tcp udp
"
735 set firewall."adblock_
${zone}${port}".src_dport="${port}"
736 set firewall."adblock_
${zone}${port}".dest_port="${port}"
737 set firewall."adblock_
${zone}${port}".target="DNAT
"
740 fwcfg="${fwcfg/adblock_${zone}${port}[ |\$]/}"
743 fwcfg="${fwcfg#"${fwcfg%%[![:space:]]*}"}"
744 fwcfg="${fwcfg%"${fwcfg##*[![:space:]]}"}"
746 if [ "${adb_enabled}" = "0" ] || [ "${adb_forcedns}" = "0" ] || [ -n "${fwcfg}" ]
748 for section in ${fwcfg}
750 uci_remove firewall "${section}"
756 # restart dns backend
760 local dns_service dns_up dns_pid dns_procfile restart_rc cnt=0 out_rc=4 in_rc="${1:-0}"
762 if [ "${adb_dns}" = "raw" ] || { [ "${in_rc}" = "0" ] && [ "${adb_dnsinotify}" = "1" ]; }
766 if [ "${in_rc}" = "0" ] && [ "${adb_dnsflush}" = "0" ]
770 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}/unbound.conf" ]
772 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" dump_cache > "${adb_tmpdir}/adb_cache.dump" 2>/dev
/null
774 "/etc/init.d/${adb_dns}" restart
>/dev
/null
2>&1
778 if [ -x "${adb_dnscachecmd}" ] && [ -f "/etc/bind/rndc.conf" ]
780 "${adb_dnscachecmd}" -c "/etc/bind/rndc.conf" reload
>/dev
/null
2>&1
783 if [ -z "${restart_rc}" ] || { [ -n "${restart_rc}" ] && [ "${restart_rc}" != "0" ]; }
785 "/etc
/init.d
/${adb_dns}" restart >/dev/null 2>&1
790 "/etc
/init.d
/${adb_dns}" restart >/dev/null 2>&1
795 if [ -z "${restart_rc}" ]
797 "/etc
/init.d
/${adb_dns}" restart >/dev/null 2>&1
801 if [ "${restart_rc}" = "0" ]
803 while [ "${cnt}" -le "${adb_dnstimeout}" ]
805 dns_service="$
(ubus
-S call service list
"{\"name\":\"${adb_dns}\"}")"
806 dns_up="$
(printf "%s" "${dns_service}" | jsonfilter
-l1 -e "@[\"${adb_dns}\"].instances.*.running")"
807 dns_pid="$
(printf "%s" "${dns_service}" | jsonfilter
-l1 -e "@[\"${adb_dns}\"].instances.*.pid")"
808 dns_procfile="$
(ls -l "/proc/${dns_pid}/fd" 2>/dev/null | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
809 if [ "${dns_up}" = "true" ] && [ -n "${dns_pid}" ] && [ -z "${dns_procfile}" ]
811 if [ -x "${adb_lookupcmd}" ] && [ "${adb_lookupdomain}" != "false
" ]
813 "${adb_lookupcmd}" "${adb_lookupdomain}" >/dev/null 2>&1
820 sleep ${adb_dnstimeout}
821 cnt=${adb_dnstimeout}
829 if [ "${out_rc}" = "0" ] && [ "${adb_dns}" = "unbound
" ]
831 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}/adb_cache.dump
" ]
833 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" load_cache < "${adb_tmpdir}/adb_cache.dump
" >/dev/null 2>&1
838 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}"
842 # backup/restore/remove blocklists
846 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
"
851 if [ "${adb_dns}" = "named
" ]
853 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
\"}"
854 if [ -n "${adb_allowip}" ]
856 > "${adb_tmpdir}/tmp.raw.
${src_name}"
857 for ip in ${adb_allowip}
859 printf "%s
" "${ip}" | "${adb_awk}" "${rset}" >> "${adb_tmpdir}/tmp.raw.${src_name}"
861 eval "${adb_dnsallowip}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.add.${src_name}"
864 if [ -n "${adb_denyip}" ] && { [ -z "${out_rc}" ] || [ "${out_rc}" = "0" ]; }
866 > "${adb_tmpdir}/tmp.raw.${src_name}"
867 for ip
in ${adb_denyip}
869 printf "%s" "${ip}" | "${adb_awk}" "${rset}" >> "${adb_tmpdir}/tmp.raw.${src_name}"
871 eval "${adb_dnsdenyip}" "${adb_tmpdir}/tmp.raw.${src_name}" >> "${adb_tmpdir}/tmp.add.${src_name}"
874 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
877 "blacklist"|
"whitelist")
879 if [ "${src_name}" = "blacklist" ] && [ -f "${adb_blacklist}" ]
881 rset
="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
882 "${adb_awk}" "${rset}" "${adb_blacklist}" | \
883 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${adb_tmpdir}/tmp.raw.${src_name}"
884 "${adb_sort}" ${adb_srtopts} -u "${adb_tmpdir}/tmp.raw.${src_name}" 2>/dev/null > "${adb_tmpfile}.${src_name}"
886 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
887 elif [ "${src_name}" = "whitelist" ] && [ -f "${adb_whitelist}" ]
889 rset
="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
890 "${adb_awk}" "${rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.raw.${src_name}"
892 if [ "${out_rc}" = "0" ]
894 rset
="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\\.\",\"\\\\.\",\$1);print tolower(\"^(|.*\\\\.)\"\$1\"$\")}"
895 "${adb_awk}" "${rset}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.rem.${src_name}"
897 if [ "${out_rc}" = "0" ] && [ "${adb_dnsallow}" != "1" ]
899 eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.add.${src_name}"
901 if [ "${out_rc}" = "0" ] && [ "${adb_jail}" = "1" ] && [ "${adb_dnsstop}" != "0" ]
903 > "${adb_jaildir}/${adb_dnsjail}"
904 if [ -n "${adb_dnsheader}" ]
906 printf "${adb_dnsheader}" >> "${adb_jaildir}/${adb_dnsjail}"
908 cat "${adb_tmpdir}/tmp.add.${src_name}" >> "${adb_jaildir}/${adb_dnsjail}"
909 printf "%s\n" "${adb_dnsstop}" >> "${adb_jaildir}/${adb_dnsjail}"
916 case "${src_name}" in
918 rset
="/^(\\.[[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{printf \"%s\n%s\n\",tolower(\"www\"\$1),tolower(substr(\$1,2,length(\$1)))}"
919 safe_url
="https://www.google.com/supported_domains"
920 safe_cname
="forcesafesearch.google.com"
921 safe_domains
="${adb_tmpdir}/tmp.load.safesearch.${src_name}"
922 if [ "${adb_backup}" = "1" ] && [ -s "${adb_backupdir}/safesearch.${src_name}.gz" ]
924 zcat
"${adb_backupdir}/safesearch.${src_name}.gz" > "${safe_domains}"
927 "${adb_fetchutil}" ${adb_fetchparm} "${safe_domains}" "${safe_url}" 2>/dev
/null
929 if [ "${adb_backup}" = "1" ] && [ "${out_rc}" = "0" ]
931 gzip -cf "${safe_domains}" > "${adb_backupdir}/safesearch.${src_name}.gz"
934 if [ "${out_rc}" = "0" ]
936 if [ -x "${adb_lookupcmd}" ]
938 safe_ips
="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
939 if [ -n "${safe_ips}" ]
941 "${adb_awk}" "${rset}" "${safe_domains}" > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
948 safe_cname="strict.bing.com"
949 safe_domains="www.bing.com"
950 if [ -x "${adb_lookupcmd}" ]
952 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
953 if [ -n "${safe_ips}" ]
955 printf "%s
\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
961 safe_cname
="safe.duckduckgo.com"
962 safe_domains
="duckduckgo.com"
963 if [ -x "${adb_lookupcmd}" ]
965 safe_ips
="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
966 if [ -n "${safe_ips}" ]
968 printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
974 safe_cname="safesearch.pixabay.com"
975 safe_domains="pixabay.com"
976 if [ -x "${adb_lookupcmd}" ]
978 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
979 if [ -n "${safe_ips}" ]
981 printf "%s
\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
987 safe_cname
="familysearch.yandex.ru"
988 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"
989 if [ -x "${adb_lookupcmd}" ]
991 safe_ips
="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
992 if [ -n "${safe_ips}" ]
994 printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
1000 if [ "${adb_safesearchmod}" = "0" ]
1002 safe_cname="restrict.youtube.com"
1004 safe_cname="restrictmoderate.youtube.com"
1006 safe_domains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
1007 if [ -x "${adb_lookupcmd}" ]
1009 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
1010 if [ -n "${safe_ips}" ]
1012 printf "%s
\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
1018 if [ "${out_rc}" = "0" ] && [ -s "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" ]
1020 > "${adb_tmpdir}/tmp.safesearch.${src_name}"
1021 if [ "${adb_dns}" = "named" ]
1023 array
="${safe_cname}"
1027 for item
in ${array}
1029 eval "${adb_dnssafesearch}" "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" >> "${adb_tmpdir}/tmp.safesearch.${src_name}"
1030 if [ "${?}" != "0" ]
1032 rm -f "${adb_tmpdir}/tmp.safesearch.${src_name}"
1037 rm -f "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
1042 gzip -cf "${src_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
1047 if [ -n "${src_name}" ] && [ -s "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
1049 zcat
"${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${src_tmpfile}"
1051 elif [ -z "${src_name}" ]
1053 for file in "${adb_backupdir}/${adb_dnsprefix}".
*.gz
1059 zcat
"${file}" > "${adb_tmpfile}.${name}" &
1060 hold
=$
((cnt
%adb_maxqueue
))
1061 if [ "${hold}" = "0" ]
1073 if [ "${adb_action}" != "start" ] && [ "${adb_action}" != "resume" ] && [ -n "${src_name}" ] && [ "${out_rc}" != "0" ]
1075 adb_sources
="${adb_sources/${src_name}}"
1079 if [ "${adb_backup}" = "1" ]
1081 rm "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev
/null
1084 adb_sources
="${adb_sources/${src_name}}"
1087 if [ "${adb_backup}" = "1" ]
1089 for src_name
in ${adb_sources}
1091 ffiles
="${ffiles} -a ! -name ${adb_dnsprefix}.${src_name}.gz"
1093 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]
1095 ffiles
="${ffiles} -a ! -name safesearch.google.gz"
1097 find "${adb_backupdir}" ${ffiles} -print0 2>/dev
/null |
xargs -0 rm 2>/dev
/null
1100 "${adb_sort}" ${adb_srtopts} -mu "${adb_tmpfile}".* 2>/dev/null > "${adb_tmpdir}/${adb_dnsfile}"
1102 rm -f "${adb_tmpfile}".
*
1106 if [ -n "${adb_dnsheader}" ]
1108 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1110 > "${adb_dnsdir}/${adb_dnsfile}"
1112 if [ -s "${adb_tmpdir}/tmp.add.iplist" ]
1114 cat "${adb_tmpdir}/tmp.add.iplist" >> "${adb_dnsdir}/${adb_dnsfile}"
1116 if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]
1118 cat "${adb_tmpdir}/tmp.add.whitelist" >> "${adb_dnsdir}/${adb_dnsfile}"
1120 for file in "${adb_tmpdir}/tmp.safesearch".
*
1124 cat "${file}" >> "${adb_dnsdir}/${adb_dnsfile}"
1127 if [ "${adb_dnsdeny}" != "0" ]
1129 eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >> "${adb_dnsdir}/${adb_dnsfile}"
1131 mv "${adb_tmpdir}/${adb_dnsfile}" "${adb_dnsdir}/${adb_dnsfile}"
1136 f_count
"${mode}" "${src_name}"
1137 out_rc
="${out_rc:-"${in_rc}"}"
1138 f_log
"debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
1142 # top level domain compression
1146 local cnt cnt_tld
source="${1}" temp_tld
="${1}.tld"
1148 "${adb_awk}" '{if(NR==1){tld=$NF};while(getline){if(index($NF,tld".")==0){print tld;tld=$NF}}print tld}' "${source}" | \
1149 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${temp_tld}"
1152 mv -f "${temp_tld}" "${source}"
1153 cnt_tld
="$(wc -l 2>/dev/null < "${source}")"
1157 f_log
"debug" "f_tld ::: source: ${source}, cnt: ${adb_cnt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
1160 # suspend/resume adblock processing
1164 local status entry
done="false" mode
="${1}"
1167 json_load_file
"${adb_rtfile}" >/dev
/null
2>&1
1168 json_select
"data" >/dev
/null
2>&1
1169 json_get_var status
"adblock_status"
1170 if [ "${mode}" = "suspend" ] && [ "${status}" = "enabled" ]
1173 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1174 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]
1176 printf "${adb_dnsheader}" > "${adb_jaildir}/${adb_dnsjail}"
1177 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]
1179 rm -f "${adb_dnsdir}/${adb_dnsjail}"
1183 elif [ "${mode}" = "resume" ] && [ "${status}" = "paused" ]
1189 if [ "${done}" = "true" ]
1191 if [ "${mode}" = "suspend" ]
1196 f_log
"info" "${mode} adblock processing"
1201 # query blocklist for certain (sub-)domains
1205 local search result prefix suffix field query_start query_end query_timeout
=30 domain
="${1}" tld
="${1#*.}"
1207 if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
1209 printf "%s\n" "::: invalid input, please submit a single (sub-)domain :::"
1211 case "${adb_dns}" in
1223 prefix
="[^\\*].*[\\.]"
1228 prefix
="[^\\*].*[\\.]"
1238 query_start
="$(date "+%s
")"
1239 while [ "${domain}" != "${tld}" ]
1241 search
="${domain//[+*~%\$&\"\']/}"
1242 search
="${search//./\\.}"
1243 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}")"
1244 printf "%s\n%s\n%s\n" ":::" "::: domain '${domain}' in active blocklist" ":::"
1245 printf "%s\n\n" "${result:-" - no match"}"
1249 if [ "${adb_backup}" = "1" ] && [ -d "${adb_backupdir}" ]
1251 search
="${1//[+*~%\$&\"\']/}"
1252 search
="${search//./\\.}"
1253 printf "%s\n%s\n%s\n" ":::" "::: domain '${1}' in backups and black-/whitelist" ":::"
1254 for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz "${adb_blacklist}" "${adb_whitelist}"
1256 suffix
="${file##*.}"
1257 if [ "${suffix}" = "gz" ]
1259 zcat
"${file}" 2>/dev
/null | \
1260 "${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}"
1262 "${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}"
1267 query_end
="$(date "+%s
")"
1268 if [ "$((query_end-query_start))" -gt "${query_timeout}" ]
1270 printf "%s\n\n" " - [...]"
1275 if [ "${result}" != "true" ]
1277 printf "%s\n\n" " - no match"
1283 # update runtime information
1287 local entry sources runtime utils memory bg_pid status
="${1:-"enabled"}"
1291 adb_endtime
="$(date "+%s
")"
1292 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)}')"
1293 if [ "$(( (adb_endtime-adb_starttime)/60 ))" -lt 60 ]
1295 runtime="${adb_action}, $(( (adb_endtime-adb_starttime)/60 ))m $(( (adb_endtime-adb_starttime)%60 ))s, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
1297 runtime="${adb_action}, n/a, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
1299 if [ "${status}" = "error" ]
1312 json_load_file "${adb_rtfile}" >/dev/null 2>&1
1315 utils="download: $(readlink -fn "${adb_fetchutil}"), sort: $(readlink -fn "${adb_sort}"), awk: $(readlink -fn "${adb_awk}")"
1316 if [ -z "${adb_cnt}" ]
1318 json_get_var adb_cnt "blocked_domains"
1319 adb_cnt="${adb_cnt%% *}"
1321 if [ -z "${runtime}" ]
1323 json_get_var runtime "last_run"
1326 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]
1329 sources="restrictive_jail"
1331 sources="$(printf "%s\n" ${adb_sources} | "${adb_sort}" | "${adb_awk}" '{ORS=" ";print $0}')"
1336 json_load_file "${adb_rtfile}" >/dev/null 2>&1
1338 json_add_string "adblock_status
" "${status:-"enabled"}"
1339 json_add_string "adblock_version
" "${adb_ver}"
1340 json_add_string "blocked_domains
" "${adb_cnt:-0}"
1341 json_add_array "active_sources
"
1342 for entry in ${sources}
1345 json_add_string "source" "${entry}"
1349 json_add_string "dns_backend
" "${adb_dns:-"-"} (${adb_dnscachecmd##*/}), ${adb_dnsdir:-"-"}"
1350 json_add_string "run_utils
" "${utils:-"-"}"
1351 json_add_string "run_ifaces
" "trigger
: ${adb_trigger:-"-"}, report
: ${adb_repiface:-"-"}"
1352 json_add_string "run_directories
" "base
: ${adb_tmpbase}, backup: ${adb_backupdir}, report: ${adb_reportdir}, jail: ${adb_jaildir}"
1353 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})"
1354 json_add_string "last_run
" "${runtime:-"-"}"
1355 json_add_string "system
" "${adb_sysver}"
1356 json_dump > "${adb_rtfile}"
1358 if [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ] && \
1359 { [ "${status}" = "error" ] || { [ "${status}" = "enabled" ] && [ "${adb_cnt}" -le "${adb_mailcnt}" ]; } }
1361 ( "${adb_mailservice}" "${adb_ver}" >/dev
/null
2>&1 )&
1364 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:-"-"}"
1371 local class
="${1}" log_msg
="${2}"
1373 if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${adb_debug}" = "1" ]; }
1375 if [ -x "${adb_loggercmd}" ]
1377 "${adb_loggercmd}" -p "${class}" -t "adblock-${adb_ver}[${$}]" "${log_msg}"
1379 printf "%s
%s
%s
\n" "${class}" "adblock-${adb_ver}[${$}]" "${log_msg}"
1381 if [ "${class}" = "err
" ]
1390 # main function for blocklist processing
1394 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
1396 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)}')"
1397 f_log
"debug" "f_main ::: memory: ${memory:-0}, max_queue: ${adb_maxqueue}, safe_search: ${adb_safesearch}, force_dns: ${adb_forcedns}, awk: ${adb_awk}"
1399 # white- and blacklist preparation
1401 for entry
in ${adb_locallist}
1403 ( f_list
"${entry}" "${entry}" )&
1406 if [ "${adb_dns}" != "raw" ] && [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]
1408 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1409 chown
"${adb_dnsuser}" "${adb_jaildir}/${adb_dnsjail}" 2>/dev
/null
1413 if [ "${adb_action}" != "resume" ]
1417 f_log
"info" "restrictive jail mode enabled successfully (${adb_sysver})"
1419 f_log
"err" "dns backend restart in jail mode failed"
1423 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]
1425 rm -f "${adb_dnsdir}/${adb_dnsjail}"
1429 # safe search preparation
1431 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]
1433 if [ -z "${adb_safesearchlist}" ]
1435 adb_safesearchlist
="google bing duckduckgo pixabay yandex youtube"
1437 for entry
in ${adb_safesearchlist}
1439 ( f_list safesearch
"${entry}" )&
1446 for src_name
in ${adb_sources}
1448 json_select
"${src_name}" >/dev
/null
2>&1
1449 if [ "${?}" != "0" ]
1451 adb_sources
="${adb_sources/${src_name}}"
1454 json_get_var src_url
"url" >/dev
/null
2>&1
1455 json_get_var src_rset
"rule" >/dev
/null
2>&1
1457 src_tmpcat
="${adb_tmpload}.${src_name}.cat"
1458 src_tmpload
="${adb_tmpload}.${src_name}.load"
1459 src_tmpsort
="${adb_tmpload}.${src_name}.sort"
1460 src_tmpfile
="${adb_tmpfile}.${src_name}"
1465 if [ -z "${src_url}" ] ||
[ -z "${src_rset}" ]
1473 if [ "${adb_backup}" = "1" ] && { [ "${adb_action}" = "start" ] || [ "${adb_action}" = "resume" ]; }
1476 if [ "${?}" = "0" ] && [ -s "${src_tmpfile}" ]
1482 # download queue processing
1484 unset src_cat src_entries
1485 if [ "${src_name}" = "shallalist
" ] || [ "${src_name}" = "utcapitole
" ]
1487 if [ "${src_name}" = "shallalist
" ] && [ -n "${adb_sha_sources}" ]
1489 src_cat="${adb_sha_sources}"
1490 elif [ "${src_name}" = "utcapitole
" ] && [ -n "${adb_utc_sources}" ]
1492 src_cat="${adb_utc_sources}"
1494 if [ -n "${src_cat}" ]
1497 src_arc="${adb_tmpdir}/${src_url##*/}"
1498 src_log="$
("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
1500 if [ "${src_rc}" = "0" ] && [ -s "${src_arc}" ]
1502 src_suffix="$
(eval printf "%s" \"\$\
{adb_src_suffix_
${src_name}:-\"domains
\"\
}\")"
1503 src_list="$
(tar -tzf "${src_arc}" 2>/dev
/null
)"
1504 for src_item in ${src_cat}
1506 src_entries="${src_entries} $(printf "%s" "${src_list}" | grep -E "${src_item}/${src_suffix}$
")"
1508 if [ -n "${src_entries}" ]
1510 tar -xOzf "${src_arc}" ${src_entries} 2>/dev/null > "${src_tmpload}"
1515 src_log
="$(printf "%s
" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1516 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1518 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]
1520 if [ -s "${adb_tmpdir}/tmp.rem.whitelist
" ]
1522 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s
/\r//g
" | \
1523 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f
=NF
;f
>1;f--
)printf "%s.",$f;print
$1}' > "${src_tmpsort}"
1525 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
1526 "${adb_awk}" 'BEGIN
{FS
="."}{for(f
=NF
;f
>1;f--
)printf "%s.",$f;print
$1}' > "${src_tmpsort}"
1529 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
1532 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]
1535 if [ "${adb_backup}" = "1" ]
1539 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
1541 f_log "info" "archive preparation of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1543 rm -f "${src_tmpfile}"
1545 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start
" ]
1547 f_log "info
" "archive extraction of
'${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1553 if [ "${src_name}" = "energized" ] && [ -n "${adb_eng_sources}" ]
1555 src_cat="${adb_eng_sources}"
1556 elif [ "${src_name}" = "stevenblack" ] && [ -n "${adb_stb_sources}" ]
1558 src_cat="${adb_stb_sources}"
1559 elif { [ "${src_name}" = "energized" ] && [ -z "${adb_eng_sources}" ]; } || \
1560 { [ "${src_name}" = "stevenblack" ] && [ -z "${adb_stb_sources}" ]; }
1565 for suffix in ${src_cat:-${src_url}}
1567 if [ "${src_url}" != "${suffix}" ]
1569 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpcat}" "${src_url}${suffix}" 2>&1)"
1571 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpcat}" ]
1573 cat "${src_tmpcat}" >> "${src_tmpload}"
1577 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpload}" "${src_url}" 2>&1)"
1581 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]
1583 if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]
1585 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
1586 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
1588 "${adb_awk}" "${src_rset}" "${src_tmpload}" |
sed "s/\r//g" | \
1589 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
1592 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
1595 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]
1598 if [ "${adb_backup}" = "1" ]
1602 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
1604 f_log
"info" "preparation of '${src_name}' failed, rc: ${src_rc}"
1606 rm -f "${src_tmpfile}"
1609 src_log
="$(printf "%s
" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1610 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1611 if [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start
" ]
1618 hold=$((cnt%adb_maxqueue))
1619 if [ "${hold}" = "0" ]
1628 # tld compression and dns restart
1630 if [ "${?}" = "0" ] && [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
1632 f_tld "${adb_tmpdir}/${adb_dnsfile}"
1635 printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
1637 chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
1641 if [ "${adb_action}" != "resume
" ]
1645 f_log "info
" "blocklist with overall
${adb_cnt} blocked domains loaded successfully
(${adb_sysver})"
1647 f_log "err
" "dns backend restart with adblock blocklist failed
"
1652 # trace dns queries via tcpdump and prepare a report
1656 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 action="${1}" count="${2:-"50"}" search="${3:-"+"}"
1658 report_raw="${adb_reportdir}/adb_report.raw
"
1659 report_srt="${adb_reportdir}/adb_report.srt
"
1660 report_jsn="${adb_reportdir}/adb_report.json
"
1661 report_txt="${adb_reportdir}/adb_mailreport.txt
"
1665 if [ "${action}" != "json
" ]
1671 for file in "${adb_reportdir}/adb_report.pcap
"*
1674 "${adb_dumpcmd}" -nn -tttt -r "${file}" 2>/dev/null | \
1675 "${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);
1676 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}"
1678 hold=$((cnt%adb_maxqueue))
1679 if [ "${hold}" = "0" ]
1686 if [ -s "${report_raw}" ]
1688 "${adb_sort}" ${adb_srtopts} -k1 -k3 -k4 -k5 -k1 -ur "${report_raw}" | \
1689 "${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}}' | \
1690 "${adb_sort}" ${adb_srtopts} -k1 -k2 -k3 -k4 -ur > "${report_srt}"
1691 rm -f "${report_raw}"
1694 if [ -s "${report_srt}" ]
1696 start="$
("${adb_awk}" 'END{printf "%s_%s",$1,$2}' "${report_srt}")"
1697 end="$
("${adb_awk}" 'NR==1{printf "%s_%s",$1,$2}' "${report_srt}")"
1698 total="$
(wc -l < "${report_srt}")"
1699 blocked="$
("${adb_awk}" '{if($5=="NX")cnt++}END{printf "%s",cnt}' "${report_srt}")"
1700 percent="$
("${adb_awk}" -v t="${total}" -v b="${blocked}" 'BEGIN{printf "%.2f%s",b/t*100,"%"}')"
1702 printf "%s\n" "{ " >> "${report_jsn}"
1703 printf "\t%s\n" "\"start_date\": \"${start%_*}\", " >> "${report_jsn}"
1704 printf "\t%s\n" "\"start_time\": \"${start#*_}\", " >> "${report_jsn}"
1705 printf "\t%s\n" "\"end_date\": \"${end%_*}\", " >> "${report_jsn}"
1706 printf "\t%s\n" "\"end_time\": \"${end#*_}\", " >> "${report_jsn}"
1707 printf "\t%s\n" "\"total\": \"${total}\", " >> "${report_jsn}"
1708 printf "\t%s\n" "\"blocked\": \"${blocked}\", " >> "${report_jsn}"
1709 printf "\t%s\n" "\"percent\": \"${percent}\", " >> "${report_jsn}"
1710 top_list
="top_clients top_domains top_blocked"
1711 for top
in ${top_list}
1713 printf "\t%s" "\"${top}\": [ " >> "${report_jsn}"
1716 "${adb_awk}" '{print $3}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c | \
1717 "${adb_sort}" ${adb_srtopts} -nr | \
1718 "${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}"
1721 "${adb_awk}" '{if($5!="NX")print $4}' "${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}" | \
1727 "${adb_sort}" ${adb_srtopts} | uniq -c | "${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 printf "\n\t%s
\n" "]," >> "${report_jsn}"
1733 search="${search//./\\.}"
1734 search="${search//[+*~%\$&\"\' ]/}"
1735 "${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}"
1736 rm -f "${report_srt}"
1740 # output preparation
1742 if [ -s "${report_jsn}" ] && { [ "${action}" = "cli" ] || [ "${action}" = "mail" ]; }
1744 printf "%s\n%s\n%s\n" ":::" "::: Adblock DNS-Query Report" ":::" >> "${report_txt}"
1746 json_load_file
"${report_jsn}"
1747 json_get_keys key_list
1748 for key
in ${key_list}
1750 json_get_var value
"${key}"
1751 eval "${key}=\"${value}\""
1753 printf " + %s\n + %s\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}" >> "${report_txt}"
1754 printf " + %s\n + %s %s\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})" >> "${report_txt}"
1755 top_list
="top_clients top_domains top_blocked requests"
1756 for top
in ${top_list}
1760 item
="::: Top 10 Clients"
1763 item
="::: Top 10 Domains"
1766 item
="::: Top 10 Blocked Domains"
1769 if json_get_type status
"${top}" && [ "${top}" != "requests" ] && [ "${status}" = "array" ]
1771 printf "%s\n%s\n%s\n" ":::" "${item}" ":::" >> "${report_txt}"
1772 json_select
"${top}"
1775 while json_get_type status
"${index}" && [ "${status}" = "object" ]
1777 json_get_values item
"${index}"
1778 printf " + %-9s::: %s\n" ${item} >> "${report_txt}"
1781 elif json_get_type status
"${top}" && [ "${top}" = "requests" ] && [ "${status}" = "array" ]
1783 printf "%s\n%s\n%s\n" ":::" "::: Latest DNS Queries" ":::" >> "${report_txt}"
1784 printf "%-15s%-15s%-45s%-80s%s\n" "Date" "Time" "Client" "Domain" "Answer" >> "${report_txt}"
1785 json_select
"${top}"
1787 while json_get_type status
"${index}" && [ "${status}" = "object" ]
1789 json_get_values item
"${index}"
1790 printf "%-15s%-15s%-45s%-80s%s\n" ${item} >> "${report_txt}"
1796 content
="$(cat "${report_txt}" 2>/dev/null)"
1797 rm -f "${report_txt}"
1802 if [ "${action}" = "cli" ]
1804 printf "%s\n" "${content}"
1805 elif [ "${action}" = "json" ]
1808 elif [ "${action}" = "mail" ] && [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ]
1810 ( "${adb_mailservice}" "${adb_ver}" "${content}" >/dev
/null
2>&1 )&
1813 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}"
1816 # source required system libraries
1818 if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
1820 .
"/lib/functions.sh"
1821 .
"/lib/functions/network.sh"
1822 .
"/usr/share/libubox/jshn.sh"
1824 f_log
"err" "system libraries not found"
1827 # version information
1829 if [ "${adb_action}" = "version" ]
1831 printf "%s\n" "${adb_ver}"
1837 adb_awk
="$(command -v gawk)"
1838 if [ ! -x "${adb_awk}" ]
1840 adb_awk
="$(command -v awk)"
1841 if [ ! -x "${adb_awk}" ]
1843 f_log
"err" "awk not found or not executable"
1849 adb_sort
="$(command -v sort)"
1850 if [ ! -x "${adb_sort}" ] ||
[ "$("${adb_sort}" --version 2>/dev/null | grep -c "coreutils
")" = "0" ]
1852 f_log
"err" "coreutils sort not found or not executable"
1855 # handle different adblock actions
1858 case "${adb_action}" in
1868 if [ "${adb_dns}" != "raw" ]
1874 if [ "${adb_dns}" != "raw" ]
1880 f_report
"${2}" "${3}" "${4}"