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