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