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.

1300 lines
41 KiB

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