Merge pull request #19865 from pprindeville/issue#19757
[feed/packages.git] / net / adblock / files / adblock.sh
1 #!/bin/sh
2 # dns based ad/abuse domain blocking
3 # Copyright (c) 2015-2022 Dirk Brenken (dev@brenken.org)
4 # This is free software, licensed under the GNU General Public License v3.
5
6 # disable (s)hellcheck in release
7 # shellcheck disable=all
8
9 # set initial defaults
10 #
11 export LC_ALL=C
12 export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
13
14 adb_ver="4.1.5"
15 adb_enabled="0"
16 adb_debug="0"
17 adb_forcedns="0"
18 adb_dnsflush="0"
19 adb_dnstimeout="20"
20 adb_safesearch="0"
21 adb_safesearchlist=""
22 adb_safesearchmod="0"
23 adb_report="0"
24 adb_trigger=""
25 adb_triggerdelay="0"
26 adb_backup="1"
27 adb_mail="0"
28 adb_mailcnt="0"
29 adb_jail="0"
30 adb_dns=""
31 adb_dnsprefix="adb_list"
32 adb_locallist="blacklist whitelist iplist"
33 adb_tmpbase="/tmp"
34 adb_backupdir="${adb_tmpbase}/adblock-Backup"
35 adb_reportdir="${adb_tmpbase}/adblock-Report"
36 adb_jaildir="/tmp"
37 adb_pidfile="/var/run/adblock.pid"
38 adb_blacklist="/etc/adblock/adblock.blacklist"
39 adb_whitelist="/etc/adblock/adblock.whitelist"
40 adb_mailservice="/etc/adblock/adblock.mail"
41 adb_dnsfile="${adb_dnsprefix}.overall"
42 adb_dnsjail="${adb_dnsprefix}.jail"
43 adb_srcarc="/etc/adblock/adblock.sources.gz"
44 adb_srcfile="${adb_tmpbase}/adb_sources.json"
45 adb_rtfile="${adb_tmpbase}/adb_runtime.json"
46 adb_loggercmd="$(command -v logger)"
47 adb_dumpcmd="$(command -v tcpdump)"
48 adb_lookupcmd="$(command -v nslookup)"
49 adb_fetchutil=""
50 adb_fetchinsecure=""
51 adb_zonelist=""
52 adb_portlist=""
53 adb_repiface=""
54 adb_replisten="53"
55 adb_repchunkcnt="5"
56 adb_repchunksize="1"
57 adb_represolve="0"
58 adb_lookupdomain="example.com"
59 adb_action="${1:-"start"}"
60 adb_packages=""
61 adb_sources=""
62 adb_cnt=""
63
64 # load & check adblock environment
65 #
66 f_load() {
67 local bg_pid iface port ports cpu core
68
69 adb_sysver="$(ubus -S call system board 2>/dev/null | jsonfilter -q -e '@.model' -e '@.release.description' |
70 "${adb_awk}" 'BEGIN{RS="";FS="\n"}{printf "%s, %s",$1,$2}')"
71 adb_memory="$("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null |
72 "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
73
74 f_conf
75
76 cpu="$(grep -c '^processor' /proc/cpuinfo 2>/dev/null)"
77 core="$(grep -cm1 '^core id' /proc/cpuinfo 2>/dev/null)"
78 [ "${cpu}" = "0" ] && cpu="1"
79 [ "${core}" = "0" ] && core="1"
80 adb_cores="$((cpu * core))"
81
82 if [ "${adb_action}" != "report" ]; then
83 f_dns
84 f_fetch
85 fi
86
87 if [ "${adb_enabled}" = "0" ]; then
88 f_extconf
89 f_temp
90 f_rmdns
91 f_jsnup "disabled"
92 f_log "info" "adblock is currently disabled, please set the config option 'adb_enabled' to '1' to use this service"
93 exit 0
94 fi
95
96 if [ "${adb_report}" = "1" ] && [ ! -x "${adb_dumpcmd}" ]; then
97 f_log "info" "Please install the package 'tcpdump' or 'tcpdump-mini' to use the reporting feature"
98 elif [ "${adb_report}" = "0" ] && [ "${adb_action}" = "report" ]; then
99 f_log "info" "Please enable the 'DNS Report' option to use the reporting feature"
100 exit 0
101 fi
102
103 bg_pid="$(pgrep -f "^${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
104 if [ -x "${adb_dumpcmd}" ] && { [ "${adb_report}" = "0" ] || { [ -n "${bg_pid}" ] && { [ "${adb_action}" = "stop" ] || [ "${adb_action}" = "restart" ]; }; }; }; then
105 if [ -n "${bg_pid}" ]; then
106 kill -HUP "${bg_pid}" 2>/dev/null
107 while kill -0 "${bg_pid}" 2>/dev/null; do
108 sleep 1
109 done
110 unset bg_pid
111 fi
112 fi
113
114 if [ -x "${adb_dumpcmd}" ] && [ "${adb_report}" = "1" ] && [ -z "${bg_pid}" ] && [ "${adb_action}" != "report" ] && [ "${adb_action}" != "stop" ]; then
115 for port in ${adb_replisten}; do
116 [ -z "${ports}" ] && ports="port ${port}" || ports="${ports} or port ${port}"
117 done
118 if [ -z "${adb_repiface}" ]; then
119 network_get_device iface "lan"
120 [ -z "${iface}" ] && network_get_physdev iface "lan"
121 [ -n "${iface}" ] && adb_repiface="${iface}"
122 [ -n "${adb_repiface}" ] && { uci_set adblock global adb_repiface "${adb_repiface}"; f_uci "adblock"; }
123 fi
124 if [ -n "${adb_reportdir}" ] && [ ! -d "${adb_reportdir}" ]; then
125 mkdir -p "${adb_reportdir}"
126 f_log "info" "report directory '${adb_reportdir}' created"
127 fi
128 if [ -n "${adb_repiface}" ] && [ -d "${adb_reportdir}" ]; then
129 ("${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 &)
130 bg_pid="$(pgrep -f "^${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
131 else
132 f_log "info" "Please set the name of the reporting network device 'adb_repiface' manually"
133 fi
134 fi
135 }
136
137 # check & set environment
138 #
139 f_env() {
140 adb_starttime="$(date "+%s")"
141 f_log "info" "adblock instance started ::: action: ${adb_action}, priority: ${adb_nice:-"0"}, pid: ${$}"
142 f_jsnup "running"
143 f_extconf
144 f_temp
145
146 if [ "${adb_dnsflush}" = "1" ] || [ "${adb_memory##*/}" -lt "64" ]; then
147 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
148 f_dnsup
149 fi
150
151 if [ ! -r "${adb_srcfile}" ]; then
152 if [ -r "${adb_srcarc}" ]; then
153 zcat "${adb_srcarc}" >"${adb_srcfile}"
154 else
155 f_log "err" "adblock source archive not found"
156 fi
157 fi
158 if [ -r "${adb_srcfile}" ] && [ "${adb_action}" != "report" ]; then
159 json_init
160 json_load_file "${adb_srcfile}"
161 else
162 f_log "err" "adblock source file not found"
163 fi
164 }
165
166 # load adblock config
167 #
168 f_conf() {
169 local cnt="0" cnt_max="10"
170
171 [ ! -r "/etc/config/adblock" ] && f_log "err" "no valid adblock config found, please re-install the package via opkg with the '--force-reinstall --force-maintainer' options"
172
173 config_cb() {
174 option_cb() {
175 local option="${1}"
176 local value="${2}"
177 eval "${option}=\"${value}\""
178 }
179 list_cb() {
180 local option="${1}"
181 local value="${2}"
182 if [ "${option}" = "adb_sources" ]; then
183 eval "${option}=\"$(printf "%s" "${adb_sources}") ${value}\""
184 elif [ "${option}" = "adb_eng_sources" ]; then
185 eval "${option}=\"$(printf "%s" "${adb_eng_sources}") ${value}\""
186 elif [ "${option}" = "adb_stb_sources" ]; then
187 eval "${option}=\"$(printf "%s" "${adb_stb_sources}") ${value}\""
188 elif [ "${option}" = "adb_utc_sources" ]; then
189 eval "${option}=\"$(printf "%s" "${adb_utc_sources}") ${value}\""
190 elif [ "${option}" = "adb_denyip" ]; then
191 eval "${option}=\"$(printf "%s" "${adb_denyip}") ${value}\""
192 elif [ "${option}" = "adb_allowip" ]; then
193 eval "${option}=\"$(printf "%s" "${adb_allowip}") ${value}\""
194 elif [ "${option}" = "adb_safesearchlist" ]; then
195 eval "${option}=\"$(printf "%s" "${adb_safesearchlist}") ${value}\""
196 elif [ "${option}" = "adb_zonelist" ]; then
197 eval "${option}=\"$(printf "%s" "${adb_zonelist}") ${value}\""
198 elif [ "${option}" = "adb_portlist" ]; then
199 eval "${option}=\"$(printf "%s" "${adb_portlist}") ${value}\""
200 fi
201 }
202 }
203 config_load adblock
204
205 if [ -z "${adb_fetchutil}" ] || [ -z "${adb_dns}" ]; then
206 while [ -z "${adb_packages}" ] && [ "${cnt}" -le "${cnt_max}" ]; do
207 adb_packages="$(opkg list-installed 2>/dev/null)"
208 cnt="$((cnt + 1))"
209 sleep 1
210 done
211 [ -z "${adb_packages}" ] && f_log "err" "local opkg package repository is not available, please set 'adb_fetchutil' and 'adb_dns' manually"
212 fi
213 }
214
215 # status helper function
216 #
217 f_char() {
218 local result input="${1}"
219
220 if [ "${input}" = "1" ]; then
221 result="✔"
222 else
223 result="✘"
224 fi
225 printf "%s" "${result}"
226 }
227
228 # load dns backend config
229 #
230 f_dns() {
231 local util utils dns_up cnt="0"
232
233 if [ -z "${adb_dns}" ]; then
234 utils="knot-resolver bind unbound dnsmasq raw"
235 for util in ${utils}; do
236 if [ "${util}" = "raw" ] || printf "%s" "${adb_packages}" | grep -q "^${util}"; then
237 if [ "${util}" = "knot-resolver" ]; then
238 util="kresd"
239 elif [ "${util}" = "bind" ]; then
240 util="named"
241 fi
242 if [ "${util}" = "raw" ] || [ -x "$(command -v "${util}")" ]; then
243 adb_dns="${util}"
244 uci_set adblock global adb_dns "${util}"
245 f_uci "adblock"
246 break
247 fi
248 fi
249 done
250 elif [ "${adb_dns}" != "raw" ] && [ ! -x "$(command -v "${adb_dns}")" ]; then
251 unset adb_dns
252 fi
253
254 if [ -n "${adb_dns}" ]; then
255 case "${adb_dns}" in
256 "dnsmasq")
257 adb_dnscachecmd="-"
258 adb_dnsinstance="${adb_dnsinstance:-"0"}"
259 adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
260 adb_dnsdir="${adb_dnsdir:-"/tmp/dnsmasq.d"}"
261 adb_dnsheader="${adb_dnsheader:-""}"
262 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"local=/\"\$0\"/\"}'"}"
263 adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"local=/\"\$0\"/#\"}'"}"
264 adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"address=/\"\$0\"/\"item\"\"}'"}"
265 adb_dnsstop="${adb_dnsstop:-"address=/#/"}"
266 ;;
267 "unbound")
268 adb_dnscachecmd="$(command -v unbound-control || printf "%s" "-")"
269 adb_dnsinstance="${adb_dnsinstance:-"0"}"
270 adb_dnsuser="${adb_dnsuser:-"unbound"}"
271 adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
272 adb_dnsheader="${adb_dnsheader:-""}"
273 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 always_nxdomain\"}'"}"
274 adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 always_transparent\"}'"}"
275 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\"}'"}"
276 adb_dnsstop="${adb_dnsstop:-"local-zone: \".\" always_nxdomain"}"
277 ;;
278 "named")
279 adb_dnscachecmd="$(command -v rndc || printf "%s" "-")"
280 adb_dnsinstance="${adb_dnsinstance:-"0"}"
281 adb_dnsuser="${adb_dnsuser:-"bind"}"
282 adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
283 adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n IN NS localhost.\n"}"
284 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
285 adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
286 adb_dnsdenyip="${adb_dnsdenyip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME .\"}'"}"
287 adb_dnsallowip="${adb_dnsallowip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME rpz-passthru.\"}'"}"
288 adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"\"\$0\" CNAME \"item\".\\n*.\"\$0\" CNAME \"item\".\"}'"}"
289 adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
290 ;;
291 "kresd")
292 adb_dnscachecmd="-"
293 adb_dnsinstance="${adb_dnsinstance:-"0"}"
294 adb_dnsuser="${adb_dnsuser:-"root"}"
295 adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
296 adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n"}"
297 adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
298 adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
299 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\"\"}'"}"
300 adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
301 ;;
302 "raw")
303 adb_dnscachecmd="-"
304 adb_dnsinstance="${adb_dnsinstance:-"0"}"
305 adb_dnsuser="${adb_dnsuser:-"root"}"
306 adb_dnsdir="${adb_dnsdir:-"/tmp"}"
307 adb_dnsheader="${adb_dnsheader:-""}"
308 adb_dnsdeny="${adb_dnsdeny:-"0"}"
309 adb_dnsallow="${adb_dnsallow:-"1"}"
310 adb_dnssafesearch="${adb_dnssafesearch:-"0"}"
311 adb_dnsstop="${adb_dnsstop:-"0"}"
312 ;;
313 esac
314 fi
315
316 if [ "${adb_dns}" != "raw" ] && { [ -z "${adb_dns}" ] || [ ! -x "$(command -v "${adb_dns}")" ]; }; then
317 f_log "err" "dns backend not found, please set 'adb_dns' manually"
318 fi
319
320 if [ "${adb_dns}" != "raw" ] && { [ "${adb_dnsdir}" = "${adb_tmpbase}" ] || [ "${adb_dnsdir}" = "${adb_backupdir}" ] || [ "${adb_dnsdir}" = "${adb_reportdir}" ]; }; then
321 f_log "err" "dns directory '${adb_dnsdir}' has been misconfigured, it must not point to the 'adb_tmpbase', 'adb_backupdir', 'adb_reportdir'"
322 fi
323
324 if [ "${adb_action}" = "start" ] && [ -z "${adb_trigger}" ]; then
325 sleep ${adb_triggerdelay}
326 fi
327
328 if [ "${adb_dns}" != "raw" ] && [ "${adb_action}" != "stop" ]; then
329 while [ "${cnt}" -le 30 ]; do
330 dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
331 if [ "${dns_up}" = "true" ]; then
332 break
333 fi
334 sleep 1
335 cnt="$((cnt + 1))"
336 done
337 fi
338
339 if [ "${adb_action}" != "stop" ]; then
340 if [ -n "${adb_dnsdir}" ] && [ ! -d "${adb_dnsdir}" ]; then
341 if mkdir -p "${adb_dnsdir}"; then
342 f_log "info" "dns backend directory '${adb_dnsdir}' created"
343 else
344 f_log "err" "dns backend directory '${adb_dnsdir}' could not be created"
345 fi
346 fi
347 [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ] && printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
348
349 if [ "${dns_up}" != "true" ]; then
350 if ! f_dnsup 4; then
351 f_log "err" "dns backend '${adb_dns}' not running or executable"
352 fi
353 fi
354
355 if [ "${adb_backup}" = "1" ] && [ -n "${adb_backupdir}" ] && [ ! -d "${adb_backupdir}" ]; then
356 if mkdir -p "${adb_backupdir}"; then
357 f_log "info" "backup directory '${adb_backupdir}' created"
358 else
359 f_log "err" "backup directory '${adb_backupdir}' could not be created"
360 fi
361 fi
362
363 if [ -n "${adb_jaildir}" ] && [ ! -d "${adb_jaildir}" ]; then
364 if mkdir -p "${adb_jaildir}"; then
365 f_log "info" "jail directory '${adb_jaildir}' created"
366 else
367 f_log "err" "jail directory '${adb_jaildir}' could not be created"
368 fi
369 fi
370 fi
371 f_log "debug" "f_dns ::: dns: ${adb_dns}, dns_dir: ${adb_dnsdir}, dns_file: ${adb_dnsfile}, dns_user: ${adb_dnsuser}, dns_instance: ${adb_dnsinstance}, backup: ${adb_backup}, backup_dir: ${adb_backupdir}, jail_dir: ${adb_jaildir}"
372 }
373
374 # load fetch utility
375 #
376 f_fetch() {
377 local util utils insecure cnt="0"
378
379 if [ -z "${adb_fetchutil}" ]; then
380 utils="aria2c curl wget uclient-fetch"
381 for util in ${utils}; do
382 if { [ "${util}" = "uclient-fetch" ] && printf "%s" "${adb_packages}" | grep -q "^libustream-"; } ||
383 { [ "${util}" = "wget" ] && printf "%s" "${adb_packages}" | grep -q "^wget -"; } ||
384 [ "${util}" = "curl" ] || [ "${util}" = "aria2c" ]; then
385 if [ -x "$(command -v "${util}")" ]; then
386 adb_fetchutil="${util}"
387 uci_set adblock global adb_fetchutil "${util}"
388 f_uci "adblock"
389 break
390 fi
391 fi
392 done
393 elif [ ! -x "$(command -v "${adb_fetchutil}")" ]; then
394 unset adb_fetchutil
395 fi
396 case "${adb_fetchutil}" in
397 "aria2c")
398 [ "${adb_fetchinsecure}" = "1" ] && insecure="--check-certificate=false"
399 adb_fetchparm="${adb_fetchparm:-"${insecure} --timeout=20 --allow-overwrite=true --auto-file-renaming=false --log-level=warn --dir=/ -o"}"
400 ;;
401 "curl")
402 [ "${adb_fetchinsecure}" = "1" ] && insecure="--insecure"
403 adb_fetchparm="${adb_fetchparm:-"${insecure} --connect-timeout 20 --fail --silent --show-error --location -o"}"
404 ;;
405 "uclient-fetch")
406 [ "${adb_fetchinsecure}" = "1" ] && insecure="--no-check-certificate"
407 adb_fetchparm="${adb_fetchparm:-"${insecure} --timeout=20 -O"}"
408 ;;
409 "wget")
410 [ "${adb_fetchinsecure}" = "1" ] && insecure="--no-check-certificate"
411 adb_fetchparm="${adb_fetchparm:-"${insecure} --no-cache --no-cookies --max-redirect=0 --timeout=20 -O"}"
412 ;;
413 esac
414 if [ -n "${adb_fetchutil}" ] && [ -n "${adb_fetchparm}" ]; then
415 adb_fetchutil="$(command -v "${adb_fetchutil}")"
416 else
417 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'"
418 fi
419 f_log "debug" "f_fetch ::: fetch_util: ${adb_fetchutil:-"-"}, fetch_parm: ${adb_fetchparm:-"-"}"
420 }
421
422 # create temporary files, directories and set dependent options
423 #
424 f_temp() {
425 if [ -d "${adb_tmpbase}" ]; then
426 adb_tmpdir="$(mktemp -p "${adb_tmpbase}" -d)"
427 adb_tmpload="$(mktemp -p "${adb_tmpdir}" -tu)"
428 adb_tmpfile="$(mktemp -p "${adb_tmpdir}" -tu)"
429 adb_srtopts="--temporary-directory=${adb_tmpdir} --compress-program=gzip --parallel=${adb_cores}"
430 else
431 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"
432 fi
433 [ ! -s "${adb_pidfile}" ] && printf "%s" "${$}" >"${adb_pidfile}"
434 f_log "debug" "f_temp ::: tmp_base: ${adb_tmpbase:-"-"}, tmp_dir: ${adb_tmpdir:-"-"}, sort_options: ${adb_srtopts}, pid_file: ${adb_pidfile:-"-"}"
435 }
436
437 # remove temporary files and directories
438 #
439 f_rmtemp() {
440 [ -d "${adb_tmpdir}" ] && rm -rf "${adb_tmpdir}"
441 rm -f "${adb_srcfile}"
442 : >"${adb_pidfile}"
443 f_log "debug" "f_rmtemp ::: tmp_dir: ${adb_tmpdir:-"-"}, src_file: ${adb_srcfile:-"-"}, pid_file: ${adb_pidfile:-"-"}"
444 }
445
446 # remove dns related files
447 #
448 f_rmdns() {
449 local status
450
451 status="$(ubus -S call service list '{"name":"adblock"}' 2>/dev/null | jsonfilter -l1 -e '@["adblock"].instances.*.running' 2>/dev/null)"
452 if [ "${adb_dns}" = "raw" ] || { [ -n "${adb_dns}" ] && [ -n "${status}" ]; }; then
453 : >"${adb_rtfile}"
454 [ "${adb_backup}" = "1" ] && rm -f "${adb_backupdir}/${adb_dnsprefix}".*.gz
455 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
456 f_dnsup 4
457 fi
458 f_rmtemp
459 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:-"-"}"
460 }
461
462 # commit uci changes
463 #
464 f_uci() {
465 local change config="${1}"
466
467 if [ -n "${config}" ]; then
468 change="$(uci -q changes "${config}" | "${adb_awk}" '{ORS=" "; print $0}')"
469 if [ -n "${change}" ]; then
470 uci_commit "${config}"
471 case "${config}" in
472 "firewall")
473 "/etc/init.d/firewall" reload >/dev/null 2>&1
474 ;;
475 "resolver")
476 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
477 f_count
478 f_jsnup "running"
479 "/etc/init.d/${adb_dns}" reload >/dev/null 2>&1
480 ;;
481 esac
482 fi
483 f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
484 fi
485 }
486
487 # get list counter
488 #
489 f_count() {
490 local file mode="${1}" name="${2}"
491
492 adb_cnt="0"
493 case "${mode}" in
494 "iplist")
495 [ -s "${adb_tmpdir}/tmp.add.${name}" ] && adb_cnt="$(wc -l 2>/dev/null <"${adb_tmpdir}/tmp.add.${name}")"
496 ;;
497 "blacklist")
498 [ -s "${adb_tmpfile}.${name}" ] && adb_cnt="$(wc -l 2>/dev/null <"${adb_tmpfile}.${name}")"
499 ;;
500 "whitelist")
501 [ -s "${adb_tmpdir}/tmp.raw.${name}" ] && { adb_cnt="$(wc -l 2>/dev/null <"${adb_tmpdir}/tmp.raw.${name}")"; rm -f "${adb_tmpdir}/tmp.raw.${name}"; }
502 ;;
503 "safesearch")
504 [ -s "${adb_tmpdir}/tmp.safesearch.${name}" ] && adb_cnt="$(wc -l 2>/dev/null <"${adb_tmpdir}/tmp.safesearch.${name}")"
505 ;;
506 "merge")
507 [ -s "${adb_tmpdir}/${adb_dnsfile}" ] && adb_cnt="$(wc -l 2>/dev/null <"${adb_tmpdir}/${adb_dnsfile}")"
508 ;;
509 "download" | "backup" | "restore")
510 [ -s "${src_tmpfile}" ] && adb_cnt="$(wc -l 2>/dev/null <"${src_tmpfile}")"
511 ;;
512 "final")
513 if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]; then
514 adb_cnt="$(wc -l 2>/dev/null <"${adb_dnsdir}/${adb_dnsfile}")"
515 if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]; then
516 adb_cnt="$((adb_cnt - $(wc -l 2>/dev/null <"${adb_tmpdir}/tmp.add.whitelist")))"
517 fi
518 for file in "${adb_tmpdir}/tmp.safesearch".*; do
519 if [ -r "${file}" ]; then
520 adb_cnt="$((adb_cnt - $(wc -l 2>/dev/null <"${file}")))"
521 fi
522 done
523 [ -n "${adb_dnsheader}" ] && adb_cnt="$(((adb_cnt - $(printf "%b" "${adb_dnsheader}" | grep -c "^")) / 2))"
524 fi
525 ;;
526 esac
527 }
528
529 # set external config options
530 #
531 f_extconf() {
532 local config config_dir config_file section zone port fwcfg
533
534 case "${adb_dns}" in
535 "dnsmasq")
536 config="dhcp"
537 config_dir="$(uci_get dhcp "@dnsmasq[${adb_dnsinstance}]" confdir | grep -Fo "${adb_dnsdir}")"
538 if [ "${adb_enabled}" = "1" ] && [ -z "${config_dir}" ]; then
539 uci_set dhcp "@dnsmasq[${adb_dnsinstance}]" confdir "${adb_dnsdir}" 2>/dev/null
540 fi
541 ;;
542 "kresd")
543 config="resolver"
544 config_file="$(uci_get resolver kresd rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
545 if [ "${adb_enabled}" = "1" ] && [ -z "${config_file}" ]; then
546 uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
547 elif [ "${adb_enabled}" = "0" ] && [ -n "${config_file}" ]; then
548 uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
549 fi
550 ;;
551 esac
552 f_uci "${config}"
553
554 config="firewall"
555 fwcfg="$(uci -qNX show "${config}" | "${adb_awk}" 'BEGIN{FS="[.=]"};/adblock_/{if(zone==$2){next}else{ORS=" ";zone=$2;print zone}}')"
556 if [ "${adb_enabled}" = "1" ] && [ "${adb_forcedns}" = "1" ] &&
557 /etc/init.d/firewall enabled; then
558 for zone in ${adb_zonelist}; do
559 for port in ${adb_portlist}; do
560 if ! printf "%s" "${fwcfg}" | grep -q "adblock_${zone}${port}[ |\$]"; then
561 uci -q batch <<-EOC
562 set firewall."adblock_${zone}${port}"="redirect"
563 set firewall."adblock_${zone}${port}".name="Adblock DNS (${zone}, ${port})"
564 set firewall."adblock_${zone}${port}".src="${zone}"
565 set firewall."adblock_${zone}${port}".proto="tcp udp"
566 set firewall."adblock_${zone}${port}".src_dport="${port}"
567 set firewall."adblock_${zone}${port}".dest_port="${port}"
568 set firewall."adblock_${zone}${port}".target="DNAT"
569 EOC
570 fi
571 fwcfg="${fwcfg/adblock_${zone}${port}[ |\$]/}"
572 done
573 done
574 fwcfg="${fwcfg#"${fwcfg%%[![:space:]]*}"}"
575 fwcfg="${fwcfg%"${fwcfg##*[![:space:]]}"}"
576 fi
577 if [ "${adb_enabled}" = "0" ] || [ "${adb_forcedns}" = "0" ] || [ -n "${fwcfg}" ]; then
578 for section in ${fwcfg}; do
579 uci_remove firewall "${section}"
580 done
581 fi
582 f_uci "${config}"
583 }
584
585 # restart dns backend
586 #
587 f_dnsup() {
588 local rset dns_service dns_up dns_pid restart_rc cnt="0" out_rc="4" in_rc="${1:-0}"
589
590 if [ "${adb_dns}" = "raw" ]; then
591 out_rc="0"
592 else
593 if [ "${in_rc}" = "0" ] && [ "${adb_dnsflush}" = "0" ]; then
594 case "${adb_dns}" in
595 "unbound")
596 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}/unbound.conf" ]; then
597 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" dump_cache >"${adb_tmpdir}/adb_cache.dump" 2>/dev/null
598 fi
599 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
600 restart_rc="${?}"
601 ;;
602 "named")
603 if [ -x "${adb_dnscachecmd}" ] && [ -f "/etc/bind/rndc.conf" ]; then
604 "${adb_dnscachecmd}" -c "/etc/bind/rndc.conf" reload >/dev/null 2>&1
605 restart_rc="${?}"
606 fi
607 if [ -z "${restart_rc}" ] || { [ -n "${restart_rc}" ] && [ "${restart_rc}" != "0" ]; }; then
608 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
609 restart_rc="${?}"
610 fi
611 ;;
612 *)
613 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
614 restart_rc="${?}"
615 ;;
616 esac
617 fi
618 if [ -z "${restart_rc}" ]; then
619 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
620 restart_rc="${?}"
621 fi
622 fi
623 if [ "${restart_rc}" = "0" ]; then
624 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
625 while [ "${cnt}" -le "${adb_dnstimeout}" ]; do
626 dns_service="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}")"
627 dns_up="$(printf "%s" "${dns_service}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
628 dns_pid="$(printf "%s" "${dns_service}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.pid")"
629 if [ "${dns_up}" = "true" ] && [ -n "${dns_pid}" ] && ! ls "/proc/${dns_pid}/fd/${adb_dnsdir}/${adb_dnsfile}" >/dev/null 2>&1; then
630 if [ -x "${adb_lookupcmd}" ] && [ -n "$(printf "%s" "${adb_lookupdomain}" | "${adb_awk}" "${rset}")" ]; then
631 if "${adb_lookupcmd}" "${adb_lookupdomain}" >/dev/null 2>&1; then
632 out_rc="0"
633 break
634 fi
635 else
636 sleep ${adb_dnstimeout}
637 cnt=${adb_dnstimeout}
638 out_rc="0"
639 break
640 fi
641 fi
642 cnt="$((cnt + 1))"
643 sleep 1
644 done
645 if [ "${out_rc}" = "0" ] && [ "${adb_dns}" = "unbound" ]; then
646 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}/adb_cache.dump" ]; then
647 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" load_cache <"${adb_tmpdir}/adb_cache.dump" >/dev/null 2>&1
648 restart_rc="${?}"
649 fi
650 fi
651 fi
652 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_timeout: ${adb_dnstimeout}, dns_cnt: ${cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
653 return "${out_rc}"
654 }
655
656 # backup/restore/remove blocklists
657 #
658 f_list() {
659 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 ffiles="-maxdepth 1 -name ${adb_dnsprefix}.*.gz"
660
661 case "${mode}" in
662 "iplist")
663 src_name="${mode}"
664 if [ "${adb_dns}" = "named" ]; then
665 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\"}"
666 if [ -n "${adb_allowip}" ]; then
667 : >"${adb_tmpdir}/tmp.raw.${src_name}"
668 for ip in ${adb_allowip}; do
669 printf "%s" "${ip}" | "${adb_awk}" "${rset}" >>"${adb_tmpdir}/tmp.raw.${src_name}"
670 done
671 eval "${adb_dnsallowip}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.add.${src_name}"
672 out_rc="${?}"
673 fi
674 if [ -n "${adb_denyip}" ] && { [ -z "${out_rc}" ] || [ "${out_rc}" = "0" ]; }; then
675 : >"${adb_tmpdir}/tmp.raw.${src_name}"
676 for ip in ${adb_denyip}; do
677 printf "%s" "${ip}" | "${adb_awk}" "${rset}" >>"${adb_tmpdir}/tmp.raw.${src_name}"
678 done
679 eval "${adb_dnsdenyip}" "${adb_tmpdir}/tmp.raw.${src_name}" >>"${adb_tmpdir}/tmp.add.${src_name}"
680 out_rc="${?}"
681 fi
682 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
683 fi
684 ;;
685 "blacklist" | "whitelist")
686 src_name="${mode}"
687 if [ "${src_name}" = "blacklist" ] && [ -f "${adb_blacklist}" ]; then
688 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
689 "${adb_awk}" "${rset}" "${adb_blacklist}" |
690 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${adb_tmpdir}/tmp.raw.${src_name}"
691 "${adb_sort}" ${adb_srtopts} -u "${adb_tmpdir}/tmp.raw.${src_name}" 2>/dev/null >"${adb_tmpfile}.${src_name}"
692 out_rc="${?}"
693 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
694 elif [ "${src_name}" = "whitelist" ] && [ -f "${adb_whitelist}" ]; then
695 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
696 printf "%s\n" "${adb_lookupdomain}" | "${adb_awk}" "${rset}" >"${adb_tmpdir}/tmp.raw.${src_name}"
697 "${adb_awk}" "${rset}" "${adb_whitelist}" >>"${adb_tmpdir}/tmp.raw.${src_name}"
698 out_rc="${?}"
699 if [ "${out_rc}" = "0" ]; then
700 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\\.\",\"\\\\.\",\$1);print tolower(\"^(|.*\\\\.)\"\$1\"$\")}"
701 "${adb_awk}" "${rset}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.rem.${src_name}"
702 out_rc="${?}"
703 if [ "${out_rc}" = "0" ] && [ "${adb_dnsallow}" != "1" ]; then
704 eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.add.${src_name}"
705 out_rc="${?}"
706 if [ "${out_rc}" = "0" ] && [ "${adb_jail}" = "1" ] && [ "${adb_dnsstop}" != "0" ]; then
707 : >"${adb_jaildir}/${adb_dnsjail}"
708 [ -n "${adb_dnsheader}" ] && printf "%b" "${adb_dnsheader}" >>"${adb_jaildir}/${adb_dnsjail}"
709 cat "${adb_tmpdir}/tmp.add.${src_name}" >>"${adb_jaildir}/${adb_dnsjail}"
710 printf "%s\n" "${adb_dnsstop}" >>"${adb_jaildir}/${adb_dnsjail}"
711 fi
712 fi
713 fi
714 fi
715 ;;
716 "safesearch")
717 case "${src_name}" in
718 "google")
719 rset="/^\\.([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{printf \"%s\n%s\n\",tolower(\"www\"\$1),tolower(substr(\$1,2,length(\$1)))}"
720 safe_url="https://www.google.com/supported_domains"
721 safe_cname="forcesafesearch.google.com"
722 safe_domains="${adb_tmpdir}/tmp.load.safesearch.${src_name}"
723 if [ "${adb_backup}" = "1" ] && [ -s "${adb_backupdir}/safesearch.${src_name}.gz" ]; then
724 zcat "${adb_backupdir}/safesearch.${src_name}.gz" >"${safe_domains}"
725 out_rc="${?}"
726 else
727 "${adb_fetchutil}" ${adb_fetchparm} "${safe_domains}" "${safe_url}" 2>/dev/null
728 out_rc="${?}"
729 if [ "${adb_backup}" = "1" ] && [ "${out_rc}" = "0" ]; then
730 gzip -cf "${safe_domains}" >"${adb_backupdir}/safesearch.${src_name}.gz"
731 out_rc="${?}"
732 fi
733 fi
734 if [ "${out_rc}" = "0" ]; then
735 if [ -x "${adb_lookupcmd}" ]; then
736 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
737 [ -n "${safe_ips}" ] && "${adb_awk}" "${rset}" "${safe_domains}" >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
738 fi
739 out_rc="${?}"
740 fi
741 ;;
742 "bing")
743 safe_cname="strict.bing.com"
744 safe_domains="www.bing.com"
745 if [ -x "${adb_lookupcmd}" ]; then
746 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
747 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
748 fi
749 out_rc="${?}"
750 ;;
751 "duckduckgo")
752 safe_cname="safe.duckduckgo.com"
753 safe_domains="duckduckgo.com"
754 if [ -x "${adb_lookupcmd}" ]; then
755 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
756 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
757 fi
758 out_rc="${?}"
759 ;;
760 "pixabay")
761 safe_cname="safesearch.pixabay.com"
762 safe_domains="pixabay.com"
763 if [ -x "${adb_lookupcmd}" ]; then
764 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
765 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
766 fi
767 out_rc="${?}"
768 ;;
769 "yandex")
770 safe_cname="familysearch.yandex.ru"
771 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"
772 if [ -x "${adb_lookupcmd}" ]; then
773 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
774 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
775 fi
776 out_rc="${?}"
777 ;;
778 "youtube")
779 if [ "${adb_safesearchmod}" = "0" ]; then
780 safe_cname="restrict.youtube.com"
781 else
782 safe_cname="restrictmoderate.youtube.com"
783 fi
784 safe_domains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
785 if [ -x "${adb_lookupcmd}" ]; then
786 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
787 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
788 fi
789 out_rc="${?}"
790 ;;
791 esac
792 if [ "${out_rc}" = "0" ] && [ -s "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" ]; then
793 : >"${adb_tmpdir}/tmp.safesearch.${src_name}"
794 [ "${adb_dns}" = "named" ] && array="${safe_cname}" || array="${safe_ips}"
795 for item in ${array}; do
796 if ! eval "${adb_dnssafesearch}" "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" >>"${adb_tmpdir}/tmp.safesearch.${src_name}"; then
797 rm -f "${adb_tmpdir}/tmp.safesearch.${src_name}"
798 break
799 fi
800 done
801 out_rc="${?}"
802 rm -f "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
803 fi
804 ;;
805 "backup")
806 (
807 gzip -cf "${src_tmpfile}" >"${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
808 out_rc="${?}"
809 ) &
810 ;;
811 "restore")
812 if [ -n "${src_name}" ] && [ -s "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]; then
813 zcat "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" >"${src_tmpfile}"
814 out_rc="${?}"
815 elif [ -z "${src_name}" ]; then
816 cnt="1"
817 for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz; do
818 if [ -r "${file}" ]; then
819 name="${file##*/}"
820 name="${name%.*}"
821 zcat "${file}" >"${adb_tmpfile}.${name}" &
822 hold="$((cnt % adb_cores))"
823 if [ "${hold}" = "0" ]; then
824 wait
825 fi
826 cnt="$((cnt + 1))"
827 fi
828 done
829 wait
830 out_rc="${?}"
831 else
832 out_rc=4
833 fi
834 if [ "${adb_action}" != "start" ] && [ "${adb_action}" != "resume" ] && [ -n "${src_name}" ] && [ "${out_rc}" != "0" ]; then
835 adb_sources="${adb_sources/${src_name}}"
836 fi
837 ;;
838 "remove")
839 [ "${adb_backup}" = "1" ] && rm "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null
840 out_rc="${?}"
841 adb_sources="${adb_sources/${src_name}}"
842 ;;
843 "merge")
844 if [ "${adb_backup}" = "1" ]; then
845 for src_name in ${adb_sources}; do
846 ffiles="${ffiles} -a ! -name ${adb_dnsprefix}.${src_name}.gz"
847 done
848 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]; then
849 ffiles="${ffiles} -a ! -name safesearch.google.gz"
850 fi
851 find "${adb_backupdir}" ${ffiles} -print0 2>/dev/null | xargs -0 rm 2>/dev/null
852 fi
853 unset src_name
854 "${adb_sort}" ${adb_srtopts} -mu "${adb_tmpfile}".* 2>/dev/null >"${adb_tmpdir}/${adb_dnsfile}"
855 out_rc="${?}"
856 rm -f "${adb_tmpfile}".*
857 ;;
858 "final")
859 unset src_name
860 { [ -n "${adb_dnsheader}" ] && printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"; } || : >"${adb_dnsdir}/${adb_dnsfile}"
861 [ -s "${adb_tmpdir}/tmp.add.iplist" ] && cat "${adb_tmpdir}/tmp.add.iplist" >>"${adb_dnsdir}/${adb_dnsfile}"
862 [ -s "${adb_tmpdir}/tmp.add.whitelist" ] && cat "${adb_tmpdir}/tmp.add.whitelist" >>"${adb_dnsdir}/${adb_dnsfile}"
863 for file in "${adb_tmpdir}/tmp.safesearch".*; do
864 [ -r "${file}" ] && cat "${file}" >>"${adb_dnsdir}/${adb_dnsfile}"
865 done
866 { [ "${adb_dnsdeny}" != "0" ] && eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >>"${adb_dnsdir}/${adb_dnsfile}"; } || mv "${adb_tmpdir}/${adb_dnsfile}" "${adb_dnsdir}/${adb_dnsfile}"
867 out_rc="${?}"
868 ;;
869 esac
870 f_count "${mode}" "${src_name}"
871 out_rc="${out_rc:-"${in_rc}"}"
872 f_log "debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
873 return "${out_rc}"
874 }
875
876 # top level domain compression
877 #
878 f_tld() {
879 local cnt cnt_tld source="${1}" temp_tld="${1}.tld"
880
881 if "${adb_awk}" '{if(NR==1){tld=$NF};while(getline){if(index($NF,tld".")==0){print tld;tld=$NF}}print tld}' "${source}" |
882 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${temp_tld}"; then
883 mv -f "${temp_tld}" "${source}"
884 cnt_tld="$(wc -l 2>/dev/null <"${source}")"
885 else
886 rm -f "${temp_tld}"
887 fi
888 f_log "debug" "f_tld ::: source: ${source}, cnt: ${adb_cnt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
889 }
890
891 # suspend/resume adblock processing
892 #
893 f_switch() {
894 local status entry done="false" mode="${1}"
895
896 json_init
897 json_load_file "${adb_rtfile}" >/dev/null 2>&1
898 json_select "data" >/dev/null 2>&1
899 json_get_var status "adblock_status"
900 if [ "${mode}" = "suspend" ] && [ "${status}" = "enabled" ]; then
901 f_env
902 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
903 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]; then
904 printf "%b" "${adb_dnsheader}" >"${adb_jaildir}/${adb_dnsjail}"
905 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]; then
906 rm -f "${adb_dnsdir}/${adb_dnsjail}"
907 fi
908 f_count
909 done="true"
910 elif [ "${mode}" = "resume" ] && [ "${status}" = "paused" ]; then
911 f_env
912 f_main
913 done="true"
914 fi
915 if [ "${done}" = "true" ]; then
916 [ "${mode}" = "suspend" ] && f_dnsup
917 f_jsnup "${mode}"
918 f_log "info" "${mode} adblock processing"
919 fi
920 f_rmtemp
921 }
922
923 # query blocklist for certain (sub-)domains
924 #
925 f_query() {
926 local search result prefix suffix field query_start query_end query_timeout=30 domain="${1}" tld="${1#*.}"
927
928 if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]; then
929 printf "%s\n" "::: invalid input, please submit a single (sub-)domain :::"
930 else
931 case "${adb_dns}" in
932 "dnsmasq")
933 prefix=".*[\\/\\.]"
934 suffix="(\\/)"
935 field="2"
936 ;;
937 "unbound")
938 prefix=".*[\"\\.]"
939 suffix="(always_nxdomain)"
940 field="3"
941 ;;
942 "named")
943 prefix="[^\\*].*[\\.]"
944 suffix="( \\.)"
945 field="1"
946 ;;
947 "kresd")
948 prefix="[^\\*].*[\\.]"
949 suffix="( \\.)"
950 field="1"
951 ;;
952 "raw")
953 prefix=".*[\\.]"
954 suffix=""
955 field="1"
956 ;;
957 esac
958 query_start="$(date "+%s")"
959 while [ "${domain}" != "${tld}" ]; do
960 search="${domain//[+*~%\$&\"\']/}"
961 search="${search//./\\.}"
962 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}")"
963 printf "%s\n%s\n%s\n" ":::" "::: domain '${domain}' in active blocklist" ":::"
964 printf "%s\n\n" "${result:-" - no match"}"
965 domain="${tld}"
966 tld="${domain#*.}"
967 done
968 if [ "${adb_backup}" = "1" ] && [ -d "${adb_backupdir}" ]; then
969 search="${1//[+*~%\$&\"\']/}"
970 search="${search//./\\.}"
971 printf "%s\n%s\n%s\n" ":::" "::: domain '${1}' in backups and black-/whitelist" ":::"
972 for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz "${adb_blacklist}" "${adb_whitelist}"; do
973 suffix="${file##*.}"
974 if [ "${suffix}" = "gz" ]; then
975 zcat "${file}" 2>/dev/null |
976 "${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}"
977 else
978 "${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}"
979 fi
980 if [ "${?}" = "0" ]; then
981 result="true"
982 query_end="$(date "+%s")"
983 if [ "$((query_end - query_start))" -gt "${query_timeout}" ]; then
984 printf "%s\n\n" " - [...]"
985 break
986 fi
987 fi
988 done
989 [ "${result}" != "true" ] && printf "%s\n\n" " - no match"
990 fi
991 fi
992 }
993
994 # update runtime information
995 #
996 f_jsnup() {
997 local entry sources runtime utils bg_pid status="${1:-"enabled"}"
998
999 adb_memory="$("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null |
1000 "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
1001
1002 case "${status}" in
1003 "enabled" | "error")
1004 adb_endtime="$(date "+%s")"
1005 if [ "$(((adb_endtime - adb_starttime) / 60))" -lt 60 ]; then
1006 runtime="${adb_action}, $(((adb_endtime - adb_starttime) / 60))m $(((adb_endtime - adb_starttime) % 60))s, ${adb_memory:-0}, $(date -Iseconds)"
1007 else
1008 runtime="${adb_action}, n/a, ${adb_memory:-0}, $(date -Iseconds)"
1009 fi
1010 [ "${status}" = "error" ] && adb_cnt="0"
1011 ;;
1012 "suspend")
1013 status="paused"
1014 ;;
1015 "resume")
1016 status=""
1017 ;;
1018 esac
1019 json_init
1020 if json_load_file "${adb_rtfile}" >/dev/null 2>&1; then
1021 utils="download: $(readlink -fn "${adb_fetchutil}"), sort: $(readlink -fn "${adb_sort}"), awk: $(readlink -fn "${adb_awk}")"
1022 [ -z "${adb_cnt}" ] && { json_get_var adb_cnt "blocked_domains"; adb_cnt="${adb_cnt%% *}"; }
1023 [ -z "${runtime}" ] && json_get_var runtime "last_run"
1024 fi
1025 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]; then
1026 adb_cnt="0"
1027 sources="restrictive_jail"
1028 else
1029 sources="$(printf "%s\n" ${adb_sources} | "${adb_sort}" | "${adb_awk}" '{ORS=" ";print $0}')"
1030 fi
1031
1032 : >"${adb_rtfile}"
1033 json_init
1034 json_load_file "${adb_rtfile}" >/dev/null 2>&1
1035 json_init
1036 json_add_string "adblock_status" "${status:-"enabled"}"
1037 json_add_string "adblock_version" "${adb_ver}"
1038 json_add_string "blocked_domains" "${adb_cnt:-0}"
1039 json_add_array "active_sources"
1040 for entry in ${sources}; do
1041 json_add_object
1042 json_add_string "source" "${entry}"
1043 json_close_object
1044 done
1045 json_close_array
1046 json_add_string "dns_backend" "${adb_dns:-"-"} (${adb_dnscachecmd##*/}), ${adb_dnsdir:-"-"}"
1047 json_add_string "run_utils" "${utils:-"-"}"
1048 json_add_string "run_ifaces" "trigger: ${adb_trigger:-"-"}, report: ${adb_repiface:-"-"}"
1049 json_add_string "run_directories" "base: ${adb_tmpbase}, backup: ${adb_backupdir}, report: ${adb_reportdir}, jail: ${adb_jaildir}"
1050 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})"
1051 json_add_string "last_run" "${runtime:-"-"}"
1052 json_add_string "system" "${adb_sysver}"
1053 json_dump >"${adb_rtfile}"
1054
1055 if [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ] &&
1056 { [ "${status}" = "error" ] || { [ "${status}" = "enabled" ] && [ "${adb_cnt}" -le "${adb_mailcnt}" ]; }; }; then
1057 ("${adb_mailservice}" "${adb_ver}" >/dev/null 2>&1) &
1058 bg_pid="${!}"
1059 fi
1060 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:-"-"}"
1061 }
1062
1063 # write to syslog
1064 #
1065 f_log() {
1066 local class="${1}" log_msg="${2}"
1067
1068 if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${adb_debug}" = "1" ]; }; then
1069 [ -x "${adb_loggercmd}" ] && "${adb_loggercmd}" -p "${class}" -t "adblock-${adb_ver}[${$}]" "${log_msg}" || \
1070 printf "%s %s %s\n" "${class}" "adblock-${adb_ver}[${$}]" "${log_msg}"
1071 if [ "${class}" = "err" ]; then
1072 f_rmdns
1073 f_jsnup "error"
1074 exit 1
1075 fi
1076 fi
1077 }
1078
1079 # main function for blocklist processing
1080 #
1081 f_main() {
1082 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 cnt
1083
1084 f_log "debug" "f_main ::: memory: ${adb_memory:-0}, cores: ${adb_cores}, safe_search: ${adb_safesearch}, force_dns: ${adb_forcedns}, awk: ${adb_awk}"
1085
1086 # white- and blacklist preparation
1087 #
1088 for entry in ${adb_locallist}; do
1089 (f_list "${entry}" "${entry}") &
1090 done
1091
1092 if [ "${adb_dns}" != "raw" ] && [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]; then
1093 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
1094 chown "${adb_dnsuser}" "${adb_jaildir}/${adb_dnsjail}" 2>/dev/null
1095 if f_dnsup; then
1096 if [ "${adb_action}" != "resume" ]; then
1097 f_jsnup "enabled"
1098 fi
1099 f_log "info" "restrictive jail mode enabled successfully (${adb_sysver})"
1100 else
1101 f_log "err" "dns backend restart in jail mode failed"
1102 fi
1103 f_rmtemp
1104 return
1105 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]; then
1106 rm -f "${adb_dnsdir}/${adb_dnsjail}"
1107 f_dnsup
1108 fi
1109
1110 # safe search preparation
1111 #
1112 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]; then
1113 [ -z "${adb_safesearchlist}" ] && adb_safesearchlist="google bing duckduckgo pixabay yandex youtube"
1114 cnt="1"
1115 for entry in ${adb_safesearchlist}; do
1116 (f_list safesearch "${entry}") &
1117 hold="$((cnt % adb_cores))"
1118 [ "${hold}" = "0" ] && wait
1119 cnt="$((cnt + 1))"
1120 done
1121 fi
1122 wait
1123
1124 # main loop
1125 #
1126 cnt="1"
1127 for src_name in ${adb_sources}; do
1128 if ! json_select "${src_name}" >/dev/null 2>&1; then
1129 adb_sources="${adb_sources/${src_name}/}"
1130 continue
1131 fi
1132 json_get_var src_url "url" >/dev/null 2>&1
1133 json_get_var src_rset "rule" >/dev/null 2>&1
1134 json_select ..
1135 src_tmpcat="${adb_tmpload}.${src_name}.cat"
1136 src_tmpload="${adb_tmpload}.${src_name}.load"
1137 src_tmpsort="${adb_tmpload}.${src_name}.sort"
1138 src_tmpfile="${adb_tmpfile}.${src_name}"
1139 src_rc=4
1140
1141 # basic pre-checks
1142 #
1143 if [ -z "${src_url}" ] || [ -z "${src_rset}" ]; then
1144 f_list remove
1145 continue
1146 fi
1147
1148 # backup mode
1149 #
1150 if [ "${adb_backup}" = "1" ] && { [ "${adb_action}" = "start" ] || [ "${adb_action}" = "resume" ]; }; then
1151 if f_list restore && [ -s "${src_tmpfile}" ]; then
1152 continue
1153 fi
1154 fi
1155
1156 # download queue processing
1157 #
1158 unset src_cat src_entries
1159 if [ "${src_name}" = "utcapitole" ] && [ -n "${adb_utc_sources}" ]; then
1160 src_cat="${adb_utc_sources}"
1161 if [ -n "${src_cat}" ]; then
1162 (
1163 src_arc="${adb_tmpdir}/${src_url##*/}"
1164 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
1165 src_rc="${?}"
1166 if [ "${src_rc}" = "0" ] && [ -s "${src_arc}" ]; then
1167 src_suffix="$(eval printf "%s" \"\$\{adb_src_suffix_${src_name}:-\"domains\"\}\")"
1168 src_list="$(tar -tzf "${src_arc}" 2>/dev/null)"
1169 for src_item in ${src_cat}; do
1170 src_entries="${src_entries} $(printf "%s" "${src_list}" | grep -E "${src_item}/${src_suffix}$")"
1171 done
1172 if [ -n "${src_entries}" ]; then
1173 tar -xOzf "${src_arc}" ${src_entries} 2>/dev/null >"${src_tmpload}"
1174 src_rc="${?}"
1175 fi
1176 : >"${src_arc}"
1177 else
1178 src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1179 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1180 fi
1181 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]; then
1182 if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]; then
1183 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1184 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1185 else
1186 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1187 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1188 fi
1189 : >"${src_tmpload}"
1190 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null >"${src_tmpfile}"
1191 src_rc="${?}"
1192 : >"${src_tmpsort}"
1193 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]; then
1194 f_list download
1195 [ "${adb_backup}" = "1" ] && f_list backup
1196 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]; then
1197 f_log "info" "archive preparation of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1198 f_list restore
1199 rm -f "${src_tmpfile}"
1200 fi
1201 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]; then
1202 f_log "info" "archive extraction of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1203 f_list restore
1204 fi
1205 ) &
1206 fi
1207 else
1208 if [ "${src_name}" = "energized" ] && [ -n "${adb_eng_sources}" ]; then
1209 src_cat="${adb_eng_sources}"
1210 elif [ "${src_name}" = "stevenblack" ] && [ -n "${adb_stb_sources}" ]; then
1211 src_cat="${adb_stb_sources}"
1212 elif { [ "${src_name}" = "energized" ] && [ -z "${adb_eng_sources}" ]; } ||
1213 { [ "${src_name}" = "stevenblack" ] && [ -z "${adb_stb_sources}" ]; }; then
1214 continue
1215 fi
1216 (
1217 for suffix in ${src_cat:-${src_url}}; do
1218 if [ "${src_url}" != "${suffix}" ]; then
1219 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpcat}" "${src_url}${suffix}" 2>&1)"
1220 src_rc="${?}"
1221 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpcat}" ]; then
1222 cat "${src_tmpcat}" >>"${src_tmpload}"
1223 : >"${src_tmpcat}"
1224 fi
1225 else
1226 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpload}" "${src_url}" 2>&1)"
1227 src_rc="${?}"
1228 fi
1229 done
1230 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]; then
1231 if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]; then
1232 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1233 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1234 else
1235 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1236 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1237 fi
1238 : >"${src_tmpload}"
1239 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null >"${src_tmpfile}"
1240 src_rc="${?}"
1241 : >"${src_tmpsort}"
1242 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]; then
1243 f_list download
1244 [ "${adb_backup}" = "1" ] && f_list backup
1245 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]; then
1246 f_log "info" "preparation of '${src_name}' failed, rc: ${src_rc}"
1247 f_list restore
1248 rm -f "${src_tmpfile}"
1249 fi
1250 else
1251 src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1252 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1253 [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ] && f_list restore
1254 fi
1255 ) &
1256 fi
1257 hold="$((cnt % adb_cores))"
1258 [ "${hold}" = "0" ] && wait
1259 cnt="$((cnt + 1))"
1260 done
1261 wait
1262
1263 # tld compression and dns restart
1264 #
1265 if f_list merge && [ -s "${adb_tmpdir}/${adb_dnsfile}" ]; then
1266 f_tld "${adb_tmpdir}/${adb_dnsfile}"
1267 f_list final
1268 else
1269 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
1270 fi
1271 chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
1272 if f_dnsup; then
1273 [ "${adb_action}" != "resume" ] && f_jsnup "enabled"
1274 f_log "info" "blocklist with overall ${adb_cnt} blocked domains loaded successfully (${adb_sysver})"
1275 else
1276 f_log "err" "dns backend restart with adblock blocklist failed"
1277 fi
1278 f_rmtemp
1279 }
1280
1281 # trace dns queries via tcpdump and prepare a report
1282 #
1283 f_report() {
1284 local report_raw report_txt content status total start end start_date start_time end_date end_time blocked percent top_list top array item index hold ports value key key_list cnt="0" resolve="-nn" action="${1}" top_count="${2:-"10"}" res_count="${3:-"50"}" search="${4:-"+"}"
1285
1286 report_raw="${adb_reportdir}/adb_report.raw"
1287 report_srt="${adb_reportdir}/adb_report.srt"
1288 report_jsn="${adb_reportdir}/adb_report.json"
1289 report_txt="${adb_reportdir}/adb_mailreport.txt"
1290
1291 # build json file
1292 #
1293 if [ "${action}" != "json" ]; then
1294 : >"${report_raw}"
1295 : >"${report_srt}"
1296 : >"${report_txt}"
1297 : >"${report_jsn}"
1298 [ "${adb_represolve}" = "1" ] && resolve=""
1299 for file in "${adb_reportdir}/adb_report.pcap"*; do
1300 (
1301 "${adb_dumpcmd}" "${resolve}" -tttt -r "${file}" 2>/dev/null |
1302 "${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);
1303 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}"
1304 ) &
1305 hold="$((cnt % adb_cores))"
1306 [ "${hold}" = "0" ] && wait
1307 cnt="$((cnt + 1))"
1308 done
1309 wait
1310 if [ -s "${report_raw}" ]; then
1311 "${adb_sort}" ${adb_srtopts} -k1 -k3 -k4 -k5 -k1 -ur "${report_raw}" |
1312 "${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}}' |
1313 "${adb_sort}" ${adb_srtopts} -k1 -k2 -k3 -k4 -ur >"${report_srt}"
1314 rm -f "${report_raw}"
1315 fi
1316
1317 if [ -s "${report_srt}" ]; then
1318 start="$("${adb_awk}" 'END{printf "%s_%s",$1,$2}' "${report_srt}")"
1319 end="$("${adb_awk}" 'NR==1{printf "%s_%s",$1,$2}' "${report_srt}")"
1320 total="$(wc -l <"${report_srt}")"
1321 blocked="$("${adb_awk}" '{if($5=="NX")cnt++}END{printf "%s",cnt}' "${report_srt}")"
1322 percent="$("${adb_awk}" -v t="${total}" -v b="${blocked}" 'BEGIN{printf "%.2f%s",b/t*100,"%"}')"
1323 : >"${report_jsn}"
1324 {
1325 printf "%s\n" "{ "
1326 printf "\t%s\n" "\"start_date\": \"${start%_*}\", "
1327 printf "\t%s\n" "\"start_time\": \"${start#*_}\", "
1328 printf "\t%s\n" "\"end_date\": \"${end%_*}\", "
1329 printf "\t%s\n" "\"end_time\": \"${end#*_}\", "
1330 printf "\t%s\n" "\"total\": \"${total}\", "
1331 printf "\t%s\n" "\"blocked\": \"${blocked}\", "
1332 printf "\t%s\n" "\"percent\": \"${percent}\", "
1333 } >>"${report_jsn}"
1334 top_list="top_clients top_domains top_blocked"
1335 for top in ${top_list}; do
1336 printf "\t%s" "\"${top}\": [ " >>"${report_jsn}"
1337 case "${top}" in
1338 "top_clients")
1339 "${adb_awk}" '{print $3}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c |
1340 "${adb_sort}" ${adb_srtopts} -nr |
1341 "${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<=${top_count})printf \",\n\t\t{\n\t\t\t\\\"count\\\": \\\"%s\\\",\n\t\t\t\\\"address\\\": \\\"%s\\\"\n\t\t}\",\$1,\$2}" >>"${report_jsn}"
1342 ;;
1343 "top_domains")
1344 "${adb_awk}" '{if($5!="NX")print $4}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c |
1345 "${adb_sort}" ${adb_srtopts} -nr |
1346 "${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<=${top_count})printf \",\n\t\t{\n\t\t\t\\\"count\\\": \\\"%s\\\",\n\t\t\t\\\"address\\\": \\\"%s\\\"\n\t\t}\",\$1,\$2}" >>"${report_jsn}"
1347 ;;
1348 "top_blocked")
1349 "${adb_awk}" '{if($5=="NX")print $4}' "${report_srt}" |
1350 "${adb_sort}" ${adb_srtopts} | uniq -c | "${adb_sort}" ${adb_srtopts} -nr |
1351 "${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<=${top_count})printf \",\n\t\t{\n\t\t\t\\\"count\\\": \\\"%s\\\",\n\t\t\t\\\"address\\\": \\\"%s\\\"\n\t\t}\",\$1,\$2}" >>"${report_jsn}"
1352 ;;
1353 esac
1354 printf "\n\t%s\n" "]," >>"${report_jsn}"
1355 done
1356 search="${search//./\\.}"
1357 search="${search//[+*~%\$&\"\' ]/}"
1358 "${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<=${res_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}"
1359 rm -f "${report_srt}"
1360 fi
1361 fi
1362
1363 # output preparation
1364 #
1365 if [ -s "${report_jsn}" ] && { [ "${action}" = "cli" ] || [ "${action}" = "mail" ]; }; then
1366 printf "%s\n%s\n%s\n" ":::" "::: Adblock DNS-Query Report" ":::" >>"${report_txt}"
1367 json_init
1368 json_load_file "${report_jsn}"
1369 json_get_keys key_list
1370 for key in ${key_list}; do
1371 json_get_var value "${key}"
1372 eval "${key}=\"${value}\""
1373 done
1374 printf " + %s\n + %s\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}" >>"${report_txt}"
1375 printf " + %s\n + %s %s\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})" >>"${report_txt}"
1376 top_list="top_clients top_domains top_blocked requests"
1377 for top in ${top_list}; do
1378 case "${top}" in
1379 "top_clients")
1380 item="::: Top Clients"
1381 ;;
1382 "top_domains")
1383 item="::: Top Domains"
1384 ;;
1385 "top_blocked")
1386 item="::: Top Blocked Domains"
1387 ;;
1388 esac
1389 if json_get_type status "${top}" && [ "${top}" != "requests" ] && [ "${status}" = "array" ]; then
1390 printf "%s\n%s\n%s\n" ":::" "${item}" ":::" >>"${report_txt}"
1391 json_select "${top}"
1392 index="1"
1393 item=""
1394 while json_get_type status "${index}" && [ "${status}" = "object" ]; do
1395 json_get_values item "${index}"
1396 printf " + %-9s::: %s\n" ${item} >>"${report_txt}"
1397 index="$((index + 1))"
1398 done
1399 elif json_get_type status "${top}" && [ "${top}" = "requests" ] && [ "${status}" = "array" ]; then
1400 printf "%s\n%s\n%s\n" ":::" "::: Latest DNS Queries" ":::" >>"${report_txt}"
1401 printf "%-15s%-15s%-45s%-80s%s\n" "Date" "Time" "Client" "Domain" "Answer" >>"${report_txt}"
1402 json_select "${top}"
1403 index="1"
1404 while json_get_type status "${index}" && [ "${status}" = "object" ]; do
1405 json_get_values item "${index}"
1406 printf "%-15s%-15s%-45s%-80s%s\n" ${item} >>"${report_txt}"
1407 index="$((index + 1))"
1408 done
1409 fi
1410 json_select ".."
1411 done
1412 content="$(cat "${report_txt}" 2>/dev/null)"
1413 rm -f "${report_txt}"
1414 fi
1415
1416 # report output
1417 #
1418 if [ "${action}" = "cli" ]; then
1419 printf "%s\n" "${content}"
1420 elif [ "${action}" = "json" ]; then
1421 cat "${report_jsn}"
1422 elif [ "${action}" = "mail" ] && [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ]; then
1423 ("${adb_mailservice}" "${adb_ver}" "${content}" >/dev/null 2>&1) &
1424 bg_pid="${!}"
1425 fi
1426 f_log "debug" "f_report ::: action: ${action}, top_count: ${top_count}, res_count: ${res_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}"
1427 }
1428
1429 # source required system libraries
1430 #
1431 if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]; then
1432 . "/lib/functions.sh"
1433 . "/lib/functions/network.sh"
1434 . "/usr/share/libubox/jshn.sh"
1435 else
1436 f_log "err" "system libraries not found"
1437 fi
1438
1439 # awk check
1440 #
1441 adb_awk="$(command -v gawk)"
1442 if [ ! -x "${adb_awk}" ]; then
1443 adb_awk="$(command -v awk)"
1444 [ ! -x "${adb_awk}" ] && f_log "err" "awk not found or not executable"
1445 fi
1446
1447 # sort check
1448 #
1449 adb_sort="$(command -v sort)"
1450 if [ ! -x "${adb_sort}" ] || ! "${adb_sort}" --version 2>/dev/null | grep -q "coreutils"; then
1451 f_log "err" "coreutils sort not found or not executable"
1452 fi
1453
1454 # handle different adblock actions
1455 #
1456 f_load
1457 case "${adb_action}" in
1458 "stop")
1459 f_rmdns
1460 ;;
1461 "restart")
1462 f_rmdns
1463 f_env
1464 f_main
1465 ;;
1466 "suspend")
1467 [ "${adb_dns}" != "raw" ] && f_switch suspend
1468 ;;
1469 "resume")
1470 [ "${adb_dns}" != "raw" ] && f_switch resume
1471 ;;
1472 "report")
1473 f_report "${2}" "${3}" "${4}" "${5}"
1474 ;;
1475 "query")
1476 f_query "${2}"
1477 ;;
1478 "start" | "reload")
1479 f_env
1480 f_main
1481 ;;
1482 esac