1 #!/bin/sh /etc/rc.common
2 # Copyright 2017-2020 Stan Grishin (stangri@melmac.net)
3 # shellcheck disable=SC2039,SC1091,SC2016
6 # shellcheck disable=SC2034
8 # shellcheck disable=SC2034
12 extra_command
'check' 'Checks if specified domain is found in current block-list'
13 extra_command
'dl' 'Force-downloads all enabled block-list'
14 extra_command
'killcache' 'Delete all cached files'
15 extra_command
'sizes' 'Displays the file-sizes of enabled block-listo'
16 extra_command
'show' 'Shows the service last-run status'
17 extra_command
'version' 'Show version information'
19 readonly packageName
='simple-adblock'
20 readonly serviceName
="$packageName $PKG_VERSION"
21 readonly addnhostsFile
="/var/run/${packageName}.addnhosts"
22 readonly addnhostsCache
="/var/run/${packageName}.addnhosts.cache"
23 readonly addnhostsGzip
="/etc/${packageName}.addnhosts.gz"
24 readonly addnhostsOutputFilter
='s|^|127.0.0.1 |;s|$||'
25 readonly addnhostsOutputFilterIPv6
='s|^|:: |;s|$||'
26 readonly dnsmasqFile
="/var/dnsmasq.d/${packageName}"
27 readonly dnsmasqCache
="/var/run/${packageName}.dnsmasq.cache"
28 readonly dnsmasqGzip
="/etc/${packageName}.dnsmasq.gz"
29 readonly dnsmasqOutputFilter
='s|^|local=/|;s|$|/|'
30 readonly ipsetFile
="/var/dnsmasq.d/${packageName}.ipset"
31 readonly ipsetCache
="/var/run/${packageName}.ipset.cache"
32 readonly ipsetGzip
="/etc/${packageName}.ipset.gz"
33 readonly ipsetOutputFilter
='s|^|ipset=/|;s|$|/adb|'
34 readonly serversFile
="/var/run/${packageName}.servers"
35 readonly serversCache
="/var/run/${packageName}.servers.cache"
36 readonly serversGzip
="/etc/${packageName}.servers.gz"
37 readonly serversOutputFilter
='s|^|server=/|;s|$|/|'
38 readonly unboundFile
="/var/lib/unbound/adb_list.${packageName}"
39 readonly unboundCache
="/var/run/${packageName}.unbound.cache"
40 readonly unboundGzip
="/etc/${packageName}.unbound.gz"
41 readonly unboundOutputFilter
='s|^|local-zone: "|;s|$|" static|'
42 readonly A_TMP
="/var/${packageName}.hosts.a.tmp"
43 readonly B_TMP
="/var/${packageName}.hosts.b.tmp"
44 readonly jsonFile
="/var/run/${packageName}.json"
45 readonly sharedMemoryError
="/dev/shm/$packageName-error"
46 readonly sharedMemoryOutput
="/dev/shm/$packageName-output"
47 readonly hostsFilter
='/localhost/d;/^#/d;/^[^0-9]/d;s/^0\.0\.0\.0.//;s/^127\.0\.0\.1.//;s/[[:space:]]*#.*$//;s/[[:cntrl:]]$//;s/[[:space:]]//g;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
48 readonly domainsFilter
='/^#/d;s/[[:space:]]*#.*$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
49 readonly _OK_
='\033[0;32m\xe2\x9c\x93\033[0m'
50 readonly _FAIL_
='\033[0;31m\xe2\x9c\x97\033[0m'
51 readonly __OK__
='\033[0;32m[\xe2\x9c\x93]\033[0m'
52 readonly __FAIL__
='\033[0;31m[\xe2\x9c\x97]\033[0m'
53 readonly _ERROR_
='\033[0;31mERROR\033[0m'
54 readonly _WARNING_
='\033[0;33mWARNING\033[0m'
56 version
() { echo "$PKG_VERSION"; }
61 statusNoInstall
) _ret
="$serviceName is not installed or not found";;
62 statusStopped
) _ret
="Stopped";;
63 statusStarting
) _ret
="Starting";;
64 statusRestarting
) _ret
="Restarting";;
65 statusForceReloading
) _ret
="Force Reloading";;
66 statusDownloading
) _ret
="Downloading";;
67 statusProcessing
) _ret
="Processing";;
68 statusError
) _ret
="Error";;
69 statusWarning
) _ret
="Warning";;
70 statusFail
) _ret
="Fail";;
71 statusSuccess
) _ret
="Success";;
78 errorOutputFileCreate
) _ret
="failed to create $outputFile file";;
79 errorFailDNSReload
) _ret
="failed to restart/reload DNS resolver";;
80 errorSharedMemory
) _ret
="failed to access shared memory";;
81 errorSorting
) _ret
="failed to sort data file";;
82 errorOptimization
) _ret
="failed to optimize data file";;
83 errorAllowListProcessing
) _ret
="failed to process allow-list";;
84 errorDataFileFormatting
) _ret
="failed to format data file";;
85 errorMovingDataFile
) _ret
="failed to move data file '${A_TMP}' to '${outputFile}'";;
86 errorCreatingCompressedCache
) _ret
="failed to create compressed cache";;
87 errorRemovingTempFiles
) _ret
="failed to remove temporary files";;
88 errorRestoreCompressedCache
) _ret
="failed to unpack compressed cache";;
89 errorRestoreCache
) _ret
="failed to move '$outputCache' to '$outputFile'";;
90 errorOhSnap
) _ret
="failed to create block-list or restart DNS resolver";;
91 errorStopping
) _ret
="failed to stop $serviceName";;
92 errorDNSReload
) _ret
="failed to reload/restart DNS resolver";;
93 errorDownloadingConfigUpdate
) _ret
="failed to download Config Update file";;
94 errorDownloadingList
) _ret
="failed to download";;
95 errorParsingList
) _ret
="failed to parse";;
96 errorParsingConfigUpdate
) _ret
="failed to parse Config Update file";;
101 output_ok
() { output
1 "$_OK_"; output
2 "$__OK__\\n"; }
102 output_okn
() { output
1 "$_OK_\\n"; output
2 "$__OK__\\n"; }
103 output_fail
() { output
1 "$_FAIL_"; output
2 "$__FAIL__\\n"; }
104 output_failn
() { output
1 "$_FAIL_\\n"; output
2 "$__FAIL__\\n"; }
105 str_replace
() { printf "%b" "$1" |
sed -e "s/$(printf "%b
" "$2")/$(printf "%b
" "$3")/g"; }
106 str_contains
() { test "$1" != "$(str_replace "$1" "$2" '')"; }
107 compare_values
() { test "$(printf '%s\n' "$@
" | sort -V | head -n 1)" != "$1"; }
108 is_chaos_calmer
() { ubus
-S call system board |
grep -q 'Chaos Calmer'; }
109 led_on
(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'default-on' > "${1}/trigger" 2>&1; fi; }
110 led_off(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'none' > "${1}/trigger" 2>&1; fi; }
111 dnsmasq_hup
() { killall
-q -HUP dnsmasq
; }
112 dnsmasq_kill
() { killall
-q -KILL dnsmasq
; }
113 dnsmasq_restart
() { /etc
/init.d
/dnsmasq restart
>/dev
/null
2>&1; }
114 unbound_restart
() { /etc
/init.d
/unbound restart
>/dev
/null
2>&1; }
115 is_force_dns_active
() { iptables-save |
grep -q -w -- '--dport 53'; }
116 is_present
() { command -v "$1" >/dev
/null
2>&1; }
119 # Can take a single parameter (text) to be output at any verbosity
120 # Or target verbosity level and text to be output at specifc verbosity
121 local msg memmsg logmsg
122 if [ $# -ne 1 ]; then
123 if [ $
((verbosity
& $1)) -gt 0 ] ||
[ "$verbosity" = "$1" ]; then shift; else return 0; fi
125 [ -t 1 ] && printf "%b" "$1"
126 msg
="${1//$serviceName /service }";
127 if [ "$(printf "%b
" "$msg" | wc -l)" -gt 0 ]; then
128 [ -s "$sharedMemoryOutput" ] && memmsg
="$(cat "$sharedMemoryOutput")"
129 logmsg
="$(printf "%b
" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
130 logger
-t "${packageName:-service} [$$]" "$(printf "%b
" "$logmsg")"
131 rm -f "$sharedMemoryOutput"
133 printf "%b" "$msg" >> "$sharedMemoryOutput"
137 serviceEnabled
=''; forceDNS
=''; forceDNSPorts
=''; parallelDL
=''; debug
='';
138 compressedCache
=''; ipv6Enabled
=''; configUpdateEnabled
=''; configUpdateURL
='';
139 bootDelay
=''; dlTimeout
=''; curlRetry
=''; verbosity
=''; led
='';
140 targetDNS
=''; dnsInstance
='';
141 allowed_domains
=''; allowed_domains_urls
='';
142 blocked_domains
=''; blocked_domains_urls
=''; blocked_hosts_urls
='';
143 dl_command
=''; dl_flag
=''; isSSLSupported
=''; allowIDN
='';
144 outputFilter
=''; outputFilterIPv6
=''; outputFile
=''; outputGzip
=''; outputCache
='';
147 load_package_config
() {
148 config_load
"$packageName"
149 config_get_bool serviceEnabled
'config' 'enabled' 1
150 config_get_bool forceDNS
'config' 'force_dns' 1
151 config_get_bool parallelDL
'config' 'parallel_downloads' 1
152 config_get_bool debug
'config' 'debug' 0
153 config_get_bool compressedCache
'config' 'compressed_cache' 0
154 config_get_bool ipv6Enabled
'config' 'ipv6_enabled' 0
155 config_get_bool configUpdateEnabled
'config' 'config_update_enabled' 0
156 config_get forceDNSPorts
'config' 'force_dns_port' '53 853'
157 config_get bootDelay
'config' 'boot_delay' '120'
158 config_get dlTimeout
'config' 'download_timeout' '20'
159 config_get curlRetry
'config' 'curl_retry' '3'
160 config_get verbosity
'config' 'verbosity' '2'
161 config_get led
'config' 'led'
162 config_get targetDNS
'config' 'dns' 'dnsmasq.servers'
163 config_get dnsInstance
'config' 'dns_instance' '0'
164 config_get allowed_domains
'config' 'allowed_domain'
165 config_get allowed_domains_urls
'config' 'allowed_domains_url'
166 config_get blocked_domains
'config' 'blocked_domain'
167 config_get blocked_domains_urls
'config' 'blocked_domains_url'
168 config_get blocked_hosts_urls
'config' 'blocked_hosts_url'
169 config_get configUpdateURL
'config' 'config_update_url' 'https://cdn.jsdelivr.net/gh/openwrt/packages/net/simple-adblock/files/simple-adblock.conf.update'
171 if [ "$targetDNS" != 'dnsmasq.addnhosts' ] && [ "$targetDNS" != 'dnsmasq.conf' ] && \
172 [ "$targetDNS" != 'dnsmasq.servers' ] && [ "$targetDNS" != 'unbound.adb_list' ] && \
173 [ "$targetDNS" != 'dnsmasq.ipset' ] ; then
174 targetDNS
='dnsmasq.servers'
179 outputFilter
="$addnhostsOutputFilter"
180 outputFile
="$addnhostsFile"
181 outputCache
="$addnhostsCache"
182 outputGzip
="$addnhostsGzip"
183 [ "$ipv6Enabled" -gt 0 ] && outputFilterIPv6
="$addnhostsOutputFilterIPv6"
184 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
185 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
186 rm -f "$serversFile" "$serversCache" "$serversGzip"
187 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
190 outputFilter
="$dnsmasqOutputFilter"
191 outputFile
="$dnsmasqFile"
192 outputCache
="$dnsmasqCache"
193 outputGzip
="$dnsmasqGzip"
194 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
195 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
196 rm -f "$serversFile" "$serversCache" "$serversGzip"
197 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
200 outputFilter
="$ipsetOutputFilter"
201 outputFile
="$ipsetFile"
202 outputCache
="$ipsetCache"
203 outputGzip
="$ipsetGzip"
204 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
205 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
206 rm -f "$serversFile" "$serversCache" "$serversGzip"
207 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
210 outputFilter
="$serversOutputFilter"
211 outputFile
="$serversFile"
212 outputCache
="$serversCache"
213 outputGzip
="$serversGzip"
214 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
215 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
216 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
217 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
220 outputFilter
="$unboundOutputFilter"
221 outputFile
="$unboundFile"
222 outputCache
="$unboundCache"
223 outputGzip
="$unboundGzip"
224 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
225 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
226 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
227 rm -f "$serversFile" "$serversCache" "$serversGzip"
230 if [ -z "${verbosity##*[!0-9]*}" ] ||
[ "$verbosity" -lt 0 ] ||
[ "$verbosity" -gt 2 ]; then
233 .
/lib
/functions
/network.sh
234 .
/usr
/share
/libubox
/jshn.sh
235 is_present
'gawk' && awk='gawk'
236 if ! is_present
'/usr/libexec/grep-gnu' ||
! is_present
'/usr/libexec/sed-gnu' || \
237 ! is_present
'/usr/libexec/sort-coreutils' ||
! is_present
'gawk'; then
238 local s
="opkg update; opkg --force-overwrite install"
239 is_present
'gawk' || s
="$s gawk"
240 is_present
'/usr/libexec/grep-gnu' || s
="$s grep"
241 is_present
'/usr/libexec/sed-gnu' || s
="$s sed"
242 is_present
'/usr/libexec/sort-coreutils' || s
="$s coreutils-sort"
243 output
"$_WARNING_: Some recommended packages are missing, install them by running:\\n"
246 # Prefer curl because it supports the file:// scheme.
247 if is_present
'curl'; then
248 dl_command
="curl --insecure --retry $curlRetry --connect-timeout $dlTimeout --silent"
250 elif is_present wget
&& wget
--version 2>/dev
/null |
grep -q "+https"; then
251 dl_command
="wget --no-check-certificate --timeout $dlTimeout -q"
254 dl_command
="uclient-fetch --no-check-certificate --timeout $dlTimeout -q"
257 led
="${led:+/sys/class/leds/$led}"
258 if curl
--version 2>/dev
/null |
grep -q "https" \
259 || wget
--version 2>/dev
/null |
grep -q "+https" \
260 ||
grep -q "libustream-mbedtls" /usr
/lib
/opkg
/status \
261 ||
grep -q "libustream-openssl" /usr
/lib
/opkg
/status \
262 ||
grep -q "libustream-wolfssl" /usr
/lib
/opkg
/status
; then
270 wan_if
=''; wan_gw
='';
273 if [ "$debug" -ne 0 ]; then
274 exec 1>>/tmp
/simple-adblock.log
279 if [ "$serviceEnabled" -eq 0 ]; then
282 output
"$packageName is currently disabled.\\n"
283 output
"Run the following commands before starting service again:\\n"
284 output
"uci set ${packageName}.config.enabled='1'; uci commit $packageName;\\n"
291 dnsmasq.addnhosts | dnsmasq.conf | dnsmasq.ipset | dnsmasq.servers
)
292 if dnsmasq
-v 2>/dev
/null |
grep -q 'no-IDN' ||
! dnsmasq
-v 2>/dev
/null |
grep -q -w 'IDN'; then
304 if dnsmasq
-v 2>/dev
/null |
grep -q 'no-ipset' ||
! dnsmasq
-v 2>/dev
/null |
grep -q -w 'ipset'; then
305 output
"$_ERROR_: DNSMASQ ipset support is enabled in $packageName, but DNSMASQ is either not installed or installed DNSMASQ does not support ipsets!\\n"
306 targetDNS
='dnsmasq.servers'
308 if ! ipset
help hash:net
>/dev
/null
2>&1; then
309 output
"$_ERROR_: DNSMASQ ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type!\\n"
310 targetDNS
='dnsmasq.servers'
315 [ ! -d "${outputFile%/*}" ] && mkdir
-p "${outputFile%/*}"
316 [ ! -d "${outputCache%/*}" ] && mkdir
-p "${outputFile%/*}"
317 [ ! -d "${outputGzip%/*}" ] && mkdir
-p "${outputFile%/*}"
318 cacheOps
'testGzip' && return 0
319 network_flush_cache
; network_find_wan wan_if
; network_get_gateway wan_gw
"$wan_if";
320 [ -n "$wan_gw" ] && return 0
321 output
"$_ERROR_: $serviceName failed to discover WAN gateway.\\n"; return 1;
325 local cfg
="$1" param
="$2"
328 if [ "$(uci -q get dhcp."$cfg".serversfile)" = "$serversFile" ]; then
329 uci
-q del dhcp.
"$cfg".serversfile
331 if ! uci
-q get dhcp.
"$cfg".addnhosts |
grep -q "$addnhostsFile"; then
332 uci add_list dhcp.
"$cfg".addnhosts
="$addnhostsFile"
335 dnsmasq.conf|dnsmasq.ipset|unbound.adb_list|cleanup
)
336 uci
-q del_list dhcp.
"$cfg".addnhosts
="$addnhostsFile"
337 if [ "$(uci -q get dhcp."$cfg".serversfile)" = "$serversFile" ]; then
338 uci
-q del dhcp.
"$cfg".serversfile
342 uci
-q del_list dhcp.
"$cfg".addnhosts
="$addnhostsFile"
343 if [ "$(uci -q get dhcp."$cfg".serversfile)" != "$serversFile" ]; then
344 uci
set dhcp.
"$cfg".serversfile
="$serversFile"
351 local param output_text i
354 if [ ! -s "$outputFile" ]; then
355 jsonOps
set status
"statusFail"
356 jsonOps add error
"errorOutputFileCreate"
357 output
"$_ERROR_: $(getErrorText 'errorOutputFileCreate')!\\n"
362 if [ "$dnsInstance" = "*" ]; then
363 config_foreach dnsmasqOps
'dnsmasq' "$targetDNS"
364 elif [ -n "$dnsInstance" ]; then
365 for i
in $dnsInstance; do
366 dnsmasqOps
"@dnsmasq[$i]" "$targetDNS"
371 dnsmasq.addnhosts|dnsmasq.servers
)
373 output_text
='Reloading DNSMASQ'
375 dnsmasq.conf|dnsmasq.ipset
)
376 param
=dnsmasq_restart
377 output_text
='Restarting DNSMASQ'
380 param
=unbound_restart
381 output_text
='Restarting Unbound'
385 if [ -n "$(uci changes dhcp)" ]; then
387 if [ "$param" = 'unbound_restart' ]; then
388 param
='dnsmasq_restart; unbound_restart;'
389 output_text
='Restarting Unbound/DNSMASQ'
391 param
=dnsmasq_restart
392 output_text
='Restarting DNSMASQ'
395 output
1 "$output_text "
396 output
2 "$output_text "
397 jsonOps
set message
"$output_text"
398 if eval "$param"; then
399 jsonOps
set status
"statusSuccess"
404 jsonOps
set status
"statusFail"
405 jsonOps add error
"errorDNSReload"
406 output
"$_ERROR_: $(getErrorText 'errorDNSReload')!\\n"
412 dnsmasq.addnhosts | dnsmasq.servers
)
415 dnsmasq.conf | dnsmasq.ipset
)
416 param
=dnsmasq_restart
419 param
=unbound_restart
422 if [ -n "$(uci changes dhcp)" ]; then
424 if [ "$param" = 'unbound_restart' ]; then
425 param
='dnsmasq_restart; unbound_restart;'
427 param
=dnsmasq_restart
435 dnsmasq.addnhosts | dnsmasq.conf | dnsmasq.ipset | dnsmasq.servers
)
436 param
=dnsmasq_restart
439 param
=unbound_restart
449 # shellcheck disable=SC2034
450 local action
="$1" param
="$2" value
="$3"
451 local status message error stats
452 local reload restart curReload curRestart ret i
453 if [ -s "$jsonFile" ]; then
454 json_load_file
"$jsonFile" 2>/dev
/null
455 json_select
'data' 2>/dev
/null
456 for i
in status message error stats reload restart
; do
457 json_get_var
$i "$i" 2>/dev
/null
464 curReload
="$parallelDL $debug $dlTimeout $allowed_domains $blocked_domains $allowed_domains_urls $blocked_domains_urls $blocked_hosts_urls $targetDNS $configUpdateEnabled $configUpdateURL"
465 curRestart
="$compressedCache $forceDNS $led $forceDNSPorts"
466 if [ ! -s "$jsonFile" ]; then
468 elif [ "$curReload" != "$reload" ]; then
470 elif [ "$curRestart" != "$restart" ]; then
476 printf "%b" "$(eval echo "\$
$param")"; return;;
480 if [ -n "$(eval echo "\$
$param")" ]; then
481 value
="$(eval echo "\$
$param") ${value}"
483 eval "$param"='${value}'
488 unset status message error stats
;;
490 unset reload restart
;;
498 reload
="$parallelDL $debug $dlTimeout $allowed_domains $blocked_domains $allowed_domains_urls $blocked_domains_urls $blocked_hosts_urls $targetDNS $configUpdateEnabled $configUpdateURL"
499 restart
="$compressedCache $forceDNS $led $forceDNSPorts"
502 eval "$param"='$value';;
507 json_add_object
'data'
508 json_add_string version
"$PKG_VERSION"
509 json_add_string status
"$status"
510 json_add_string message
"$message"
511 json_add_string error
"$error"
512 json_add_string stats
"$stats"
513 json_add_string reload
"$reload"
514 json_add_string restart
"$restart"
516 json_dump
> "$jsonFile"
524 [ -s "$outputFile" ] && { mv -f "$outputFile" "$outputCache"; true
> "$outputFile"; } >/dev
/null
2>/dev
/null
528 [ -s "$outputCache" ] && mv "$outputCache" "$outputFile" >/dev
/null
2>/dev
/null
532 [ -s "$outputCache" ]
536 [ -s "$outputGzip" ] && gzip -t -c "$outputGzip"
540 R_TMP
="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
541 if gzip < "$outputFile" > "$R_TMP"; then
542 if mv "$R_TMP" "$outputGzip"; then
553 expand|unpack|expandGzip|unpackGzip
)
554 [ -s "$outputGzip" ] && gzip -dc < "$outputGzip" > "$outputCache"
561 local label
type D_TMP R_TMP
562 if [ -z "$1" ] ||
[ -z "$2" ] ||
[ -z "$3" ]; then return 1; fi
563 label
="${1##*//}"; label
="${label%%/*}";
564 if [ "$2" = 'hosts' ]; then
565 label
="Hosts: $label"; filter
="$hostsFilter";
567 label
="Domains: $label"; filter
="$domainsFilter";
569 if [ "$3" = 'blocked' ]; then
570 type='Blocked'; D_TMP
="$B_TMP";
572 type='Allowed'; D_TMP
="$A_TMP";
574 if [ "${1:0:5}" == "https" ] && [ -z "$isSSLSupported" ]; then
576 output
2 "[DL] $type $label $__FAIL__\\n"
577 echo "errorNoSSLSupport|${1}" >> "$sharedMemoryError"
580 while [ -z "$R_TMP" ] ||
[ -e "$R_TMP" ]; do
581 R_TMP
="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
583 if ! $dl_command "$1" $dl_flag "$R_TMP" 2>/dev
/null ||
[ ! -s "$R_TMP" ]; then
585 output
2 "[DL] $type $label $__FAIL__\\n"
586 echo "errorDownloadingList|${1}" >> "$sharedMemoryError"
588 sed -i "$filter" "$R_TMP"
589 if [ ! -s "$R_TMP" ]; then
591 output
2 "[DL] $type $label $__FAIL__\\n"
592 echo "errorParsingList|${1}" >> "$sharedMemoryError"
594 cat "${R_TMP}" >> "$D_TMP"
596 output
2 "[DL] $type $label $__OK__\\n"
603 process_config_update
() {
605 [ "$configUpdateEnabled" -eq 0 ] && return 0
606 label
="${1##*//}"; label
="${label%%/*}";
607 while [ -z "$R_TMP" ] ||
[ -e "$R_TMP" ]; do
608 R_TMP
="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
610 if ! $dl_command "$1" $dl_flag "$R_TMP" 2>/dev
/null ||
[ ! -s "$R_TMP" ]; then
612 output
2 "[DL] Config Update: $label $__FAIL__\\n"
613 jsonOps add error
"errorDownloadingConfigUpdate"
615 if [ -s "$R_TMP" ] && sed -f "$R_TMP" -i /etc
/config
/simple-adblock
2>/dev
/null
; then
617 output
2 "[DL] Config Update: $label $__OK__\\n"
620 output
2 "[DL] Config Update: $label $__FAIL__\\n"
621 jsonOps add error
"errorParsingConfigUpdate"
629 local hf w_filter j
=0 R_TMP
631 jsonOps
set message
"$(getStatusText "statusDownloading
")..."
632 jsonOps
set status
"statusDownloading"
634 rm -f "$A_TMP" "$B_TMP" "$outputFile" "$outputCache" "$outputGzip"
635 if [ "$($awk '/^MemFree/ {print int($2/1000)}' "/proc
/meminfo
")" -lt 32 ]; then
636 output
3 'Low free memory, restarting resolver... '
637 if dnsOps
'quiet'; then
643 touch $A_TMP; touch $B_TMP;
644 output
1 'Downloading lists '
645 process_config_update
"$configUpdateURL"
646 rm -f "$sharedMemoryError"
647 if [ -n "$blocked_hosts_urls" ]; then
648 for hf
in ${blocked_hosts_urls}; do
649 if [ "$parallelDL" -gt 0 ]; then
650 process_url
"$hf" 'hosts' 'blocked' &
652 process_url
"$hf" 'hosts' 'blocked'
656 if [ -n "$blocked_domains_urls" ]; then
657 for hf
in ${blocked_domains_urls}; do
658 if [ "$parallelDL" -gt 0 ]; then
659 process_url
"$hf" 'domains' 'blocked' &
661 process_url
"$hf" 'domains' 'blocked'
665 if [ -n "$allowed_domains_urls" ]; then
666 for hf
in ${allowed_domains_urls}; do
667 if [ "$parallelDL" -gt 0 ]; then
668 process_url
"$hf" 'domains' 'allowed' &
670 process_url
"$hf" 'domains' 'allowed'
676 if [ -s "$sharedMemoryError" ]; then
677 while IFS
= read -r line
; do
678 jsonOps add error
"$line"
679 done < "$sharedMemoryError"
680 rm -f "$sharedMemoryError"
683 [ -n "$blocked_domains" ] && for hf
in ${blocked_domains}; do echo "$hf" |
sed "$domainsFilter" >> $B_TMP; done
684 allowed_domains
="${allowed_domains}
686 [ -n "$allowed_domains" ] && for hf
in ${allowed_domains}; do hf
="$(echo "$hf" | sed 's/\./\\./g')"; w_filter
="$w_filter/${hf}$/d;"; done
688 [ ! -s "$B_TMP" ] && return 1
690 output
1 'Processing downloads '
691 output
2 'Sorting combined list '
692 jsonOps
set message
"$(getStatusText "statusProcessing
"): sorting combined list"
693 if [ "$allowIDN" -gt 0 ]; then
694 if sort -u "$B_TMP" > "$A_TMP"; then
698 jsonOps add error
"errorSorting"
701 if sort -u "$B_TMP" |
grep -E -v '[^a-zA-Z0-9=/.-]' > "$A_TMP"; then
705 jsonOps add error
"errorSorting"
709 if [ "$targetDNS" = 'dnsmasq.conf' ] || \
710 [ "$targetDNS" = 'dnsmasq.ipset' ] || \
711 [ "$targetDNS" = 'dnsmasq.servers' ] || \
712 [ "$targetDNS" = 'unbound.adb_list' ]; then
713 # TLD optimization written by Dirk Brenken (dev@brenken.org)
714 output
2 'Optimizing combined list '
715 jsonOps
set message
"$(getStatusText "statusProcessing
"): optimizing combined list"
716 # sed -E 'G;:t;s/(.*)(\.)(.*)(\n)(.*)/\1\4\5\2\3/;tt;s/(.*)\n(\.)(.*)/\3\2\1/' is actually slower than command below
717 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$A_TMP" > "$B_TMP"; then
718 if sort "$B_TMP" > "$A_TMP"; then
719 if $awk '{if(NR=1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "$A_TMP" > "$B_TMP"; then
720 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$B_TMP" > "$A_TMP"; then
721 if sort -u "$A_TMP" > "$B_TMP"; then
725 jsonOps add error
"errorOptimization"
730 jsonOps add error
"errorOptimization"
734 jsonOps add error
"errorOptimization"
739 jsonOps add error
"errorOptimization"
743 jsonOps add error
"errorOptimization"
750 output
2 'Allowing domains '
751 jsonOps
set message
"$(getStatusText "statusProcessing
"): allowing domains"
752 if sed -i "$w_filter" "$B_TMP"; then
756 jsonOps add error
"errorAllowListProcessing"
759 output
2 'Formatting merged file '
760 jsonOps
set message
"$(getStatusText "statusProcessing
"): formatting merged file"
761 if [ -z "$outputFilterIPv6" ]; then
762 if sed "$outputFilter" "$B_TMP" > "$A_TMP"; then
766 jsonOps add error
"errorDataFileFormatting"
771 if sed "$outputFilter" "$B_TMP" > "$A_TMP" && \
772 sed "$outputFilterIPv6" "$B_TMP" >> "$A_TMP"; then
776 jsonOps add error
"errorDataFileFormatting"
784 output
2 'Creating DNSMASQ addnhosts file '
785 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ addnhosts file"
788 output
2 'Creating DNSMASQ config file '
789 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ config file"
792 output
2 'Creating DNSMASQ ipset file '
793 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ ipset file"
796 output
2 'Creating DNSMASQ servers file '
797 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ servers file"
800 output
2 'Creating Unbound adb_list file '
801 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating Unbound adb_list file"
804 if mv "$A_TMP" "$outputFile"; then
808 jsonOps add error
"errorMovingDataFile"
810 if [ "$compressedCache" -gt 0 ]; then
811 output
2 'Creating compressed cache '
812 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating compressed cache"
813 if cacheOps
'createGzip'; then
817 jsonOps add error
"errorCreatingCompressedCache"
822 output
2 'Removing temporary files '
823 jsonOps
set message
"$(getStatusText "statusProcessing
"): removing temporary files"
824 rm -f "/tmp/${packageName}_tmp.*" "$A_TMP" "$B_TMP" "$outputCache" || j
=1
825 if [ $j -eq 0 ]; then
829 jsonOps add error
"errorRemovingTempFiles"
837 rc_procd start_service
'on_boot' && rc_procd service_triggers
841 is_enabled
'on_start' ||
return 1
842 local action status error message stats c
844 status
="$(jsonOps get status)"
845 error
="$(jsonOps get error)"
846 message
="$(jsonOps get message)"
847 stats
="$(jsonOps get stats)"
848 action
="$(jsonOps get triggers)"
850 if [ "$action" = 'on_boot' ] ||
[ "$1" = 'on_boot' ]; then
851 if cacheOps
'testGzip' || cacheOps
'test'; then
856 elif [ "$action" = 'download' ] ||
[ "$1" = 'download' ] ||
[ -n "$error" ]; then
858 elif [ ! -s "$outputFile" ]; then
859 if cacheOps
'testGzip' || cacheOps
'test'; then
864 elif [ "$action" = 'restart' ] ||
[ "$1" = 'restart' ]; then
866 elif [ -s "$outputFile" ] && [ "$status" = "statusSuccess" ] && [ -z "$error" ]; then
876 procd_open_instance
'main'
877 procd_set_param
command /bin
/true
878 procd_set_param stdout
1
879 procd_set_param stderr
1
881 json_add_array firewall
882 if [ "$forceDNS" -ne 0 ]; then
883 for c
in $forceDNSPorts; do
884 if netstat
-tuln |
grep LISTEN |
grep ":${c}" >/dev
/null
2>&1; then
886 json_add_string
type 'redirect'
887 json_add_string target
'DNAT'
888 json_add_string src
'lan'
889 json_add_string proto
'tcp udp'
890 json_add_string src_dport
"$c"
891 json_add_string dest_port
"$c"
892 json_add_string reflection
'0'
896 json_add_string
type 'rule'
897 json_add_string src
'lan'
898 json_add_string dest
'*'
899 json_add_string proto
'tcp udp'
900 json_add_string dest_port
"$c"
901 json_add_string target
'REJECT'
906 if [ "$targetDNS" = 'dnsmasq.ipset' ]; then
908 json_add_string
type 'ipset'
909 json_add_string name
'adb'
910 json_add_string match
'dest_net'
911 json_add_string storage
'hash'
914 json_add_string
type 'rule'
915 json_add_string ipset
'adb'
916 json_add_string src
'lan'
917 json_add_string dest
'*'
918 json_add_string proto
'tcp udp'
919 json_add_string target
'REJECT'
926 if [ "$action" = 'restore' ]; then
927 output
0 "Starting $serviceName... "
928 output
3 "Starting $serviceName...\\n"
929 jsonOps
set status
"statusStarting"
930 if cacheOps
'testGzip' && ! cacheOps
'test' && [ ! -s "$outputFile" ]; then
931 output
3 'Found compressed cache file, unpacking it '
932 jsonOps
set message
'found compressed cache file, unpacking it.'
933 if cacheOps
'unpackGzip'; then
937 jsonOps add error
"errorRestoreCompressedCache"
938 output
"$_ERROR_: $(getErrorText 'errorRestoreCompressedCache')!\\n"
942 if cacheOps
'test' && [ ! -s "$outputFile" ]; then
943 output
3 'Found cache file, reusing it '
944 jsonOps
set message
'found cache file, reusing it.'
945 if cacheOps
'restore'; then
950 jsonOps add error
"errorRestoreCache"
951 output
"$_ERROR_: $(getErrorText 'errorRestoreCache')!\\n"
956 if [ "$action" = 'download' ]; then
957 if [ -s "$outputFile" ] || cacheOps
'test' || cacheOps
'testGzip'; then
958 output
0 "Force-reloading $serviceName... "
959 output
3 "Force-reloading $serviceName...\\n"
960 jsonOps
set status
"statusForceReloading"
962 output
0 "Starting $serviceName... "
963 output
3 "Starting $serviceName...\\n"
964 jsonOps
set status
"statusStarting"
969 if [ "$action" = 'restart' ]; then
970 output
0 "Restarting $serviceName... "
971 output
3 "Restarting $serviceName...\\n"
972 jsonOps
set status
"statusRestarting"
975 if [ "$action" = 'start' ]; then
976 output
0 "Starting $serviceName... "
977 output
3 "Starting $serviceName...\\n"
978 jsonOps
set status
"statusStarting"
981 if [ -s "$outputFile" ] && [ "$(jsonOps get status)" != "statusFail" ]; then
982 output
0 "$__OK__\\n";
984 jsonOps
set status
"statusSuccess"
985 jsonOps
set stats
"$serviceName is blocking $(wc -l < "$outputFile") domains (with ${targetDNS})"
988 output
0 "$__FAIL__\\n";
989 jsonOps
set status
"statusFail"
990 jsonOps add error
"errorOhSnap"
995 service_started
() { procd_set_config_changed firewall
; }
996 service_stopped
() { procd_set_config_changed firewall
; }
997 restart_service
() { rc_procd start_service
'restart'; }
998 reload_service
() { restart_service
; }
999 restart
() { restart_service
; }
1000 reload
() { restart_service
; }
1001 dl
() { rc_procd start_service
'download'; }
1003 rm -f "$addnhostsCache" "$addnhostsGzip"
1004 rm -f "$dnsmasqCache" "$dnsmasqGzip"
1005 rm -f "$ipsetCache" "$ipsetGzip"
1006 rm -f "$serversCache" "$serversGzip"
1007 rm -f "$unboundCache" "$unboundGzip"
1009 config_foreach dnsmasqOps
'dnsmasq' 'cleanup'
1010 uci
-q commit
'dhcp'
1014 show
() { showstatus
; }
1015 status_service
() { showstatus
; }
1017 local c url status message error stats
1018 status
="$(jsonOps get status)"
1019 message
="$(jsonOps get message)"
1020 error
="$(jsonOps get error)"
1021 stats
="$(jsonOps get stats)"
1022 if [ "$status" = "statusSuccess" ]; then
1023 output
"$stats "; output_okn
;
1025 [ -n "$status" ] && status
="$(getStatusText "$status")"
1026 if [ -n "$status" ] && [ -n "$message" ]; then
1027 status
="${status}: $message"
1029 [ -n "$status" ] && output
"$serviceName $status\\n"
1031 if [ -n "$error" ]; then
1036 errorDownloadingList|errorParsingList
)
1037 output
"$_ERROR_: $(getErrorText "$c") $url!\\n";;
1039 output
"$_ERROR_: $(getErrorText "$c")!\\n";;
1048 if [ -s "$outputFile" ]; then
1049 output
"Stopping $serviceName... "
1051 if dnsOps
'on_stop'; then
1053 output
0 "$__OK__\\n"; output_okn
;
1054 jsonOps
set status
"statusStopped"
1057 output
0 "$__FAIL__\\n"; output_fail
;
1058 jsonOps
set status
"statusFail"
1059 jsonOps add error
"errorStopping"
1060 output
"$_ERROR_: $(getErrorText 'errorStopping')!\\n"
1065 service_triggers
() {
1067 procd_add_config_trigger
'config.change' "${packageName}" /etc
/init.d
/${packageName} reload
1068 procd_add_reload_interface_trigger
'wan'
1069 procd_add_interface_trigger
'interface.*.up' 'wan' /etc
/init.d
/${packageName} reload
1076 c
="$(grep -c "$string" "$outputFile")"
1077 if [ ! -s "$outputFile" ]; then
1078 echo "No block-list ('$outputFile') found."
1079 elif [ -z "$string" ]; then
1080 echo "Usage: /etc/init.d/${packageName} check string"
1081 elif [ "$c" -gt 0 ]; then
1082 if [ "$c" -gt 1 ]; then
1083 echo "Found $c matches for '$string' in '$outputFile':"
1085 echo "Found 1 match for '$string' in '$outputFile':"
1087 case "$targetDNS" in
1089 grep "$string" "$outputFile" |
sed 's|^127.0.0.1 ||;s|^:: ||;';;
1091 grep "$string" "$outputFile" |
sed 's|local=/||;s|/$||;';;
1093 grep "$string" "$outputFile" |
sed 's|ipset=/||;s|/adb$||;';;
1095 grep "$string" "$outputFile" |
sed 's|server=/||;s|/$||;';;
1097 grep "$string" "$outputFile" |
sed 's|^local-zone: "||;s|" static$||;';;
1100 echo "The $string is not found in current block-list ('$outputFile')."
1109 for i
in $blocked_domains_urls; do
1110 [ "${i//melmac}" != "$i" ] && continue
1111 if $dl_command "$i" $dl_flag /tmp
/sast
2>/dev
/null
&& [ -s /tmp
/sast
]; then
1112 echo "# File size: $(du -sh /tmp/sast | $awk '{print $1}')"
1113 if compare_values
"$(du -sk /tmp/sast)" "500"; then
1114 echo "# block-list too big for most routers"
1115 elif compare_values
"$(du -sk /tmp/sast)" "100"; then
1116 echo "# block-list may be too big for some routers"
1119 echo " list blocked_domains_url '$i'"
1122 echo "# site was down on last check"
1123 echo "# list blocked_domains_url '$i'"
1128 for i
in $blocked_hosts_urls; do
1129 if $dl_command "$i" $dl_flag /tmp
/sast
2>/dev
/null
&& [ -s /tmp
/sast
]; then
1130 echo "# File size: $(du -sh /tmp/sast | $awk '{print $1}')"
1131 if compare_values
"$(du -sk /tmp/sast)" "500"; then
1132 echo "# block-list too big for most routers"
1133 elif compare_values
"$(du -sk /tmp/sast)" "100"; then
1134 echo "# block-list may be too big for some routers"
1137 echo " list blocked_hosts_url '$i'"
1140 echo "# site was down on last check"
1141 echo "# list blocked_hosts_url '$i'"