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