1 #!/bin/sh /etc/rc.common
2 # Copyright 2017-2020 Stan Grishin (stangri@melmac.net)
3 # shellcheck disable=SC2039,SC1091,SC2016,SC3043,SC3057,SC3060
6 # shellcheck disable=SC2034
8 # shellcheck disable=SC2034
12 if type extra_command
1>/dev
/null
2>&1; then
13 extra_command
'check' 'Checks if specified domain is found in current block-list'
14 extra_command
'dl' 'Force-downloads all enabled block-list'
15 extra_command
'killcache' 'Delete all cached files'
16 extra_command
'sizes' 'Displays the file-sizes of enabled block-lists'
17 extra_command
'version' 'Show version information'
19 # shellcheck disable=SC2034
20 EXTRA_COMMANDS
='check dl killcache sizes status_service version'
21 # shellcheck disable=SC2034
22 EXTRA_HELP
=' check Checks if specified domain is found in current block-list
23 dl Force-downloads all enabled block-list
24 sizes Displays the file-sizes of enabled block-lists'
27 readonly packageName
='simple-adblock'
28 readonly serviceName
="$packageName $PKG_VERSION"
29 readonly addnhostsFile
="/var/run/${packageName}.addnhosts"
30 readonly addnhostsCache
="/var/run/${packageName}.addnhosts.cache"
31 readonly addnhostsGzip
="/etc/${packageName}.addnhosts.gz"
32 readonly addnhostsOutputFilter
='s|^|127.0.0.1 |;s|$||'
33 readonly addnhostsOutputFilterIPv6
='s|^|:: |;s|$||'
34 readonly dnsmasqFile
="/var/dnsmasq.d/${packageName}"
35 readonly dnsmasqCache
="/var/run/${packageName}.dnsmasq.cache"
36 readonly dnsmasqGzip
="/etc/${packageName}.dnsmasq.gz"
37 readonly dnsmasqOutputFilter
='s|^|local=/|;s|$|/|'
38 readonly ipsetFile
="/var/dnsmasq.d/${packageName}.ipset"
39 readonly ipsetCache
="/var/run/${packageName}.ipset.cache"
40 readonly ipsetGzip
="/etc/${packageName}.ipset.gz"
41 readonly ipsetOutputFilter
='s|^|ipset=/|;s|$|/adb|'
42 readonly serversFile
="/var/run/${packageName}.servers"
43 readonly serversCache
="/var/run/${packageName}.servers.cache"
44 readonly serversGzip
="/etc/${packageName}.servers.gz"
45 readonly serversOutputFilter
='s|^|server=/|;s|$|/|'
46 readonly unboundFile
="/var/lib/unbound/adb_list.${packageName}"
47 readonly unboundCache
="/var/run/${packageName}.unbound.cache"
48 readonly unboundGzip
="/etc/${packageName}.unbound.gz"
49 readonly unboundOutputFilter
='s|^|local-zone: "|;s|$|" static|'
50 readonly A_TMP
="/var/${packageName}.hosts.a.tmp"
51 readonly B_TMP
="/var/${packageName}.hosts.b.tmp"
52 readonly jsonFile
="/var/run/${packageName}.json"
53 readonly sharedMemoryError
="/dev/shm/$packageName-error"
54 readonly sharedMemoryOutput
="/dev/shm/$packageName-output"
55 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;'
56 readonly domainsFilter
='/^#/d;s/[[:space:]]*#.*$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
57 readonly _OK_
='\033[0;32m\xe2\x9c\x93\033[0m'
58 readonly _FAIL_
='\033[0;31m\xe2\x9c\x97\033[0m'
59 readonly __OK__
='\033[0;32m[\xe2\x9c\x93]\033[0m'
60 readonly __FAIL__
='\033[0;31m[\xe2\x9c\x97]\033[0m'
61 readonly _ERROR_
='\033[0;31mERROR\033[0m'
62 readonly _WARNING_
='\033[0;33mWARNING\033[0m'
64 version
() { echo "$PKG_VERSION"; }
69 statusNoInstall
) _ret
="$serviceName is not installed or not found";;
70 statusStopped
) _ret
="Stopped";;
71 statusStarting
) _ret
="Starting";;
72 statusRestarting
) _ret
="Restarting";;
73 statusForceReloading
) _ret
="Force Reloading";;
74 statusDownloading
) _ret
="Downloading";;
75 statusProcessing
) _ret
="Processing";;
76 statusError
) _ret
="Error";;
77 statusWarning
) _ret
="Warning";;
78 statusFail
) _ret
="Fail";;
79 statusSuccess
) _ret
="Success";;
86 errorOutputFileCreate
) _ret
="failed to create $outputFile file";;
87 errorFailDNSReload
) _ret
="failed to restart/reload DNS resolver";;
88 errorSharedMemory
) _ret
="failed to access shared memory";;
89 errorSorting
) _ret
="failed to sort data file";;
90 errorOptimization
) _ret
="failed to optimize data file";;
91 errorAllowListProcessing
) _ret
="failed to process allow-list";;
92 errorDataFileFormatting
) _ret
="failed to format data file";;
93 errorMovingDataFile
) _ret
="failed to move data file '${A_TMP}' to '${outputFile}'";;
94 errorCreatingCompressedCache
) _ret
="failed to create compressed cache";;
95 errorRemovingTempFiles
) _ret
="failed to remove temporary files";;
96 errorRestoreCompressedCache
) _ret
="failed to unpack compressed cache";;
97 errorRestoreCache
) _ret
="failed to move '$outputCache' to '$outputFile'";;
98 errorOhSnap
) _ret
="failed to create block-list or restart DNS resolver";;
99 errorStopping
) _ret
="failed to stop $serviceName";;
100 errorDNSReload
) _ret
="failed to reload/restart DNS resolver";;
101 errorDownloadingConfigUpdate
) _ret
="failed to download Config Update file";;
102 errorDownloadingList
) _ret
="failed to download";;
103 errorParsingList
) _ret
="failed to parse";;
104 errorParsingConfigUpdate
) _ret
="failed to parse Config Update file";;
109 output_ok
() { output
1 "$_OK_"; output
2 "$__OK__\\n"; }
110 output_okn
() { output
1 "$_OK_\\n"; output
2 "$__OK__\\n"; }
111 output_fail
() { output
1 "$_FAIL_"; output
2 "$__FAIL__\\n"; }
112 output_failn
() { output
1 "$_FAIL_\\n"; output
2 "$__FAIL__\\n"; }
113 str_replace
() { printf "%b" "$1" |
sed -e "s/$(printf "%b
" "$2")/$(printf "%b
" "$3")/g"; }
114 str_contains
() { test "$1" != "$(str_replace "$1" "$2" '')"; }
115 compare_values
() { test "$(printf '%s\n' "$@
" | sort -V | head -n 1)" != "$1"; }
116 is_chaos_calmer
() { ubus
-S call system board |
grep -q 'Chaos Calmer'; }
117 led_on
(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'default-on' > "${1}/trigger" 2>&1; fi; }
118 led_off(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'none' > "${1}/trigger" 2>&1; fi; }
119 dnsmasq_hup
() { killall
-q -s HUP dnsmasq
; }
120 dnsmasq_kill
() { killall
-q -s KILL dnsmasq
; }
121 dnsmasq_restart
() { /etc
/init.d
/dnsmasq restart
>/dev
/null
2>&1; }
122 unbound_restart
() { /etc
/init.d
/unbound restart
>/dev
/null
2>&1; }
123 is_present
() { command -v "$1" >/dev
/null
2>&1; }
126 # Can take a single parameter (text) to be output at any verbosity
127 # Or target verbosity level and text to be output at specifc verbosity
128 local msg memmsg logmsg
129 if [ $# -ne 1 ]; then
130 if [ $
((verbosity
& $1)) -gt 0 ] ||
[ "$verbosity" = "$1" ]; then shift; else return 0; fi
132 [ -t 1 ] && printf "%b" "$1"
133 msg
="${1//$serviceName /service }";
134 if [ "$(printf "%b
" "$msg" | wc -l)" -gt 0 ]; then
135 [ -s "$sharedMemoryOutput" ] && memmsg
="$(cat "$sharedMemoryOutput")"
136 logmsg
="$(printf "%b
" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
137 logger
-t "${packageName:-service} [$$]" "$(printf "%b
" "$logmsg")"
138 rm -f "$sharedMemoryOutput"
140 printf "%b" "$msg" >> "$sharedMemoryOutput"
144 serviceEnabled
=''; forceDNS
=''; forceDNSPorts
=''; parallelDL
=''; debug
='';
145 compressedCache
=''; ipv6Enabled
=''; configUpdateEnabled
=''; configUpdateURL
='';
146 bootDelay
=''; dlTimeout
=''; curlRetry
=''; verbosity
=''; led
='';
147 targetDNS
=''; dnsInstance
='';
148 allowed_domains
=''; allowed_domains_urls
='';
149 blocked_domains
=''; blocked_domains_urls
=''; blocked_hosts_urls
='';
150 dl_command
=''; dl_flag
=''; isSSLSupported
=''; allowIDN
='';
151 outputFilter
=''; outputFilterIPv6
=''; outputFile
=''; outputGzip
=''; outputCache
='';
154 load_package_config
() {
155 config_load
"$packageName"
156 config_get_bool serviceEnabled
'config' 'enabled' 1
157 config_get_bool forceDNS
'config' 'force_dns' 1
158 config_get_bool parallelDL
'config' 'parallel_downloads' 1
159 config_get_bool debug
'config' 'debug' 0
160 config_get_bool compressedCache
'config' 'compressed_cache' 0
161 config_get_bool ipv6Enabled
'config' 'ipv6_enabled' 0
162 config_get_bool configUpdateEnabled
'config' 'config_update_enabled' 0
163 config_get forceDNSPorts
'config' 'force_dns_port' '53 853'
164 config_get bootDelay
'config' 'boot_delay' '120'
165 config_get dlTimeout
'config' 'download_timeout' '20'
166 config_get curlRetry
'config' 'curl_retry' '3'
167 config_get verbosity
'config' 'verbosity' '2'
168 config_get led
'config' 'led'
169 config_get targetDNS
'config' 'dns' 'dnsmasq.servers'
170 config_get dnsInstance
'config' 'dns_instance' '0'
171 config_get allowed_domains
'config' 'allowed_domain'
172 config_get allowed_domains_urls
'config' 'allowed_domains_url'
173 config_get blocked_domains
'config' 'blocked_domain'
174 config_get blocked_domains_urls
'config' 'blocked_domains_url'
175 config_get blocked_hosts_urls
'config' 'blocked_hosts_url'
176 config_get configUpdateURL
'config' 'config_update_url' 'https://cdn.jsdelivr.net/gh/openwrt/packages/net/simple-adblock/files/simple-adblock.conf.update'
178 if [ "$targetDNS" != 'dnsmasq.addnhosts' ] && [ "$targetDNS" != 'dnsmasq.conf' ] && \
179 [ "$targetDNS" != 'dnsmasq.servers' ] && [ "$targetDNS" != 'unbound.adb_list' ] && \
180 [ "$targetDNS" != 'dnsmasq.ipset' ] ; then
181 targetDNS
='dnsmasq.servers'
186 outputFilter
="$addnhostsOutputFilter"
187 outputFile
="$addnhostsFile"
188 outputCache
="$addnhostsCache"
189 outputGzip
="$addnhostsGzip"
190 [ "$ipv6Enabled" -gt 0 ] && outputFilterIPv6
="$addnhostsOutputFilterIPv6"
191 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
192 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
193 rm -f "$serversFile" "$serversCache" "$serversGzip"
194 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
197 outputFilter
="$dnsmasqOutputFilter"
198 outputFile
="$dnsmasqFile"
199 outputCache
="$dnsmasqCache"
200 outputGzip
="$dnsmasqGzip"
201 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
202 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
203 rm -f "$serversFile" "$serversCache" "$serversGzip"
204 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
207 outputFilter
="$ipsetOutputFilter"
208 outputFile
="$ipsetFile"
209 outputCache
="$ipsetCache"
210 outputGzip
="$ipsetGzip"
211 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
212 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
213 rm -f "$serversFile" "$serversCache" "$serversGzip"
214 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
217 outputFilter
="$serversOutputFilter"
218 outputFile
="$serversFile"
219 outputCache
="$serversCache"
220 outputGzip
="$serversGzip"
221 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
222 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
223 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
224 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
227 outputFilter
="$unboundOutputFilter"
228 outputFile
="$unboundFile"
229 outputCache
="$unboundCache"
230 outputGzip
="$unboundGzip"
231 rm -f "$addnhostsFile" "$addnhostsCache" "$addnhostsGzip"
232 rm -f "$dnsmasqFile" "$dnsmasqCache" "$dnsmasqGzip"
233 rm -f "$ipsetFile" "$ipsetCache" "$ipsetGzip"
234 rm -f "$serversFile" "$serversCache" "$serversGzip"
237 if [ -z "${verbosity##*[!0-9]*}" ] ||
[ "$verbosity" -lt 0 ] ||
[ "$verbosity" -gt 2 ]; then
240 .
/lib
/functions
/network.sh
241 .
/usr
/share
/libubox
/jshn.sh
242 is_present
'gawk' && awk='gawk'
243 if ! is_present
'/usr/libexec/grep-gnu' ||
! is_present
'/usr/libexec/sed-gnu' || \
244 ! is_present
'/usr/libexec/sort-coreutils' ||
! is_present
'gawk'; then
245 local s
="opkg update; opkg --force-overwrite install"
246 is_present
'gawk' || s
="$s gawk"
247 is_present
'/usr/libexec/grep-gnu' || s
="$s grep"
248 is_present
'/usr/libexec/sed-gnu' || s
="$s sed"
249 is_present
'/usr/libexec/sort-coreutils' || s
="$s coreutils-sort"
250 output
"$_WARNING_: Some recommended packages are missing, install them by running:\\n"
253 # Prefer curl because it supports the file:// scheme.
254 if is_present
'curl'; then
255 dl_command
="curl --insecure --retry $curlRetry --connect-timeout $dlTimeout --silent"
257 elif is_present
'/usr/libexec/wget-ssl'; then
258 dl_command
="/usr/libexec/wget-ssl --no-check-certificate --timeout $dlTimeout -q"
260 elif is_present wget
&& wget
--version 2>/dev
/null |
grep -q "+https"; then
261 dl_command
="wget --no-check-certificate --timeout $dlTimeout -q"
264 dl_command
="uclient-fetch --no-check-certificate --timeout $dlTimeout -q"
267 led
="${led:+/sys/class/leds/$led}"
268 if curl
--version 2>/dev
/null |
grep -q "https" \
269 || wget
--version 2>/dev
/null |
grep -q "+https" \
270 ||
grep -q "libustream-mbedtls" /usr
/lib
/opkg
/status \
271 ||
grep -q "libustream-openssl" /usr
/lib
/opkg
/status \
272 ||
grep -q "libustream-wolfssl" /usr
/lib
/opkg
/status
; then
280 wan_if
=''; wan_gw
='';
283 if [ "$debug" -ne 0 ]; then
284 exec 1>>/tmp
/simple-adblock.log
289 if [ "$serviceEnabled" -eq 0 ]; then
292 output
"$packageName is currently disabled.\\n"
293 output
"Run the following commands before starting service again:\\n"
294 output
"uci set ${packageName}.config.enabled='1'; uci commit $packageName;\\n"
301 dnsmasq.addnhosts | dnsmasq.conf | dnsmasq.ipset | dnsmasq.servers
)
302 if dnsmasq
-v 2>/dev
/null |
grep -q 'no-IDN' ||
! dnsmasq
-v 2>/dev
/null |
grep -q -w 'IDN'; then
314 if dnsmasq
-v 2>/dev
/null |
grep -q 'no-ipset' ||
! dnsmasq
-v 2>/dev
/null |
grep -q -w 'ipset'; then
315 output
"$_ERROR_: DNSMASQ ipset support is enabled in $packageName, but DNSMASQ is either not installed or installed DNSMASQ does not support ipsets!\\n"
316 targetDNS
='dnsmasq.servers'
318 if ! ipset
help hash:net
>/dev
/null
2>&1; then
319 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"
320 targetDNS
='dnsmasq.servers'
325 [ ! -d "${outputFile%/*}" ] && mkdir
-p "${outputFile%/*}"
326 [ ! -d "${outputCache%/*}" ] && mkdir
-p "${outputFile%/*}"
327 [ ! -d "${outputGzip%/*}" ] && mkdir
-p "${outputFile%/*}"
328 cacheOps
'testGzip' && return 0
329 network_flush_cache
; network_find_wan wan_if
; network_get_gateway wan_gw
"$wan_if";
330 [ -n "$wan_gw" ] && return 0
331 output
"$_ERROR_: $serviceName failed to discover WAN gateway.\\n"; return 1;
335 local cfg
="$1" param
="$2"
338 if [ "$(uci -q get dhcp."$cfg".serversfile)" = "$serversFile" ]; then
339 uci
-q del dhcp.
"$cfg".serversfile
341 if ! uci
-q get dhcp.
"$cfg".addnhosts |
grep -q "$addnhostsFile"; then
342 uci add_list dhcp.
"$cfg".addnhosts
="$addnhostsFile"
345 dnsmasq.conf|dnsmasq.ipset|unbound.adb_list|cleanup
)
346 uci
-q del_list dhcp.
"$cfg".addnhosts
="$addnhostsFile"
347 if [ "$(uci -q get dhcp."$cfg".serversfile)" = "$serversFile" ]; then
348 uci
-q del dhcp.
"$cfg".serversfile
352 uci
-q del_list dhcp.
"$cfg".addnhosts
="$addnhostsFile"
353 if [ "$(uci -q get dhcp."$cfg".serversfile)" != "$serversFile" ]; then
354 uci
set dhcp.
"$cfg".serversfile
="$serversFile"
361 local param output_text i
364 if [ ! -s "$outputFile" ]; then
365 jsonOps
set status
"statusFail"
366 jsonOps add error
"errorOutputFileCreate"
367 output
"$_ERROR_: $(getErrorText 'errorOutputFileCreate')!\\n"
372 if [ "$dnsInstance" = "*" ]; then
373 config_foreach dnsmasqOps
'dnsmasq' "$targetDNS"
374 elif [ -n "$dnsInstance" ]; then
375 for i
in $dnsInstance; do
376 dnsmasqOps
"@dnsmasq[$i]" "$targetDNS"
381 dnsmasq.addnhosts|dnsmasq.servers
)
383 output_text
='Reloading DNSMASQ'
385 dnsmasq.conf|dnsmasq.ipset
)
386 param
=dnsmasq_restart
387 output_text
='Restarting DNSMASQ'
390 param
=unbound_restart
391 output_text
='Restarting Unbound'
395 if [ -n "$(uci changes dhcp)" ]; then
397 if [ "$param" = 'unbound_restart' ]; then
398 param
='dnsmasq_restart; unbound_restart;'
399 output_text
='Restarting Unbound/DNSMASQ'
401 param
=dnsmasq_restart
402 output_text
='Restarting DNSMASQ'
405 output
1 "$output_text "
406 output
2 "$output_text "
407 jsonOps
set message
"$output_text"
408 if eval "$param"; then
409 jsonOps
set status
"statusSuccess"
414 jsonOps
set status
"statusFail"
415 jsonOps add error
"errorDNSReload"
416 output
"$_ERROR_: $(getErrorText 'errorDNSReload')!\\n"
422 dnsmasq.addnhosts | dnsmasq.servers
)
425 dnsmasq.conf | dnsmasq.ipset
)
426 param
=dnsmasq_restart
429 param
=unbound_restart
432 if [ -n "$(uci changes dhcp)" ]; then
434 if [ "$param" = 'unbound_restart' ]; then
435 param
='dnsmasq_restart; unbound_restart;'
437 param
=dnsmasq_restart
445 dnsmasq.addnhosts | dnsmasq.conf | dnsmasq.ipset | dnsmasq.servers
)
446 param
=dnsmasq_restart
449 param
=unbound_restart
459 # shellcheck disable=SC2034
460 local action
="$1" param
="$2" value
="$3"
461 local status message error stats
462 local reload restart curReload curRestart ret i
463 if [ -s "$jsonFile" ]; then
464 json_load_file
"$jsonFile" 2>/dev
/null
465 json_select
'data' 2>/dev
/null
466 for i
in status message error stats reload restart
; do
467 json_get_var
$i "$i" 2>/dev
/null
474 curReload
="$parallelDL $debug $dlTimeout $allowed_domains $blocked_domains $allowed_domains_urls $blocked_domains_urls $blocked_hosts_urls $targetDNS $configUpdateEnabled $configUpdateURL"
475 curRestart
="$compressedCache $forceDNS $led $forceDNSPorts"
476 if [ ! -s "$jsonFile" ]; then
478 elif [ "$curReload" != "$reload" ]; then
480 elif [ "$curRestart" != "$restart" ]; then
486 printf "%b" "$(eval echo "\$
$param")"; return;;
490 if [ -n "$(eval echo "\$
$param")" ]; then
491 value
="$(eval echo "\$
$param") ${value}"
493 eval "$param"='${value}'
498 unset status message error stats
;;
500 unset reload restart
;;
508 reload
="$parallelDL $debug $dlTimeout $allowed_domains $blocked_domains $allowed_domains_urls $blocked_domains_urls $blocked_hosts_urls $targetDNS $configUpdateEnabled $configUpdateURL"
509 restart
="$compressedCache $forceDNS $led $forceDNSPorts"
512 eval "$param"='$value';;
517 json_add_object
'data'
518 json_add_string version
"$PKG_VERSION"
519 json_add_string status
"$status"
520 json_add_string message
"$message"
521 json_add_string error
"$error"
522 json_add_string stats
"$stats"
523 json_add_string reload
"$reload"
524 json_add_string restart
"$restart"
526 json_dump
> "$jsonFile"
534 [ -s "$outputFile" ] && { mv -f "$outputFile" "$outputCache"; true
> "$outputFile"; } >/dev
/null
2>/dev
/null
538 [ -s "$outputCache" ] && mv "$outputCache" "$outputFile" >/dev
/null
2>/dev
/null
542 [ -s "$outputCache" ]
546 [ -s "$outputGzip" ] && gzip -t -c "$outputGzip"
550 R_TMP
="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
551 if gzip < "$outputFile" > "$R_TMP"; then
552 if mv "$R_TMP" "$outputGzip"; then
563 expand|unpack|expandGzip|unpackGzip
)
564 [ -s "$outputGzip" ] && gzip -dc < "$outputGzip" > "$outputCache"
571 local label
type D_TMP R_TMP
572 if [ -z "$1" ] ||
[ -z "$2" ] ||
[ -z "$3" ]; then return 1; fi
573 label
="${1##*//}"; label
="${label%%/*}";
574 if [ "$2" = 'hosts' ]; then
575 label
="Hosts: $label"; filter
="$hostsFilter";
577 label
="Domains: $label"; filter
="$domainsFilter";
579 if [ "$3" = 'blocked' ]; then
580 type='Blocked'; D_TMP
="$B_TMP";
582 type='Allowed'; D_TMP
="$A_TMP";
584 if [ "${1:0:5}" = "https" ] && [ -z "$isSSLSupported" ]; then
586 output
2 "[DL] $type $label $__FAIL__\\n"
587 echo "errorNoSSLSupport|${1}" >> "$sharedMemoryError"
590 while [ -z "$R_TMP" ] ||
[ -e "$R_TMP" ]; do
591 R_TMP
="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
593 if ! $dl_command "$1" $dl_flag "$R_TMP" 2>/dev
/null ||
[ ! -s "$R_TMP" ]; then
595 output
2 "[DL] $type $label $__FAIL__\\n"
596 echo "errorDownloadingList|${1}" >> "$sharedMemoryError"
598 sed -i "$filter" "$R_TMP"
599 if [ ! -s "$R_TMP" ]; then
601 output
2 "[DL] $type $label $__FAIL__\\n"
602 echo "errorParsingList|${1}" >> "$sharedMemoryError"
604 cat "${R_TMP}" >> "$D_TMP"
606 output
2 "[DL] $type $label $__OK__\\n"
613 process_config_update
() {
615 [ "$configUpdateEnabled" -eq 0 ] && return 0
616 label
="${1##*//}"; label
="${label%%/*}";
617 while [ -z "$R_TMP" ] ||
[ -e "$R_TMP" ]; do
618 R_TMP
="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
620 if ! $dl_command "$1" $dl_flag "$R_TMP" 2>/dev
/null ||
[ ! -s "$R_TMP" ]; then
622 output
2 "[DL] Config Update: $label $__FAIL__\\n"
623 jsonOps add error
"errorDownloadingConfigUpdate"
625 if [ -s "$R_TMP" ] && sed -f "$R_TMP" -i /etc
/config
/simple-adblock
2>/dev
/null
; then
627 output
2 "[DL] Config Update: $label $__OK__\\n"
630 output
2 "[DL] Config Update: $label $__FAIL__\\n"
631 jsonOps add error
"errorParsingConfigUpdate"
639 local hf w_filter j
=0 R_TMP
641 jsonOps
set message
"$(getStatusText "statusDownloading
")..."
642 jsonOps
set status
"statusDownloading"
644 rm -f "$A_TMP" "$B_TMP" "$outputFile" "$outputCache" "$outputGzip"
645 if [ "$($awk '/^MemFree/ {print int($2/1000)}' "/proc
/meminfo
")" -lt 32 ]; then
646 output
3 'Low free memory, restarting resolver... '
647 if dnsOps
'quiet'; then
653 touch $A_TMP; touch $B_TMP;
654 output
1 'Downloading lists '
655 process_config_update
"$configUpdateURL"
656 rm -f "$sharedMemoryError"
657 if [ -n "$blocked_hosts_urls" ]; then
658 for hf
in ${blocked_hosts_urls}; do
659 if [ "$parallelDL" -gt 0 ]; then
660 process_url
"$hf" 'hosts' 'blocked' &
662 process_url
"$hf" 'hosts' 'blocked'
666 if [ -n "$blocked_domains_urls" ]; then
667 for hf
in ${blocked_domains_urls}; do
668 if [ "$parallelDL" -gt 0 ]; then
669 process_url
"$hf" 'domains' 'blocked' &
671 process_url
"$hf" 'domains' 'blocked'
675 if [ -n "$allowed_domains_urls" ]; then
676 for hf
in ${allowed_domains_urls}; do
677 if [ "$parallelDL" -gt 0 ]; then
678 process_url
"$hf" 'domains' 'allowed' &
680 process_url
"$hf" 'domains' 'allowed'
686 if [ -s "$sharedMemoryError" ]; then
687 while IFS
= read -r line
; do
688 jsonOps add error
"$line"
689 done < "$sharedMemoryError"
690 rm -f "$sharedMemoryError"
693 [ -n "$blocked_domains" ] && for hf
in ${blocked_domains}; do echo "$hf" |
sed "$domainsFilter" >> $B_TMP; done
694 allowed_domains
="${allowed_domains}
696 [ -n "$allowed_domains" ] && for hf
in ${allowed_domains}; do hf
="$(echo "$hf" | sed 's/\./\\./g')"; w_filter
="$w_filter/${hf}$/d;"; done
698 [ ! -s "$B_TMP" ] && return 1
700 output
1 'Processing downloads '
701 output
2 'Sorting combined list '
702 jsonOps
set message
"$(getStatusText "statusProcessing
"): sorting combined list"
703 if [ "$allowIDN" -gt 0 ]; then
704 if sort -u "$B_TMP" > "$A_TMP"; then
708 jsonOps add error
"errorSorting"
711 if sort -u "$B_TMP" |
grep -E -v '[^a-zA-Z0-9=/.-]' > "$A_TMP"; then
715 jsonOps add error
"errorSorting"
719 if [ "$targetDNS" = 'dnsmasq.conf' ] || \
720 [ "$targetDNS" = 'dnsmasq.ipset' ] || \
721 [ "$targetDNS" = 'dnsmasq.servers' ] || \
722 [ "$targetDNS" = 'unbound.adb_list' ]; then
723 # TLD optimization written by Dirk Brenken (dev@brenken.org)
724 output
2 'Optimizing combined list '
725 jsonOps
set message
"$(getStatusText "statusProcessing
"): optimizing combined list"
726 # sed -E 'G;:t;s/(.*)(\.)(.*)(\n)(.*)/\1\4\5\2\3/;tt;s/(.*)\n(\.)(.*)/\3\2\1/' is actually slower than command below
727 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$A_TMP" > "$B_TMP"; then
728 if sort "$B_TMP" > "$A_TMP"; then
729 if $awk '{if(NR=1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "$A_TMP" > "$B_TMP"; then
730 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$B_TMP" > "$A_TMP"; then
731 if sort -u "$A_TMP" > "$B_TMP"; then
735 jsonOps add error
"errorOptimization"
740 jsonOps add error
"errorOptimization"
744 jsonOps add error
"errorOptimization"
749 jsonOps add error
"errorOptimization"
753 jsonOps add error
"errorOptimization"
760 output
2 'Allowing domains '
761 jsonOps
set message
"$(getStatusText "statusProcessing
"): allowing domains"
762 if sed -i "$w_filter" "$B_TMP"; then
766 jsonOps add error
"errorAllowListProcessing"
769 output
2 'Formatting merged file '
770 jsonOps
set message
"$(getStatusText "statusProcessing
"): formatting merged file"
771 if [ -z "$outputFilterIPv6" ]; then
772 if sed "$outputFilter" "$B_TMP" > "$A_TMP"; then
776 jsonOps add error
"errorDataFileFormatting"
781 if sed "$outputFilter" "$B_TMP" > "$A_TMP" && \
782 sed "$outputFilterIPv6" "$B_TMP" >> "$A_TMP"; then
786 jsonOps add error
"errorDataFileFormatting"
794 output
2 'Creating DNSMASQ addnhosts file '
795 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ addnhosts file"
798 output
2 'Creating DNSMASQ config file '
799 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ config file"
802 output
2 'Creating DNSMASQ ipset file '
803 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ ipset file"
806 output
2 'Creating DNSMASQ servers file '
807 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating DNSMASQ servers file"
810 output
2 'Creating Unbound adb_list file '
811 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating Unbound adb_list file"
814 if mv "$A_TMP" "$outputFile"; then
818 jsonOps add error
"errorMovingDataFile"
820 if [ "$compressedCache" -gt 0 ]; then
821 output
2 'Creating compressed cache '
822 jsonOps
set message
"$(getStatusText "statusProcessing
"): creating compressed cache"
823 if cacheOps
'createGzip'; then
827 jsonOps add error
"errorCreatingCompressedCache"
832 output
2 'Removing temporary files '
833 jsonOps
set message
"$(getStatusText "statusProcessing
"): removing temporary files"
834 rm -f "/tmp/${packageName}_tmp.*" "$A_TMP" "$B_TMP" "$outputCache" || j
=1
835 if [ $j -eq 0 ]; then
839 jsonOps add error
"errorRemovingTempFiles"
847 rc_procd start_service
'on_boot' && rc_procd service_triggers
851 is_enabled
'on_start' ||
return 1
852 local action status error message stats c
854 status
="$(jsonOps get status)"
855 error
="$(jsonOps get error)"
856 message
="$(jsonOps get message)"
857 stats
="$(jsonOps get stats)"
858 action
="$(jsonOps get triggers)"
860 if [ "$action" = 'on_boot' ] ||
[ "$1" = 'on_boot' ]; then
861 if cacheOps
'testGzip' || cacheOps
'test'; then
866 elif [ "$action" = 'download' ] ||
[ "$1" = 'download' ] ||
[ -n "$error" ]; then
868 elif [ ! -s "$outputFile" ]; then
869 if cacheOps
'testGzip' || cacheOps
'test'; then
874 elif [ "$action" = 'restart' ] ||
[ "$1" = 'restart' ]; then
876 elif [ -s "$outputFile" ] && [ "$status" = "statusSuccess" ] && [ -z "$error" ]; then
886 procd_open_instance
'main'
887 procd_set_param
command /bin
/true
888 procd_set_param stdout
1
889 procd_set_param stderr
1
891 json_add_array firewall
892 if [ "$forceDNS" -ne 0 ]; then
893 for c
in $forceDNSPorts; do
894 if netstat
-tuln |
grep LISTEN |
grep ":${c}" >/dev
/null
2>&1; then
896 json_add_string
type redirect
897 json_add_string target DNAT
898 json_add_string src lan
899 json_add_string proto
"tcp udp"
900 json_add_string src_dport
"$c"
901 json_add_string dest_port
"$c"
902 json_add_boolean reflection
0
906 json_add_string
type rule
907 json_add_string src lan
908 json_add_string dest
"*"
909 json_add_string proto
"tcp udp"
910 json_add_string dest_port
"$c"
911 json_add_string target REJECT
916 if [ "$targetDNS" = 'dnsmasq.ipset' ]; then
918 json_add_string
type ipset
919 json_add_string name adb
920 json_add_string match dest_net
921 json_add_string storage
hash
924 json_add_string
type rule
925 json_add_string ipset adb
926 json_add_string src lan
927 json_add_string dest
"*"
928 json_add_string proto
"tcp udp"
929 json_add_string target REJECT
936 if [ "$action" = 'restore' ]; then
937 output
0 "Starting $serviceName... "
938 output
3 "Starting $serviceName...\\n"
939 jsonOps
set status
"statusStarting"
940 if cacheOps
'testGzip' && ! cacheOps
'test' && [ ! -s "$outputFile" ]; then
941 output
3 'Found compressed cache file, unpacking it '
942 jsonOps
set message
'found compressed cache file, unpacking it.'
943 if cacheOps
'unpackGzip'; then
947 jsonOps add error
"errorRestoreCompressedCache"
948 output
"$_ERROR_: $(getErrorText 'errorRestoreCompressedCache')!\\n"
952 if cacheOps
'test' && [ ! -s "$outputFile" ]; then
953 output
3 'Found cache file, reusing it '
954 jsonOps
set message
'found cache file, reusing it.'
955 if cacheOps
'restore'; then
960 jsonOps add error
"errorRestoreCache"
961 output
"$_ERROR_: $(getErrorText 'errorRestoreCache')!\\n"
966 if [ "$action" = 'download' ]; then
967 if [ -s "$outputFile" ] || cacheOps
'test' || cacheOps
'testGzip'; then
968 output
0 "Force-reloading $serviceName... "
969 output
3 "Force-reloading $serviceName...\\n"
970 jsonOps
set status
"statusForceReloading"
972 output
0 "Starting $serviceName... "
973 output
3 "Starting $serviceName...\\n"
974 jsonOps
set status
"statusStarting"
979 if [ "$action" = 'restart' ]; then
980 output
0 "Restarting $serviceName... "
981 output
3 "Restarting $serviceName...\\n"
982 jsonOps
set status
"statusRestarting"
985 if [ "$action" = 'start' ]; then
986 output
0 "Starting $serviceName... "
987 output
3 "Starting $serviceName...\\n"
988 jsonOps
set status
"statusStarting"
991 if [ -s "$outputFile" ] && [ "$(jsonOps get status)" != "statusFail" ]; then
992 output
0 "$__OK__\\n";
994 jsonOps
set status
"statusSuccess"
995 jsonOps
set stats
"$serviceName is blocking $(wc -l < "$outputFile") domains (with ${targetDNS})"
998 output
0 "$__FAIL__\\n";
999 jsonOps
set status
"statusFail"
1000 jsonOps add error
"errorOhSnap"
1005 service_started
() { procd_set_config_changed firewall
; }
1006 service_stopped
() { procd_set_config_changed firewall
; }
1008 restart_service
() { rc_procd start_service
'restart'; }
1009 reload_service
() { rc_procd start_service
'restart'; }
1010 dl
() { rc_procd start_service
'download'; }
1013 rm -f "$addnhostsCache" "$addnhostsGzip"
1014 rm -f "$dnsmasqCache" "$dnsmasqGzip"
1015 rm -f "$ipsetCache" "$ipsetGzip"
1016 rm -f "$serversCache" "$serversGzip"
1017 rm -f "$unboundCache" "$unboundGzip"
1019 config_foreach dnsmasqOps
'dnsmasq' 'cleanup'
1020 uci
-q commit
'dhcp'
1025 local c url status message error stats
1026 config_load
"$packageName"
1027 config_get verbosity
'config' 'verbosity' '2'
1028 status
="$(jsonOps get status)"
1029 message
="$(jsonOps get message)"
1030 error
="$(jsonOps get error)"
1031 stats
="$(jsonOps get stats)"
1032 if [ "$status" = "statusSuccess" ]; then
1033 output
"$stats "; output_okn
;
1035 [ -n "$status" ] && status
="$(getStatusText "$status")"
1036 if [ -n "$status" ] && [ -n "$message" ]; then
1037 status
="${status}: $message"
1039 [ -n "$status" ] && output
"$serviceName $status\\n"
1041 if [ -n "$error" ]; then
1046 errorDownloadingList|errorParsingList
)
1047 output
"$_ERROR_: $(getErrorText "$c") $url!\\n";;
1049 output
"$_ERROR_: $(getErrorText "$c")!\\n";;
1058 if [ -s "$outputFile" ]; then
1059 output
"Stopping $serviceName... "
1061 if dnsOps
'on_stop'; then
1063 output
0 "$__OK__\\n"; output_okn
;
1064 jsonOps
set status
"statusStopped"
1067 output
0 "$__FAIL__\\n"; output_fail
;
1068 jsonOps
set status
"statusFail"
1069 jsonOps add error
"errorStopping"
1070 output
"$_ERROR_: $(getErrorText 'errorStopping')!\\n"
1075 service_triggers
() {
1077 procd_add_config_trigger
'config.change' "${packageName}" /etc
/init.d
/${packageName} reload
1078 procd_add_reload_interface_trigger
'wan'
1079 procd_add_interface_trigger
'interface.*.up' 'wan' /etc
/init.d
/${packageName} reload
1086 c
="$(grep -c "$string" "$outputFile")"
1087 if [ ! -s "$outputFile" ]; then
1088 echo "No block-list ('$outputFile') found."
1089 elif [ -z "$string" ]; then
1090 echo "Usage: /etc/init.d/${packageName} check string"
1091 elif [ "$c" -gt 0 ]; then
1092 if [ "$c" -gt 1 ]; then
1093 echo "Found $c matches for '$string' in '$outputFile':"
1095 echo "Found 1 match for '$string' in '$outputFile':"
1097 case "$targetDNS" in
1099 grep "$string" "$outputFile" |
sed 's|^127.0.0.1 ||;s|^:: ||;';;
1101 grep "$string" "$outputFile" |
sed 's|local=/||;s|/$||;';;
1103 grep "$string" "$outputFile" |
sed 's|ipset=/||;s|/adb$||;';;
1105 grep "$string" "$outputFile" |
sed 's|server=/||;s|/$||;';;
1107 grep "$string" "$outputFile" |
sed 's|^local-zone: "||;s|" static$||;';;
1110 echo "The $string is not found in current block-list ('$outputFile')."
1119 for i
in $blocked_domains_urls; do
1120 [ "${i//melmac}" != "$i" ] && continue
1121 if $dl_command "$i" $dl_flag /tmp
/sast
2>/dev
/null
&& [ -s /tmp
/sast
]; then
1122 echo "# File size: $(du -sh /tmp/sast | $awk '{print $1}')"
1123 if compare_values
"$(du -sk /tmp/sast)" "500"; then
1124 echo "# block-list too big for most routers"
1125 elif compare_values
"$(du -sk /tmp/sast)" "100"; then
1126 echo "# block-list may be too big for some routers"
1129 echo " list blocked_domains_url '$i'"
1132 echo "# site was down on last check"
1133 echo "# list blocked_domains_url '$i'"
1138 for i
in $blocked_hosts_urls; do
1139 if $dl_command "$i" $dl_flag /tmp
/sast
2>/dev
/null
&& [ -s /tmp
/sast
]; then
1140 echo "# File size: $(du -sh /tmp/sast | $awk '{print $1}')"
1141 if compare_values
"$(du -sk /tmp/sast)" "500"; then
1142 echo "# block-list too big for most routers"
1143 elif compare_values
"$(du -sk /tmp/sast)" "100"; then
1144 echo "# block-list may be too big for some routers"
1147 echo " list blocked_hosts_url '$i'"
1150 echo "# site was down on last check"
1151 echo "# list blocked_hosts_url '$i'"