2 # function library used by adblock-update.sh
3 # written by Dirk Brenken (openwrt@brenken.org)
5 # f_envload: load adblock environment
9 # source in openwrt function library
11 if [ -r "/lib/functions.sh" ]
16 f_log
"openwrt function library not found" "${rc}"
20 # source in openwrt network library
22 if [ -r "/lib/functions/network.sh" ]
24 .
"/lib/functions/network.sh"
27 f_log
"openwrt network library not found" "${rc}"
31 # set initial defaults,
32 # may be overwritten by setting appropriate adblock config options in global section of /etc/config/adblock
36 adb_nullipv4
="192.0.2.1"
37 adb_nullipv6
="::ffff:c000:0201"
38 adb_whitelist
="/etc/adblock/adblock.whitelist"
39 adb_whitelist_rset
="\$1 ~/^([A-Za-z0-9_-]+\.){1,}[A-Za-z]+/{print tolower(\$1)}"
42 # function to parse global section by callback
47 if [ "${type}" = "adblock" ]
53 eval "${option}=\"${value}\""
60 # function to parse 'service' and 'source' sections
64 local value opt section
="${1}" options
="adb_dir adb_src adb_src_rset adb_src_cat"
65 config_get switch
"${section}" "enabled"
66 if [ "${switch}" = "1" ]
68 if [ "${section}" != "backup" ]
70 eval "adb_sources=\"${adb_sources} ${section}\""
74 config_get value
"${section}" "${opt}"
77 eval "${opt}_${section}=\"${value}\""
83 # check opkg availability
85 if [ -r "/var/lock/opkg.lock" ]
88 f_log
"adblock installation finished successfully, 'opkg' currently locked by package installer"
92 # get list with all installed openwrt packages
94 pkg_list
="$(opkg list-installed)"
95 if [ -z "${pkg_list}" ]
98 f_log
"empty openwrt package list" "${rc}"
102 # load adblock config and start parsing functions
105 config_foreach parse_config service
106 config_foreach parse_config
source
108 # check 'enabled' & 'version' config options
110 if [ -z "${adb_enabled}" ] || [ -z "${adb_cfgversion}" ] || [ "${adb_cfgversion}" != "${adb_scriptver%.*}" ]
113 f_log
"outdated adblock configuration found, please use latest version from '/etc/adblock/adblock.conf.default'" "${rc}"
116 if [ $
((adb_enabled
)) -ne 1 ]
119 f_log
"adblock is currently disabled, please set adblock.global.adb_enabled=1' to use this service"
123 # set more script defaults (can't be overwritten by adblock config options)
126 adb_tmpfile
="$(mktemp -tu)"
127 adb_tmpdir
="$(mktemp -p /tmp -d)"
128 adb_dnsdir
="/tmp/dnsmasq.d"
129 adb_dnsprefix
="adb_list"
130 adb_fetch
="/usr/bin/wget"
132 unset adb_srclist adb_revsrclist adb_errsrclist
134 # get lan ip addresses
136 network_get_ipaddr adb_ipv4
"${adb_lanif}"
137 network_get_ipaddr6 adb_ipv6
"${adb_lanif}"
138 if [ -z "${adb_ipv4}" ] && [ -z "${adb_ipv6}" ]
141 f_log
"no valid IPv4/IPv6 configuration found (${adb_lanif}), please set 'adb_lanif' manually" "${rc}"
146 # f_envcheck: check/set environment prerequisites
152 # check logical update interfaces (with default route)
154 network_find_wan adb_wanif4
155 network_find_wan6 adb_wanif6
156 if [ -z "${adb_wanif4}" ] && [ -z "${adb_wanif6}" ]
159 f_log
"no valid IPv4/IPv6 interface with default route found, IPv4 mode will be assumed"
162 # check general package dependencies
167 f_depend
"kmod-ipt-nat"
169 # check ipv6 related package dependencies
171 if [ -n "${adb_wanif6}" ]
173 check
="$(printf "${pkg_list}" | grep "^ip6tables
-")"
176 f_log
"package 'ip6tables' not found, IPv6 support will be disabled"
179 check
="$(printf "${pkg_list}" | grep "^kmod-ipt-nat6
-")"
182 f_log
"package 'kmod-ipt-nat6' not found, IPv6 support will be disabled"
188 # check ca-certificates package and set fetch parms accordingly
190 fetch_parm
="--no-config --quiet --tries=1 --no-cache --no-cookies --max-redirect=0 --dns-timeout=5 --connect-timeout=5 --read-timeout=5"
191 check
="$(printf "${pkg_list}" | grep "^ca-certificates
-")"
194 fetch_parm
="${fetch_parm} --no-check-certificate"
197 # check adblock temp directory
199 if [ -n "${adb_tmpdir}" ] && [ -d "${adb_tmpdir}" ]
201 f_space
"${adb_tmpdir}"
202 if [ "${space_ok}" = "false" ]
204 if [ $
((av_space
)) -le 2000 ]
207 f_log
"not enough free space in '${adb_tmpdir}' (avail. ${av_space} kb)" "${rc}"
210 f_log
"not enough free space to handle all adblock list sources at once in '${adb_tmpdir}' (avail. ${av_space} kb)"
215 f_log
"temp directory not found" "${rc}"
221 mem_total
="$(awk '$1 ~ /^MemTotal/ {printf $2}' "/proc
/meminfo
")"
222 mem_free
="$(awk '$1 ~ /^MemFree/ {printf $2}' "/proc
/meminfo
")"
223 mem_swap
="$(awk '$1 ~ /^SwapTotal/ {printf $2}' "/proc
/meminfo
")"
224 if [ $
((mem_total
)) -le 64000 ] && [ $
((mem_swap
)) -eq 0 ]
227 f_log
"not enough free memory, overall sort processing will be disabled (total: ${mem_total}, free: ${mem_free}, swap: ${mem_swap})"
232 # check backup configuration
234 if [ -n "${adb_dir_backup}" ] && [ -d "${adb_dir_backup}" ]
236 f_space
"${adb_dir_backup}"
237 if [ "${space_ok}" = "false" ]
239 f_log
"not enough free space in '${adb_dir_backup}'(avail. ${av_space} kb), backup/restore will be disabled"
242 f_log
"backup/restore will be enabled"
247 f_log
"backup/restore will be disabled"
250 # check running dnsmasq instance & set defaults
252 rc
="$(ps | grep -q "[d
]nsmasq
"; printf ${?})"
255 if [ -n "${adb_wanif4}" ] && [ -n "${adb_wanif6}" ]
257 adb_dnsformat
="awk -v ipv4="${adb_nullipv4}" -v ipv6="${adb_nullipv6}" '{print \"address=/\"\$0\"/\"ipv4\"\n\"\"address=/\"\$0\"/\"ipv6}'"
258 elif [ -n "${adb_wanif4}" ]
260 adb_dnsformat="awk -v ipv4="${adb_nullipv4}" '{print
\"address
=/\"\
$0\"/\"ipv4
}'"
262 adb_dnsformat="awk -v ipv6="${adb_nullipv6}" '{print
\"address
=/\"\
$0\"/\"ipv6
}'"
266 f_log "please enable the local dns server to use adblock" "${rc}"
270 # check running firewall
272 check="$(/usr/sbin/iptables -vnL | grep -F "DROP")"
276 f_log "please enable the local firewall to use adblock" "${rc}"
280 # check ipv4/iptables configuration
282 if [ -n "${adb_wanif4}" ]
284 f_firewall "IPv4" "nat" "A" "prerouting_rule" "adb-nat" "-p tcp -d ${adb_nullipv4} -m multiport --dports 80,443 -j DNAT --to-destination ${adb_ipv4}:${adb_nullport}"
285 f_firewall "IPv4" "filter" "A" "forwarding_rule" "adb-fwd" "-p tcp -d ${adb_nullipv4} -j REJECT --reject-with tcp-reset"
286 f_firewall "IPv4" "filter" "A" "forwarding_rule" "adb-fwd" "-d ${adb_nullipv4} -j REJECT --reject-with icmp-host-unreachable"
287 f_firewall "IPv4" "filter" "A" "output_rule" "adb-out" "-p tcp -d ${adb_nullipv4} -j REJECT --reject-with tcp-reset"
288 f_firewall "IPv4" "filter" "A" "output_rule" "adb-out" "-d ${adb_nullipv4} -j REJECT --reject-with icmp-host-unreachable"
289 if [ $((adb_forcedns)) -eq 1 ]
291 f_firewall "IPv4" "nat" "A" "prerouting_rule" "adb-dns" "-p udp --dport 53 -j DNAT --to-destination ${adb_ipv4}:53"
292 f_firewall "IPv4" "nat" "A" "prerouting_rule" "adb-dns" "-p tcp --dport 53 -j DNAT --to-destination ${adb_ipv4}:53"
294 if [ "${fw_done}" = "true" ]
296 f_log "created volatile IPv4 firewall ruleset"
301 # check ipv6/ip6tables configuration
303 if [ -n "${adb_wanif6}" ]
305 f_firewall "IPv6" "nat" "A" "PREROUTING" "adb-nat" "-p tcp -d ${adb_nullipv6} -m multiport --dports 80,443 -j DNAT --to-destination [${adb_ipv6}]:${adb_nullport}"
306 f_firewall "IPv6" "filter" "A" "forwarding_rule" "adb-fwd" "-p tcp -d ${adb_nullipv6} -j REJECT --reject-with tcp-reset"
307 f_firewall "IPv6" "filter" "A" "forwarding_rule" "adb-fwd" "-d ${adb_nullipv6} -j REJECT --reject-with icmp6-addr-unreachable"
308 f_firewall "IPv6" "filter" "A" "output_rule" "adb-out" "-p tcp -d ${adb_nullipv6} -j REJECT --reject-with tcp-reset"
309 f_firewall "IPv6" "filter" "A" "output_rule" "adb-out" "-d ${adb_nullipv6} -j REJECT --reject-with icmp6-addr-unreachable"
310 if [ $((adb_forcedns)) -eq 1 ]
312 f_firewall "IPv6" "nat" "A" "PREROUTING" "adb-dns" "-p udp --dport 53 -j DNAT --to-destination [${adb_ipv6}]:53"
313 f_firewall "IPv6" "nat" "A" "PREROUTING" "adb-dns" "-p tcp --dport 53 -j DNAT --to-destination [${adb_ipv6}]:53"
315 if [ "${fw_done}" = "true" ]
317 f_log "created volatile IPv6 firewall ruleset"
322 # check volatile adblock uhttpd instance configuration
324 rc="$(ps | grep -q "[u]httpd.*\-h /www/adblock"; printf ${?})"
327 if [ -n "${adb_wanif4}" ] && [ -n "${adb_wanif6}" ]
329 uhttpd -h "/www/adblock" -k 0 -N 100 -t 0 -T 1 -D -S -E "/index.html" -p "${adb_ipv4}:${adb_nullport}" -p "[${adb_ipv6}]:${adb_nullport}"
331 elif [ -n "${adb_wanif4}" ]
333 uhttpd -h "/www/adblock" -k 0 -N 100 -t 0 -T 1 -D -S -E "/index.html" -p "${adb_ipv4}:${adb_nullport}"
336 uhttpd -h "/www/adblock" -k 0 -N 100 -t 0 -T 1 -D -S -E "/index.html" -p "[${adb_ipv6}]:${adb_nullport}"
341 f_log "created volatile uhttpd instance"
343 f_log "failed to initialize volatile uhttpd instance" "${rc}"
348 # check whitelist entries
350 if [ -s "${adb_whitelist}" ]
352 awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
355 # remove no longer used opkg package list
360 # f_depend: check package dependencies
367 check="$(printf "${pkg_list}" | grep "^${package} -")"
371 f_log "package '${package}' not found" "${rc}"
376 # f_firewall: set iptables rules for ipv4/ipv6
381 local iptv4="/usr/sbin/iptables"
382 local iptv6="/usr/sbin/ip6tables"
390 # select appropriate iptables executable
392 if [ "${proto}" = "IPv4" ]
399 # check whether iptables rule already applied and proceed accordingly
401 rc="$("${ipt}" -w -t "${table}" -C "${chain}" -m comment --comment "${notes}" ${rules}; printf ${?})"
404 "${ipt}" -w -t "${table}" -"${ctype}" "${chain}" -m comment --comment "${notes}" ${rules}
410 f_log "failed to initialize volatile ${proto} firewall rule '${notes}'" "${rc}"
416 # f_log: log messages to stdout and syslog
425 # check for terminal session
432 # log to different output devices and set log class accordingly
434 if [ -n "${log_msg}" ]
436 if [ $((log_rc)) -gt 0 ]
439 log_rc=", rc: ${log_rc}"
440 log_msg="${log_msg}${log_rc}"
442 /usr/bin/logger ${log_parm} -t "adblock[${adb_pid}] ${class}" "${log_msg}" 2>&1
446 ################################################
447 # f_space: check mount points/space requirements
455 av_space="$(df "${mp}" | tail -n1 | awk '{printf $4}')"
456 if [ $((av_space)) -lt $((adb_minspace)) ]
463 # f_cntconfig: calculate counters in config
472 for list in $(ls -ASr "${adb_dnsdir}/${adb_dnsprefix}."*)
474 src_name="${list/*./}"
475 count="$(wc -l < "${list}")"
476 if [ -n "${adb_wanif4}" ] && [ -n "${adb_wanif6}" ]
480 ${adb_uci} -q set "adblock.${src_name}.adb_src_count=${count}"
481 count_sum=$((count_sum + count))
483 ${adb_uci} -q set "adblock.global.adb_overall_count=${count_sum}"
486 # f_rmconfig: remove counters & timestamps in given config sections
492 for list in ${rm_done}
494 src_name="${list/*./}"
495 if [ -n "${restore_done}" ]
497 ${adb_uci} -q set "adblock.${src_name}.adb_src_timestamp=list restored"
499 ${adb_uci} -q delete "adblock.${src_name}.adb_src_count"
500 ${adb_uci} -q delete "adblock.${src_name}.adb_src_timestamp"
506 # f_restore: restore last adblock list backups and restart dnsmasq
513 # remove bogus adblock lists
515 if [ -n "${adb_revsrclist}" ]
517 rm_done="$(find "${adb_dnsdir}" -maxdepth 1 -type f \( ${adb_revsrclist} \) -print -exec rm -f "{}" \;)"
519 if [ $((rc)) -eq 0 ] && [ -n "${rm_done}" ]
521 f_rmconfig "${rm_done}"
522 f_log "all bogus adblock lists removed"
523 elif [ $((rc)) -ne 0 ]
525 f_log "error during removal of bogus adblock lists" "${rc}"
532 if [ "${backup_ok}" = "true" ]
534 restore_done="$(find "${adb_dir_backup}" -maxdepth 1 -type f -name "${adb_dnsprefix}.*" -print -exec cp -pf "{}" "${adb_dnsdir}" \;)"
536 if [ $((rc)) -eq 0 ] && [ -n "${restore_done}" ]
538 f_log "all available backups restored"
539 elif [ $((rc)) -ne 0 ] && [ -n "${restore_done}" ]
541 f_log "error during restore of adblock lists" "${rc}"
545 f_log "backup service disabled, nothing to restore"
548 # (re-)try dnsmasq restart without bogus adblock lists / with backups
550 if [ -n "${restore_done}" ] || [ -n "${rm_done}" ]
552 /etc/init.d/dnsmasq restart
554 rc="$(ps | grep -q "[d]nsmasq"; printf ${?})"
559 f_log "adblock lists with overall ${adb_count} domains loaded"
562 f_log "dnsmasq restart failed, please check 'logread
' output" "${rc}"
568 # f_exit: delete (temporary) files, generate statistics and exit
574 local iptv4="/usr/sbin/iptables"
575 local iptv6="/usr/sbin/ip6tables"
577 # delete temporary files & directories
579 if [ -f "${adb_tmpfile}" ]
581 rm -f "${adb_tmpfile}"
583 if [ -d "${adb_tmpdir}" ]
585 rm -rf "${adb_tmpdir}"
588 # final log message and iptables statistics
592 if [ -n "${adb_wanif4}" ]
594 ipv4_adblock="$(${iptv4} -t nat -vnL | awk '$11 ~
/^adb-nat$
/ {sum += $1} END
{printf sum}')"
595 ipv4_adblock="$((${ipv4_adblock} + $(${iptv4} -vnL | awk '$11 ~ /^adb-(fwd|out)$/ {sum += $1} END {printf sum}')))"
597 if [ -n "${adb_wanif6}" ]
599 ipv6_adblock="$
(${iptv6} -t nat
-vnL |
awk '$10 ~ /^adb-nat$/ {sum += $1} END {printf sum}')"
600 ipv6_adblock="$
((${ipv6_adblock} + $(${iptv6} -vnL | awk '$10 ~ /^adb-(fwd|out)$/ {sum += $1} END
{printf sum}')))"
602 if [ -n "$(${adb_uci} -q changes adblock)" ]
604 ${adb_uci} -q commit "adblock"
606 f_log "firewall statistics (IPv4/IPv6): ${ipv4_adblock}/${ipv6_adblock} ad related packets blocked"
607 f_log "domain adblock processing finished successfully (${adb_scriptver}, ${openwrt_version}, $(/bin/date "+%d.%m.%Y %H:%M:%S"))"
608 elif [ $((rc)) -gt 0 ]
610 if [ -n "$(${adb_uci} -q changes adblock)" ]
612 ${adb_uci} -q revert "adblock"
614 f_log "domain adblock processing failed (${adb_scriptver}, ${openwrt_version}, $(/bin/date "+%d.%m.%Y %H:%M:%S"))"
618 rm -f "${adb_pidfile}"