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.

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