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