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.

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