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