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