Merge pull request #4367 from dibdot/adblock
[feed/packages.git] / net / adblock / files / adblock.sh
1 #!/bin/sh
2 # dns based ad/abuse domain blocking
3 # written by Dirk Brenken (dev@brenken.org)
4
5 # This is free software, licensed under the GNU General Public License v3.
6 # You should have received a copy of the GNU General Public License
7 # along with this program. If not, see <http://www.gnu.org/licenses/>.
8
9 # set initial defaults
10 #
11 LC_ALL=C
12 PATH="/usr/sbin:/usr/bin:/sbin:/bin"
13 adb_ver="2.6.4"
14 adb_sysver="$(ubus -S call system board | jsonfilter -e '@.release.description')"
15 adb_enabled=1
16 adb_debug=0
17 adb_forcesrt=0
18 adb_forcedns=0
19 adb_backup=0
20 adb_backupdir="/mnt"
21 adb_whitelist="/etc/adblock/adblock.whitelist"
22 adb_whitelist_rset="\$1 ~/^([A-Za-z0-9_-]+\.){1,}[A-Za-z]+/{print tolower(\"^\"\$1\"\\\|[.]\"\$1)}"
23 adb_fetch="/usr/bin/wget"
24 adb_fetchparm="--quiet --no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"
25 adb_dnslist="dnsmasq unbound"
26 adb_dnsprefix="adb_list"
27 adb_rtfile="/tmp/adb_runtime.json"
28 adb_sources=""
29 adb_src_cat_shalla=""
30 adb_action="${1}"
31
32 # f_envload: load adblock environment
33 #
34 f_envload()
35 {
36 local services dns_up cnt=0
37
38 # source in system library
39 #
40 if [ -r "/lib/functions.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
41 then
42 . "/lib/functions.sh"
43 . "/usr/share/libubox/jshn.sh"
44 else
45 f_log "error" "system libraries not found"
46 fi
47
48 # parse global section by callback
49 #
50 config_cb()
51 {
52 local type="${1}"
53 if [ "${type}" = "adblock" ]
54 then
55 option_cb()
56 {
57 local option="${1}"
58 local value="${2}"
59 eval "${option}=\"${value}\""
60 }
61 else
62 reset_cb
63 fi
64 }
65
66 # parse 'source' sections
67 #
68 parse_config()
69 {
70 local value opt section="${1}" options="enabled adb_src adb_src_rset adb_src_cat"
71 eval "adb_sources=\"${adb_sources} ${section}\""
72 for opt in ${options}
73 do
74 config_get value "${section}" "${opt}"
75 if [ -n "${value}" ]
76 then
77 eval "${opt}_${section}=\"${value}\""
78 fi
79 done
80 }
81
82 # load adblock config
83 #
84 config_load adblock
85 config_foreach parse_config source
86
87 # set dns backend environment
88 #
89 while [ ${cnt} -le 20 ]
90 do
91 services="$(ubus -S call service list 2>/dev/null)"
92 if [ -n "${services}" ]
93 then
94 for dns in ${adb_dnslist}
95 do
96 dns_up="$(printf "%s" "${services}" | jsonfilter -l1 -e "@.${dns}.instances.*.running")"
97 if [ "${dns_up}" = "true" ]
98 then
99 case "${dns}" in
100 dnsmasq)
101 adb_dns="${dns}"
102 adb_dnsdir="${adb_dnsdir:="/tmp/dnsmasq.d"}"
103 adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
104 adb_dnsformat="awk '{print \"local=/\"\$0\"/\"}'"
105 break 2
106 ;;
107 unbound)
108 adb_dns="${dns}"
109 adb_dnsdir="${adb_dnsdir:="/var/lib/unbound"}"
110 adb_dnshidedir="${adb_dnsdir}/.adb_hidden"
111 adb_dnsformat="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
112 break 2
113 ;;
114 esac
115 fi
116 done
117 fi
118 sleep 1
119 cnt=$((cnt+1))
120 done
121 if [ -z "${adb_dns}" ] || [ -z "${adb_dnsformat}" ] || [ ! -x "$(command -v ${adb_dns})" ] || [ ! -d "${adb_dnsdir}" ]
122 then
123 f_log "error" "no active/supported DNS backend found"
124 fi
125
126 # force dns to local resolver
127 #
128 if [ ${adb_forcedns} -eq 1 ] && [ -z "$(uci -q get firewall.adblock_dns)" ]
129 then
130 uci -q set firewall.adblock_dns="redirect"
131 uci -q set firewall.adblock_dns.name="Adblock DNS"
132 uci -q set firewall.adblock_dns.src="lan"
133 uci -q set firewall.adblock_dns.proto="tcp udp"
134 uci -q set firewall.adblock_dns.src_dport="53"
135 uci -q set firewall.adblock_dns.dest_port="53"
136 uci -q set firewall.adblock_dns.target="DNAT"
137 elif [ ${adb_forcedns} -eq 0 ] && [ -n "$(uci -q get firewall.adblock_dns)" ]
138 then
139 uci -q delete firewall.adblock_dns
140 fi
141 if [ -n "$(uci -q changes firewall)" ]
142 then
143 uci -q commit firewall
144 if [ $(/etc/init.d/firewall enabled; printf "%u" ${?}) -eq 0 ]
145 then
146 /etc/init.d/firewall reload >/dev/null 2>&1
147 fi
148 fi
149 }
150
151 # f_envcheck: check/set environment prerequisites
152 #
153 f_envcheck()
154 {
155 local ssl_lib
156
157 # check 'enabled' option
158 #
159 if [ ${adb_enabled} -ne 1 ]
160 then
161 if [ -n "$(ls -dA "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null)" ]
162 then
163 f_rmdns
164 f_dnsrestart
165 fi
166 f_log "info " "adblock is currently disabled, please set adb_enabled to '1' to use this service"
167 exit 0
168 fi
169
170 # check fetch utility
171 #
172 ssl_lib="-"
173 if [ -x "${adb_fetch}" ]
174 then
175 if [ "$(readlink -fn "${adb_fetch}")" = "/usr/bin/wget-nossl" ]
176 then
177 adb_fetchparm="--quiet --no-cache --no-cookies --max-redirect=0 --timeout=10 -O"
178 elif [ "$(readlink -fn "/bin/wget")" = "/bin/busybox" ] || [ "$(readlink -fn "${adb_fetch}")" = "/bin/busybox" ]
179 then
180 adb_fetch="/bin/busybox"
181 adb_fetchparm="-q -O"
182 else
183 ssl_lib="built-in"
184 fi
185 fi
186 if [ ! -x "${adb_fetch}" ] && [ "$(readlink -fn "/bin/wget")" = "/bin/uclient-fetch" ]
187 then
188 adb_fetch="/bin/uclient-fetch"
189 if [ -f "/lib/libustream-ssl.so" ]
190 then
191 adb_fetchparm="-q --timeout=10 --no-check-certificate -O"
192 ssl_lib="libustream-ssl"
193 else
194 adb_fetchparm="-q --timeout=10 -O"
195 fi
196 fi
197 if [ ! -x "${adb_fetch}" ] || [ -z "${adb_fetch}" ] || [ -z "${adb_fetchparm}" ]
198 then
199 f_log "error" "no download utility found, please install 'uclient-fetch' with 'libustream-mbedtls' or the full 'wget' package"
200 fi
201 adb_fetchinfo="${adb_fetch##*/} (${ssl_lib})"
202
203 # create dns hideout directory
204 #
205 if [ ! -d "${adb_dnshidedir}" ]
206 then
207 mkdir -p -m 660 "${adb_dnshidedir}"
208 chown -R "${adb_dns}":"${adb_dns}" "${adb_dnshidedir}" 2>/dev/null
209 else
210 rm -f "${adb_dnshidedir}/${adb_dnsprefix}"*
211 fi
212
213 # create adblock temp file/directory
214 #
215 adb_tmpload="$(mktemp -tu)"
216 adb_tmpfile="$(mktemp -tu)"
217 adb_tmpdir="$(mktemp -p /tmp -d)"
218
219 # prepare whitelist entries
220 #
221 if [ -s "${adb_whitelist}" ]
222 then
223 awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
224 fi
225 }
226
227 # f_rmtemp: remove temporary files & directories
228 #
229 f_rmtemp()
230 {
231 if [ -d "${adb_tmpdir}" ]
232 then
233 rm -f "${adb_tmpload}"
234 rm -f "${adb_tmpfile}"
235 rm -rf "${adb_tmpdir}"
236 fi
237 }
238
239 # f_rmdns: remove dns related files & directories
240 #
241 f_rmdns()
242 {
243 if [ -n "${adb_dns}" ]
244 then
245 rm -f "${adb_dnsdir}/${adb_dnsprefix}"*
246 rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
247 rm -rf "${adb_dnshidedir}"
248 > "${adb_rtfile}"
249 fi
250 }
251
252 # f_dnsrestart: restart the dns backend
253 #
254 f_dnsrestart()
255 {
256 local cnt=0
257
258 "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
259 while [ ${cnt} -le 10 ]
260 do
261 adb_dnsup="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@.${adb_dns}.instances.*.running")"
262 if [ "${adb_dnsup}" = "true" ]
263 then
264 break
265 fi
266 cnt=$((cnt+1))
267 sleep 1
268 done
269 }
270
271 # f_list: backup/restore/remove block lists
272 #
273 f_list()
274 {
275 local mode="${1}" in_rc="${adb_rc}" cnt=0
276
277 case "${mode}" in
278 backup)
279 cnt="$(wc -l < "${adb_tmpfile}")"
280 if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
281 then
282 gzip -cf "${adb_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
283 adb_rc=${?}
284 fi
285 ;;
286 restore)
287 if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
288 then
289 rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
290 if [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
291 then
292 gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${adb_tmpfile}"
293 adb_rc=${?}
294 fi
295 fi
296 ;;
297 remove)
298 rm -f "${adb_dnsdir}/${adb_dnsprefix}.${src_name}"
299 if [ -d "${adb_backupdir}" ]
300 then
301 rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
302 fi
303 adb_rc=${?}
304 ;;
305 esac
306 f_log "debug" "name: ${src_name}, mode: ${mode}, count: ${cnt}, in_rc: ${in_rc}, out_rc: ${adb_rc}"
307 }
308
309 # f_switch: suspend/resume adblock processing
310 #
311 f_switch()
312 {
313 if [ -d "${adb_dnshidedir}" ]
314 then
315 local source target status mode="${1}"
316 local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
317 local dns_passive="$(find "${adb_dnshidedir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
318
319 if [ -n "${dns_active}" ] && [ "${mode}" = "suspend" ]
320 then
321 source="${adb_dnsdir}/${adb_dnsprefix}"
322 target="${adb_dnshidedir}"
323 status="suspended"
324 elif [ -n "${dns_passive}" ] && [ "${mode}" = "resume" ]
325 then
326 source="${adb_dnshidedir}/${adb_dnsprefix}"
327 target="${adb_dnsdir}"
328 status="resumed"
329 fi
330 if [ -n "${status}" ]
331 then
332 mv -f "${source}"* "${target}"
333 f_dnsrestart
334 f_log "info " "adblock processing ${status}"
335 fi
336 fi
337 }
338
339 # f_query: query block lists for certain (sub-)domains
340 #
341 f_query()
342 {
343 local search result cnt
344 local domain="${1}"
345 local tld="${domain#*.}"
346 local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
347
348 if [ -z "${dns_active}" ]
349 then
350 printf "%s\n" "::: no active block lists found, please start / resume adblock first"
351 elif [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
352 then
353 printf "%s\n" "::: invalid domain input, please submit a specific (sub-)domain, e.g. 'www.abc.xyz'"
354 else
355 cd "${adb_dnsdir}"
356 while [ "${domain}" != "${tld}" ]
357 do
358 search="${domain//./\.}"
359 result="$(grep -Hm1 "[/\"\.]${search}[/\"]" "${adb_dnsprefix}"* | awk -F ':|=|/|\"' '{printf(" %-20s : %s\n",$1,$4)}')"
360 printf "%s\n" "::: distinct results for domain '${domain}'"
361 printf "%s\n" "${result:=" no match"}"
362 domain="${tld}"
363 tld="${domain#*.}"
364 done
365 fi
366 }
367
368 # f_status: output runtime information
369 #
370 f_status()
371 {
372 local key keylist value
373
374 if [ -s "${adb_rtfile}" ]
375 then
376 local dns_active="$(find "${adb_dnsdir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
377 local dns_passive="$(find "${adb_dnshidedir}" -maxdepth 1 -type f -name "${adb_dnsprefix}*" -print)"
378
379 if [ -n "${dns_active}" ]
380 then
381 value="active"
382 elif [ -n "${dns_passive}" ] || [ -z "${dns_active}" ]
383 then
384 value="no domains blocked"
385 fi
386 printf "%s\n" "::: adblock runtime information"
387 printf " %-15s : %s\n" "status" "${value}"
388 json_load "$(cat "${adb_rtfile}" 2>/dev/null)"
389 json_select data
390 json_get_keys keylist
391 for key in ${keylist}
392 do
393 json_get_var value "${key}"
394 printf " %-15s : %s\n" "${key}" "${value}"
395 done
396 fi
397 }
398
399 # f_log: write to syslog, exit on error
400 #
401 f_log()
402 {
403 local class="${1}" log_msg="${2}"
404
405 if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
406 then
407 logger -t "adblock-[${adb_ver}] ${class}" "${log_msg}"
408 if [ "${class}" = "error" ]
409 then
410 logger -t "adblock-[${adb_ver}] ${class}" "Please check 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md' (${adb_sysver})"
411 f_rmtemp
412 if [ -n "$(ls -dA "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null)" ]
413 then
414 f_rmdns
415 f_dnsrestart
416 fi
417 exit 255
418 fi
419 fi
420 }
421
422 # main function for block list processing
423 #
424 f_main()
425 {
426 local enabled url cnt sum_cnt=0 mem_total=0
427 local src_name src_rset shalla_archive
428 mem_total="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc/meminfo" 2>/dev/null)"
429
430 f_log "info " "start adblock processing ..."
431 f_log "debug" "action: ${adb_action}, backup: ${adb_backup}, dns: ${adb_dns}, fetch: ${adb_fetchinfo}, memory: ${mem_total}, force srt/dns: ${adb_forcesrt}/${adb_forcedns}"
432 > "${adb_rtfile}"
433 for src_name in ${adb_sources}
434 do
435 eval "enabled=\"\${enabled_${src_name}}\""
436 eval "url=\"\${adb_src_${src_name}}\""
437 eval "src_rset=\"\${adb_src_rset_${src_name}}\""
438 adb_dnsfile="${adb_tmpdir}/${adb_dnsprefix}.${src_name}"
439 > "${adb_tmpload}"
440 > "${adb_tmpfile}"
441 adb_rc=0
442
443 # basic pre-checks
444 #
445 f_log "debug" "name: ${src_name}, enabled: ${enabled}, url: ${url}, rset: ${src_rset}"
446 if [ "${enabled}" != "1" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
447 then
448 f_list remove
449 continue
450 fi
451
452 # download block list
453 #
454 if [ "${src_name}" = "blacklist" ]
455 then
456 cat "${url}" 2>/dev/null > "${adb_tmpload}"
457 adb_rc=${?}
458 elif [ "${src_name}" = "shalla" ]
459 then
460 shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
461 "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}" 2>/dev/null
462 adb_rc=${?}
463 if [ ${adb_rc} -eq 0 ]
464 then
465 for category in ${adb_src_cat_shalla}
466 do
467 tar -xOzf "${shalla_archive}" "BL/${category}/domains" >> "${adb_tmpload}"
468 adb_rc=${?}
469 if [ ${adb_rc} -ne 0 ]
470 then
471 break
472 fi
473 done
474 fi
475 rm -f "${shalla_archive}"
476 rm -rf "${adb_tmpdir}/BL"
477 else
478 "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}" 2>/dev/null
479 adb_rc=${?}
480 fi
481
482 # check download result and prepare domain output (incl. tld compression, list backup & restore)
483 #
484 if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
485 then
486 awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
487 if [ -s "${adb_tmpfile}" ]
488 then
489 awk -F "." '{for(f=NF;f > 1;f--) printf "%s.", $f;print $1}' "${adb_tmpfile}" 2>/dev/null | sort -u > "${adb_tmpload}"
490 awk '{if(NR==1){tld=$NF};while(getline){if($NF !~ tld"\\."){print tld;tld=$NF}}print tld}' "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
491 awk -F "." '{for(f=NF;f > 1;f--) printf "%s.", $f;print $1}' "${adb_tmpfile}" 2>/dev/null > "${adb_tmpload}"
492 mv -f "${adb_tmpload}" "${adb_tmpfile}"
493 f_list backup
494 else
495 f_list restore
496 fi
497 else
498 f_list restore
499 fi
500
501 # remove whitelist domains, final list preparation
502 #
503 if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
504 then
505 if [ -s "${adb_tmpdir}/tmp.whitelist" ]
506 then
507 grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpfile}" 2>/dev/null | eval "${adb_dnsformat}" > "${adb_dnsfile}"
508 else
509 eval "${adb_dnsformat}" "${adb_tmpfile}" > "${adb_dnsfile}"
510 fi
511 adb_rc=${?}
512 if [ ${adb_rc} -ne 0 ]
513 then
514 f_list remove
515 fi
516 else
517 f_list remove
518 fi
519 done
520
521 # overall sort
522 #
523 for src_name in $(ls -dASr "${adb_tmpdir}/${adb_dnsprefix}"* 2>/dev/null)
524 do
525 if [ ${mem_total} -ge 64000 ] || [ ${adb_forcesrt} -eq 1 ]
526 then
527 if [ -s "${adb_tmpdir}/blocklist.overall" ]
528 then
529 sort "${adb_tmpdir}/blocklist.overall" "${adb_tmpdir}/blocklist.overall" "${src_name}" | uniq -u > "${adb_tmpdir}/tmp.blocklist"
530 mv -f "${adb_tmpdir}/tmp.blocklist" "${src_name}"
531 fi
532 cat "${src_name}" >> "${adb_tmpdir}/blocklist.overall"
533 fi
534 cnt="$(wc -l < "${src_name}")"
535 sum_cnt=$((sum_cnt + cnt))
536 done
537
538 # restart the dns backend and export runtime information
539 #
540 mv -f "${adb_tmpdir}/${adb_dnsprefix}"* "${adb_dnsdir}" 2>/dev/null
541 chown "${adb_dns}":"${adb_dns}" "${adb_dnsdir}/${adb_dnsprefix}"* 2>/dev/null
542 f_rmtemp
543 f_dnsrestart
544 if [ "${adb_dnsup}" = "true" ]
545 then
546 json_init
547 json_add_object "data"
548 json_add_string "adblock_version" "${adb_ver}"
549 json_add_string "blocked_domains" "${sum_cnt}"
550 json_add_string "fetch_info" "${adb_fetchinfo}"
551 json_add_string "dns_backend" "${adb_dns}"
552 json_add_string "last_rundate" "$(/bin/date "+%d.%m.%Y %H:%M:%S")"
553 json_add_string "system" "${adb_sysver}"
554 json_close_object
555 json_dump > "${adb_rtfile}"
556 f_log "info " "block lists with overall ${sum_cnt} domains loaded successfully (${adb_sysver})"
557 else
558 f_log "error" "dns backend restart with active block lists failed"
559 fi
560 }
561
562 # handle different adblock actions
563 #
564 f_envload
565 case "${adb_action}" in
566 stop)
567 f_rmtemp
568 f_rmdns
569 f_dnsrestart
570 ;;
571 restart)
572 f_rmtemp
573 f_rmdns
574 f_envcheck
575 f_main
576 ;;
577 suspend)
578 f_switch suspend
579 ;;
580 resume)
581 f_switch resume
582 ;;
583 query)
584 f_query "${2}"
585 ;;
586 status)
587 f_status
588 ;;
589 *)
590 f_envcheck
591 f_main
592 ;;
593 esac
594 exit 0