You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1411 lines
45 KiB

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