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