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