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