adblock-fast: bugfix: pause command
[feed/packages.git] / net / adblock-fast / files / etc / init.d / adblock-fast
1 #!/bin/sh /etc/rc.common
2 # Copyright 2023 MOSSDeF, Stan Grishin (stangri@melmac.ca)
3 # shellcheck disable=SC3043
4
5 # shellcheck disable=SC2034
6 START=94
7 # shellcheck disable=SC2034
8 USE_PROCD=1
9 LC_ALL=C
10
11 readonly PKG_VERSION='dev-test'
12 readonly packageName='adblock-fast'
13 readonly serviceName="$packageName $PKG_VERSION"
14 readonly packageConfigFile="/etc/config/${packageName}"
15 readonly dnsmasqAddnhostsFile="/var/run/${packageName}/dnsmasq.addnhosts"
16 readonly dnsmasqAddnhostsCache="/var/run/${packageName}/dnsmasq.addnhosts.cache"
17 readonly dnsmasqAddnhostsGzip="${packageName}.dnsmasq.addnhosts.gz"
18 readonly dnsmasqAddnhostsFilter='s|^|127.0.0.1 |;s|$||'
19 readonly dnsmasqAddnhostsFilterIPv6='s|^|:: |;s|$||'
20 readonly dnsmasqConfFile="/tmp/dnsmasq.d/${packageName}"
21 readonly dnsmasqConfCache="/var/run/${packageName}/dnsmasq.conf.cache"
22 readonly dnsmasqConfGzip="${packageName}.dnsmasq.conf.gz"
23 readonly dnsmasqConfFilter='s|^|local=/|;s|$|/|'
24 readonly dnsmasqIpsetFile="/tmp/dnsmasq.d/${packageName}.ipset"
25 readonly dnsmasqIpsetCache="/var/run/${packageName}/dnsmasq.ipset.cache"
26 readonly dnsmasqIpsetGzip="${packageName}.dnsmasq.ipset.gz"
27 readonly dnsmasqIpsetFilter='s|^|ipset=/|;s|$|/adb|'
28 readonly dnsmasqNftsetFile="/tmp/dnsmasq.d/${packageName}.nftset"
29 readonly dnsmasqNftsetCache="/var/run/${packageName}/dnsmasq.nftset.cache"
30 readonly dnsmasqNftsetGzip="${packageName}.dnsmasq.nftset.gz"
31 readonly dnsmasqNftsetFilter='s|^|nftset=/|;s|$|/4#inet#fw4#adb4|'
32 readonly dnsmasqNftsetFilterIPv6='s|^|nftset=/|;s|$|/4#inet#fw4#adb4,6#inet#fw4#adb6|'
33 readonly dnsmasqServersFile="/var/run/${packageName}/dnsmasq.servers"
34 readonly dnsmasqServersCache="/var/run/${packageName}/dnsmasq.servers.cache"
35 readonly dnsmasqServersGzip="${packageName}.dnsmasq.servers.gz"
36 readonly dnsmasqServersFilter='s|^|server=/|;s|$|/|'
37 readonly smartdnsDomainSetFile="/var/run/${packageName}/smartdns.domainset"
38 readonly smartdnsDomainSetCache="/var/run/${packageName}/smartdns.domainset.cache"
39 readonly smartdnsDomainSetConfig="/var/run/${packageName}/smartdns.domainset.conf"
40 readonly smartdnsDomainSetGzip="${packageName}.smartdns.domainset.gz"
41 readonly smartdnsDomainSetFilter=';'
42 readonly smartdnsIpsetFile="/var/run/${packageName}/smartdns.ipset"
43 readonly smartdnsIpsetCache="/var/run/${packageName}/smartdns.ipset.cache"
44 readonly smartdnsIpsetConfig="/var/run/${packageName}/smartdns.ipset.conf"
45 readonly smartdnsIpsetGzip="${packageName}.smartdns.ipset.gz"
46 readonly smartdnsIpsetFilter=';'
47 readonly smartdnsNftsetFile="/var/run/${packageName}/smartdns.nftset"
48 readonly smartdnsNftsetCache="/var/run/${packageName}/smartdns.nftset.cache"
49 readonly smartdnsNftsetConfig="/var/run/${packageName}/smartdns.nftset.conf"
50 readonly smartdnsNftsetGzip="${packageName}.smartdns.nftset.gz"
51 readonly smartdnsNftsetFilter=';'
52 readonly unboundFile="/var/lib/unbound/adb_list.${packageName}"
53 readonly unboundCache="/var/run/${packageName}/unbound.cache"
54 readonly unboundGzip="${packageName}.unbound.gz"
55 readonly unboundFilter='s|^|local-zone: "|;s|$|" static|'
56 readonly A_TMP="/var/${packageName}.a.tmp"
57 readonly B_TMP="/var/${packageName}.b.tmp"
58 readonly SED_TMP="/var/${packageName}.sed.tmp"
59 readonly runningConfigFile="/dev/shm/${packageName}.config"
60 readonly runningErrorFile="/dev/shm/${packageName}.error"
61 readonly runningStatusFile="/dev/shm/${packageName}.status"
62 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;'
63 readonly domainsFilter='/^#/d;s/[[:space:]]*#.*$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
64 readonly adBlockPlusFilter='/^#/d;/^!/d;s/[[:space:]]*#.*$//;s/^||//;s/\^$//;s/[[:space:]]*$//;s/[[:cntrl:]]$//;/[[:space:]]/d;/[`~!@#\$%\^&\*()=+;:"'\'',<>?/\|[{}]/d;/]/d;/\./!d;/^$/d;/[^[:alnum:]_.-]/d;'
65 readonly dnsmasqFileFilter='\|^server=/[[:alnum:]_.-].*/|!d;s|server=/||;s|/.*$||'
66 readonly dnsmasq2FileFilter='\|^local=/[[:alnum:]_.-].*/|!d;s|local=/||;s|/.*$||'
67 readonly dnsmasq3FileFilter='\|^address=/[[:alnum:]_.-].*/|!d;s|address=/||;s|/.*$||'
68 readonly _ERROR_='\033[0;31mERROR\033[0m'
69 readonly _OK_='\033[0;32m\xe2\x9c\x93\033[0m'
70 readonly _FAIL_='\033[0;31m\xe2\x9c\x97\033[0m'
71 readonly __OK__='\033[0;32m[\xe2\x9c\x93]\033[0m'
72 readonly __FAIL__='\033[0;31m[\xe2\x9c\x97]\033[0m'
73 readonly _WARNING_='\033[0;33mWARNING\033[0m'
74 # shellcheck disable=SC2155
75 readonly ipset="$(command -v ipset)"
76 # shellcheck disable=SC2155
77 readonly nft="$(command -v nft)"
78 readonly canaryDomainsMozilla='use-application-dns.net'
79 readonly canaryDomainsiCloud='mask.icloud.com mask-h2.icloud.com'
80 readonly triggersReload='parallel_downloads debug download_timeout allowed_domain blocked_domain allowed_url blocked_url dns config_update_enabled config_update_url dnsmasq_config_file_url curl_additional_param curl_max_file_size curl_retry'
81 readonly triggersRestart='compressed_cache compressed_cache_dir force_dns led force_dns_port'
82
83 dl_command=
84 dl_flag=
85 isSSLSupported=
86 outputFilter=
87 outputFilterIPv6=
88 outputFile=
89 outputGzip=
90 outputCache=
91 awk='awk'
92 load_environment_flag=
93 allowed_url=
94 blocked_url=
95 fw4_restart_flag=
96
97 # shellcheck disable=SC1091
98 . /lib/functions.sh
99 # shellcheck disable=SC1091
100 . /lib/functions/network.sh
101 # shellcheck disable=SC1091
102 . /usr/share/libubox/jshn.sh
103
104 append_newline() { is_newline_ending "$1" || echo '' >> "$1"; }
105 check_ipset() { { command -v ipset && /usr/sbin/ipset help hash:net; } >/dev/null 2>&1; }
106 check_nft() { command -v nft >/dev/null 2>&1; }
107 check_dnsmasq() { command -v dnsmasq >/dev/null 2>&1; }
108 check_dnsmasq_ipset() {
109 local o;
110 check_dnsmasq || return 1
111 o="$(dnsmasq -v 2>/dev/null)"
112 check_ipset && ! echo "$o" | grep -q 'no-ipset' && echo "$o" | grep -q 'ipset'
113 }
114 check_dnsmasq_nftset() {
115 local o;
116 check_dnsmasq || return 1
117 o="$(dnsmasq -v 2>/dev/null)"
118 check_nft && ! echo "$o" | grep -q 'no-nftset' && echo "$o" | grep -q 'nftset'
119 }
120 check_smartdns() { command -v smartdns >/dev/null 2>&1; }
121 check_smartdns_ipset() { check_smartdns && check_ipset; }
122 check_smartdns_nftset() { check_smartdns && check_nft; }
123 check_unbound() { command -v unbound >/dev/null 2>&1; }
124 config_cache() {
125 local param="$1" var="$2"
126 local _reload="$triggersReload"
127 local _restart="$triggersRestart"
128 local i ret
129 case "$param" in
130 create|set)
131 cp -f "/etc/config/${packageName}" "$runningConfigFile"
132 ;;
133 get)
134 case "$var" in
135 trigger_fw4)
136 ret='false'
137 if [ -s "$runningConfigFile" ]; then
138 local UCI_CONFIG_DIR="${runningConfigFile%/*}"
139 is_fw4_restart_needed && ret='true'
140 fi
141 printf "%b" "$ret"
142 return
143 ;;
144 trigger_service)
145 local old_allowed_url old_blocked_url
146 if [ ! -s "$runningConfigFile" ]; then
147 ret='on_boot'
148 else
149 for i in $_reload; do
150 local val_current val_old UCI_CONFIG_DIR
151 case "$i" in
152 allowed_url)
153 val_current="$allowed_url"
154 config_load "$runningConfigFile"
155 config_foreach append_url 'file_url' old_allowed_url old_blocked_url
156 val_old="$old_allowed_url"
157 ;;
158 blocked_url)
159 val_current="$blocked_url"
160 config_load "$runningConfigFile"
161 config_foreach append_url 'file_url' old_allowed_url old_blocked_url
162 val_old="$old_blocked_url"
163 ;;
164 *)
165 UCI_CONFIG_DIR=
166 val_current="$(uci_get "$packageName" 'config' "$i")"
167 UCI_CONFIG_DIR="${runningConfigFile%/*}"
168 val_old="$(uci_get "$packageName" 'config' "$i")"
169 ;;
170 esac
171 if [ "$val_current" != "$val_old" ]; then
172 ret='download'
173 unset _restart
174 break
175 fi
176 done
177 for i in $_restart; do
178 local val_current val_old UCI_CONFIG_DIR
179 UCI_CONFIG_DIR=
180 val_current="$(uci_get "$packageName" 'config' "$i")"
181 UCI_CONFIG_DIR="${runningConfigFile%/*}"
182 val_old="$(uci_get "$packageName" 'config' "$i")"
183 if [ "$val_current" != "$val_old" ]; then
184 ret='restart'
185 break
186 fi
187 done
188 fi
189 printf "%b" "$ret"
190 return
191 ;;
192 *)
193 local UCI_CONFIG_DIR="${runningConfigFile%/*}"
194 ret="$(uci_get "$packageName" 'config' "$var")"
195 printf "%b" "$ret"
196 return
197 ;;
198 esac
199 ;;
200 esac
201 }
202 debug() { local i j; for i in "$@"; do eval "j=\$$i"; echo "${i}: ${j} "; done; }
203 dns_set_output_values() {
204 case "$1" in
205 dnsmasq.addnhosts)
206 outputFilter="$dnsmasqAddnhostsFilter"
207 outputFile="$dnsmasqAddnhostsFile"
208 outputCache="$dnsmasqAddnhostsCache"
209 outputGzip="${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
210 if [ "$ipv6_enabled" -ne '0' ]; then
211 outputFilterIPv6="$dnsmasqAddnhostsFilterIPv6"
212 fi
213 ;;
214 dnsmasq.conf)
215 outputFilter="$dnsmasqConfFilter"
216 outputFile="$dnsmasqConfFile"
217 outputCache="$dnsmasqConfCache"
218 outputGzip="${compressed_cache_dir}/${dnsmasqConfGzip}"
219 ;;
220 dnsmasq.ipset)
221 outputFilter="$dnsmasqIpsetFilter"
222 outputFile="$dnsmasqIpsetFile"
223 outputCache="$dnsmasqIpsetCache"
224 outputGzip="${compressed_cache_dir}/${dnsmasqIpsetGzip}"
225 ;;
226 dnsmasq.nftset)
227 if [ "$ipv6_enabled" -ne '0' ]; then
228 outputFilter="$dnsmasqNftsetFilterIPv6"
229 else
230 outputFilter="$dnsmasqNftsetFilter"
231 fi
232 outputFile="$dnsmasqNftsetFile"
233 outputCache="$dnsmasqNftsetCache"
234 outputGzip="${compressed_cache_dir}/${dnsmasqNftsetGzip}"
235 ;;
236 dnsmasq.servers)
237 outputFilter="$dnsmasqServersFilter"
238 outputFile="$dnsmasqServersFile"
239 outputCache="$dnsmasqServersCache"
240 outputGzip="${compressed_cache_dir}/${dnsmasqServersGzip}"
241 ;;
242 smartdns.domainset)
243 outputFilter="$smartdnsDomainSetFilter"
244 outputFile="$smartdnsDomainSetFile"
245 outputCache="$smartdnsDomainSetCache"
246 outputGzip="${compressed_cache_dir}/${smartdnsDomainSetGzip}"
247 outputConfig="$smartdnsDomainSetConfig"
248 ;;
249 smartdns.ipset)
250 outputFilter="$smartdnsIpsetFilter"
251 outputFile="$smartdnsIpsetFile"
252 outputCache="$smartdnsIpsetCache"
253 outputGzip="${compressed_cache_dir}/${smartdnsIpsetGzip}"
254 outputConfig="$smartdnsIpsetConfig"
255 ;;
256 smartdns.nftset)
257 outputFilter="$smartdnsNftsetFilter"
258 outputFile="$smartdnsNftsetFile"
259 outputCache="$smartdnsNftsetCache"
260 outputGzip="${compressed_cache_dir}/${smartdnsNftsetGzip}"
261 outputConfig="$smartdnsNftsetConfig"
262 ;;
263 unbound.adb_list)
264 outputFilter="$unboundFilter"
265 outputFile="$unboundFile"
266 outputCache="$unboundCache"
267 outputGzip="$unboundGzip"
268 ;;
269 esac
270 }
271 dnsmasq_hup() { killall -q -s HUP dnsmasq; }
272 dnsmasq_kill() { killall -q -s KILL dnsmasq; }
273 dnsmasq_restart() { /etc/init.d/dnsmasq restart >/dev/null 2>&1; }
274 is_enabled() { uci_get "$1" 'config' 'enabled' '0'; }
275 is_fw4_restart_needed() {
276 [ "$fw4_restart_flag" = 'true' ] && return 0
277 local dns force_dns
278 dns="$(uci_get "$packageName" 'config' 'dns' 'dnsmasq.servers')"
279 force_dns="$(uci_get "$packageName" 'config' 'force_dns' '1')"
280 if [ "$force_dns" = '1' ]; then
281 return 0
282 elif [ "$dns" = 'dnsmasq.ipset' ]; then
283 return 0
284 elif [ "$dns" = 'dnsmasq.nftset' ]; then
285 return 0
286 elif [ "$dns" = 'smartdns.ipset' ]; then
287 return 0
288 elif [ "$dns" = 'smartdns.nftset' ]; then
289 return 0
290 else
291 return 1
292 fi
293 }
294 is_integer() {
295 case "$1" in
296 (*[!0123456789]*) return 1;;
297 ('') return 1;;
298 (*) return 0;;
299 esac
300 }
301 is_greater() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; }
302 is_greater_or_equal() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" = "$2"; }
303 # shellcheck disable=SC3057
304 is_https_url() { [ "${1:0:8}" = "https://" ]; }
305 is_newline_ending() { [ "$(tail -c1 "$1" | wc -l)" -ne '0' ]; }
306 is_present() { command -v "$1" >/dev/null 2>&1; }
307 is_running() {
308 local i j
309 i="$(json 'get' 'status')"
310 j="$(ubus_get_data 'status')"
311 if [ "$i" = 'statusStopped' ] || [ -z "${i}${j}" ]; then
312 return 1
313 else
314 return 0
315 fi
316 }
317 ipset() { "$ipset" "$@" >/dev/null 2>&1; }
318 get_version() { grep -m1 -A2 -w "^Package: $1$" /usr/lib/opkg/status | sed -n 's/Version: //p'; }
319 get_ram_free() { ubus call system info | jsonfilter -e '@.memory.free'; }
320 get_ram_total() { ubus call system info | jsonfilter -e '@.memory.total'; }
321 led_on(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'default-on' > "${1}/trigger" 2>&1; fi; }
322 led_off(){ if [ -n "${1}" ] && [ -e "${1}/trigger" ]; then echo 'none' > "${1}/trigger" 2>&1; fi; }
323 logger() { /usr/bin/logger -t "$packageName" "$@"; }
324 nft() { "$nft" "$@" >/dev/null 2>&1; }
325 output_ok() { output 1 "$_OK_"; output 2 "$__OK__\\n"; }
326 output_okn() { output 1 "$_OK_\\n"; output 2 "$__OK__\\n"; }
327 output_fail() { output 1 "$_FAIL_"; output 2 "$__FAIL__\\n"; }
328 output_failn() { output 1 "$_FAIL_\\n"; output 2 "$__FAIL__\\n"; }
329 print_json_bool() { json_init; json_add_boolean "$1" "$2"; json_dump; json_cleanup; }
330 print_json_int() { json_init; json_add_int "$1" "$2"; json_dump; json_cleanup; }
331 print_json_string() { json_init; json_add_string "$1" "$2"; json_dump; json_cleanup; }
332 sanitize_dir() { [ -d "$(readlink -fn "$1")" ] && readlink -fn "$1"; }
333 smartdns_restart() { /etc/init.d/smartdns restart >/dev/null 2>&1; }
334 str_contains() { test "$1" != "$(str_replace "$1" "$2" '')"; }
335 str_contains_word() { echo "$1" | grep -q -w "$2"; }
336 # shellcheck disable=SC2018,SC2019
337 str_to_lower() { echo "$1" | tr 'A-Z' 'a-z'; }
338 # shellcheck disable=SC2018,SC2019
339 str_to_upper() { echo "$1" | tr 'a-z' 'A-Z'; }
340 str_replace() { printf "%b" "$1" | sed -e "s/$(printf "%b" "$2")/$(printf "%b" "$3")/g"; }
341 ubus_get_data() { ubus call service list "{ 'name': '$packageName' }" | jsonfilter -e "@['${packageName}'].instances.main.data.${1}"; }
342 ubus_get_ports() { ubus call service list "{ 'name': '$packageName' }" | jsonfilter -e "@['${packageName}'].instances.main.data.firewall.*.dest_port"; }
343 uci_get_protocol() { uci_get 'network' "$1" 'proto'; }
344 unbound_restart() { /etc/init.d/unbound restart >/dev/null 2>&1; }
345
346 json() {
347 # shellcheck disable=SC2034
348 local action="$1" param="$2" value="$3"
349 shift 3
350 # shellcheck disable=SC2124
351 local extras="$@" line
352 local status message error stats
353 local ret i
354 if [ -s "$runningStatusFile" ]; then
355 json_load_file "$runningStatusFile" 2>/dev/null
356 json_select 'data' 2>/dev/null
357 for i in status message error stats; do
358 json_get_var "$i" "$i" 2>/dev/null
359 done
360 fi
361 case "$action" in
362 get)
363 printf "%b" "$(eval echo "\$$param")"
364 return
365 ;;
366 add)
367 line="$(eval echo "\$$param")"
368 eval "$param"='${line:+$line }${value}${extras:+|$extras}'
369 ;;
370 del)
371 case "$param" in
372 all)
373 unset status message error stats;;
374 *)
375 unset "$param";;
376 esac
377 ;;
378 set)
379 eval "$param"='${value}${extras:+|$extras}'
380 ;;
381 esac
382 json_init
383 json_add_object 'data'
384 json_add_string version "$PKG_VERSION"
385 json_add_string status "$status"
386 json_add_string message "$message"
387 json_add_string error "$error"
388 json_add_string stats "$stats"
389 json_close_object
390 mkdir -p "${runningStatusFile%/*}"
391 json_dump > "$runningStatusFile"
392 sync
393 }
394
395 get_local_filesize() {
396 local file="$1" size
397 [ -f "$file" ] || return 0
398 if is_present stat; then
399 size="$(stat -c%s "$file")"
400 elif is_present wc; then
401 size="$(wc -c < "$file")"
402 fi
403 # shellcheck disable=SC3037
404 echo -en "$size"
405 }
406
407 get_url_filesize() {
408 local url="$1" size size_command
409 [ -n "$url" ] || return 0
410 is_present 'curl' || return 0
411 size_command='curl --silent --insecure --fail --head --request GET'
412 # size="$($size_command "$url" | grep -Po '^[cC]ontent-[lL]ength: \K\w+')"
413 size="$($size_command "$url" | grep -Eo '^[cC]ontent-[lL]ength: (.*)' | awk '{print $2}')"
414 # shellcheck disable=SC3037
415 echo -en "$size"
416 }
417
418 output() {
419 # Target verbosity level with the first parameter being an integer
420 is_integer() {
421 case "$1" in
422 (*[!0123456789]*) return 1;;
423 ('') return 1;;
424 (*) return 0;;
425 esac
426 }
427 local msg memmsg logmsg text
428 local sharedMemoryOutput="/dev/shm/$packageName-output"
429 if [ -z "$verbosity" ] && [ -n "$packageName" ]; then
430 verbosity="$(uci_get "$packageName" 'config' 'verbosity' '2')"
431 fi
432 if [ $# -ne 1 ] && is_integer "$1"; then
433 if [ $((verbosity & $1)) -gt 0 ] || [ "$verbosity" = "$1" ]; then shift; text="$*"; else return 0; fi
434 fi
435 text="${text:-$*}";
436 [ -t 1 ] && printf "%b" "$text"
437 # shellcheck disable=SC3060
438 msg="${text//$serviceName /service }";
439 if [ "$(printf "%b" "$msg" | wc -l)" -gt 0 ]; then
440 [ -s "$sharedMemoryOutput" ] && memmsg="$(cat "$sharedMemoryOutput")"
441 logmsg="$(printf "%b" "${memmsg}${msg}" | sed 's/\x1b\[[0-9;]*m//g')"
442 logger -t "${packageName:-service} [$$]" "$(printf "%b" "$logmsg")"
443 rm -f "$sharedMemoryOutput"
444 else
445 printf "%b" "$msg" >> "$sharedMemoryOutput"
446 fi
447 }
448
449 uci_add_list_if_new() {
450 local PACKAGE="$1"
451 local CONFIG="$2"
452 local OPTION="$3"
453 local VALUE="$4"
454 local i
455 [ -n "$PACKAGE" ] && [ -n "$CONFIG" ] && [ -n "$OPTION" ] && [ -n "$VALUE" ] || return 1
456 for i in $(uci_get "$PACKAGE" "$CONFIG" "$OPTION"); do
457 [ "$i" = "$VALUE" ] && return 0
458 done
459 uci_add_list "$PACKAGE" "$CONFIG" "$OPTION" "$VALUE"
460 }
461
462 uci_changes() {
463 local PACKAGE="$1"
464 local CONFIG="$2"
465 local OPTION="$3"
466 if [ -s "${UCI_CONFIG_DIR:-/etc/config/}${PACKAGE}" ]; then
467 /sbin/uci ${UCI_CONFIG_DIR:+-c $UCI_CONFIG_DIR} changes "$PACKAGE${CONFIG:+.$CONFIG}${OPTION:+.$OPTION}"
468 fi
469 }
470
471 if type extra_command 1>/dev/null 2>&1; then
472 extra_command 'allow' 'Allows domain in current block-list and config'
473 extra_command 'check' 'Checks if specified domain is found in current block-list'
474 extra_command 'check_lists' 'Checks if specified domain is found in enabled block-lists'
475 extra_command 'dl' 'Force-downloads all enabled block-list'
476 extra_command 'killcache' 'Delete all cached files'
477 extra_command 'pause' 'Pauses AdBlocking for specified number of seconds (default: 60)'
478 extra_command 'sizes' 'Displays the file-sizes of enabled block-lists'
479 extra_command 'version' 'Show version information'
480 else
481 # shellcheck disable=SC2034
482 EXTRA_COMMANDS='allow check dl killcache pause sizes status_service version'
483 # shellcheck disable=SC2034
484 EXTRA_HELP=' allow Allows domain(s) in current block-list and config
485 check Checks if specified domain is found in current block-list
486 dl Force-downloads all enabled block-list
487 pause Pauses AdBlocking for specified number of seconds (default: 60)
488 sizes Displays the file-sizes of enabled block-lists'
489 fi
490
491 get_text() {
492 local r
493 case "$1" in
494 errorConfigValidationFail) r="$packageName config validation failed";;
495 errorServiceDisabled) r="$packageName is currently disabled";;
496 errorNoDnsmasqIpset)
497 r="dnsmasq ipset support is enabled in $packageName, but dnsmasq is either not installed or installed dnsmasq does not support ipset";;
498 errorNoIpset)
499 r="dnsmasq ipset support is enabled in $packageName, but ipset is either not installed or installed ipset does not support 'hash:net' type";;
500 errorNoDnsmasqNftset)
501 r="dnsmasq nft set support is enabled in $packageName, but dnsmasq is either not installed or installed dnsmasq does not support nft set";;
502 errorNoNft) r="dnsmasq nft sets support is enabled in $packageName, but nft is not installed";;
503 errorNoWanGateway) r="The ${serviceName} failed to discover WAN gateway";;
504 errorOutputDirCreate) r="failed to create directory for %s file";;
505 errorOutputFileCreate) r="failed to create $outputFile file";;
506 errorFailDNSReload) r="failed to restart/reload DNS resolver";;
507 errorSharedMemory) r="failed to access shared memory";;
508 errorSorting) r="failed to sort data file";;
509 errorOptimization) r="failed to optimize data file";;
510 errorAllowListProcessing) r="failed to process allow-list";;
511 errorDataFileFormatting) r="failed to format data file";;
512 errorMovingDataFile) r="failed to move data file '${A_TMP}' to '${outputFile}'";;
513 errorCreatingCompressedCache) r="failed to create compressed cache";;
514 errorRemovingTempFiles) r="failed to remove temporary files";;
515 errorRestoreCompressedCache) r="failed to unpack compressed cache";;
516 errorRestoreCache) r="failed to move '$outputCache' to '$outputFile'";;
517 errorOhSnap) r="failed to create block-list or restart DNS resolver";;
518 errorStopping) r="failed to stop $serviceName";;
519 errorDNSReload) r="failed to reload/restart DNS resolver";;
520 errorDownloadingConfigUpdate) r="failed to download Config Update file";;
521 errorDownloadingList) r="failed to download";;
522 errorParsingConfigUpdate) r="failed to parse Config Update file";;
523 errorParsingList) r="failed to parse";;
524 errorNoSSLSupport) r="no HTTPS/SSL support on device";;
525 errorCreatingDirectory) r="failed to create output/cache/gzip file directory";;
526 errorDetectingFileType) r="failed to detect format";;
527 errorNothingToDo) r="no blocked list URLs nor blocked-domains enabled";;
528 errorTooLittleRam) r="free ram (%s) is not enough to process all enabled block-lists";;
529
530 statusNoInstall) r="$serviceName is not installed or not found";;
531 statusStopped) r="Stopped";;
532 statusStarting) r="Starting";;
533 statusRestarting) r="Restarting";;
534 statusForceReloading) r="Force Reloading";;
535 statusDownloading) r="Downloading";;
536 statusProcessing) r="Processing";;
537 statusFail) r="failed to start";;
538 statusSuccess) r="Success";;
539
540 warningExternalDnsmasqConfig)
541 r="use of external dnsmasq config file detected, please set 'dns' option to 'dnsmasq.conf'";;
542 warningMissingRecommendedPackages) r="some recommended packages are missing";;
543 warningInvalidCompressedCacheDir) r="invalid compressed cache directory '%s'";;
544 warningFreeRamCheckFail) r="can't detect free RAM";;
545 esac
546 shift
547 # shellcheck disable=SC2059
548 printf "$r" "$@"
549 }
550
551 load_network() {
552 local param="$1"
553 local i j wan_if wan_gw
554 local counter wan_if_timeout="$procd_boot_wan_timeout" wan_gw_timeout='5'
555 counter=0
556 while [ -z "$wan_if" ]; do
557 network_flush_cache
558 network_find_wan wan_if
559 if [ -n "$wan_if" ]; then
560 output "WAN interface found: '${wan_if}'.\\n"
561 break
562 fi
563 if [ "$counter" -gt "$wan_if_timeout" ]; then
564 output "WAN interface timeout, assuming 'wan'.\\n"
565 wan_if='wan'
566 break
567 fi
568 counter=$((counter+1))
569 output "Waiting to discover WAN Interface...\\n"
570 sleep 1
571 done
572
573 counter=0
574 if [ "$(uci_get_protocol "$wan_if")" = 'pppoe' ]; then
575 wan_gw_timeout=$((wan_gw_timeout+10))
576 fi
577 while [ "$counter" -le "$wan_gw_timeout" ]; do
578 network_flush_cache
579 network_get_gateway wan_gw "$wan_if"
580 if [ -n "$wan_gw" ]; then
581 output "WAN gateway found: '${wan_gw}.'\\n"
582 return 0
583 fi
584 counter=$((counter+1))
585 output "Waiting to discover $wan_if gateway...\\n"
586 sleep 1
587 done
588 json add error 'errorNoWanGateway'
589 output "${_ERROR_}: $(get_text 'errorNoWanGateway')!\\n"; return 1;
590 }
591
592 append_url() {
593 local cfg="$1" allow_var="${2:-allowed_url}" block_var="${3:-blocked_url}"
594 local old_value
595 local en action url
596 config_get_bool en "$cfg" enabled '1'
597 config_get action "$cfg" action 'block'
598 config_get url "$cfg" url
599 if [ "$en" = '1' ]; then
600 if [ "$action" = 'allow' ]; then
601 old_value=$(eval echo "\$$allow_var")
602 old_value="${old_value:+$old_value }${url}"
603 eval "$allow_var"="\$old_value"
604 else
605 old_value=$(eval echo "\$$block_var")
606 old_value="${old_value:+$old_value }${url}"
607 eval "$block_var"="\$old_value"
608 fi
609 fi
610 }
611
612 detect_file_type() {
613 local file="$1"
614 if [ "$(head -1 "$file")" = '[Adblock Plus]' ] || \
615 grep -q '^||' "$file"; then
616 echo 'adblockplus'
617 elif grep -q '^server=' "$file"; then
618 echo 'dnsmasq'
619 elif grep -q '^local=' "$file"; then
620 echo 'dnsmasq2'
621 elif grep -q '^address=' "$file"; then
622 echo 'dnsmasq3'
623 elif grep -q '^0\.0\.0\.0' "$file" || grep -q '^127\.0\.0\.1' "$file"; then
624 echo 'hosts'
625 elif [ -n "$(sed "$domainsFilter" "$file" | head -1)" ]; then
626 echo 'domains'
627 fi
628 }
629
630 load_environment() {
631 local i j
632 local validation_result="$1" param="$2"
633
634 [ -z "$load_environment_flag" ] || return 0
635
636 if [ "$validation_result" != '0' ]; then
637 json add error 'errorConfigValidationFail'
638 output "${_ERROR_}: $(get_text 'errorConfigValidationFail')!\\n"
639 output "Please check if the '$packageConfigFile' contains correct values for config options.\\n"
640 return 1
641 fi
642
643 if [ "$enabled" -eq 0 ]; then
644 json add error 'errorServiceDisabled'
645 output "${_ERROR_}: $(get_text 'errorServiceDisabled')!\\n"
646 output "Run the following commands before starting service again:\\n"
647 output "uci set ${packageName}.config.enabled='1'; uci commit $packageName;\\n"
648 return 1
649 fi
650
651 if [ "$debug" -ne '0' ]; then
652 exec 1>>"/tmp/$packageName.log"
653 exec 2>&1
654 set -x
655 fi
656
657 # TODO: check for resolver and error out on start
658
659 if [ -n "$dnsmasq_config_file_url" ]; then
660 case "$dns" in
661 dnsmasq.conf) :;;
662 *)
663 if [ "$param" != 'quiet' ]; then
664 json add warning 'warningExternalDnsmasqConfig'
665 output "${_WARNING_}: $(get_text 'warningExternalDnsmasqConfig')!\\n"
666 fi
667 ;;
668 esac
669 fi
670
671 case "$dns" in
672 dnsmasq.*)
673 if dnsmasq -v 2>/dev/null | grep -q 'no-IDN' || ! dnsmasq -v 2>/dev/null | grep -q -w 'IDN'; then
674 allow_non_ascii='0'
675 fi
676 ;;
677 smartdns.*)
678 allow_non_ascii='0'
679 ;;
680 unbound.*)
681 allow_non_ascii='1'
682 ;;
683 esac
684
685 case "$dns" in
686 dnsmasq.ipset)
687 if dnsmasq -v 2>/dev/null | grep -q 'no-ipset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'ipset'; then
688 if [ "$param" != 'quiet' ]; then
689 json add error 'errorNoDnsmasqIpset'
690 output "${_ERROR_}: $(get_text 'errorNoDnsmasqIpset')!\\n"
691 fi
692 dns='dnsmasq.servers'
693 fi
694 if ! ipset help hash:net; then
695 if [ "$param" != 'quiet' ]; then
696 json add error 'errorNoIpset'
697 output "${_ERROR_}: $(get_text 'errorNoIpset')!\\n"
698 fi
699 dns='dnsmasq.servers'
700 fi
701 ;;
702 dnsmasq.nftset)
703 if dnsmasq -v 2>/dev/null | grep -q 'no-nftset' || ! dnsmasq -v 2>/dev/null | grep -q -w 'nftset'; then
704 if [ "$param" != 'quiet' ]; then
705 json add error 'errorNoDnsmasqNftset'
706 output "${_ERROR_}: $(get_text 'errorNoDnsmasqNftset')!\\n"
707 fi
708 dns='dnsmasq.servers'
709 fi
710 if [ -z "$nft" ]; then
711 if [ "$param" != 'quiet' ]; then
712 json add error 'errorNoNft'
713 output "${_ERROR_}: $(get_text 'errorNoNft')!\\n"
714 fi
715 dns='dnsmasq.servers'
716 fi
717 ;;
718 smartdns.ipset)
719 if ! ipset help hash:net; then
720 if [ "$param" != 'quiet' ]; then
721 json add error 'errorNoIpset'
722 output "${_ERROR_}: $(get_text 'errorNoIpset')!\\n"
723 fi
724 dns='smartdns.domainset'
725 fi
726 ;;
727 smartdns.nftset)
728 if [ -z "$nft" ]; then
729 if [ "$param" != 'quiet' ]; then
730 json add error 'errorNoNft'
731 output "${_ERROR_}: $(get_text 'errorNoNft')!\\n"
732 fi
733 dns='smartdns.domainset'
734 fi
735 ;;
736 esac
737
738 if [ "$(sanitize_dir "$compressed_cache_dir")" = '/' ]; then
739 compressed_cache_dir=''
740 elif [ -n "$(sanitize_dir "$compressed_cache_dir")" ]; then
741 compressed_cache_dir="$(sanitize_dir "$compressed_cache_dir")"
742 else
743 json add warning 'warningInvalidCompressedCacheDir' "$compressed_cache_dir"
744 output "${_WARNING_}: $(get_text 'warningInvalidCompressedCacheDir' "$compressed_cache_dir")!\\n"
745 compressed_cache_dir="/etc"
746 fi
747
748 dns_set_output_values "$dns"
749
750 [ "$dns" = 'dnsmasq.addnhosts' ] || rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
751 [ "$dns" = 'dnsmasq.conf' ] || rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "${compressed_cache_dir}/${dnsmasqConfGzip}"
752 [ "$dns" = 'dnsmasq.ipset' ] || rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "${compressed_cache_dir}/${dnsmasqIpsetGzip}"
753 [ "$dns" = 'dnsmasq.nftset' ] || rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "${compressed_cache_dir}/${dnsmasqNftsetGzip}"
754 [ "$dns" = 'dnsmasq.servers' ] || rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "${compressed_cache_dir}/${dnsmasqServersGzip}"
755 [ "$dns" = 'smartdns.domainset' ] || rm -f "$smartdnsDomainSetFile" "$smartdnsDomainSetCache" "${compressed_cache_dir}/${smartdnsDomainSetGzip}" "$smartdnsDomainSetConfig"
756 [ "$dns" = 'smartdns.ipset' ] || rm -f "$smartdnsIpsetFile" "$smartdnsIpsetCache" "${compressed_cache_dir}/${smartdnsIpsetGzip}" "$smartdnsIpsetConfig"
757 [ "$dns" = 'smartdns.nftset' ] || rm -f "$smartdnsNftsetFile" "$smartdnsNftsetCache" "${compressed_cache_dir}/${smartdnsNftsetGzip}" "$smartdnsNftsetConfig"
758 [ "$dns" = 'unbound.adb_list' ] || rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
759
760 for i in "$runningConfigFile" "$runningErrorFile" "$runningStatusFile" "$outputFile" "$outputCache" "$outputGzip" "$outputConfig"; do
761 [ -n "$i" ] || continue
762 if ! mkdir -p "${i%/*}"; then
763 if [ "$param" != 'quiet' ]; then
764 json add error 'errorOutputDirCreate' "$i"
765 output "${_ERROR_}: $(get_text 'errorOutputDirCreate' "$i")!\\n"
766 fi
767 fi
768 done
769
770 is_present 'gawk' && awk='gawk'
771 if ! is_present '/usr/libexec/grep-gnu' || ! is_present '/usr/libexec/sed-gnu' || \
772 ! is_present '/usr/libexec/sort-coreutils' || ! is_present 'gawk'; then
773 local s
774 is_present 'gawk' || s="${s:+$s }gawk"
775 is_present '/usr/libexec/grep-gnu' || s="${s:+$s }grep"
776 is_present '/usr/libexec/sed-gnu' || s="${s:+$s }sed"
777 is_present '/usr/libexec/sort-coreutils' || s="${s:+$s }coreutils-sort"
778 if [ "$param" != 'quiet' ]; then
779 json add warning 'warningMissingRecommendedPackages' "$s"
780 output "${_WARNING_}: $(get_text 'warningMissingRecommendedPackages'), install them by running:\\n"
781 output "opkg update; opkg --force-overwrite install $s;\\n"
782 fi
783 fi
784 # Prefer curl because it supports the file:// scheme.
785 if is_present 'curl'; then
786 dl_command='curl --silent --insecure'
787 dl_command="${dl_command}${curl_additional_param:+ $curl_additional_param}"
788 dl_command="${dl_command}${curl_max_file_size:+ --max-filesize $curl_max_file_size}"
789 dl_command="${dl_command}${curl_retry:+ --retry $curl_retry}"
790 dl_command="${dl_command}${download_timeout:+ --connect-timeout $download_timeout}"
791 dl_flag='-o'
792 elif is_present '/usr/libexec/wget-ssl'; then
793 dl_command='/usr/libexec/wget-ssl --no-check-certificate -q'
794 dl_command="${dl_command}${download_timeout:+ --timeout $download_timeout}"
795 dl_flag="-O"
796 size_command='/usr/libexec/wget-ssl --no-check-certificate -q -O /dev/null --server-response'
797 size_command="${size_command}${download_timeout:+ --timeout $download_timeout}"
798 elif is_present wget && wget --version 2>/dev/null | grep -q "+https"; then
799 dl_command="wget --no-check-certificate -q"
800 dl_command="${dl_command}${download_timeout:+ --timeout $download_timeout}"
801 dl_flag="-O"
802 size_command='wget --no-check-certificate -q -O /dev/null --server-response'
803 size_command="${size_command}${download_timeout:+ --timeout $download_timeout}"
804 else
805 dl_command="uclient-fetch --no-check-certificate -q"
806 dl_command="${dl_command}${download_timeout:+ --timeout $download_timeout}"
807 dl_flag="-O"
808 fi
809 led="${led:+/sys/class/leds/$led}"
810 if curl --version 2>/dev/null | grep -q "https" \
811 || wget --version 2>/dev/null | grep -q "+https" \
812 || grep -q "libustream-mbedtls" /usr/lib/opkg/status \
813 || grep -q "libustream-openssl" /usr/lib/opkg/status \
814 || grep -q "libustream-wolfssl" /usr/lib/opkg/status; then
815 isSSLSupported=1
816 else
817 unset isSSLSupported
818 fi
819 config_load "$packageName"
820 config_foreach append_url 'file_url'
821 load_environment_flag=1
822 cache 'test' && return 0
823 cache 'test_gzip' && return 0
824 if [ "$param" = 'on_boot' ]; then
825 load_network "$param"
826 return "$?"
827 else
828 return 0
829 fi
830 }
831
832 resolver() {
833 _dnsmasq_instance_config() {
834 local cfg="$1" param="$2"
835 [ -s "/etc/config/dhcp" ] || return 0
836 case "$param" in
837 dnsmasq.addnhosts)
838 if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" = "$dnsmasqServersFile" ]; then
839 uci_remove 'dhcp' "$cfg" 'serversfile'
840 fi
841 uci_add_list_if_new 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
842 ;;
843 cleanup|dnsmasq.conf|dnsmasq.ipset|dnsmasq.nftset|unbound.adb_list)
844 uci_remove_list 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
845 if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" = "$dnsmasqServersFile" ]; then
846 uci_remove 'dhcp' "$cfg" 'serversfile'
847 fi
848 ;;
849 dnsmasq.servers)
850 uci_remove_list 'dhcp' "$cfg" 'addnhosts' "$dnsmasqAddnhostsFile"
851 if [ "$(uci_get 'dhcp' "$cfg" 'serversfile')" != "$dnsmasqServersFile" ]; then
852 uci_set 'dhcp' "$cfg" 'serversfile' "$dnsmasqServersFile"
853 fi
854 ;;
855 esac
856 }
857 _smartdns_instance_config() {
858 [ -s "/etc/config/smartdns" ] || return 0
859 local cfg="$1" param="$2"
860 case "$param" in
861 cleanup)
862 uci_remove_list 'smartdns' "$cfg" 'conf_files' "$outputConfig"
863 rm -f "$outputConfig"
864 ;;
865 smartdns.domainset)
866 { echo "domain-set -name adblock-fast -file $outputFile"; \
867 echo "domain-rules /domain-set:adblock-fast/ -a #"; } > "$outputConfig"
868 uci_add_list_if_new 'smartdns' "$cfg" 'conf_files' "$outputConfig"
869 ;;
870 smartdns.ipset)
871 { echo "domain-set -name adblock-fast -file $outputFile"; \
872 echo "domain-rules /domain-set:adblock-fast/ -ipset adb"; } > "$outputConfig"
873 uci_add_list_if_new 'smartdns' "$cfg" 'conf_files' "$outputConfig"
874 ;;
875 smartdns.nftset)
876 local nftset="#4:inet#fw4#adb4"
877 [ "$ipv6_enabled" -ne '0' ] && nftset="${nftset},#6:inet#fw4#adb6"
878 { echo "domain-set -name adblock-fast -file $outputFile"; \
879 echo "domain-rules /domain-set:adblock-fast/ -nftset $nftset"; } > "$outputConfig"
880 uci_add_list_if_new 'smartdns' "$cfg" 'conf_files' "$outputConfig"
881 ;;
882 esac
883 }
884
885 local param output_text i
886 case $1 in
887 cleanup)
888 rm -f "$dnsmasqAddnhostsFile" "$dnsmasqAddnhostsCache" "${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
889 rm -f "$dnsmasqConfFile" "$dnsmasqConfCache" "${compressed_cache_dir}/${dnsmasqConfGzip}"
890 rm -f "$dnsmasqIpsetFile" "$dnsmasqIpsetCache" "${compressed_cache_dir}/${dnsmasqIpsetGzip}"
891 rm -f "$dnsmasqNftsetFile" "$dnsmasqNftsetCache" "${compressed_cache_dir}/${dnsmasqNftsetGzip}"
892 rm -f "$dnsmasqServersFile" "$dnsmasqServersCache" "${compressed_cache_dir}/${dnsmasqServersGzip}"
893 rm -f "$smartdnsDomainSetFile" "$smartdnsDomainSetCache" "${compressed_cache_dir}/${smartdnsDomainSetGzip}" "$smartdnsDomainSetConfig"
894 rm -f "$smartdnsIpsetFile" "$smartdnsIpsetCache" "${compressed_cache_dir}/${smartdnsIpsetGzip}" "$smartdnsIpsetConfig"
895 rm -f "$smartdnsNftsetFile" "$smartdnsNftsetCache" "${compressed_cache_dir}/${smartdnsNftsetGzip}" "$smartdnsNftsetConfig"
896 rm -f "$unboundFile" "$unboundCache" "$unboundGzip"
897 if [ -s "/etc/config/dhcp" ]; then
898 config_load 'dhcp'
899 config_foreach _dnsmasq_instance_config 'dnsmasq' 'cleanup'
900 [ -n "$(uci_changes 'dhcp')" ] && uci_commit 'dhcp'
901 fi
902 if [ -s "/etc/config/smartdns" ]; then
903 config_load 'smartdns'
904 config_foreach _smartdns_instance_config 'smartdns' 'cleanup'
905 [ -n "$(uci_changes 'smartdns')" ] && uci_commit 'smartdns'
906 fi
907 ;;
908 on_start)
909 if [ ! -s "$outputFile" ]; then
910 json set status 'statusFail'
911 json add error 'errorOutputFileCreate'
912 output "${_ERROR_}: $(get_text 'errorOutputFileCreate')!\\n"
913 return 1
914 fi
915
916 config_load 'dhcp'
917 if [ "$dnsmasq_instance" = "*" ]; then
918 config_foreach _dnsmasq_instance_config 'dnsmasq' "$dns"
919 elif [ -n "$dnsmasq_instance" ]; then
920 for i in $dnsmasq_instance; do
921 _dnsmasq_instance_config "@dnsmasq[$i]" "$dns" || _dnsmasq_instance_config "$i" "$dns"
922 done
923 fi
924 config_load 'smartdns'
925 if [ "$smartdns_instance" = "*" ]; then
926 config_foreach _smartdns_instance_config 'smartdns' "$dns"
927 elif [ -n "$smartdns_instance" ]; then
928 for i in $smartdns_instance; do
929 _smartdns_instance_config "@smartdns[$i]" "$dns" || _smartdns_instance_config "$i" "$dns"
930 done
931 fi
932
933 case "$dns" in
934 dnsmasq.*)
935 chmod 660 "$outputFile"
936 chown root:dnsmasq "$outputFile"
937 param='dnsmasq_restart'
938 output_text='Restarting dnsmasq'
939 ;;
940 smartdns.*)
941 chmod 660 "$outputFile" "$outputConfig"
942 chown root:root "$outputFile" "$outputConfig"
943 param='smartdns_restart'
944 output_text='Restarting SmartDNS'
945 ;;
946 unbound.*)
947 chmod 660 "$outputFile"
948 chown root:unbound "$outputFile"
949 param='unbound_restart'
950 output_text='Restarting Unbound'
951 ;;
952 esac
953
954 if [ -n "$(uci_changes dhcp)" ]; then
955 uci_commit 'dhcp'
956 if ! str_contains "$param" 'dnsmasq_restart'; then
957 param="${param:+"$param; dnsmasq_restart"}"
958 output_text="${output_text}/dnsmasq"
959 fi
960 fi
961 if [ -n "$(uci_changes smartdns)" ]; then
962 uci_commit 'smartdns'
963 if ! str_contains "$param" 'smartdns_restart'; then
964 param="${param:+"$param; "}smartdns_restart"
965 output_text="${output_text}/smartDNS"
966 fi
967 fi
968 output 1 "$output_text "
969 output 2 "$output_text "
970 json set message "$output_text"
971 if eval "$param"; then
972 json set status 'statusSuccess'
973 led_on "$led"
974 output_okn
975 else
976 output_fail
977 json set status 'statusFail'
978 json add error 'errorDNSReload'
979 output "${_ERROR_}: $(get_text 'errorDNSReload')!\\n"
980 return 1
981 fi
982 ;;
983 on_stop)
984 case "$dns" in
985 dnsmasq.*)
986 param='dnsmasq_restart'
987 ;;
988 smartdns.*)
989 param='smartdns_restart'
990 ;;
991 unbound.*)
992 param='unbound_restart'
993 ;;
994 esac
995 if [ -n "$(uci_changes dhcp)" ]; then
996 uci_commit 'dhcp'
997 str_contains "$param" 'dnsmasq_restart' || param="${param:+"$param; dnsmasq_restart"}"
998 fi
999 if [ -n "$(uci_changes smartdns)" ]; then
1000 uci_commit 'smartdns'
1001 str_contains "$param" 'smartdns_restart' || param="${param:+"$param; "}smartdns_restart"
1002 fi
1003 eval "$param"
1004 return $?
1005 ;;
1006 quiet|quiet_restart)
1007 case "$dns" in
1008 dnsmasq.*)
1009 param='dnsmasq_restart'
1010 ;;
1011 smartdns.*)
1012 param='smartdns_restart'
1013 ;;
1014 unbound.*)
1015 param='unbound_restart'
1016 ;;
1017 esac
1018 eval "$param"
1019 return $?
1020 ;;
1021 esac
1022 }
1023
1024 cache() {
1025 local R_TMP
1026 case "$1" in
1027 create|backup)
1028 [ -s "$outputFile" ] && { mv -f "$outputFile" "$outputCache"; } >/dev/null 2>/dev/null
1029 return $?
1030 ;;
1031 restore|use)
1032 [ -s "$outputCache" ] && mv "$outputCache" "$outputFile" >/dev/null 2>/dev/null
1033 return $?
1034 ;;
1035 test)
1036 [ -s "$outputCache" ]
1037 return $?
1038 ;;
1039 test_gzip)
1040 [ -s "$outputGzip" ] && gzip -t -c "$outputGzip"
1041 return $?
1042 ;;
1043 create_gzip)
1044 rm -f "$outputGzip" >/dev/null 2>/dev/null
1045 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
1046 if gzip < "$outputFile" > "$R_TMP"; then
1047 if mv "$R_TMP" "$outputGzip"; then
1048 rm -f "$R_TMP"
1049 return 0
1050 else
1051 rm -f "$R_TMP"
1052 return 1
1053 fi
1054 else
1055 return 1
1056 fi
1057 ;;
1058 expand|unpack|unpack_gzip)
1059 [ -s "$outputGzip" ] && gzip -dc < "$outputGzip" > "$outputCache"
1060 return $?
1061 ;;
1062 esac
1063 }
1064
1065 process_file_url_wrapper() {
1066 if [ "$2" != '0' ]; then
1067 json add error 'errorConfigValidationFail'
1068 output "${_ERROR_}: $(get_text 'errorConfigValidationFail')!\\n"
1069 output "Please check if the '$packageConfigFile' contains correct values for config options.\\n"
1070 fi
1071 if [ "$parallel_downloads" -gt 0 ]; then
1072 process_file_url "$1" &
1073 else
1074 process_file_url "$1"
1075 fi
1076 }
1077
1078 process_file_url() {
1079 local cfg="$1" new_size
1080 local label type D_TMP R_TMP filter
1081 if [ -z "$cfg" ] || [ -n "${2}${3}" ]; then
1082 url="$2"
1083 action="$3"
1084 fi
1085
1086 [ "$enabled" = '1' ] || return 0
1087 [ -n "$url" ] || return 1
1088
1089 label="${url##*//}"
1090 label="${label%%/*}"
1091 label="File: $label"
1092 case "$action" in
1093 allow) type='Allowed'; D_TMP="$A_TMP"
1094 ;;
1095 block) type='Blocked'; D_TMP="$B_TMP"
1096 ;;
1097 file) type='File'; D_TMP="$B_TMP"
1098 ;;
1099 esac
1100 if is_https_url "$url" && [ -z "$isSSLSupported" ]; then
1101 output 1 "$_FAIL_"
1102 output 2 "[DL] $type $label $__FAIL__\\n"
1103 echo "errorNoSSLSupport|${1}" >> "$runningErrorFile"
1104 return 0
1105 fi
1106 while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
1107 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
1108 done
1109 if [ -z "$url" ] || ! $dl_command "$url" "$dl_flag" "$R_TMP" 2>/dev/null || \
1110 [ ! -s "$R_TMP" ]; then
1111 output 1 "$_FAIL_"
1112 output 2 "[DL] $type $label $__FAIL__\\n"
1113 echo "errorDownloadingList|${url}" >> "$runningErrorFile"
1114 else
1115 append_newline "$R_TMP"
1116 [ -n "$cfg" ] && new_size="$(get_local_filesize "$R_TMP")"
1117 if [ -n "$new_size" ] && [ "$size" != "$new_size" ]; then
1118 uci_set "$packageName" "$cfg" 'size' "$size"
1119 fi
1120 format="$(detect_file_type "$R_TMP")"
1121 case "$format" in
1122 adblockplus) filter="$adBlockPlusFilter";;
1123 dnsmasq) filter="$dnsmasqFileFilter";;
1124 dnsmasq2) filter="$dnsmasq2FileFilter";;
1125 dnsmasq3) filter="$dnsmasq3FileFilter";;
1126 domains) filter="$domainsFilter";;
1127 hosts) filter="$hostsFilter";;
1128 *)
1129 output 1 "$_FAIL_"
1130 output 2 "[DL] $type $label $__FAIL__\\n"
1131 echo "errorDetectingFileType|${url}" >> "$runningErrorFile"
1132 rm -f "$R_TMP"
1133 return 0
1134 ;;
1135 esac
1136 if [ -n "$filter" ] && [ "$action" != 'file' ]; then
1137 sed -i "$filter" "$R_TMP"
1138 fi
1139 if [ ! -s "$R_TMP" ]; then
1140 output 1 "$_FAIL_"
1141 output 2 "[DL] $type $label ($format) $__FAIL__\\n"
1142 echo "errorParsingList|${url}" >> "$runningErrorFile"
1143 else
1144 append_newline "$R_TMP"
1145 cat "${R_TMP}" >> "$D_TMP"
1146 output 1 "$_OK_"
1147 output 2 "[DL] $type $label ($format) $__OK__\\n"
1148 fi
1149 fi
1150 rm -f "$R_TMP"
1151 return 0
1152 }
1153
1154 download_dnsmasq_file() {
1155 json set message "$(get_text 'statusDownloading')..."
1156 json set status 'statusDownloading'
1157
1158 rm -f "$A_TMP" "$B_TMP" "$SED_TMP" "$outputFile" "$outputCache" "$outputGzip"
1159 if [ "$(get_ram_free)" -lt 32 ]; then
1160 output 3 'Low free memory, restarting resolver '
1161 if resolver 'quiet_restart'; then
1162 output_okn
1163 else
1164 output_failn
1165 fi
1166 fi
1167 touch "$A_TMP" "$B_TMP" "$SED_TMP"
1168 output 1 'Downloading dnsmasq file '
1169 rm -f "$runningErrorFile"
1170 process_file_url '' "$dnsmasq_config_file_url" 'file'
1171 if [ -s "$runningErrorFile" ]; then
1172 while IFS= read -r line; do
1173 json add error "$line"
1174 done < "$runningErrorFile"
1175 rm -f "$runningErrorFile"
1176 fi
1177 output 2 'Moving dnsmasq file '
1178 if mv "$B_TMP" "$outputFile"; then
1179 output 2 "$__OK__\\n"
1180 else
1181 output 2 "$__FAIL__\\n"
1182 json add error 'errorMovingDataFile'
1183 fi
1184 output 1 '\n'
1185 }
1186
1187 download_lists() {
1188 _ram_check() {
1189 _config_calculate_sizes() {
1190 local cfg="$1"
1191 local en size url
1192 config_get_bool en "$cfg" enabled '1'
1193 config_get size "$cfg" size
1194 config_get url "$cfg" url
1195 [ "$en" = '0' ] && return 0
1196 [ -n "$size" ] || size="$(get_url_filesize "$url")"
1197 [ -n "$size" ] && total_sizes=$((total_sizes+size))
1198 }
1199 local i free_mem total_sizes
1200 free_mem="$(get_ram_free)"
1201 if [ -z "$free_mem" ]; then
1202 json add warnning 'warningFreeRamCheckFail'
1203 output "${_WARNING_}: $(get_text 'warningFreeRamCheckFail')!\\n"
1204 return 0
1205 fi
1206 config_load "$packageName"
1207 config_foreach _config_calculate_sizes 'file_url'
1208 if [ $((free_mem)) -lt $((total_sizes * 2)) ]; then
1209 json add error 'errorTooLittleRam' "$free_mem"
1210 output "${_ERROR_}: $(get_text 'errorTooLittleRam' "$free_mem")!\\n"
1211 return 1
1212 else
1213 return 0
1214 fi
1215 }
1216 local hf j=0 R_TMP
1217
1218 _ram_check || return 1
1219
1220 json set message "$(get_text 'statusDownloading')..."
1221 json set status 'statusDownloading'
1222
1223 rm -f "$A_TMP" "$B_TMP" "$SED_TMP" "$outputFile" "$outputCache" "$outputGzip"
1224 if [ "$(get_ram_total)" -lt 33554432 ]; then
1225 output 3 'Low free memory, restarting resolver '
1226 if resolver 'quiet_restart'; then
1227 output_okn
1228 else
1229 output_failn
1230 fi
1231 fi
1232 touch "$A_TMP" "$B_TMP" "$SED_TMP"
1233 output 1 'Downloading lists '
1234 rm -f "$runningErrorFile"
1235 config_load "$packageName"
1236 config_foreach load_validate_file_url_section 'file_url' process_file_url_wrapper
1237 wait
1238 if [ -n "$(uci_changes "$packageName")" ]; then
1239 output 2 "Saving updated file size(s) "
1240 if uci_commit "$packageName"; then output_okn; else output_failn; fi
1241 fi
1242 output 1 '\n'
1243
1244 if [ -s "$runningErrorFile" ]; then
1245 while IFS= read -r line; do
1246 json add error "$line"
1247 done < "$runningErrorFile"
1248 rm -f "$runningErrorFile"
1249 fi
1250
1251 if [ "$canary_domains_icloud" -ne '0' ]; then
1252 canaryDomains="${canaryDomains:+$canaryDomains }${canaryDomainsiCloud}"
1253 fi
1254 if [ "$canary_domains_mozilla" -ne '0' ]; then
1255 canaryDomains="${canaryDomains:+$canaryDomains }${canaryDomainsMozilla}"
1256 fi
1257
1258 append_newline "$B_TMP"
1259 for hf in $blocked_domain $canaryDomains; do
1260 printf "%s\n" "$(echo "$hf" | sed "$domainsFilter")" >> "$B_TMP"
1261 done
1262 allowed_domain="${allowed_domain}
1263 $(sed '/^[[:space:]]*$/d' "$A_TMP")"
1264 for hf in ${allowed_domain}; do
1265 hf="$(echo "$hf" | sed 's/\./\\./g')"
1266 echo "/(^|\.)${hf}$/d;" >> "$SED_TMP"
1267 done
1268
1269 sed -i '/^[[:space:]]*$/d' "$B_TMP"
1270 [ ! -s "$B_TMP" ] && return 1
1271
1272 output 1 'Processing downloads '
1273 output 2 'Sorting combined list '
1274 json set status 'statusProcessing'
1275 json set message "$(get_text 'statusProcessing'): sorting combined list"
1276 if [ "$allow_non_ascii" -gt 0 ]; then
1277 if sort -u "$B_TMP" > "$A_TMP"; then
1278 output_ok
1279 else
1280 output_failn
1281 json add error 'errorSorting'
1282 fi
1283 else
1284 if sort -u "$B_TMP" | grep -E -v '[^a-zA-Z0-9=/.-]' > "$A_TMP"; then
1285 output_ok
1286 else
1287 output_failn
1288 json add error 'errorSorting'
1289 fi
1290 fi
1291
1292 if [ "$dns" = 'dnsmasq.conf' ] || \
1293 [ "$dns" = 'dnsmasq.ipset' ] || \
1294 [ "$dns" = 'dnsmasq.nftset' ] || \
1295 [ "$dns" = 'dnsmasq.servers' ] || \
1296 [ "$dns" = 'smartdns.domainset' ] || \
1297 [ "$dns" = 'smartdns.ipset' ] || \
1298 [ "$dns" = 'smartdns.nftset' ] || \
1299 [ "$dns" = 'unbound.adb_list' ]; then
1300 # TLD optimization written by Dirk Brenken (dev@brenken.org)
1301 output 2 'Optimizing combined list '
1302 json set message "$(get_text 'statusProcessing'): optimizing combined list"
1303 # sed -E 'G;:t;s/(.*)(\.)(.*)(\n)(.*)/\1\4\5\2\3/;tt;s/(.*)\n(\.)(.*)/\3\2\1/' is actually slower than command below
1304 # shellcheck disable=SC2016
1305 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$A_TMP" > "$B_TMP"; then
1306 if sort "$B_TMP" > "$A_TMP"; then
1307 if $awk '{if(NR=1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "$A_TMP" > "$B_TMP"; then
1308 if $awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "$B_TMP" > "$A_TMP"; then
1309 if sort -u "$A_TMP" > "$B_TMP"; then
1310 output_ok
1311 else
1312 output_failn
1313 json add error 'errorOptimization'
1314 mv "$A_TMP" "$B_TMP"
1315 fi
1316 else
1317 output_failn
1318 json add error 'errorOptimization'
1319 fi
1320 else
1321 output_failn
1322 json add error 'errorOptimization'
1323 mv "$A_TMP" "$B_TMP"
1324 fi
1325 else
1326 output_failn
1327 json add error 'errorOptimization'
1328 fi
1329 else
1330 output_failn
1331 json add error 'errorOptimization'
1332 mv "$A_TMP" "$B_TMP"
1333 fi
1334 else
1335 mv "$A_TMP" "$B_TMP"
1336 fi
1337
1338 if [ -s "$SED_TMP" ]; then
1339 output 2 'Allowing domains '
1340 json set message "$(get_text 'statusProcessing'): allowing domains"
1341 if sed -i -E -f "$SED_TMP" "$B_TMP"; then
1342 output_ok
1343 else
1344 output_failn
1345 json add error 'errorAllowListProcessing'
1346 fi
1347 fi
1348 output 2 'Formatting merged file '
1349 json set message "$(get_text 'statusProcessing'): formatting merged file"
1350 if [ -z "$outputFilterIPv6" ]; then
1351 if sed "$outputFilter" "$B_TMP" > "$A_TMP"; then
1352 output_ok
1353 else
1354 output_failn
1355 json add error 'errorDataFileFormatting'
1356 fi
1357 else
1358 case "$dns" in
1359 dnsmasq.addnhosts)
1360 if sed "$outputFilter" "$B_TMP" > "$A_TMP" && \
1361 sed "$outputFilterIPv6" "$B_TMP" >> "$A_TMP"; then
1362 output_ok
1363 else
1364 output_failn
1365 json add error 'errorDataFileFormatting'
1366 fi
1367 ;;
1368 esac
1369 fi
1370
1371 case "$dns" in
1372 dnsmasq.addnhosts)
1373 output 2 'Creating dnsmasq addnhosts file '
1374 json set message "$(get_text 'statusProcessing'): creating dnsmasq addnhosts file"
1375 ;;
1376 dnsmasq.conf)
1377 output 2 'Creating dnsmasq config file '
1378 json set message "$(get_text 'statusProcessing'): creating dnsmasq config file"
1379 ;;
1380 dnsmasq.ipset)
1381 output 2 'Creating dnsmasq ipset file '
1382 json set message "$(get_text 'statusProcessing'): creating dnsmasq ipset file"
1383 ;;
1384 dnsmasq.nftset)
1385 output 2 'Creating dnsmasq nft set file '
1386 json set message "$(get_text 'statusProcessing'): creating dnsmasq nft set file"
1387 ;;
1388 dnsmasq.servers)
1389 output 2 'Creating dnsmasq servers file '
1390 json set message "$(get_text 'statusProcessing'): creating dnsmasq servers file"
1391 ;;
1392 smartdns.domainset)
1393 output 2 'Creating smartdns domain-set file '
1394 json set message "$(get_text 'statusProcessing'): creating smartdns domain-set file"
1395 ;;
1396 smartdns.ipset)
1397 output 2 'Creating smartdns domain-set file '
1398 json set message "$(get_text 'statusProcessing'): creating smartdns ipset file"
1399 ;;
1400 smartdns.nftset)
1401 output 2 'Creating smartdns domain-set file '
1402 json set message "$(get_text 'statusProcessing'): creating smartdns nft set file"
1403 ;;
1404 unbound.adb_list)
1405 output 2 'Creating Unbound adb_list file '
1406 json set message "$(get_text 'statusProcessing'): creating Unbound adb_list file"
1407 ;;
1408 esac
1409
1410 if mv "$A_TMP" "$outputFile"; then
1411 output_ok
1412 else
1413 output_failn
1414 json add error 'errorMovingDataFile'
1415 fi
1416 if [ "$compressed_cache" -gt 0 ]; then
1417 output 2 'Creating compressed cache '
1418 json set message "$(get_text 'statusProcessing'): creating compressed cache"
1419 if cache 'create_gzip'; then
1420 output_ok
1421 else
1422 output_failn
1423 json add error 'errorCreatingCompressedCache'
1424 fi
1425 else
1426 rm -f "$outputGzip"
1427 fi
1428 output 2 'Removing temporary files '
1429 json set message "$(get_text 'statusProcessing'): removing temporary files"
1430 rm -f "/tmp/${packageName}_tmp.*" "$A_TMP" "$B_TMP" "$SED_TMP" "$outputCache" || j=1
1431 if [ $j -eq 0 ]; then
1432 output_ok
1433 else
1434 output_failn
1435 json add error 'errorRemovingTempFiles'
1436 fi
1437 output 1 '\n'
1438 }
1439
1440 adb_allow() {
1441 local c hf string="$1"
1442 local validation_result="$3"
1443 load_environment "$validation_result" 'quiet' || return 1
1444 if [ ! -s "$outputFile" ]; then
1445 output "No block-list ('$outputFile') found.\\n"
1446 return 0
1447 elif [ -z "$string" ]; then
1448 output "Usage: /etc/init.d/${packageName} allow 'domain' ...\\n"
1449 return 0
1450 elif [ -n "$dnsmasq_config_file_url" ]; then
1451 output "Allowing individual domains is not possible when using external dnsmasq config file.\\n"
1452 return 0
1453 fi
1454 case "$dns" in
1455 dnsmasq.*)
1456 output 1 "Allowing domain(s) and restarting dnsmasq "
1457 output 2 "Allowing domain(s) \\n"
1458 for c in $string; do
1459 output 2 " $c "
1460 hf="$(echo "$c" | sed 's/\./\\./g')"
1461 if sed -i "\:\(/\|\.\)${hf}/:d" "$outputFile" && \
1462 uci_add_list_if_new "${packageName}" 'config' 'allowed_domain' "$c"; then
1463 output_ok
1464 else
1465 output_fail
1466 fi
1467 done
1468 if [ "$compressed_cache" -gt 0 ]; then
1469 output 2 'Creating compressed cache '
1470 if cache 'create_gzip'; then
1471 output_ok
1472 else
1473 output_failn
1474 fi
1475 fi
1476 output 2 "Committing changes to config "
1477 if uci_commit "$packageName"; then
1478 allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
1479 config_cache 'create'
1480 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
1481 output_ok;
1482 if [ "$dns" = 'dnsmasq.ipset' ]; then
1483 output 2 "Flushing adb ipset "
1484 if ipset -q -! flush adb; then output_ok; else output_fail; fi
1485 fi
1486 if [ "$dns" = 'dnsmasq.nftset' ]; then
1487 output 2 "Flushing adb nft sets "
1488 nft flush set inet fw4 adb6
1489 if nft flush set inet fw4 adb4; then output_ok; else output_fail; fi
1490 fi
1491 output 2 "Restarting dnsmasq "
1492 if dnsmasq_restart; then output_okn; else output_failn; fi
1493 else
1494 output_fail;
1495 fi
1496 ;;
1497 smartdns.*)
1498 output 1 "Allowing domain(s) and restarting smartdns "
1499 output 2 "Allowing domain(s) \\n"
1500 for c in $string; do
1501 output 2 " $c "
1502 hf="$(echo "$c" | sed 's/\./\\./g')"
1503 if sed -i "\:\(\"\|\.\)${hf}\":d" "$outputFile" && \
1504 uci_add_list_if_new "$packageName" 'config' 'allowed_domain' "$string"; then
1505 output_ok
1506 else
1507 output_fail
1508 fi
1509 done
1510 if [ "$compressed_cache" -gt 0 ]; then
1511 output 2 'Creating compressed cache '
1512 if cache 'create_gzip'; then
1513 output_ok
1514 else
1515 output_failn
1516 fi
1517 fi
1518 output 2 "Committing changes to config "
1519 if uci_commit "$packageName"; then
1520 allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
1521 config_cache 'create'
1522 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
1523 output_ok;
1524 output 2 "Restarting Unbound "
1525 if unbound_restart; then output_okn; else output_failn; fi
1526 else
1527 output_fail;
1528 fi
1529 ;;
1530 unbound.*)
1531 output 1 "Allowing domain(s) and restarting Unbound "
1532 output 2 "Allowing domain(s) \\n"
1533 for c in $string; do
1534 output 2 " $c "
1535 hf="$(echo "$c" | sed 's/\./\\./g')"
1536 if sed -i "\:\(\"\|\.\)${hf}\":d" "$outputFile" && \
1537 uci_add_list_if_new "$packageName" 'config' 'allowed_domain' "$string"; then
1538 output_ok
1539 else
1540 output_fail
1541 fi
1542 done
1543 if [ "$compressed_cache" -gt 0 ]; then
1544 output 2 'Creating compressed cache '
1545 if cache 'create_gzip'; then
1546 output_ok
1547 else
1548 output_failn
1549 fi
1550 fi
1551 output 2 "Committing changes to config "
1552 if uci_commit "$packageName"; then
1553 allowed_domain="$(uci_get "$packageName" 'config' 'allowed_domain')"
1554 config_cache 'create'
1555 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
1556 output_ok;
1557 output 2 "Restarting Unbound "
1558 if unbound_restart; then output_okn; else output_failn; fi
1559 else
1560 output_fail;
1561 fi
1562 ;;
1563 esac
1564 }
1565
1566 adb_check() {
1567 local c param="$1"
1568 local validation_result="$3"
1569 load_environment "$validation_result" 'quiet' || return 1
1570 if [ ! -s "$outputFile" ]; then
1571 output "No block-list ('$outputFile') found.\\n"
1572 return 0
1573 elif [ -z "$param" ]; then
1574 output "Usage: /etc/init.d/${packageName} check 'domain' ...\\n"
1575 return 0
1576 fi
1577 for string in ${param}; do
1578 c="$(grep -c "$string" "$outputFile")"
1579 if [ "$c" -gt 0 ]; then
1580 if [ "$c" -eq 1 ]; then
1581 output "Found 1 match for '$string' in '$outputFile'.\\n"
1582 else
1583 output "Found $c matches for '$string' in '$outputFile'.\\n"
1584 fi
1585 if [ "$c" -le 20 ]; then
1586 case "$dns" in
1587 dnsmasq.addnhosts)
1588 grep "$string" "$outputFile" | sed 's|^127.0.0.1 ||;s|^:: ||;';;
1589 dnsmasq.conf)
1590 grep "$string" "$outputFile" | sed 's|local=/||;s|/$||;';;
1591 dnsmasq.ipset)
1592 grep "$string" "$outputFile" | sed 's|ipset=/||;s|/adb$||;';;
1593 dnsmasq.nftset)
1594 grep "$string" "$outputFile" | sed 's|nftset=/||;s|/4#inet#adb#adb4||;';;
1595 dnsmasq.servers)
1596 grep "$string" "$outputFile" | sed 's|server=/||;s|/$||;';;
1597 smartdns.*)
1598 grep "$string" "$outputFile";;
1599 unbound.adb_list)
1600 grep "$string" "$outputFile" | sed 's|^local-zone: "||;s|" static$||;';;
1601 esac
1602 fi
1603 else
1604 output "The '$string' is not found in current block-list ('$outputFile').\\n"
1605 fi
1606 done
1607 }
1608
1609 adb_check_lists() {
1610 _check_list() {
1611 local cfg="$1"
1612 local en size url R_TMP string c
1613 config_get_bool en "$cfg" enabled '1'
1614 config_get action "$cfg" action 'block'
1615 config_get url "$cfg" url
1616 [ "$en" = '0' ] && return 0
1617 [ "$action" != 'block' ] && return 0
1618 if is_https_url "$url" && [ -z "$isSSLSupported" ]; then
1619 output "[DL] $url $__FAIL__\\n"
1620 fi
1621 while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
1622 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
1623 done
1624 if [ -z "$url" ] || ! $dl_command "$url" "$dl_flag" "$R_TMP" 2>/dev/null || \
1625 [ ! -s "$R_TMP" ]; then
1626 output "[DL] $url $__FAIL__\\n"
1627 else
1628 append_newline "$R_TMP"
1629 for string in ${param}; do
1630 c="$(grep -c "$string" "$R_TMP")"
1631 if [ "$c" -gt 0 ]; then
1632 if [ "$c" -eq 1 ]; then
1633 output "Found 1 match for '$string' in '$url'.\\n"
1634 else
1635 output "Found $c matches for '$string' in '$url'.\\n"
1636 fi
1637 grep "$string" "$R_TMP"
1638 else
1639 output "The '$string' is not found in '$url'.\\n"
1640 fi
1641 done
1642 rm -f "$R_TMP"
1643 fi
1644 }
1645 local param="$1"
1646 local validation_result="$3"
1647 load_environment "$validation_result" 'quiet' || return 1
1648 if [ -z "$param" ]; then
1649 output "Usage: /etc/init.d/${packageName} check_lists 'domain' ...\\n"
1650 return 0
1651 fi
1652 config_load "$packageName"
1653 config_foreach _check_list 'file_url'
1654 return 0
1655 }
1656
1657 adb_config_update() {
1658 local R_TMP label
1659 local param validation_result="$3"
1660 case "$1" in
1661 on_boot) param="$1";;
1662 *) param='quiet';;
1663 esac
1664 load_environment "$validation_result" "$param" || return 1
1665 label="${config_update_url##*//}"
1666 label="${label%%/*}";
1667 [ "$config_update_enabled" -ne '0' ] || return 0
1668
1669 if [ "$param" != 'download' ]; then
1670 cache 'test' && return 0
1671 cache 'test_gzip' && return 0
1672 fi
1673 output 1 'Updating config '
1674 while [ -z "$R_TMP" ] || [ -e "$R_TMP" ]; do
1675 R_TMP="$(mktemp -u -q -t ${packageName}_tmp.XXXXXXXX)"
1676 done
1677 if ! $dl_command "$config_update_url" "$dl_flag" "$R_TMP" 2>/dev/null || [ ! -s "$R_TMP" ]; then
1678 append_newline "$R_TMP"
1679 output 1 "$_FAIL_\\n"
1680 output 2 "[DL] Config Update: $label $__FAIL__\\n"
1681 json add error 'errorDownloadingConfigUpdate'
1682 else
1683 if [ -s "$R_TMP" ] && sed -f "$R_TMP" -i "$packageConfigFile" 2>/dev/null; then
1684 output 1 "$_OK_\\n"
1685 output 2 "[DL] Config Update: $label $__OK__\\n"
1686 else
1687 output 1 "$_FAIL_\\n"
1688 output 2 "[DL] Config Update: $label $__FAIL__\\n"
1689 json add error 'errorParsingConfigUpdate'
1690 fi
1691 fi
1692 rm -f "$R_TMP"
1693 return 0
1694 }
1695
1696 adb_sizes() {
1697 _config_add_url_size() {
1698 local cfg="$1" url size
1699 config_get url "$cfg" url
1700 size="$(get_url_filesize "$url")"
1701 output "$url${size:+: $size} "
1702 if [ -n "$size" ]; then
1703 uci_set "$packageName" "$cfg" 'size' "$size"
1704 output_okn
1705 else
1706 output_failn
1707 fi
1708 }
1709 local i
1710 local validation_result="$3"
1711 load_environment "$validation_result" 'quiet' || return 1
1712 config_load "$packageName"
1713 config_foreach _config_add_url_size 'file_url'
1714 uci_commit "$packageName"
1715 }
1716
1717 # shellcheck disable=SC2120
1718 adb_start() {
1719 local action status error message stats c
1720 local param="$1" validation_result="$3"
1721
1722 load_environment "$validation_result" "$param" || return 1
1723
1724 status="$(json get 'status')"
1725 error="$(json get 'error')"
1726 message="$(json get 'message')"
1727 stats="$(json get 'stats')"
1728 action="$(config_cache get 'trigger_service')"
1729 fw4_restart_flag="$(config_cache get 'trigger_fw4')"
1730
1731 if [ "$action" = 'on_boot' ] || [ "$param" = 'on_boot' ] || [ "$param" = 'on_pause' ]; then
1732 if cache 'test_gzip' || cache 'test'; then
1733 action='restore'
1734 else
1735 action='download'
1736 fi
1737 elif [ "$action" = 'download' ] || [ "$param" = 'download' ] || [ -n "$error" ]; then
1738 action='download'
1739 elif [ ! -s "$outputFile" ]; then
1740 if cache 'test_gzip' || cache 'test'; then
1741 action='restore'
1742 else
1743 action='download'
1744 fi
1745 elif [ "$action" = 'restart' ] || [ "$param" = 'restart' ]; then
1746 action='restart'
1747 elif [ -s "$outputFile" ] && [ "$status" = "statusSuccess" ] && [ -z "$error" ]; then
1748 status_service 'quiet'
1749 return 0
1750 else
1751 action='download'
1752 fi
1753
1754 json del all
1755 config_cache 'create'
1756
1757 if [ "$action" = 'restore' ]; then
1758 output 0 "Starting $serviceName... "
1759 output 3 "Starting $serviceName...\\n"
1760 json set status 'statusStarting'
1761 if cache 'test_gzip' && ! cache 'test' && [ ! -s "$outputFile" ]; then
1762 output 3 'Found compressed cache file, unpacking it '
1763 json set message 'found compressed cache file, unpacking it.'
1764 if cache 'unpack_gzip'; then
1765 output_okn
1766 else
1767 output_failn
1768 json add error 'errorRestoreCompressedCache'
1769 output "${_ERROR_}: $(get_text 'errorRestoreCompressedCache')!\\n"
1770 action='download'
1771 fi
1772 fi
1773 if cache 'test' && [ ! -s "$outputFile" ]; then
1774 output 3 'Found cache file, reusing it '
1775 json set message 'found cache file, reusing it.'
1776 if cache 'restore'; then
1777 output_okn
1778 resolver 'on_start'
1779 else
1780 output_failn
1781 json add error 'errorRestoreCache'
1782 output "${_ERROR_}: $(get_text 'errorRestoreCache')!\\n"
1783 action='download'
1784 fi
1785 fi
1786 fi
1787 if [ "$action" = 'download' ]; then
1788 if [ -z "$blocked_url" ] && [ -z "$blocked_domain" ]; then
1789 json set status 'statusFail'
1790 json add error 'errorNothingToDo'
1791 output "${_ERROR_}: $(get_text 'errorNothingToDo')!\\n"
1792 else
1793 if [ -s "$outputFile" ] || cache 'test' || cache 'test_gzip'; then
1794 output 0 "Force-reloading $serviceName... "
1795 output 3 "Force-reloading $serviceName...\\n"
1796 json set status 'statusForceReloading'
1797 else
1798 output 0 "Starting $serviceName... "
1799 output 3 "Starting $serviceName...\\n"
1800 json set status 'statusStarting'
1801 fi
1802 resolver 'cleanup'
1803 if [ "$dns" = 'dnsmasq.conf' ] && [ -n "$dnsmasq_config_file_url" ]; then
1804 download_dnsmasq_file
1805 else
1806 download_lists
1807 fi
1808 resolver 'on_start'
1809 fi
1810 fi
1811 if [ "$action" = 'restart' ]; then
1812 output 0 "Restarting $serviceName... "
1813 output 3 "Restarting $serviceName...\\n"
1814 json set status 'statusRestarting'
1815 resolver 'on_start'
1816 fi
1817 if [ "$action" = 'start' ]; then
1818 output 0 "Starting $serviceName... "
1819 output 3 "Starting $serviceName...\\n"
1820 json set status 'statusStarting'
1821 resolver 'on_start'
1822 fi
1823 if [ -s "$outputFile" ] && [ "$(json get status)" != "statusFail" ]; then
1824 output 0 "$__OK__\\n";
1825 json del message
1826 json set status 'statusSuccess'
1827 json set stats "$serviceName is blocking $(wc -l < "$outputFile") domains (with ${dns})"
1828 status_service 'quiet'
1829
1830 else
1831 output 0 "$__FAIL__\\n";
1832 json set status 'statusFail'
1833 json add error 'errorOhSnap'
1834 status_service 'quiet'
1835 fi
1836
1837 procd_open_instance 'main'
1838 procd_set_param command /bin/true
1839 procd_set_param stdout 1
1840 procd_set_param stderr 1
1841 procd_open_data
1842 json_add_string 'status' "$(json get status)"
1843 json_add_string 'errors' "$(json get error)"
1844 json_add_string 'warnings' "$(json get warning)"
1845 if [ -s "$outputFile" ]; then
1846 json_add_int 'entries' "$(wc -l < "$outputFile")"
1847 else
1848 json_add_int 'entries' '0'
1849 fi
1850 json_add_array firewall
1851 if [ "$force_dns" -ne '0' ]; then
1852 # shellcheck disable=SC3060
1853 for c in ${force_dns_port/,/ }; do
1854 if netstat -tuln | grep LISTEN | grep ":${c}" >/dev/null 2>&1; then
1855 json_add_object ""
1856 json_add_string type redirect
1857 json_add_string target DNAT
1858 json_add_string src lan
1859 json_add_string proto "tcp udp"
1860 json_add_string src_dport "$c"
1861 json_add_string dest_port "$c"
1862 json_add_string family any
1863 json_add_boolean reflection 0
1864 json_close_object
1865 else
1866 json_add_object ""
1867 json_add_string type rule
1868 json_add_string src lan
1869 json_add_string dest "*"
1870 json_add_string proto "tcp udp"
1871 json_add_string dest_port "$c"
1872 json_add_string target REJECT
1873 json_close_object
1874 fi
1875 done
1876 fi
1877 case "$dns" in
1878 dnsmasq.ipset|smartdns.ipset)
1879 json_add_object ""
1880 json_add_string type ipset
1881 json_add_string name adb
1882 json_add_string match dest_net
1883 json_add_string storage hash
1884 json_close_object
1885 json_add_object ""
1886 json_add_string type rule
1887 json_add_string ipset adb
1888 json_add_string src lan
1889 json_add_string dest "*"
1890 json_add_string proto "tcp udp"
1891 json_add_string target REJECT
1892 json_close_object
1893 ;;
1894 dnsmasq.nftset|smartdns.nftset)
1895 json_add_object ""
1896 json_add_string type ipset
1897 json_add_string name adb4
1898 json_add_string family 4
1899 json_add_string match dest_net
1900 json_close_object
1901 json_add_object ""
1902 json_add_string type rule
1903 json_add_string ipset adb4
1904 json_add_string src lan
1905 json_add_string dest "*"
1906 json_add_string proto "tcp udp"
1907 json_add_string target REJECT
1908 json_close_object
1909 if [ "$ipv6_enabled" -ne '0' ]; then
1910 json_add_object ""
1911 json_add_string type ipset
1912 json_add_string name adb6
1913 json_add_string family 6
1914 json_add_string match dest_net
1915 json_close_object
1916 json_add_object ""
1917 json_add_string type rule
1918 json_add_string ipset adb6
1919 json_add_string src lan
1920 json_add_string dest "*"
1921 json_add_string proto "tcp udp"
1922 json_add_string target REJECT
1923 json_close_object
1924 fi
1925 ;;
1926 esac
1927 json_close_array
1928 procd_close_data
1929 procd_close_instance
1930 return 0
1931 }
1932
1933 adb_status() {
1934 local param="$1"
1935 local c status message error warning stats text
1936 status="$(json get status)"
1937 message="$(json get message)"
1938 error="$(json get error)"
1939 warning="$(json get warning)"
1940 stats="$(json get stats)"
1941 if [ "$status" = "statusSuccess" ]; then
1942 output "$stats "; output_okn;
1943 else
1944 [ -n "$status" ] && status="$(get_text "$status")"
1945 if [ -n "$status" ] && [ -n "$message" ]; then
1946 status="${status}: $message"
1947 fi
1948 [ -n "$status" ] && output "$serviceName $status!\\n"
1949 fi
1950 if [ "$param" != 'quiet' ] && [ -n "$error" ]; then
1951 for c in $error; do
1952 local error_param="${c##*|}"
1953 local error_code="${c%|*}"
1954 output "${_ERROR_}: $(get_text "$error_code" "$error_param")!\\n"
1955 done
1956 fi
1957 if [ "$param" != 'quiet' ] && [ -n "$warning" ]; then
1958 for c in $warning; do
1959 local warning_param="${c##*|}"
1960 local warning_code="${c%|*}"
1961 output "${_WARNING_}: $(get_text "$warning_code" "$warning_param").\\n"
1962 done
1963 fi
1964 return 0
1965 }
1966
1967 # shellcheck disable=SC2120
1968 adb_stop() {
1969 local validation_result="$3"
1970 load_environment "$validation_result" 'quiet' || return 0
1971 if [ -s "$outputFile" ]; then
1972 output "Stopping $serviceName... "
1973 cache 'create'
1974 if resolver 'on_stop'; then
1975 ipset -q -! flush adb
1976 ipset -q -! destroy adb
1977 nft delete set inet fw4 adb4
1978 nft delete set inet fw4 adb6
1979 led_off "$led"
1980 output 0 "$__OK__\\n"; output_okn;
1981 json set status 'statusStopped'
1982 json del message
1983 else
1984 output 0 "$__FAIL__\\n"; output_fail;
1985 json set status 'statusFail'
1986 json add error 'errorStopping'
1987 output "${_ERROR_}: $(get_text 'errorStopping')!\\n"
1988 fi
1989 fi
1990 return 0
1991 }
1992
1993 adb_pause() {
1994 local timeout="${1:-$pause_timeout}"
1995 local validation_result="$3"
1996 adb_stop 'on_pause' '' "$validation_result"
1997 output "Sleeping for $timeout seconds... "
1998 if is_integer "$timeout" && sleep "$timeout"; then
1999 output_okn
2000 else
2001 output_failn
2002 fi
2003 adb_start 'on_pause' '' "$validation_result"
2004 }
2005
2006 allow() { load_validate_config 'config' adb_allow "'$*'"; }
2007 boot() {
2008 local procd_boot_delay
2009 ubus -t 30 wait_for network.interface 2>/dev/null
2010 config_load "$packageName"
2011 config_get procd_boot_delay 'config' 'procd_boot_delay' '0'
2012 # shellcheck disable=SC2154
2013 { is_integer "$procd_boot_delay" && sleep "$procd_boot_delay"; \
2014 rc_procd start_service 'on_boot' && service_started 'on_boot'; } &
2015 }
2016 check() { load_validate_config 'config' adb_check "'$*'"; }
2017 check_lists() { load_validate_config 'config' adb_check_lists "'$*'"; }
2018 dl() { rc_procd start_service 'download'; }
2019 killcache() {
2020 local compressed_cache_dir
2021 config_load "$packageName"
2022 config_get compressed_cache_dir 'config' 'compressed_cache_dir' '/etc'
2023 if [ "$(sanitize_dir "$compressed_cache_dir")" = '/' ]; then
2024 compressed_cache_dir=''
2025 elif [ -n "$(sanitize_dir "$compressed_cache_dir")" ]; then
2026 compressed_cache_dir="$(sanitize_dir "$compressed_cache_dir")"
2027 else
2028 compressed_cache_dir="/etc"
2029 fi
2030 rm -f "$dnsmasqAddnhostsCache" "${compressed_cache_dir}/${dnsmasqAddnhostsGzip}"
2031 rm -f "$dnsmasqConfCache" "${compressed_cache_dir}/${dnsmasqConfGzip}"
2032 rm -f "$dnsmasqIpsetCache" "${compressed_cache_dir}/${dnsmasqIpsetGzip}"
2033 rm -f "$dnsmasqNftsetCache" "${compressed_cache_dir}/${dnsmasqNftsetGzip}"
2034 rm -f "$dnsmasqServersCache" "${compressed_cache_dir}/${dnsmasqServersGzip}"
2035 rm -f "$smartdnsDomainSetCache" "${compressed_cache_dir}/${smartdnsDomainSetGzip}"
2036 rm -f "$smartdnsIpsetCache" "${compressed_cache_dir}/${smartdnsIpsetGzip}"
2037 rm -f "$smartdnsNftsetCache" "${compressed_cache_dir}/${smartdnsNftsetGzip}"
2038 rm -f "$unboundCache" "${compressed_cache_dir}/${unboundGzip}"
2039 resolver 'cleanup'
2040 return 0
2041 }
2042 reload_service() { rc_procd start_service 'restart'; }
2043 restart_service() { rc_procd start_service 'restart'; }
2044 service_started() { is_fw4_restart_needed && procd_set_config_changed firewall; }
2045 service_stopped() { is_fw4_restart_needed && procd_set_config_changed firewall; }
2046 service_triggers() {
2047 local wan wan6 i
2048 local procd_trigger_wan6
2049 config_load "$packageName"
2050 config_get_bool procd_trigger_wan6 'config' 'procd_trigger_wan6' '0'
2051 network_flush_cache
2052 network_find_wan wan
2053 wan="${wan:-wan}"
2054 if [ "$procd_trigger_wan6" -ne '0' ]; then
2055 network_find_wan6 wan6
2056 wan6="${wan6:-wan6}"
2057 fi
2058 for i in "$wan" "$wan6"; do
2059 [ -n "$i" ] && procd_add_interface_trigger "interface.*" "$i" "/etc/init.d/${packageName}" start
2060 done
2061 procd_add_config_trigger "config.change" "$packageName" "/etc/init.d/${packageName}" reload
2062 }
2063 sizes() { load_validate_config 'config' adb_sizes "''"; }
2064 start_service() {
2065 load_validate_config 'config' adb_config_update "'$*'"
2066 load_validate_config 'config' adb_start "'$*'"
2067 }
2068 status_service() { adb_status "$@"; }
2069 stop_service() { load_validate_config 'config' adb_stop "'$*'"; }
2070 pause() { load_validate_config 'config' adb_pause "'$*'"; }
2071 version() { echo "$PKG_VERSION"; }
2072
2073 load_validate_file_url_section() {
2074 uci_load_validate "$packageName" "$packageName" "$1" "$2" \
2075 'enabled:bool:1' \
2076 'action:or("allow", "block"):block' \
2077 'size:or(uinteger, "")' \
2078 'url:string'
2079 }
2080
2081 load_validate_config() {
2082 local enabled
2083 local force_dns
2084 local force_dns_port
2085 local parallel_downloads
2086 local debug
2087 local compressed_cache
2088 local compressed_cache_dir
2089 local ipv6_enabled
2090 local allow_non_ascii
2091 local canary_domains_icloud
2092 local canary_domains_mozilla
2093 local config_update_enabled
2094 local config_update_url
2095 local download_timeout
2096 local pause_timeout
2097 local curl_additional_param
2098 local curl_max_file_size
2099 local curl_retry
2100 local verbosity
2101 local procd_trigger_wan6
2102 local procd_boot_wan_timeout
2103 local led
2104 local dns
2105 local dnsmasq_instance
2106 local allowed_domain
2107 local blocked_domain
2108 local dnsmasq_config_file_url
2109 uci_load_validate "$packageName" "$packageName" "$1" "${2}${3:+ $3}" \
2110 'enabled:bool:0' \
2111 'force_dns:bool:1' \
2112 'force_dns_port:list(integer):53,853' \
2113 'parallel_downloads:bool:1' \
2114 'debug:bool:0' \
2115 'compressed_cache:bool:0' \
2116 'compressed_cache_dir:directory:/etc' \
2117 'ipv6_enabled:bool:0' \
2118 'allow_non_ascii:bool:0' \
2119 'canary_domains_icloud:bool:0' \
2120 'canary_domains_mozilla:bool:0' \
2121 'config_update_enabled:bool:0' \
2122 'config_update_url:string:https://cdn.jsdelivr.net/gh/openwrt/packages/net/adblock-fast/files/adblock-fast.config.update' \
2123 'download_timeout:range(1,60):20' \
2124 'pause_timeout:range(1,60):20' \
2125 'curl_additional_param:or("", string)' \
2126 'curl_max_file_size:or("", uinteger)' \
2127 'curl_retry:range(0,30):3' \
2128 'verbosity:range(0,2):2' \
2129 'procd_trigger_wan6:bool:0' \
2130 'procd_boot_wan_timeout:integer:60' \
2131 'led:or("", "none", file, device, string)' \
2132 'dns:or("dnsmasq.addnhosts", "dnsmasq.conf", "dnsmasq.ipset", "dnsmasq.nftset", "dnsmasq.servers", "smartdns.domainset", "smartdns.ipset", "smartdns.nftset", "unbound.adb_list"):dnsmasq.servers' \
2133 'dnsmasq_instance:list(or(integer, string)):*' \
2134 'smartdns_instance:list(or(integer, string)):*' \
2135 'allowed_domain:list(string)' \
2136 'blocked_domain:list(string)' \
2137 'dnsmasq_config_file_url:string'
2138 }