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