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.

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