Merge pull request #20731 from pprindeville/isc-dhcp-update-4.4.3-P1
[feed/packages.git] / net / adblock / files / adblock.sh
1 #!/bin/sh
2 # dns based ad/abuse domain blocking
3 # Copyright (c) 2015-2023 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 set firewall."adblock_${zone}${port}".family="any"
570 EOC
571 fi
572 fwcfg="${fwcfg/adblock_${zone}${port}[ |\$]/}"
573 done
574 done
575 fwcfg="${fwcfg#"${fwcfg%%[![:space:]]*}"}"
576 fwcfg="${fwcfg%"${fwcfg##*[![:space:]]}"}"
577 fi
578 if [ "${adb_enabled}" = "0" ] || [ "${adb_forcedns}" = "0" ] || [ -n "${fwcfg}" ]; then
579 for section in ${fwcfg}; do
580 uci_remove firewall "${section}"
581 done
582 fi
583 f_uci "${config}"
584 }
585
586 # restart dns backend
587 #
588 f_dnsup() {
589 local rset dns_service dns_up dns_pid restart_rc cnt="0" out_rc="4" in_rc="${1:-0}"
590
591 if [ "${adb_dns}" = "raw" ]; then
592 out_rc="0"
593 else
594 if [ "${in_rc}" = "0" ] && [ "${adb_dnsflush}" = "0" ]; then
595 case "${adb_dns}" in
596 "unbound")
597 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}/unbound.conf" ]; then
598 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" dump_cache >"${adb_tmpdir}/adb_cache.dump" 2>/dev/null
599 fi
600 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
601 restart_rc="${?}"
602 ;;
603 "named")
604 if [ -x "${adb_dnscachecmd}" ] && [ -f "/etc/bind/rndc.conf" ]; then
605 "${adb_dnscachecmd}" -c "/etc/bind/rndc.conf" reload >/dev/null 2>&1
606 restart_rc="${?}"
607 fi
608 if [ -z "${restart_rc}" ] || { [ -n "${restart_rc}" ] && [ "${restart_rc}" != "0" ]; }; then
609 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
610 restart_rc="${?}"
611 fi
612 ;;
613 *)
614 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
615 restart_rc="${?}"
616 ;;
617 esac
618 fi
619 if [ -z "${restart_rc}" ]; then
620 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
621 restart_rc="${?}"
622 fi
623 fi
624 if [ "${restart_rc}" = "0" ]; then
625 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
626 while [ "${cnt}" -le "${adb_dnstimeout}" ]; do
627 dns_service="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}")"
628 dns_up="$(printf "%s" "${dns_service}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
629 dns_pid="$(printf "%s" "${dns_service}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.pid")"
630 if [ "${dns_up}" = "true" ] && [ -n "${dns_pid}" ] && ! ls "/proc/${dns_pid}/fd/${adb_dnsdir}/${adb_dnsfile}" >/dev/null 2>&1; then
631 if [ -x "${adb_lookupcmd}" ] && [ -n "$(printf "%s" "${adb_lookupdomain}" | "${adb_awk}" "${rset}")" ]; then
632 if "${adb_lookupcmd}" "${adb_lookupdomain}" >/dev/null 2>&1; then
633 out_rc="0"
634 break
635 fi
636 else
637 sleep ${adb_dnstimeout}
638 cnt=${adb_dnstimeout}
639 out_rc="0"
640 break
641 fi
642 fi
643 cnt="$((cnt + 1))"
644 sleep 1
645 done
646 if [ "${out_rc}" = "0" ] && [ "${adb_dns}" = "unbound" ]; then
647 if [ -x "${adb_dnscachecmd}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}/adb_cache.dump" ]; then
648 "${adb_dnscachecmd}" -c "${adb_dnsdir}/unbound.conf" load_cache <"${adb_tmpdir}/adb_cache.dump" >/dev/null 2>&1
649 restart_rc="${?}"
650 fi
651 fi
652 fi
653 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}"
654 return "${out_rc}"
655 }
656
657 # backup/restore/remove blocklists
658 #
659 f_list() {
660 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"
661
662 case "${mode}" in
663 "iplist")
664 src_name="${mode}"
665 if [ "${adb_dns}" = "named" ]; then
666 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\"}"
667 if [ -n "${adb_allowip}" ]; then
668 : >"${adb_tmpdir}/tmp.raw.${src_name}"
669 for ip in ${adb_allowip}; do
670 printf "%s" "${ip}" | "${adb_awk}" "${rset}" >>"${adb_tmpdir}/tmp.raw.${src_name}"
671 done
672 eval "${adb_dnsallowip}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.add.${src_name}"
673 out_rc="${?}"
674 fi
675 if [ -n "${adb_denyip}" ] && { [ -z "${out_rc}" ] || [ "${out_rc}" = "0" ]; }; then
676 : >"${adb_tmpdir}/tmp.raw.${src_name}"
677 for ip in ${adb_denyip}; do
678 printf "%s" "${ip}" | "${adb_awk}" "${rset}" >>"${adb_tmpdir}/tmp.raw.${src_name}"
679 done
680 eval "${adb_dnsdenyip}" "${adb_tmpdir}/tmp.raw.${src_name}" >>"${adb_tmpdir}/tmp.add.${src_name}"
681 out_rc="${?}"
682 fi
683 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
684 fi
685 ;;
686 "blacklist" | "whitelist")
687 src_name="${mode}"
688 if [ "${src_name}" = "blacklist" ] && [ -f "${adb_blacklist}" ]; then
689 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
690 "${adb_awk}" "${rset}" "${adb_blacklist}" >"${adb_tmpdir}/tmp.raw.${src_name}"
691 if [ -s "${adb_whitelist}" ]; then
692 "${adb_awk}" 'NR==FNR{member[$1];next}!($1 in member)' "${adb_whitelist}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.deduplicate.${src_name}"
693 else
694 cat "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.deduplicate.${src_name}"
695 fi
696 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${adb_tmpdir}/tmp.deduplicate.${src_name}" >"${adb_tmpdir}/tmp.raw.${src_name}"
697 "${adb_sort}" ${adb_srtopts} -u "${adb_tmpdir}/tmp.raw.${src_name}" 2>/dev/null >"${adb_tmpfile}.${src_name}"
698 out_rc="${?}"
699 rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
700 elif [ "${src_name}" = "whitelist" ] && [ -f "${adb_whitelist}" ]; then
701 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
702 printf "%s\n" "${adb_lookupdomain}" | "${adb_awk}" "${rset}" >"${adb_tmpdir}/tmp.raw.${src_name}"
703 "${adb_awk}" "${rset}" "${adb_whitelist}" >>"${adb_tmpdir}/tmp.raw.${src_name}"
704 out_rc="${?}"
705 if [ "${out_rc}" = "0" ]; then
706 rset="/^([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\\.\",\"\\\\.\",\$1);print tolower(\"^(|.*\\\\.)\"\$1\"$\")}"
707 "${adb_awk}" "${rset}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.rem.${src_name}"
708 out_rc="${?}"
709 if [ "${out_rc}" = "0" ] && [ "${adb_dnsallow}" != "1" ]; then
710 eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw.${src_name}" >"${adb_tmpdir}/tmp.add.${src_name}"
711 out_rc="${?}"
712 if [ "${out_rc}" = "0" ] && [ "${adb_jail}" = "1" ] && [ "${adb_dnsstop}" != "0" ]; then
713 : >"${adb_jaildir}/${adb_dnsjail}"
714 [ -n "${adb_dnsheader}" ] && printf "%b" "${adb_dnsheader}" >>"${adb_jaildir}/${adb_dnsjail}"
715 cat "${adb_tmpdir}/tmp.add.${src_name}" >>"${adb_jaildir}/${adb_dnsjail}"
716 printf "%s\n" "${adb_dnsstop}" >>"${adb_jaildir}/${adb_dnsjail}"
717 fi
718 fi
719 fi
720 fi
721 ;;
722 "safesearch")
723 case "${src_name}" in
724 "google")
725 rset="/^\\.([[:alnum:]_-]{1,63}\\.)+[[:alpha:]]+([[:space:]]|$)/{printf \"%s\n%s\n\",tolower(\"www\"\$1),tolower(substr(\$1,2,length(\$1)))}"
726 safe_url="https://www.google.com/supported_domains"
727 safe_cname="forcesafesearch.google.com"
728 safe_domains="${adb_tmpdir}/tmp.load.safesearch.${src_name}"
729 if [ "${adb_backup}" = "1" ] && [ -s "${adb_backupdir}/safesearch.${src_name}.gz" ]; then
730 zcat "${adb_backupdir}/safesearch.${src_name}.gz" >"${safe_domains}"
731 out_rc="${?}"
732 else
733 "${adb_fetchutil}" ${adb_fetchparm} "${safe_domains}" "${safe_url}" 2>/dev/null
734 out_rc="${?}"
735 if [ "${adb_backup}" = "1" ] && [ "${out_rc}" = "0" ]; then
736 gzip -cf "${safe_domains}" >"${adb_backupdir}/safesearch.${src_name}.gz"
737 out_rc="${?}"
738 fi
739 fi
740 if [ "${out_rc}" = "0" ]; then
741 if [ -x "${adb_lookupcmd}" ]; then
742 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
743 [ -n "${safe_ips}" ] && "${adb_awk}" "${rset}" "${safe_domains}" >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
744 fi
745 out_rc="${?}"
746 fi
747 ;;
748 "bing")
749 safe_cname="strict.bing.com"
750 safe_domains="www.bing.com"
751 if [ -x "${adb_lookupcmd}" ]; then
752 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
753 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
754 fi
755 out_rc="${?}"
756 ;;
757 "duckduckgo")
758 safe_cname="safe.duckduckgo.com"
759 safe_domains="duckduckgo.com"
760 if [ -x "${adb_lookupcmd}" ]; then
761 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
762 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
763 fi
764 out_rc="${?}"
765 ;;
766 "pixabay")
767 safe_cname="safesearch.pixabay.com"
768 safe_domains="pixabay.com"
769 if [ -x "${adb_lookupcmd}" ]; then
770 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
771 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
772 fi
773 out_rc="${?}"
774 ;;
775 "yandex")
776 safe_cname="familysearch.yandex.ru"
777 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"
778 if [ -x "${adb_lookupcmd}" ]; then
779 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
780 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
781 fi
782 out_rc="${?}"
783 ;;
784 "youtube")
785 if [ "${adb_safesearchmod}" = "0" ]; then
786 safe_cname="restrict.youtube.com"
787 else
788 safe_cname="restrictmoderate.youtube.com"
789 fi
790 safe_domains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
791 if [ -x "${adb_lookupcmd}" ]; then
792 safe_ips="$("${adb_lookupcmd}" "${safe_cname}" 2>/dev/null | "${adb_awk}" '/^Address[ 0-9]*: /{ORS=" ";print $NF}')"
793 [ -n "${safe_ips}" ] && printf "%s\n" ${safe_domains} >"${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
794 fi
795 out_rc="${?}"
796 ;;
797 esac
798 if [ "${out_rc}" = "0" ] && [ -s "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" ]; then
799 : >"${adb_tmpdir}/tmp.safesearch.${src_name}"
800 [ "${adb_dns}" = "named" ] && array="${safe_cname}" || array="${safe_ips}"
801 for item in ${array}; do
802 if ! eval "${adb_dnssafesearch}" "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" >>"${adb_tmpdir}/tmp.safesearch.${src_name}"; then
803 rm -f "${adb_tmpdir}/tmp.safesearch.${src_name}"
804 break
805 fi
806 done
807 out_rc="${?}"
808 rm -f "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
809 fi
810 ;;
811 "backup")
812 (
813 gzip -cf "${src_tmpfile}" >"${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
814 out_rc="${?}"
815 ) &
816 ;;
817 "restore")
818 if [ -n "${src_name}" ] && [ -s "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]; then
819 zcat "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" >"${src_tmpfile}"
820 out_rc="${?}"
821 elif [ -z "${src_name}" ]; then
822 cnt="1"
823 for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz; do
824 if [ -r "${file}" ]; then
825 name="${file##*/}"
826 name="${name%.*}"
827 zcat "${file}" >"${adb_tmpfile}.${name}" &
828 hold="$((cnt % adb_cores))"
829 if [ "${hold}" = "0" ]; then
830 wait
831 fi
832 cnt="$((cnt + 1))"
833 fi
834 done
835 wait
836 out_rc="${?}"
837 else
838 out_rc=4
839 fi
840 if [ "${adb_action}" != "start" ] && [ "${adb_action}" != "resume" ] && [ -n "${src_name}" ] && [ "${out_rc}" != "0" ]; then
841 adb_sources="${adb_sources/${src_name}}"
842 fi
843 ;;
844 "remove")
845 [ "${adb_backup}" = "1" ] && rm "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null
846 out_rc="${?}"
847 adb_sources="${adb_sources/${src_name}}"
848 ;;
849 "merge")
850 if [ "${adb_backup}" = "1" ]; then
851 for src_name in ${adb_sources}; do
852 ffiles="${ffiles} -a ! -name ${adb_dnsprefix}.${src_name}.gz"
853 done
854 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]; then
855 ffiles="${ffiles} -a ! -name safesearch.google.gz"
856 fi
857 find "${adb_backupdir}" ${ffiles} -print0 2>/dev/null | xargs -0 rm 2>/dev/null
858 fi
859 unset src_name
860 "${adb_sort}" ${adb_srtopts} -mu "${adb_tmpfile}".* 2>/dev/null >"${adb_tmpdir}/${adb_dnsfile}"
861 out_rc="${?}"
862 rm -f "${adb_tmpfile}".*
863 ;;
864 "final")
865 unset src_name
866 { [ -n "${adb_dnsheader}" ] && printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"; } || : >"${adb_dnsdir}/${adb_dnsfile}"
867 [ -s "${adb_tmpdir}/tmp.add.iplist" ] && cat "${adb_tmpdir}/tmp.add.iplist" >>"${adb_dnsdir}/${adb_dnsfile}"
868 [ -s "${adb_tmpdir}/tmp.add.whitelist" ] && cat "${adb_tmpdir}/tmp.add.whitelist" >>"${adb_dnsdir}/${adb_dnsfile}"
869 for file in "${adb_tmpdir}/tmp.safesearch".*; do
870 [ -r "${file}" ] && cat "${file}" >>"${adb_dnsdir}/${adb_dnsfile}"
871 done
872 { [ "${adb_dnsdeny}" != "0" ] && eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >>"${adb_dnsdir}/${adb_dnsfile}"; } || mv "${adb_tmpdir}/${adb_dnsfile}" "${adb_dnsdir}/${adb_dnsfile}"
873 out_rc="${?}"
874 ;;
875 esac
876 f_count "${mode}" "${src_name}"
877 out_rc="${out_rc:-"${in_rc}"}"
878 f_log "debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
879 return "${out_rc}"
880 }
881
882 # top level domain compression
883 #
884 f_tld() {
885 local cnt cnt_tld source="${1}" temp_tld="${1}.tld"
886
887 if "${adb_awk}" '{if(NR==1){tld=$NF};while(getline){if(index($NF,tld".")==0){print tld;tld=$NF}}print tld}' "${source}" |
888 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${temp_tld}"; then
889 mv -f "${temp_tld}" "${source}"
890 cnt_tld="$(wc -l 2>/dev/null <"${source}")"
891 else
892 rm -f "${temp_tld}"
893 fi
894 f_log "debug" "f_tld ::: source: ${source}, cnt: ${adb_cnt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
895 }
896
897 # suspend/resume adblock processing
898 #
899 f_switch() {
900 local status entry done="false" mode="${1}"
901
902 json_init
903 json_load_file "${adb_rtfile}" >/dev/null 2>&1
904 json_select "data" >/dev/null 2>&1
905 json_get_var status "adblock_status"
906 if [ "${mode}" = "suspend" ] && [ "${status}" = "enabled" ]; then
907 f_env
908 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
909 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]; then
910 printf "%b" "${adb_dnsheader}" >"${adb_jaildir}/${adb_dnsjail}"
911 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]; then
912 rm -f "${adb_dnsdir}/${adb_dnsjail}"
913 fi
914 f_count
915 done="true"
916 elif [ "${mode}" = "resume" ] && [ "${status}" = "paused" ]; then
917 f_env
918 f_main
919 done="true"
920 fi
921 if [ "${done}" = "true" ]; then
922 [ "${mode}" = "suspend" ] && f_dnsup
923 f_jsnup "${mode}"
924 f_log "info" "${mode} adblock processing"
925 fi
926 f_rmtemp
927 }
928
929 # query blocklist for certain (sub-)domains
930 #
931 f_query() {
932 local search result prefix suffix field query_start query_end query_timeout=30 domain="${1}" tld="${1#*.}"
933
934 if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]; then
935 printf "%s\n" "::: invalid input, please submit a single (sub-)domain :::"
936 else
937 case "${adb_dns}" in
938 "dnsmasq")
939 prefix=".*[\\/\\.]"
940 suffix="(\\/)"
941 field="2"
942 ;;
943 "unbound")
944 prefix=".*[\"\\.]"
945 suffix="(always_nxdomain)"
946 field="3"
947 ;;
948 "named")
949 prefix="[^\\*].*[\\.]"
950 suffix="( \\.)"
951 field="1"
952 ;;
953 "kresd")
954 prefix="[^\\*].*[\\.]"
955 suffix="( \\.)"
956 field="1"
957 ;;
958 "raw")
959 prefix=".*[\\.]"
960 suffix=""
961 field="1"
962 ;;
963 esac
964 query_start="$(date "+%s")"
965 while [ "${domain}" != "${tld}" ]; do
966 search="${domain//[+*~%\$&\"\']/}"
967 search="${search//./\\.}"
968 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}")"
969 printf "%s\n%s\n%s\n" ":::" "::: domain '${domain}' in active blocklist" ":::"
970 printf "%s\n\n" "${result:-" - no match"}"
971 domain="${tld}"
972 tld="${domain#*.}"
973 done
974 if [ "${adb_backup}" = "1" ] && [ -d "${adb_backupdir}" ]; then
975 search="${1//[+*~%\$&\"\']/}"
976 search="${search//./\\.}"
977 printf "%s\n%s\n%s\n" ":::" "::: domain '${1}' in backups and black-/whitelist" ":::"
978 for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz "${adb_blacklist}" "${adb_whitelist}"; do
979 suffix="${file##*.}"
980 if [ "${suffix}" = "gz" ]; then
981 zcat "${file}" 2>/dev/null |
982 "${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}"
983 else
984 "${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}"
985 fi
986 if [ "${?}" = "0" ]; then
987 result="true"
988 query_end="$(date "+%s")"
989 if [ "$((query_end - query_start))" -gt "${query_timeout}" ]; then
990 printf "%s\n\n" " - [...]"
991 break
992 fi
993 fi
994 done
995 [ "${result}" != "true" ] && printf "%s\n\n" " - no match"
996 fi
997 fi
998 }
999
1000 # update runtime information
1001 #
1002 f_jsnup() {
1003 local entry sources runtime utils bg_pid status="${1:-"enabled"}"
1004
1005 adb_memory="$("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null |
1006 "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
1007
1008 case "${status}" in
1009 "enabled" | "error")
1010 adb_endtime="$(date "+%s")"
1011 if [ "$(((adb_endtime - adb_starttime) / 60))" -lt 60 ]; then
1012 runtime="${adb_action}, $(((adb_endtime - adb_starttime) / 60))m $(((adb_endtime - adb_starttime) % 60))s, ${adb_memory:-0}, $(date -Iseconds)"
1013 else
1014 runtime="${adb_action}, n/a, ${adb_memory:-0}, $(date -Iseconds)"
1015 fi
1016 [ "${status}" = "error" ] && adb_cnt="0"
1017 ;;
1018 "suspend")
1019 status="paused"
1020 ;;
1021 "resume")
1022 status=""
1023 ;;
1024 esac
1025 json_init
1026 if json_load_file "${adb_rtfile}" >/dev/null 2>&1; then
1027 utils="download: $(readlink -fn "${adb_fetchutil}"), sort: $(readlink -fn "${adb_sort}"), awk: $(readlink -fn "${adb_awk}")"
1028 [ -z "${adb_cnt}" ] && { json_get_var adb_cnt "blocked_domains"; adb_cnt="${adb_cnt%% *}"; }
1029 [ -z "${runtime}" ] && json_get_var runtime "last_run"
1030 fi
1031 if [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]; then
1032 adb_cnt="0"
1033 sources="restrictive_jail"
1034 else
1035 sources="$(printf "%s\n" ${adb_sources} | "${adb_sort}" | "${adb_awk}" '{ORS=" ";print $0}')"
1036 fi
1037
1038 : >"${adb_rtfile}"
1039 json_init
1040 json_load_file "${adb_rtfile}" >/dev/null 2>&1
1041 json_init
1042 json_add_string "adblock_status" "${status:-"enabled"}"
1043 json_add_string "adblock_version" "${adb_ver}"
1044 json_add_string "blocked_domains" "${adb_cnt:-0}"
1045 json_add_array "active_sources"
1046 for entry in ${sources}; do
1047 json_add_object
1048 json_add_string "source" "${entry}"
1049 json_close_object
1050 done
1051 json_close_array
1052 json_add_string "dns_backend" "${adb_dns:-"-"} (${adb_dnscachecmd##*/}), ${adb_dnsdir:-"-"}"
1053 json_add_string "run_utils" "${utils:-"-"}"
1054 json_add_string "run_ifaces" "trigger: ${adb_trigger:-"-"}, report: ${adb_repiface:-"-"}"
1055 json_add_string "run_directories" "base: ${adb_tmpbase}, backup: ${adb_backupdir}, report: ${adb_reportdir}, jail: ${adb_jaildir}"
1056 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})"
1057 json_add_string "last_run" "${runtime:-"-"}"
1058 json_add_string "system" "${adb_sysver}"
1059 json_dump >"${adb_rtfile}"
1060
1061 if [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ] &&
1062 { [ "${status}" = "error" ] || { [ "${status}" = "enabled" ] && [ "${adb_cnt}" -le "${adb_mailcnt}" ]; }; }; then
1063 ("${adb_mailservice}" "${adb_ver}" >/dev/null 2>&1) &
1064 bg_pid="${!}"
1065 fi
1066 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:-"-"}"
1067 }
1068
1069 # write to syslog
1070 #
1071 f_log() {
1072 local class="${1}" log_msg="${2}"
1073
1074 if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${adb_debug}" = "1" ]; }; then
1075 [ -x "${adb_loggercmd}" ] && "${adb_loggercmd}" -p "${class}" -t "adblock-${adb_ver}[${$}]" "${log_msg}" || \
1076 printf "%s %s %s\n" "${class}" "adblock-${adb_ver}[${$}]" "${log_msg}"
1077 if [ "${class}" = "err" ]; then
1078 f_rmdns
1079 f_jsnup "error"
1080 exit 1
1081 fi
1082 fi
1083 }
1084
1085 # main function for blocklist processing
1086 #
1087 f_main() {
1088 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
1089
1090 f_log "debug" "f_main ::: memory: ${adb_memory:-0}, cores: ${adb_cores}, safe_search: ${adb_safesearch}, force_dns: ${adb_forcedns}, awk: ${adb_awk}"
1091
1092 # white- and blacklist preparation
1093 #
1094 for entry in ${adb_locallist}; do
1095 (f_list "${entry}" "${entry}") &
1096 done
1097
1098 if [ "${adb_dns}" != "raw" ] && [ "${adb_jail}" = "1" ] && [ "${adb_jaildir}" = "${adb_dnsdir}" ]; then
1099 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
1100 chown "${adb_dnsuser}" "${adb_jaildir}/${adb_dnsjail}" 2>/dev/null
1101 if f_dnsup; then
1102 if [ "${adb_action}" != "resume" ]; then
1103 f_jsnup "enabled"
1104 fi
1105 f_log "info" "restrictive jail mode enabled successfully (${adb_sysver})"
1106 else
1107 f_log "err" "dns backend restart in jail mode failed"
1108 fi
1109 f_rmtemp
1110 return
1111 elif [ -f "${adb_dnsdir}/${adb_dnsjail}" ]; then
1112 rm -f "${adb_dnsdir}/${adb_dnsjail}"
1113 f_dnsup
1114 fi
1115
1116 # safe search preparation
1117 #
1118 if [ "${adb_safesearch}" = "1" ] && [ "${adb_dnssafesearch}" != "0" ]; then
1119 [ -z "${adb_safesearchlist}" ] && adb_safesearchlist="google bing duckduckgo pixabay yandex youtube"
1120 cnt="1"
1121 for entry in ${adb_safesearchlist}; do
1122 (f_list safesearch "${entry}") &
1123 hold="$((cnt % adb_cores))"
1124 [ "${hold}" = "0" ] && wait
1125 cnt="$((cnt + 1))"
1126 done
1127 fi
1128 wait
1129
1130 # main loop
1131 #
1132 cnt="1"
1133 for src_name in ${adb_sources}; do
1134 if ! json_select "${src_name}" >/dev/null 2>&1; then
1135 adb_sources="${adb_sources/${src_name}/}"
1136 continue
1137 fi
1138 json_get_var src_url "url" >/dev/null 2>&1
1139 json_get_var src_rset "rule" >/dev/null 2>&1
1140 json_select ..
1141 src_tmpcat="${adb_tmpload}.${src_name}.cat"
1142 src_tmpload="${adb_tmpload}.${src_name}.load"
1143 src_tmpsort="${adb_tmpload}.${src_name}.sort"
1144 src_tmpfile="${adb_tmpfile}.${src_name}"
1145 src_rc=4
1146
1147 # basic pre-checks
1148 #
1149 if [ -z "${src_url}" ] || [ -z "${src_rset}" ]; then
1150 f_list remove
1151 continue
1152 fi
1153
1154 # backup mode
1155 #
1156 if [ "${adb_backup}" = "1" ] && { [ "${adb_action}" = "start" ] || [ "${adb_action}" = "resume" ]; }; then
1157 if f_list restore && [ -s "${src_tmpfile}" ]; then
1158 continue
1159 fi
1160 fi
1161
1162 # download queue processing
1163 #
1164 unset src_cat src_entries
1165 if [ "${src_name}" = "utcapitole" ] && [ -n "${adb_utc_sources}" ]; then
1166 src_cat="${adb_utc_sources}"
1167 if [ -n "${src_cat}" ]; then
1168 (
1169 src_arc="${adb_tmpdir}/${src_url##*/}"
1170 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
1171 src_rc="${?}"
1172 if [ "${src_rc}" = "0" ] && [ -s "${src_arc}" ]; then
1173 src_suffix="$(eval printf "%s" \"\$\{adb_src_suffix_${src_name}:-\"domains\"\}\")"
1174 src_list="$(tar -tzf "${src_arc}" 2>/dev/null)"
1175 for src_item in ${src_cat}; do
1176 src_entries="${src_entries} $(printf "%s" "${src_list}" | grep -E "${src_item}/${src_suffix}$")"
1177 done
1178 if [ -n "${src_entries}" ]; then
1179 tar -xOzf "${src_arc}" ${src_entries} 2>/dev/null >"${src_tmpload}"
1180 src_rc="${?}"
1181 fi
1182 : >"${src_arc}"
1183 else
1184 src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1185 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1186 fi
1187 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]; then
1188 if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]; then
1189 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1190 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1191 else
1192 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1193 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1194 fi
1195 : >"${src_tmpload}"
1196 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null >"${src_tmpfile}"
1197 src_rc="${?}"
1198 : >"${src_tmpsort}"
1199 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]; then
1200 f_list download
1201 [ "${adb_backup}" = "1" ] && f_list backup
1202 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]; then
1203 f_log "info" "archive preparation of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1204 f_list restore
1205 rm -f "${src_tmpfile}"
1206 fi
1207 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]; then
1208 f_log "info" "archive extraction of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
1209 f_list restore
1210 fi
1211 ) &
1212 fi
1213 else
1214 if [ "${src_name}" = "energized" ] && [ -n "${adb_eng_sources}" ]; then
1215 src_cat="${adb_eng_sources}"
1216 elif [ "${src_name}" = "stevenblack" ] && [ -n "${adb_stb_sources}" ]; then
1217 src_cat="${adb_stb_sources}"
1218 elif { [ "${src_name}" = "energized" ] && [ -z "${adb_eng_sources}" ]; } ||
1219 { [ "${src_name}" = "stevenblack" ] && [ -z "${adb_stb_sources}" ]; }; then
1220 continue
1221 fi
1222 (
1223 for suffix in ${src_cat:-${src_url}}; do
1224 if [ "${src_url}" != "${suffix}" ]; then
1225 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpcat}" "${src_url}${suffix}" 2>&1)"
1226 src_rc="${?}"
1227 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpcat}" ]; then
1228 cat "${src_tmpcat}" >>"${src_tmpload}"
1229 : >"${src_tmpcat}"
1230 fi
1231 else
1232 src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpload}" "${src_url}" 2>&1)"
1233 src_rc="${?}"
1234 fi
1235 done
1236 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]; then
1237 if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]; then
1238 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1239 grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1240 else
1241 "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" |
1242 "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' >"${src_tmpsort}"
1243 fi
1244 : >"${src_tmpload}"
1245 "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null >"${src_tmpfile}"
1246 src_rc="${?}"
1247 : >"${src_tmpsort}"
1248 if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]; then
1249 f_list download
1250 [ "${adb_backup}" = "1" ] && f_list backup
1251 elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]; then
1252 f_log "info" "preparation of '${src_name}' failed, rc: ${src_rc}"
1253 f_list restore
1254 rm -f "${src_tmpfile}"
1255 fi
1256 else
1257 src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
1258 f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
1259 [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ] && f_list restore
1260 fi
1261 ) &
1262 fi
1263 hold="$((cnt % adb_cores))"
1264 [ "${hold}" = "0" ] && wait
1265 cnt="$((cnt + 1))"
1266 done
1267 wait
1268
1269 # tld compression and dns restart
1270 #
1271 if f_list merge && [ -s "${adb_tmpdir}/${adb_dnsfile}" ]; then
1272 f_tld "${adb_tmpdir}/${adb_dnsfile}"
1273 f_list final
1274 else
1275 printf "%b" "${adb_dnsheader}" >"${adb_dnsdir}/${adb_dnsfile}"
1276 fi
1277 chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
1278 if f_dnsup; then
1279 [ "${adb_action}" != "resume" ] && f_jsnup "enabled"
1280 f_log "info" "blocklist with overall ${adb_cnt} blocked domains loaded successfully (${adb_sysver})"
1281 else
1282 f_log "err" "dns backend restart with adblock blocklist failed"
1283 fi
1284 f_rmtemp
1285 }
1286
1287 # trace dns queries via tcpdump and prepare a report
1288 #
1289 f_report() {
1290 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:-"+"}"
1291
1292 report_raw="${adb_reportdir}/adb_report.raw"
1293 report_srt="${adb_reportdir}/adb_report.srt"
1294 report_jsn="${adb_reportdir}/adb_report.json"
1295 report_txt="${adb_reportdir}/adb_mailreport.txt"
1296
1297 # build json file
1298 #
1299 if [ "${action}" != "json" ]; then
1300 : >"${report_raw}"
1301 : >"${report_srt}"
1302 : >"${report_txt}"
1303 : >"${report_jsn}"
1304 [ "${adb_represolve}" = "1" ] && resolve=""
1305 for file in "${adb_reportdir}/adb_report.pcap"*; do
1306 (
1307 "${adb_dumpcmd}" "${resolve}" -tttt -r "${file}" 2>/dev/null |
1308 "${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);
1309 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}"
1310 ) &
1311 hold="$((cnt % adb_cores))"
1312 [ "${hold}" = "0" ] && wait
1313 cnt="$((cnt + 1))"
1314 done
1315 wait
1316 if [ -s "${report_raw}" ]; then
1317 "${adb_sort}" ${adb_srtopts} -k1 -k3 -k4 -k5 -k1 -ur "${report_raw}" |
1318 "${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}}' |
1319 "${adb_sort}" ${adb_srtopts} -k1 -k2 -k3 -k4 -ur >"${report_srt}"
1320 rm -f "${report_raw}"
1321 fi
1322
1323 if [ -s "${report_srt}" ]; then
1324 start="$("${adb_awk}" 'END{printf "%s_%s",$1,$2}' "${report_srt}")"
1325 end="$("${adb_awk}" 'NR==1{printf "%s_%s",$1,$2}' "${report_srt}")"
1326 total="$(wc -l <"${report_srt}")"
1327 blocked="$("${adb_awk}" '{if($5=="NX")cnt++}END{printf "%s",cnt}' "${report_srt}")"
1328 percent="$("${adb_awk}" -v t="${total}" -v b="${blocked}" 'BEGIN{printf "%.2f%s",b/t*100,"%"}')"
1329 : >"${report_jsn}"
1330 {
1331 printf "%s\n" "{ "
1332 printf "\t%s\n" "\"start_date\": \"${start%_*}\", "
1333 printf "\t%s\n" "\"start_time\": \"${start#*_}\", "
1334 printf "\t%s\n" "\"end_date\": \"${end%_*}\", "
1335 printf "\t%s\n" "\"end_time\": \"${end#*_}\", "
1336 printf "\t%s\n" "\"total\": \"${total}\", "
1337 printf "\t%s\n" "\"blocked\": \"${blocked}\", "
1338 printf "\t%s\n" "\"percent\": \"${percent}\", "
1339 } >>"${report_jsn}"
1340 top_list="top_clients top_domains top_blocked"
1341 for top in ${top_list}; do
1342 printf "\t%s" "\"${top}\": [ " >>"${report_jsn}"
1343 case "${top}" in
1344 "top_clients")
1345 "${adb_awk}" '{print $3}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c |
1346 "${adb_sort}" ${adb_srtopts} -nr |
1347 "${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}"
1348 ;;
1349 "top_domains")
1350 "${adb_awk}" '{if($5!="NX")print $4}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c |
1351 "${adb_sort}" ${adb_srtopts} -nr |
1352 "${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}"
1353 ;;
1354 "top_blocked")
1355 "${adb_awk}" '{if($5=="NX")print $4}' "${report_srt}" |
1356 "${adb_sort}" ${adb_srtopts} | uniq -c | "${adb_sort}" ${adb_srtopts} -nr |
1357 "${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}"
1358 ;;
1359 esac
1360 printf "\n\t%s\n" "]," >>"${report_jsn}"
1361 done
1362 search="${search//./\\.}"
1363 search="${search//[+*~%\$&\"\' ]/}"
1364 "${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}"
1365 rm -f "${report_srt}"
1366 fi
1367 fi
1368
1369 # output preparation
1370 #
1371 if [ -s "${report_jsn}" ] && { [ "${action}" = "cli" ] || [ "${action}" = "mail" ]; }; then
1372 printf "%s\n%s\n%s\n" ":::" "::: Adblock DNS-Query Report" ":::" >>"${report_txt}"
1373 json_init
1374 json_load_file "${report_jsn}"
1375 json_get_keys key_list
1376 for key in ${key_list}; do
1377 json_get_var value "${key}"
1378 eval "${key}=\"${value}\""
1379 done
1380 printf " + %s\n + %s\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}" >>"${report_txt}"
1381 printf " + %s\n + %s %s\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})" >>"${report_txt}"
1382 top_list="top_clients top_domains top_blocked requests"
1383 for top in ${top_list}; do
1384 case "${top}" in
1385 "top_clients")
1386 item="::: Top Clients"
1387 ;;
1388 "top_domains")
1389 item="::: Top Domains"
1390 ;;
1391 "top_blocked")
1392 item="::: Top Blocked Domains"
1393 ;;
1394 esac
1395 if json_get_type status "${top}" && [ "${top}" != "requests" ] && [ "${status}" = "array" ]; then
1396 printf "%s\n%s\n%s\n" ":::" "${item}" ":::" >>"${report_txt}"
1397 json_select "${top}"
1398 index="1"
1399 item=""
1400 while json_get_type status "${index}" && [ "${status}" = "object" ]; do
1401 json_get_values item "${index}"
1402 printf " + %-9s::: %s\n" ${item} >>"${report_txt}"
1403 index="$((index + 1))"
1404 done
1405 elif json_get_type status "${top}" && [ "${top}" = "requests" ] && [ "${status}" = "array" ]; then
1406 printf "%s\n%s\n%s\n" ":::" "::: Latest DNS Queries" ":::" >>"${report_txt}"
1407 printf "%-15s%-15s%-45s%-80s%s\n" "Date" "Time" "Client" "Domain" "Answer" >>"${report_txt}"
1408 json_select "${top}"
1409 index="1"
1410 while json_get_type status "${index}" && [ "${status}" = "object" ]; do
1411 json_get_values item "${index}"
1412 printf "%-15s%-15s%-45s%-80s%s\n" ${item} >>"${report_txt}"
1413 index="$((index + 1))"
1414 done
1415 fi
1416 json_select ".."
1417 done
1418 content="$(cat "${report_txt}" 2>/dev/null)"
1419 rm -f "${report_txt}"
1420 fi
1421
1422 # report output
1423 #
1424 if [ "${action}" = "cli" ]; then
1425 printf "%s\n" "${content}"
1426 elif [ "${action}" = "json" ]; then
1427 cat "${report_jsn}"
1428 elif [ "${action}" = "mail" ] && [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ]; then
1429 ("${adb_mailservice}" "${adb_ver}" "${content}" >/dev/null 2>&1) &
1430 bg_pid="${!}"
1431 fi
1432 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}"
1433 }
1434
1435 # source required system libraries
1436 #
1437 if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]; then
1438 . "/lib/functions.sh"
1439 . "/lib/functions/network.sh"
1440 . "/usr/share/libubox/jshn.sh"
1441 else
1442 f_log "err" "system libraries not found"
1443 fi
1444
1445 # awk check
1446 #
1447 adb_awk="$(command -v gawk)"
1448 if [ ! -x "${adb_awk}" ]; then
1449 adb_awk="$(command -v awk)"
1450 [ ! -x "${adb_awk}" ] && f_log "err" "awk not found or not executable"
1451 fi
1452
1453 # sort check
1454 #
1455 adb_sort="$(command -v sort)"
1456 if [ ! -x "${adb_sort}" ] || ! "${adb_sort}" --version 2>/dev/null | grep -q "coreutils"; then
1457 f_log "err" "coreutils sort not found or not executable"
1458 fi
1459
1460 # handle different adblock actions
1461 #
1462 f_load
1463 case "${adb_action}" in
1464 "stop")
1465 f_rmdns
1466 ;;
1467 "restart")
1468 f_rmdns
1469 f_env
1470 f_main
1471 ;;
1472 "suspend")
1473 [ "${adb_dns}" != "raw" ] && f_switch suspend
1474 ;;
1475 "resume")
1476 [ "${adb_dns}" != "raw" ] && f_switch resume
1477 ;;
1478 "report")
1479 f_report "${2}" "${3}" "${4}" "${5}"
1480 ;;
1481 "query")
1482 f_query "${2}"
1483 ;;
1484 "start" | "reload")
1485 f_env
1486 f_main
1487 ;;
1488 esac