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