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