Merge pull request #19372 from cotequeiroz/libgd
[feed/packages.git] / net / simple-adblock / files / simple-adblock.init
1 #!/bin/sh /etc/rc.common
2 # Copyright 2017-2022 Stan Grishin (stangri@melmac.ca)
3 # shellcheck disable=SC2039,SC1091,SC2016,SC3043,SC3057,SC3060
4 PKG_VERSION='dev-test'
5
6 # shellcheck disable=SC2034
7 START=94
8 # shellcheck disable=SC2034
9 USE_PROCD=1
10 LC_ALL=C
11
12 if type extra_command 1>/dev/null 2>&1; then
13 extra_command 'allow' 'Allows domain in current block-list and config'
14 extra_command 'check' 'Checks if specified domain is found in current block-list'
15 extra_command 'dl' 'Force-downloads all enabled block-list'
16 extra_command 'killcache' 'Delete all cached files'
17 extra_command 'sizes' 'Displays the file-sizes of enabled block-lists'
18 extra_command 'version' 'Show version information'
19 else
20 # shellcheck disable=SC2034
21 EXTRA_COMMANDS='allow check dl killcache sizes status_service version'
22 # shellcheck disable=SC2034
23 EXTRA_HELP=' allow Allows domain(s) in current block-list and config
24 check Checks if specified domain is found in current block-list
25 dl Force-downloads all enabled block-list
26 sizes Displays the file-sizes of enabled block-lists'
27 fi
28
29 readonly packageName='simple-adblock'
30 readonly serviceName="$packageName $PKG_VERSION"
31 readonly packageConfigFile="/etc/config/${packageName}"
32 readonly dnsmasqAddnhostsFile="/var/run/${packageName}/dnsmasq.addnhosts"
33 readonly dnsmasqAddnhostsCache="/var/run/${packageName}/dnsmasq.addnhosts.cache"
34 readonly dnsmasqAddnhostsGzip="/etc/${packageName}.dnsmasq.addnhosts.gz"
35 readonly dnsmasqAddnhostsFilter='s|^|127.0.0.1 |;s|$||'
36 readonly dnsmasqAddnhostsFilterIPv6='s|^|:: |;s|$||'
37 readonly dnsmasqConfFile="/tmp/dnsmasq.d/${packageName}"
38 readonly dnsmasqConfCache="/var/run/${packageName}/dnsmasq.conf.cache"
39 readonly dnsmasqConfGzip="/etc/${packageName}.dnsmasq.conf.gz"
40 readonly dnsmasqConfFilter='s|^|local=/|;s|$|/|'
41 readonly dnsmasqIpsetFile="/tmp/dnsmasq.d/${packageName}.ipset"
42 readonly dnsmasqIpsetCache="/var/run/${packageName}/dnsmasq.ipset.cache"
43 readonly dnsmasqIpsetGzip="/etc/${packageName}.dnsmasq.ipset.gz"
44 readonly dnsmasqIpsetFilter='s|^|ipset=/|;s|$|/adb|'
45 readonly dnsmasqNftsetFile="/tmp/dnsmasq.d/${packageName}.nftset"
46 readonly dnsmasqNftsetCache="/var/run/${packageName}/dnsmasq.nftset.cache"
47 readonly dnsmasqNftsetGzip="/etc/${packageName}.dnsmasq.nftset.gz"
48 readonly dnsmasqNftsetFilter='s|^|nftset=/|;s|$|/4#inet#fw4#adb4|'
49 readonly dnsmasqNftsetFilterIPv6='s|^|nftset=/|;s|$|/4#inet#fw4#adb4,6#inet#fw4#adb6|'
50 readonly dnsmasqServersFile="/var/run/${packageName}/dnsmasq.servers"
51 readonly dnsmasqServersCache="/var/run/${packageName}/dnsmasq.servers.cache"
52 readonly dnsmasqServersGzip="/etc/${packageName}.dnsmasq.servers.gz"
53 readonly dnsmasqServersFilter='s|^|server=/|;s|$|/|'
54 readonly unboundFile="/var/lib/unbound/adb_list.${packageName}"
55 readonly unboundCache="/var/run/${packageName}/unbound.cache"
56 readonly unboundGzip="/etc/${packageName}.unbound.gz"
57 readonly unboundFilter='s|^|local-zone: "|;s|$|" static|'
58 readonly A_TMP="/var/${packageName}.hosts.a.tmp"
59 readonly B_TMP="/var/${packageName}.hosts.b.tmp"
60 readonly jsonFile="/var/run/${packageName}/${packageName}.json"
61 readonly sharedMemoryError="/dev/shm/$packageName-error"
62 readonly sharedMemoryOutput="/dev/shm/$packageName-output"
63 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;'
64 readonly domainsFilter='/^#/d;s/[[:space:]]*#.*$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
65 readonly _OK_='\033[0;32m\xe2\x9c\x93\033[0m'
66 readonly _FAIL_='\033[0;31m\xe2\x9c\x97\033[0m'
67 readonly __OK__='\033[0;32m[\xe2\x9c\x93]\033[0m'
68 readonly __FAIL__='\033[0;31m[\xe2\x9c\x97]\033[0m'
69 readonly _ERROR_='\033[0;31mERROR\033[0m'
70 readonly _WARNING_='\033[0;33mWARNING\033[0m'
71 # shellcheck disable=SC2155
72 readonly ipset="$(command -v ipset)"
73 # shellcheck disable=SC2155
74 readonly nft="$(command -v nft)"
75 readonly canaryDomainsMozilla='use-application-dns.net'
76 readonly canaryDomainsiCloud='mask.icloud.com mask-h2.icloud.com'
77 # readonly canaryDomains="$canaryDomainsMozilla $canaryDomainsiCloud"
78
79 debug() { local i j; for i in "$@"; do eval "j=\$$i"; echo "${i}: ${j} "; done; }
80
81 uci_add_list_if_new() {
82 local PACKAGE="$1"
83 local CONFIG="$2"
84 local OPTION="$3"
85 local VALUE="$4"
86 local i
87 [ -n "$PACKAGE" ] && [ -n "$CONFIG" ] && [ -n "$OPTION" ] && [ -n "$VALUE" ] || return 1
88 for i in $(uci_get "$PACKAGE" "$CONFIG" "$OPTION"); do
89 [ "$i" = "$VALUE" ] && return 0
90 done
91 uci_add_list "$PACKAGE" "$CONFIG" "$OPTION" "$VALUE"
92 }
93 uci_changes() {
94 local PACKAGE="$1"
95 local CONFIG="$2"
96 local OPTION="$3"
97 /sbin/uci ${UCI_CONFIG_DIR:+-c $UCI_CONFIG_DIR} changes "$PACKAGE${CONFIG:+.$CONFIG}${OPTION:+.$OPTION}"
98 }
99
100 ipset() { "$ipset" "$@" >/dev/null 2>&1; }
101 nft() { "$nft" "$@" >/dev/null 2>&1; }
102
103 get_status_text() {
104 local _ret
105 case "$1" in
106 statusNoInstall) _ret="$serviceName is not installed or not found";;
107 statusStopped) _ret="Stopped";;
108 statusStarting) _ret="Starting";;
109 statusRestarting) _ret="Restarting";;
110 statusForceReloading) _ret="Force Reloading";;
111 statusDownloading) _ret="Downloading";;
112 statusProcessing) _ret="Processing";;
113 statusError) _ret="Error";;
114 statusWarning) _ret="Warning";;
115 statusFail) _ret="Fail";;
116 statusSuccess) _ret="Success";;
117 esac
118 printf "%b" "$_ret"
119 }
120 get_error_text() {
121 local _ret
122 case "$1" in
123 errorOutputFileCreate) _ret="failed to create $outputFile file";;
124 errorFailDNSReload) _ret="failed to restart/reload DNS resolver";;
125 errorSharedMemory) _ret="failed to access shared memory";;
126 errorSorting) _ret="failed to sort data file";;
127 errorOptimization) _ret="failed to optimize data file";;
128 errorAllowListProcessing) _ret="failed to process allow-list";;
129 errorDataFileFormatting) _ret="failed to format data file";;
130 errorMovingDataFile) _ret="failed to move data file '${A_TMP}' to '${outputFile}'";;
131 errorCreatingCompressedCache) _ret="failed to create compressed cache";;
132 errorRemovingTempFiles) _ret="failed to remove temporary files";;
133 errorRestoreCompressedCache) _ret="failed to unpack compressed cache";;
134 errorRestoreCache) _ret="failed to move '$outputCache' to '$outputFile'";;
135 errorOhSnap) _ret="failed to create block-list or restart DNS resolver";;
136 errorStopping) _ret="failed to stop $serviceName";;
137 errorDNSReload) _ret="failed to reload/restart DNS resolver";;
138 errorDownloadingConfigUpdate) _ret="failed to download Config Update file";;
139 errorDownloadingList) _ret="failed to download";;
140 errorParsingConfigUpdate) _ret="failed to parse Config Update file";;
141 errorParsingList) _ret="failed to parse";;
142 errorNoSSLSupport) _ret="no HTTPS/SSL support on device";;
143 errorCreatingDirectory) _ret="failed to create output/cache/gzip file directory";;
144 esac
145 printf "%b" "$_ret"
146 }
147
148 output_ok() { output 1 "$_OK_"; output 2 "$__OK__\\n"; }
149 output_okn() { output 1 "$_OK_\\n"; output 2 "$__OK__\\n"; }
150 output_fail() { output 1 "$_FAIL_"; output 2 "$__FAIL__\\n"; }
151 output_failn() { output 1 "$_FAIL_\\n"; output 2 "$__FAIL__\\n"; }
152 str_replace() { printf "%b" "$1" | sed -e "s/$(printf "%b" "$2")/$(printf "%b" "$3")/g"; }
153 str_contains() { test "$1" != "$(str_replace "$1" "$2" '')"; }
154 is_greater() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }
155 is_greater_or_equal() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" = "$2"; }
156 is_chaos_calmer() { ubus -S call system board | grep -q 'Chaos Calmer'; }
157 led_on(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'default-on' > "${1}/trigger" 2>&1; fi; }
158 led_off(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'none' > "${1}/trigger" 2>&1; fi; }
159 dnsmasq_hup() { killall -q -s HUP dnsmasq; }
160 dnsmasq_kill() { killall -q -s KILL dnsmasq; }
161 dnsmasq_restart() { /etc/init.d/dnsmasq restart >/dev/null 2>&1; }
162 unbound_restart() { /etc/init.d/unbound restart >/dev/null 2>&1; }
163 is_present() { command -v "$1" >/dev/null 2>&1; }
164
165 output() {
166 # Can take a single parameter (text) to be output at any verbosity
167 # Or target verbosity level and text to be output at specifc verbosity
168 local msg memmsg logmsg
169 verbosity="${verbosity:-2}"
170 if [ $# -ne 1 ]; then
171 if [ $((verbosity & $1)) -gt 0 ] || [ "$verbosity" = "$1" ]; then shift; else return 0; fi
172 fi
173 [ -t 1 ] && printf "%b" "$1"
174 msg="${1//$serviceName /service }";
175 if [ "$(printf "%b" "$msg" | wc -l)" -gt 0 ]; then
176 [ -s "$sharedMemoryOutput" ] && memmsg="$(cat "$sharedMemoryOutput")"
177 logmsg="$(printf "%b" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
178 logger -t "${packageName:-service} [$$]" "$(printf "%b" "$logmsg")"
179 rm -f "$sharedMemoryOutput"
180 else
181 printf "%b" "$msg" >> "$sharedMemoryOutput"
182 fi
183 }
184
185 load_environment() {
186 local i j wan_if wan_gw
187 local validation_result="$1"
188
189 if [ "$validation_result" != '0' ]; then
190 output "${_ERROR_}: $packageName config validation failed!\\n"
191 output "Please check if the '$packageConfigFile' contains correct values for config options.\\n"
192 exit 1
193 fi
194
195 if [ "$enabled" -eq 0 ]; then
196 output "$packageName is currently disabled.\\n"
197 output "Run the following commands before starting service again:\\n"
198 output "uci set ${packageName}.config.enabled='1'; uci commit $packageName;\\n"
199 return 1
200 fi
201
202 if [ "$debug" -ne 0 ]; then
203 exec 1>>/tmp/simple-adblock.log
204 exec 2>&1
205 set -x
206 fi
207
208 case $dns in
209 dnsmasq.addnhosts|dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset|dnsmasq.servers)
210 if dnsmasq -v 2>/dev/null | grep -q 'no-IDN' || ! dnsmasq -v 2>/dev/null | grep -q -w 'IDN'; then
211 allow_non_ascii=0
212 fi
213 ;;
214 unbound.adb_list)
215 allow_non_ascii=1;;
216 esac
217
218 case $dns in
219 dnsmasq.ipset)
220 if dnsmasq -v 2>/dev/null | grep -q 'no-ipset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'ipset'; then
221 output "$_ERROR_: dnsmasq ipset support is enabled in $packageName, but dnsmasq is either not installed or installed dnsmasq does not support ipset!\\n"
222 dns='dnsmasq.servers'
223 fi
224 if ! ipset help hash:net; then
225 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"
226 dns='dnsmasq.servers'
227 fi
228 ;;
229 dnsmasq.nftset)
230 if dnsmasq -v 2>/dev/null | grep -q 'no-nftset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'nftset'; then
231 output "$_ERROR_: dnsmasq nft sets support is enabled in $packageName, but dnsmasq is either not installed or installed dnsmasq does not support nft sets!\\n"
232 dns='dnsmasq.servers'
233 fi
234 if [ -z "$nft" ]; then
235 output "$_ERROR_: dnsmasq nft sets support is enabled in $packageName, but nft is not installed!\\n"
236 dns='dnsmasq.servers'
237 fi
238 ;;
239 esac
240
241 case "$dns" in
242 dnsmasq.addnhosts)
243 outputFilter="$dnsmasqAddnhostsFilter"
244 outputFile="$dnsmasqAddnhostsFile"
245 outputCache="$dnsmasqAddnhostsCache"
246 outputGzip="$dnsmasqAddnhostsGzip"
247 if [ "$ipv6_enabled" -ne 0 ]; then
248 outputFilterIPv6="$dnsmasqAddnhostsFilterIPv6"
249 fi
250 rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "$dnsmasqConfGzip"
251 rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "$dnsmasqIpsetGzip"
252 rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "$dnsmasqNftsetGzip"
253 rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "$dnsmasqServersGzip"
254 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
255 ;;
256 dnsmasq.conf)
257 outputFilter="$dnsmasqConfFilter"
258 outputFile="$dnsmasqConfFile"
259 outputCache="$dnsmasqConfCache"
260 outputGzip="$dnsmasqConfGzip"
261 rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "$dnsmasqAddnhostsGzip"
262 rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "$dnsmasqIpsetGzip"
263 rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "$dnsmasqNftsetGzip"
264 rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "$dnsmasqServersGzip"
265 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
266 ;;
267 dnsmasq.ipset)
268 outputFilter="$dnsmasqIpsetFilter"
269 outputFile="$dnsmasqIpsetFile"
270 outputCache="$dnsmasqIpsetCache"
271 outputGzip="$dnsmasqIpsetGzip"
272 rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "$dnsmasqAddnhostsGzip"
273 rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "$dnsmasqConfGzip"
274 rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "$dnsmasqNftsetGzip"
275 rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "$dnsmasqServersGzip"
276 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
277 ;;
278 dnsmasq.nftset)
279 if [ "$ipv6_enabled" -ne 0 ]; then
280 outputFilter="$dnsmasqNftsetFilterIPv6"
281 else
282 outputFilter="$dnsmasqNftsetFilter"
283 fi
284 outputFile="$dnsmasqNftsetFile"
285 outputCache="$dnsmasqNftsetCache"
286 outputGzip="$dnsmasqNftsetGzip"
287 rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "$dnsmasqAddnhostsGzip"
288 rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "$dnsmasqConfGzip"
289 rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "$dnsmasqIpsetGzip"
290 rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "$dnsmasqServersGzip"
291 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
292 ;;
293 dnsmasq.servers)
294 outputFilter="$dnsmasqServersFilter"
295 outputFile="$dnsmasqServersFile"
296 outputCache="$dnsmasqServersCache"
297 outputGzip="$dnsmasqServersGzip"
298 rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "$dnsmasqAddnhostsGzip"
299 rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "$dnsmasqConfGzip"
300 rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "$dnsmasqIpsetGzip"
301 rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "$dnsmasqNftsetGzip"
302 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
303 ;;
304 unbound.adb_list)
305 outputFilter="$unboundFilter"
306 outputFile="$unboundFile"
307 outputCache="$unboundCache"
308 outputGzip="$unboundGzip"
309 rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "$dnsmasqAddnhostsGzip"
310 rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "$dnsmasqConfGzip"
311 rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "$dnsmasqIpsetGzip"
312 rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "$dnsmasqNftsetGzip"
313 rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "$dnsmasqServersGzip"
314 ;;
315 esac
316
317 for i in "$outputFile" "$outputCache" "$outputGzip"; do
318 if ! mkdir -p "$(dirname "$i")"; then
319 output "$_ERROR_: Unable to create directory for $i!\\n"
320 json add error "errorOutputFileCreate"
321 fi
322 done
323
324 . /lib/functions/network.sh
325 . /usr/share/libubox/jshn.sh
326
327 is_present 'gawk' && awk='gawk'
328 if ! is_present '/usr/libexec/grep-gnu' || ! is_present '/usr/libexec/sed-gnu' || \
329 ! is_present '/usr/libexec/sort-coreutils' || ! is_present 'gawk'; then
330 local s="opkg update; opkg --force-overwrite install"
331 is_present 'gawk' || s="$s gawk"
332 is_present '/usr/libexec/grep-gnu' || s="$s grep"
333 is_present '/usr/libexec/sed-gnu' || s="$s sed"
334 is_present '/usr/libexec/sort-coreutils' || s="$s coreutils-sort"
335 output "$_WARNING_: Some recommended packages are missing, install them by running:\\n"
336 output "$s;\\n"
337 fi
338 # Prefer curl because it supports the file:// scheme.
339 if is_present 'curl'; then
340 dl_command="curl --insecure --retry $curl_retry --connect-timeout $download_timeout --silent"
341 dl_flag="-o"
342 elif is_present '/usr/libexec/wget-ssl'; then
343 dl_command="/usr/libexec/wget-ssl --no-check-certificate --timeout $download_timeout -q"
344 dl_flag="-O"
345 elif is_present wget && wget --version 2>/dev/null | grep -q "+https"; then
346 dl_command="wget --no-check-certificate --timeout $download_timeout -q"
347 dl_flag="-O"
348 else
349 dl_command="uclient-fetch --no-check-certificate --timeout $download_timeout -q"
350 dl_flag="-O"
351 fi
352 led="${led:+/sys/class/leds/$led}"
353 if curl --version 2>/dev/null | grep -q "https" \
354 || wget --version 2>/dev/null | grep -q "+https" \
355 || grep -q "libustream-mbedtls" /usr/lib/opkg/status \
356 || grep -q "libustream-openssl" /usr/lib/opkg/status \
357 || grep -q "libustream-wolfssl" /usr/lib/opkg/status; then
358 isSSLSupported=1
359 else
360 unset isSSLSupported
361 fi
362 cache 'test_gzip' && return 0
363 network_flush_cache; network_find_wan wan_if; network_get_gateway wan_gw "$wan_if";
364 [ -n "$wan_gw" ] && return 0
365 output "$_ERROR_: $serviceName failed to discover WAN gateway.\\n"; return 1;
366 }
367
368 dnsmasq() {
369 local cfg="$1" param="$2"
370 case "$param" in
371 dnsmasq.addnhosts)
372 if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" = "$dnsmasqServersFile" ]; then
373 uci_remove 'dhcp' "$cfg" 'serversfile'
374 fi
375 uci_add_list_if_new 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
376 ;;
377 cleanup|dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset|unbound.adb_list)
378 uci_remove_list 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
379 if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" = "$dnsmasqServersFile" ]; then
380 uci_remove 'dhcp' "$cfg" 'serversfile'
381 fi
382 ;;
383 dnsmasq.servers)
384 uci_remove_list 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
385 if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" != "$dnsmasqServersFile" ]; then
386 uci_set 'dhcp' "$cfg" 'serversfile' "$dnsmasqServersFile"
387 fi
388 ;;
389 esac
390 }
391
392 dns() {
393 local param output_text i
394 case $1 in
395 on_start)
396 if [ ! -s "$outputFile" ]; then
397 json set status "statusFail"
398 json add error "errorOutputFileCreate"
399 output "$_ERROR_: $(get_error_text 'errorOutputFileCreate')!\\n"
400 return 1
401 fi
402
403 config_load 'dhcp'
404 if [ "$dns_instance" = "*" ]; then
405 config_foreach dnsmasq 'dnsmasq' "$dns"
406 elif [ -n "$dns_instance" ]; then
407 for i in $dns_instance; do
408 dnsmasq "@dnsmasq[$i]" "$dns" || dnsmasq "$i" "$dns"
409 done
410 fi
411
412 case "$dns" in
413 dnsmasq.addnhosts|dnsmasq.servers)
414 param=dnsmasq_restart
415 output_text='Reloading dnsmasq'
416 ;;
417 dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset)
418 param=dnsmasq_restart
419 output_text='Restarting dnsmasq'
420 ;;
421 unbound.adb_list)
422 param=unbound_restart
423 output_text='Restarting Unbound'
424 ;;
425 esac
426
427 if [ -n "$(uci_changes dhcp)" ]; then
428 uci_commit dhcp
429 if [ "$param" = 'unbound_restart' ]; then
430 param='dnsmasq_restart; unbound_restart;'
431 output_text='Restarting Unbound/dnsmasq'
432 else
433 param=dnsmasq_restart
434 output_text='Restarting dnsmasq'
435 fi
436 fi
437 output 1 "$output_text "
438 output 2 "$output_text "
439 json set message "$output_text"
440 if eval "$param"; then
441 json set status "statusSuccess"
442 led_on "$led"
443 output_okn
444 else
445 output_fail
446 json set status "statusFail"
447 json add error "errorDNSReload"
448 output "$_ERROR_: $(get_error_text 'errorDNSReload')!\\n"
449 return 1
450 fi
451 ;;
452 on_stop)
453 case "$dns" in
454 dnsmasq.addnhosts|dnsmasq.servers)
455 param=dnsmasq_restart
456 ;;
457 dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset)
458 param=dnsmasq_restart
459 ;;
460 unbound.adb_list)
461 param=unbound_restart
462 ;;
463 esac
464 if [ -n "$(uci_changes dhcp)" ]; then
465 uci_commit dhcp
466 if [ "$param" = 'unbound_restart' ]; then
467 param='dnsmasq_restart; unbound_restart;'
468 else
469 param=dnsmasq_restart
470 fi
471 fi
472 eval "$param"
473 return $?
474 ;;
475 quiet)
476 case "$dns" in
477 dnsmasq.addnhosts|dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset|dnsmasq.servers)
478 param=dnsmasq_restart
479 ;;
480 unbound.adb_list)
481 param=unbound_restart
482 ;;
483 esac
484 eval "$param"
485 return $?
486 ;;
487 esac
488 }
489
490 json() {
491 # shellcheck disable=SC2034
492 local action="$1" param="$2" value="$3"
493 local status message error stats
494 local reload restart curReload curRestart ret i
495 if [ -s "$jsonFile" ]; then
496 json_load_file "$jsonFile" 2>/dev/null
497 json_select 'data' 2>/dev/null
498 for i in status message error stats reload restart; do
499 json_get_var $i "$i" 2>/dev/null
500 done
501 fi
502 case "$action" in
503 get)
504 case "$param" in
505 triggers)
506 curReload="$parallel_downloads $debug $download_timeout $allowed_domain $blocked_domain $allowed_domains_url $blocked_domains_url $blocked_hosts_url $dns $config_update_enabled $config_update_url"
507 curRestart="$compressed_cache $force_dns $led $force_dns_port"
508 if [ ! -s "$jsonFile" ]; then
509 ret='on_boot'
510 elif [ "$curReload" != "$reload" ]; then
511 ret='download'
512 elif [ "$curRestart" != "$restart" ]; then
513 ret='restart'
514 fi
515 printf "%b" "$ret"
516 return;;
517 *)
518 printf "%b" "$(eval echo "\$$param")"; return;;
519 esac
520 ;;
521 add)
522 if [ -n "$(eval echo "\$$param")" ]; then
523 value="$(eval echo "\$$param") ${value}"
524 fi
525 eval "$param"='${value}'
526 ;;
527 del)
528 case "$param" in
529 all)
530 unset status message error stats;;
531 triggers)
532 unset reload restart;;
533 *)
534 unset "$param";;
535 esac
536 ;;
537 set)
538 case "$param" in
539 triggers)
540 reload="$parallel_downloads $debug $download_timeout $allowed_domain $blocked_domain $allowed_domains_url $blocked_domains_url $blocked_hosts_url $dns $config_update_enabled $config_update_url"
541 restart="$compressed_cache $force_dns $led $force_dns_port"
542 ;;
543 *)
544 eval "$param"='$value';;
545 esac
546 ;;
547 esac
548 json_init
549 json_add_object 'data'
550 json_add_string version "$PKG_VERSION"
551 json_add_string status "$status"
552 json_add_string message "$message"
553 json_add_string error "$error"
554 json_add_string stats "$stats"
555 json_add_string reload "$reload"
556 json_add_string restart "$restart"
557 json_close_object
558 json_dump > "$jsonFile"
559 sync
560 }
561
562 cache() {
563 local R_TMP
564 case "$1" in
565 create|backup)
566 [ -s "$outputFile" ] && { mv -f "$outputFile" "$outputCache"; true > "$outputFile"; } >/dev/null 2>/dev/null
567 return $?
568 ;;
569 restore|use)
570 [ -s "$outputCache" ] && mv "$outputCache" "$outputFile" >/dev/null 2>/dev/null
571 return $?
572 ;;
573 test)
574 [ -s "$outputCache" ]
575 return $?
576 ;;
577 test_gzip)
578 [ -s "$outputGzip" ] && gzip -t -c "$outputGzip"
579 return $?
580 ;;
581 create_gzip)
582 rm -f "$outputGzip" >/dev/null 2>/dev/null
583 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
584 if gzip < "$outputFile" > "$R_TMP"; then
585 if mv "$R_TMP" "$outputGzip"; then
586 rm -f "$R_TMP"
587 return 0
588 else
589 rm -f "$R_TMP"
590 return 1
591 fi
592 else
593 return 1
594 fi
595 ;;
596 expand|unpack|unpack_gzip)
597 [ -s "$outputGzip" ] && gzip -dc < "$outputGzip" > "$outputCache"
598 return $?
599 ;;
600 esac
601 }
602
603 process_url() {
604 local label type D_TMP R_TMP
605 if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then return 1; fi
606 label="${1##*//}"; label="${label%%/*}";
607 if [ "$2" = 'hosts' ]; then
608 label="Hosts: $label"; filter="$hostsFilter";
609 else
610 label="Domains: $label"; filter="$domainsFilter";
611 fi
612 if [ "$3" = 'blocked' ]; then
613 type='Blocked'; D_TMP="$B_TMP";
614 else
615 type='Allowed'; D_TMP="$A_TMP";
616 fi
617 if [ "${1:0:5}" = "https" ] && [ -z "$isSSLSupported" ]; then
618 output 1 "$_FAIL_"
619 output 2 "[DL] $type $label $__FAIL__\\n"
620 echo "errorNoSSLSupport|${1}" >> "$sharedMemoryError"
621 return 0
622 fi
623 while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
624 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
625 done
626 if ! $dl_command "$1" $dl_flag "$R_TMP" 2>/dev/null || [ ! -s "$R_TMP" ]; then
627 output 1 "$_FAIL_"
628 output 2 "[DL] $type $label $__FAIL__\\n"
629 echo "errorDownloadingList|${1}" >> "$sharedMemoryError"
630 else
631 sed -i "$filter" "$R_TMP"
632 if [ ! -s "$R_TMP" ]; then
633 output 1 "$_FAIL_"
634 output 2 "[DL] $type $label $__FAIL__\\n"
635 echo "errorParsingList|${1}" >> "$sharedMemoryError"
636 else
637 cat "${R_TMP}" >> "$D_TMP"
638 output 1 "$_OK_"
639 output 2 "[DL] $type $label $__OK__\\n"
640 fi
641 fi
642 rm -f "$R_TMP"
643 return 0
644 }
645
646 download_lists() {
647 local hf w_filter j=0 R_TMP
648
649 json set message "$(get_status_text "statusDownloading")..."
650 json set status "statusDownloading"
651
652 rm -f "$A_TMP" "$B_TMP" "$outputFile" "$outputCache" "$outputGzip"
653 if [ "$($awk '/^MemFree/ {print int($2/1000)}' "/proc/meminfo")" -lt 32 ]; then
654 output 3 'Low free memory, restarting resolver '
655 if dns 'quiet'; then
656 output_okn
657 else
658 output_fail
659 fi
660 fi
661 touch $A_TMP; touch $B_TMP;
662 output 1 'Downloading lists '
663 rm -f "$sharedMemoryError"
664 for hf in ${blocked_hosts_url}; do
665 if [ "$parallel_downloads" -gt 0 ]; then
666 process_url "$hf" 'hosts' 'blocked' &
667 else
668 process_url "$hf" 'hosts' 'blocked'
669 fi
670 done
671 for hf in ${blocked_domains_url}; do
672 if [ "$parallel_downloads" -gt 0 ]; then
673 process_url "$hf" 'domains' 'blocked' &
674 else
675 process_url "$hf" 'domains' 'blocked'
676 fi
677 done
678 for hf in ${allowed_domains_url}; do
679 if [ "$parallel_downloads" -gt 0 ]; then
680 process_url "$hf" 'domains' 'allowed' &
681 else
682 process_url "$hf" 'domains' 'allowed'
683 fi
684 done
685 wait
686 output 1 '\n'
687 if [ -s "$sharedMemoryError" ]; then
688 while IFS= read -r line; do
689 json add error "$line"
690 done < "$sharedMemoryError"
691 rm -f "$sharedMemoryError"
692 fi
693
694 if [ "$canary_domains_icloud" -ne 0 ]; then
695 canaryDomains="${canaryDomains:+$canaryDomains }${canaryDomainsiCloud}"
696 fi
697 if [ "$canary_domains_mozilla" -ne 0 ]; then
698 canaryDomains="${canaryDomains:+$canaryDomains }${canaryDomainsMozilla}"
699 fi
700
701 for hf in $blocked_domain $canaryDomains; do echo "$hf" | sed "$domainsFilter" >> $B_TMP; done
702 allowed_domain="${allowed_domain}
703 $(cat $A_TMP)"
704 for hf in ${allowed_domain}; do hf="$(echo "$hf" | sed 's/\./\\./g')"; w_filter="$w_filter/^${hf}$/d;/\.${hf}$/d;"; done
705
706 [ ! -s "$B_TMP" ] && return 1
707
708 output 1 'Processing downloads '
709 output 2 'Sorting combined list '
710 json set message "$(get_status_text "statusProcessing"): sorting combined list"
711 if [ "$allow_non_ascii" -gt 0 ]; then
712 if sort -u "$B_TMP" > "$A_TMP"; then
713 output_ok
714 else
715 output_failn
716 json add error "errorSorting"
717 fi
718 else
719 if sort -u "$B_TMP" | grep -E -v '[^a-zA-Z0-9=/.-]' > "$A_TMP"; then
720 output_ok
721 else
722 output_failn
723 json add error "errorSorting"
724 fi
725 fi
726
727 if [ "$dns" = 'dnsmasq.conf' ] || \
728 [ "$dns" = 'dnsmasq.ipset' ] || \
729 [ "$dns" = 'dnsmasq.nftset' ] || \
730 [ "$dns" = 'dnsmasq.servers' ] || \
731 [ "$dns" = 'unbound.adb_list' ]; then
732 # TLD optimization written by Dirk Brenken (dev@brenken.org)
733 output 2 'Optimizing combined list '
734 json set message "$(get_status_text "statusProcessing"): optimizing combined list"
735 # sed -E 'G;:t;s/(.*)(\.)(.*)(\n)(.*)/\1\4\5\2\3/;tt;s/(.*)\n(\.)(.*)/\3\2\1/' is actually slower than command below
736 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$A_TMP" > "$B_TMP"; then
737 if sort "$B_TMP" > "$A_TMP"; then
738 if $awk '{if(NR=1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "$A_TMP" > "$B_TMP"; then
739 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$B_TMP" > "$A_TMP"; then
740 if sort -u "$A_TMP" > "$B_TMP"; then
741 output_ok
742 else
743 output_failn
744 json add error "errorOptimization"
745 mv "$A_TMP" "$B_TMP"
746 fi
747 else
748 output_failn
749 json add error "errorOptimization"
750 fi
751 else
752 output_failn
753 json add error "errorOptimization"
754 mv "$A_TMP" "$B_TMP"
755 fi
756 else
757 output_failn
758 json add error "errorOptimization"
759 fi
760 else
761 output_failn
762 json add error "errorOptimization"
763 mv "$A_TMP" "$B_TMP"
764 fi
765 else
766 mv "$A_TMP" "$B_TMP"
767 fi
768
769 output 2 'Allowing domains '
770 json set message "$(get_status_text "statusProcessing"): allowing domains"
771 if sed -i "$w_filter" "$B_TMP"; then
772 output_ok
773 else
774 output_failn
775 json add error "errorAllowListProcessing"
776 fi
777
778 output 2 'Formatting merged file '
779 json set message "$(get_status_text "statusProcessing"): formatting merged file"
780 if [ -z "$outputFilterIPv6" ]; then
781 if sed "$outputFilter" "$B_TMP" > "$A_TMP"; then
782 output_ok
783 else
784 output_failn
785 json add error "errorDataFileFormatting"
786 fi
787 else
788 case "$dns" in
789 dnsmasq.addnhosts)
790 if sed "$outputFilter" "$B_TMP" > "$A_TMP" && \
791 sed "$outputFilterIPv6" "$B_TMP" >> "$A_TMP"; then
792 output_ok
793 else
794 output_failn
795 json add error "errorDataFileFormatting"
796 fi
797 ;;
798 esac
799 fi
800
801 case "$dns" in
802 dnsmasq.addnhosts)
803 output 2 'Creating dnsmasq addnhosts file '
804 json set message "$(get_status_text "statusProcessing"): creating dnsmasq addnhosts file"
805 ;;
806 dnsmasq.conf)
807 output 2 'Creating dnsmasq config file '
808 json set message "$(get_status_text "statusProcessing"): creating dnsmasq config file"
809 ;;
810 dnsmasq.ipset)
811 output 2 'Creating dnsmasq ipset file '
812 json set message "$(get_status_text "statusProcessing"): creating dnsmasq ipset file"
813 ;;
814 dnsmasq.nftset)
815 output 2 'Creating dnsmasq nft set file '
816 json set message "$(get_status_text "statusProcessing"): creating dnsmasq nft set file"
817 ;;
818 dnsmasq.servers)
819 output 2 'Creating dnsmasq servers file '
820 json set message "$(get_status_text "statusProcessing"): creating dnsmasq servers file"
821 ;;
822 unbound.adb_list)
823 output 2 'Creating Unbound adb_list file '
824 json set message "$(get_status_text "statusProcessing"): creating Unbound adb_list file"
825 ;;
826 esac
827
828 if mv "$A_TMP" "$outputFile"; then
829 output_ok
830 else
831 output_failn
832 json add error "errorMovingDataFile"
833 fi
834 if [ "$compressed_cache" -gt 0 ]; then
835 output 2 'Creating compressed cache '
836 json set message "$(get_status_text "statusProcessing"): creating compressed cache"
837 if cache 'create_gzip'; then
838 output_ok
839 else
840 output_failn
841 json add error "errorCreatingCompressedCache"
842 fi
843 else
844 rm -f "$outputGzip"
845 fi
846 output 2 'Removing temporary files '
847 json set message "$(get_status_text "statusProcessing"): removing temporary files"
848 rm -f "/tmp/${packageName}_tmp.*" "$A_TMP" "$B_TMP" "$outputCache" || j=1
849 if [ $j -eq 0 ]; then
850 output_ok
851 else
852 output_failn
853 json add error "errorRemovingTempFiles"
854 fi
855 output 1 '\n'
856 }
857
858 adb_allow() {
859 local c hf string="$1"
860 local validation_result="$3"
861 load_environment "$validation_result"
862 if [ ! -s "$outputFile" ]; then
863 output "No block-list ('$outputFile') found.\\n"
864 elif [ -z "$string" ]; then
865 output "Usage: /etc/init.d/${packageName} allow 'domain' ...\\n"
866 else
867 case "$dns" in
868 dnsmasq.addnhosts|dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset|dnsmasq.servers)
869 output 1 "Allowing domain(s) and restarting dnsmasq "
870 output 2 "Allowing domain(s) \\n"
871 for c in $string; do
872 output 2 " $c "
873 hf="$(echo "$c" | sed 's/\./\\./g')"
874 if sed -i "/^${hf}$/d;/\.${hf}$/d;" "$outputFile" && \
875 uci_add_list_if_new "${packageName}" 'config' 'allowed_domain' "$c"; then
876 output_ok
877 else
878 output_fail
879 fi
880 done
881 if [ "$compressed_cache" -gt 0 ]; then
882 output 2 'Creating compressed cache '
883 if cache 'create_gzip'; then
884 output_ok
885 else
886 output_failn
887 fi
888 fi
889 output 2 "Committing changes to config "
890 if [ -n "$(uci_changes "$packageName")" ] && uci_commit "$packageName"; then
891 allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
892 json set triggers
893 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
894 output_ok;
895 if [ "$dns" = 'dnsmasq.ipset' ]; then
896 output 2 "Flushing adb ipset "
897 if ipset -q -! flush adb; then output_ok; else output_fail; fi
898 fi
899 if [ "$dns" = 'dnsmasq.nftset' ]; then
900 output 2 "Flushing adb nft sets "
901 nft flush set inet fw4 adb6
902 if nft flush set inet fw4 adb4; then output_ok; else output_fail; fi
903 fi
904 output 2 "Restarting dnsmasq "
905 if dnsmasq_restart; then output_okn; else output_failn; fi
906 else
907 output_fail;
908 fi
909 ;;
910 unbound.adb_list)
911 output 1 "Allowing domain(s) and restarting Unbound "
912 output 2 "Allowing domain(s) \\n"
913 for c in $string; do
914 output 2 " $c "
915 if sed -i "/${string}/d" "$outputFile" && \
916 uci_add_list_if_new "$packageName" 'config' 'allowed_domain' "$string"; then
917 output_ok
918 else
919 output_fail
920 fi
921 done
922 if [ "$compressed_cache" -gt 0 ]; then
923 output 2 'Creating compressed cache '
924 if cache 'create_gzip'; then
925 output_ok
926 else
927 output_failn
928 fi
929 fi
930 output 2 "Committing changes to config "
931 if [ -n "$(uci_changes "$packageName")" ] && uci_commit "$packageName"; then
932 allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
933 json set triggers
934 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
935 output_ok;
936 output 2 "Restarting Unbound "
937 if unbound_restart; then output_okn; else output_failn; fi
938 else
939 output_fail;
940 fi
941 ;;
942 esac
943 fi
944 }
945
946 adb_check() {
947 local c param="$1"
948 local validation_result="$3"
949 load_environment "$validation_result"
950 if [ ! -s "$outputFile" ]; then
951 output "No block-list ('$outputFile') found.\\n"
952 elif [ -z "$param" ]; then
953 output "Usage: /etc/init.d/${packageName} check 'domain' ...\\n"
954 else
955 for string in ${param}; do
956 c="$(grep -c "$string" "$outputFile")"
957 if [ "$c" -gt 0 ]; then
958 if [ "$c" -eq 1 ]; then
959 output "Found 1 match for '$string' in '$outputFile'.\\n"
960 else
961 output "Found $c matches for '$string' in '$outputFile'.\\n"
962 fi
963 if [ "$c" -le 20 ]; then
964 case "$dns" in
965 dnsmasq.addnhosts)
966 grep "$string" "$outputFile" | sed 's|^127.0.0.1 ||;s|^:: ||;';;
967 dnsmasq.conf)
968 grep "$string" "$outputFile" | sed 's|local=/||;s|/$||;';;
969 dnsmasq.ipset)
970 grep "$string" "$outputFile" | sed 's|ipset=/||;s|/adb$||;';;
971 dnsmasq.nftset)
972 grep "$string" "$outputFile" | sed 's|nftset=/||;s|/4#inet#adb#adb4||;';;
973 dnsmasq.servers)
974 grep "$string" "$outputFile" | sed 's|server=/||;s|/$||;';;
975 unbound.adb_list)
976 grep "$string" "$outputFile" | sed 's|^local-zone: "||;s|" static$||;';;
977 esac
978 fi
979 else
980 output "The '$string' is not found in current block-list ('$outputFile').\\n"
981 fi
982 done
983 fi
984 }
985
986 adb_config_update() {
987 local R_TMP label
988 local param="$1" validation_result="$3"
989 load_environment "$validation_result"
990 label="${config_update_url##*//}"
991 label="${label%%/*}";
992 [ "$config_update_enabled" -ne 0 ] || return 0
993
994 if [ "$param" != 'download' ]; then
995 cache 'test' && return 0
996 cache 'test_gzip' && return 0
997 fi
998 output 1 'Updating config '
999 while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
1000 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
1001 done
1002 if ! $dl_command "$config_update_url" $dl_flag "$R_TMP" 2>/dev/null || [ ! -s "$R_TMP" ]; then
1003 output 1 "$_FAIL_\\n"
1004 output 2 "[DL] Config Update: $label $__FAIL__\\n"
1005 json add error "errorDownloadingConfigUpdate"
1006 else
1007 if [ -s "$R_TMP" ] && sed -f "$R_TMP" -i "$packageConfigFile" 2>/dev/null; then
1008 output 1 "$_OK_\\n"
1009 output 2 "[DL] Config Update: $label $__OK__\\n"
1010 else
1011 output 1 "$_FAIL_\\n"
1012 output 2 "[DL] Config Update: $label $__FAIL__\\n"
1013 json add error "errorParsingConfigUpdate"
1014 fi
1015 fi
1016 rm -f "$R_TMP"
1017 return 0
1018 }
1019
1020 adb_sizes() {
1021 local i
1022 local validation_result="$3"
1023 load_environment "$validation_result"
1024
1025 echo "# $(date)"
1026 for i in $blocked_domains_url; do
1027 [ "${i//melmac}" != "$i" ] && continue
1028 if $dl_command "$i" $dl_flag /tmp/sast 2>/dev/null && [ -s /tmp/sast ]; then
1029 echo "# File size: $(du -sh /tmp/sast | $awk '{print $1}')"
1030 if is_greater "$(du -sk /tmp/sast)" "500"; then
1031 echo "# block-list too big for most routers"
1032 elif is_greater "$(du -sk /tmp/sast)" "100"; then
1033 echo "# block-list may be too big for some routers"
1034 fi
1035 rm -rf /tmp/sast
1036 echo " list blocked_domains_url '$i'"
1037 echo ""
1038 else
1039 echo "# site was down on last check"
1040 echo "# list blocked_domains_url '$i'"
1041 echo ""
1042 fi
1043 done
1044 for i in $blocked_hosts_url; do
1045 if $dl_command "$i" $dl_flag /tmp/sast 2>/dev/null && [ -s /tmp/sast ]; then
1046 echo "# File size: $(du -sh /tmp/sast | $awk '{print $1}')"
1047 if is_greater "$(du -sk /tmp/sast)" "500"; then
1048 echo "# block-list too big for most routers"
1049 elif is_greater "$(du -sk /tmp/sast)" "100"; then
1050 echo "# block-list may be too big for some routers"
1051 fi
1052 rm -rf /tmp/sast
1053 echo " list blocked_hosts_url '$i'"
1054 echo ""
1055 else
1056 echo "# site was down on last check"
1057 echo "# list blocked_hosts_url '$i'"
1058 echo ""
1059 fi
1060 done
1061 }
1062
1063 adb_start() {
1064 local action status error message stats c
1065 local validation_result="$3"
1066
1067 load_environment "$validation_result"
1068
1069 status="$(json get status)"
1070 error="$(json get error)"
1071 message="$(json get message)"
1072 stats="$(json get stats)"
1073 action="$(json get triggers)"
1074
1075 if [ "$action" = 'on_boot' ] || [ "$1" = 'on_boot' ]; then
1076 if cache 'test_gzip' || cache 'test'; then
1077 action='restore'
1078 else
1079 action='download'
1080 fi
1081 elif [ "$action" = 'download' ] || [ "$1" = 'download' ] || [ -n "$error" ]; then
1082 action='download'
1083 elif [ ! -s "$outputFile" ]; then
1084 if cache 'test_gzip' || cache 'test'; then
1085 action='restore'
1086 else
1087 action='download'
1088 fi
1089 elif [ "$action" = 'restart' ] || [ "$1" = 'restart' ]; then
1090 action='restart'
1091 elif [ -s "$outputFile" ] && [ "$status" = "statusSuccess" ] && [ -z "$error" ]; then
1092 status_service
1093 exit 0
1094 else
1095 action='download'
1096 fi
1097
1098 json del all
1099 json set triggers
1100
1101 procd_open_instance 'main'
1102 procd_set_param command /bin/true
1103 procd_set_param stdout 1
1104 procd_set_param stderr 1
1105 procd_open_data
1106 json_add_array firewall
1107 if [ "$force_dns" -ne 0 ]; then
1108 for c in $force_dns_port; do
1109 if netstat -tuln | grep LISTEN | grep ":${c}" >/dev/null 2>&1; then
1110 json_add_object ""
1111 json_add_string type redirect
1112 json_add_string target DNAT
1113 json_add_string src lan
1114 json_add_string proto "tcp udp"
1115 json_add_string src_dport "$c"
1116 json_add_string dest_port "$c"
1117 json_add_boolean reflection 0
1118 json_close_object
1119 else
1120 json_add_object ""
1121 json_add_string type rule
1122 json_add_string src lan
1123 json_add_string dest "*"
1124 json_add_string proto "tcp udp"
1125 json_add_string dest_port "$c"
1126 json_add_string target REJECT
1127 json_close_object
1128 fi
1129 done
1130 fi
1131 case "$dns" in
1132 dnsmasq.ipset)
1133 json_add_object ""
1134 json_add_string type ipset
1135 json_add_string name adb
1136 json_add_string match dest_net
1137 json_add_string storage hash
1138 json_close_object
1139 json_add_object ""
1140 json_add_string type rule
1141 json_add_string ipset adb
1142 json_add_string src lan
1143 json_add_string dest "*"
1144 json_add_string proto "tcp udp"
1145 json_add_string target REJECT
1146 json_close_object
1147 ;;
1148 dnsmasq.nftset)
1149 json_add_object ""
1150 json_add_string type ipset
1151 json_add_string name adb4
1152 json_add_string family 4
1153 json_add_string match dest_net
1154 json_close_object
1155 json_add_object ""
1156 json_add_string type rule
1157 json_add_string ipset adb4
1158 json_add_string src lan
1159 json_add_string dest "*"
1160 json_add_string proto "tcp udp"
1161 json_add_string target REJECT
1162 json_close_object
1163 if [ "$ipv6_enabled" -ne 0 ]; then
1164 json_add_object ""
1165 json_add_string type ipset
1166 json_add_string name adb6
1167 json_add_string family 6
1168 json_add_string match dest_net
1169 json_close_object
1170 json_add_object ""
1171 json_add_string type rule
1172 json_add_string ipset adb6
1173 json_add_string src lan
1174 json_add_string dest "*"
1175 json_add_string proto "tcp udp"
1176 json_add_string target REJECT
1177 json_close_object
1178 fi
1179 ;;
1180 esac
1181 json_close_array
1182 procd_close_data
1183 procd_close_instance
1184
1185 if [ "$action" = 'restore' ]; then
1186 output 0 "Starting $serviceName... "
1187 output 3 "Starting $serviceName...\\n"
1188 json set status "statusStarting"
1189 if cache 'test_gzip' && ! cache 'test' && [ ! -s "$outputFile" ]; then
1190 output 3 'Found compressed cache file, unpacking it '
1191 json set message 'found compressed cache file, unpacking it.'
1192 if cache 'unpack_gzip'; then
1193 output_okn
1194 else
1195 output_failn
1196 json add error "errorRestoreCompressedCache"
1197 output "$_ERROR_: $(get_error_text 'errorRestoreCompressedCache')!\\n"
1198 action='download'
1199 fi
1200 fi
1201 if cache 'test' && [ ! -s "$outputFile" ]; then
1202 output 3 'Found cache file, reusing it '
1203 json set message 'found cache file, reusing it.'
1204 if cache 'restore'; then
1205 output_okn
1206 dns 'on_start'
1207 else
1208 output_failn
1209 json add error "errorRestoreCache"
1210 output "$_ERROR_: $(get_error_text 'errorRestoreCache')!\\n"
1211 action='download'
1212 fi
1213 fi
1214 fi
1215 if [ "$action" = 'download' ]; then
1216 if [ -s "$outputFile" ] || cache 'test' || cache 'test_gzip'; then
1217 output 0 "Force-reloading $serviceName... "
1218 output 3 "Force-reloading $serviceName...\\n"
1219 json set status "statusForceReloading"
1220 else
1221 output 0 "Starting $serviceName... "
1222 output 3 "Starting $serviceName...\\n"
1223 json set status "statusStarting"
1224 fi
1225 download_lists
1226 dns 'on_start'
1227 fi
1228 if [ "$action" = 'restart' ]; then
1229 output 0 "Restarting $serviceName... "
1230 output 3 "Restarting $serviceName...\\n"
1231 json set status "statusRestarting"
1232 dns 'on_start'
1233 fi
1234 if [ "$action" = 'start' ]; then
1235 output 0 "Starting $serviceName... "
1236 output 3 "Starting $serviceName...\\n"
1237 json set status "statusStarting"
1238 dns 'on_start'
1239 fi
1240 if [ -s "$outputFile" ] && [ "$(json get status)" != "statusFail" ]; then
1241 output 0 "$__OK__\\n";
1242 json del message
1243 json set status "statusSuccess"
1244 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
1245 status_service
1246 else
1247 output 0 "$__FAIL__\\n";
1248 json set status "statusFail"
1249 json add error "errorOhSnap"
1250 status_service
1251 fi
1252 }
1253
1254 adb_status() {
1255 local c url status message error stats
1256 local validation_result="$3"
1257 load_environment "$validation_result"
1258 status="$(json get status)"
1259 message="$(json get message)"
1260 error="$(json get error)"
1261 stats="$(json get stats)"
1262 if [ "$status" = "statusSuccess" ]; then
1263 output "$stats "; output_okn;
1264 else
1265 [ -n "$status" ] && status="$(get_status_text "$status")"
1266 if [ -n "$status" ] && [ -n "$message" ]; then
1267 status="${status}: $message"
1268 fi
1269 [ -n "$status" ] && output "$serviceName $status\\n"
1270 fi
1271 if [ -n "$error" ]; then
1272 for c in $error; do
1273 url="${c##*|}"
1274 c="${c%|*}"
1275 case "$c" in
1276 errorDownloadingList|errorParsingList)
1277 output "$_ERROR_: $(get_error_text "$c") $url!\\n";;
1278 *)
1279 output "$_ERROR_: $(get_error_text "$c")!\\n";;
1280 esac
1281 n=$((n+1))
1282 done
1283 fi
1284 }
1285
1286 adb_stop() {
1287 local validation_result="$3"
1288 load_environment "$validation_result"
1289 if [ -s "$outputFile" ]; then
1290 output "Stopping $serviceName... "
1291 cache 'create'
1292 if dns 'on_stop'; then
1293 ipset -q -! flush adb
1294 ipset -q -! destroy adb
1295 nft delete set inet fw4 adb4
1296 nft delete set inet fw4 adb6
1297 led_off "$led"
1298 output 0 "$__OK__\\n"; output_okn;
1299 json set status "statusStopped"
1300 json del message
1301 else
1302 output 0 "$__FAIL__\\n"; output_fail;
1303 json set status "statusFail"
1304 json add error "errorStopping"
1305 output "$_ERROR_: $(get_error_text 'errorStopping')!\\n"
1306 fi
1307 fi
1308 }
1309
1310 boot() {
1311 local boot_delay
1312 config_load "$packageName"
1313 config_get boot_delay 'config' 'boot_delay' '120'
1314 sleep "$boot_delay" >/dev/null 2>&1
1315 rc_procd start_service 'on_boot' && rc_procd service_triggers
1316 }
1317 service_started() { procd_set_config_changed firewall; }
1318 service_stopped() { procd_set_config_changed firewall; }
1319 restart_service() { rc_procd start_service 'restart'; }
1320 reload_service() { rc_procd start_service 'restart'; }
1321 start_service() {
1322 load_validate_config 'config' adb_config_update "'$*'"
1323 load_validate_config 'config' adb_start "'$*'"
1324 }
1325 stop_service() { load_validate_config 'config' adb_stop "'$*'"; }
1326 status_service() { load_validate_config 'config' adb_status "''"; }
1327 service_triggers() {
1328 procd_open_trigger
1329 procd_add_config_trigger 'config.change' "${packageName}" /etc/init.d/${packageName} reload
1330 procd_add_reload_interface_trigger 'wan'
1331 procd_add_interface_trigger 'interface.*.up' 'wan' /etc/init.d/${packageName} reload
1332 procd_close_trigger
1333 }
1334 allow() { load_validate_config 'config' adb_allow "'$*'"; }
1335 check() { load_validate_config 'config' adb_check "'$*'"; }
1336 dl() { rc_procd start_service 'download'; }
1337 killcache() {
1338 rm -f "$dnsmasqAddnhostsCache" "$dnsmasqAddnhostsGzip"
1339 rm -f "$dnsmasqConfCache" "$dnsmasqConfGzip"
1340 rm -f "$dnsmasqIpsetCache" "$dnsmasqIpsetGzip"
1341 rm -f "$dnsmasqNftsetCache" "$dnsmasqNftsetGzip"
1342 rm -f "$dnsmasqServersCache" "$dnsmasqServersGzip"
1343 rm -f "$unboundCache" "$unboundGzip"
1344 config_load 'dhcp'
1345 config_foreach dnsmasq 'dnsmasq' 'cleanup'
1346 uci_commit 'dhcp'
1347 return 0
1348 }
1349 sizes() { load_validate_config 'config' adb_sizes "''"; }
1350 version() { echo "$PKG_VERSION"; }
1351
1352 load_validate_config() {
1353 local dl_command
1354 local dl_flag
1355 local isSSLSupported
1356 local outputFilter
1357 local outputFilterIPv6
1358 local outputFile
1359 local outputGzip
1360 local outputCache
1361 local awk='awk'
1362 local enabled
1363 local force_dns
1364 local force_dns_port
1365 local parallel_downloads
1366 local debug
1367 local compressed_cache
1368 local ipv6_enabled
1369 local allow_non_ascii
1370 local canary_domains_icloud
1371 local canary_domains_mozilla
1372 local config_update_enabled
1373 local config_update_url
1374 local boot_delay
1375 local download_timeout
1376 local curl_retry
1377 local verbosity
1378 local led
1379 local dns
1380 local dns_instance
1381 local allowed_domain
1382 local allowed_domains_url
1383 local blocked_domain
1384 local blocked_domains_url
1385 local blocked_hosts_url
1386 uci_load_validate "$packageName" "$packageName" "$1" "${2}${3:+ $3}" \
1387 'enabled:bool:0' \
1388 'force_dns:bool:1' \
1389 'force_dns_port:list(integer):53 853' \
1390 'parallel_downloads:bool:1' \
1391 'debug:bool:0' \
1392 'compressed_cache:bool:0' \
1393 'ipv6_enabled:bool:0' \
1394 'allow_non_ascii:bool:0' \
1395 'canary_domains_icloud:bool:0' \
1396 'canary_domains_mozilla:bool:0' \
1397 'config_update_enabled:bool:0' \
1398 'config_update_url:string:https://cdn.jsdelivr.net/gh/openwrt/packages/net/simple-adblock/files/simple-adblock.conf.update' \
1399 'boot_delay:range(0,240):120' \
1400 'download_timeout:range(1,40):20' \
1401 'curl_retry:range(1,5):3' \
1402 'verbosity:range(0,2):2' \
1403 'led:or("", "none", file, device, string)' \
1404 'dns:or("dnsmasq.addnhosts", "dnsmasq.conf", "dnsmasq.ipset", "dnsmasq.servers", "unbound.adb_list"):dnsmasq.servers' \
1405 'dns_instance:or(list(integer, string)):0' \
1406 'allowed_domain:list(string)' \
1407 'allowed_domains_url:list(string)' \
1408 'blocked_domain:list(string)' \
1409 'blocked_domains_url:list(string)' \
1410 'blocked_hosts_url:list(string)'
1411 }