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