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.

1080 lines
34 KiB

  1. #!/bin/sh
  2. # dns based ad/abuse domain blocking
  3. # written by Dirk Brenken (dev@brenken.org)
  4. # This is free software, licensed under the GNU General Public License v3.
  5. # You should have received a copy of the GNU General Public License
  6. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  7. # set initial defaults
  8. #
  9. LC_ALL=C
  10. PATH="/usr/sbin:/usr/bin:/sbin:/bin"
  11. adb_ver="3.5.4-2"
  12. adb_sysver="unknown"
  13. adb_enabled=0
  14. adb_debug=0
  15. adb_backup_mode=0
  16. adb_forcesrt=0
  17. adb_forcedns=0
  18. adb_jail=0
  19. adb_maxqueue=4
  20. adb_notify=0
  21. adb_notifycnt=0
  22. adb_triggerdelay=0
  23. adb_backup=0
  24. adb_backupdir="/mnt"
  25. adb_fetchutil="uclient-fetch"
  26. adb_dns="dnsmasq"
  27. adb_dnsprefix="adb_list"
  28. adb_dnsfile="${adb_dnsprefix}.overall"
  29. adb_dnsjail="${adb_dnsprefix}.jail"
  30. adb_dnsflush=0
  31. adb_whitelist="/etc/adblock/adblock.whitelist"
  32. adb_rtfile="/tmp/adb_runtime.json"
  33. adb_hashutil="$(command -v sha256sum)"
  34. adb_hashold=""
  35. adb_hashnew=""
  36. adb_cnt=""
  37. adb_rc=0
  38. adb_action="${1:-"start"}"
  39. adb_pidfile="/var/run/adblock.pid"
  40. # load adblock environment
  41. #
  42. f_envload()
  43. {
  44. local dns_up sys_call sys_desc sys_model sys_ver cnt=0
  45. # get system information
  46. #
  47. sys_call="$(ubus -S call system board 2>/dev/null)"
  48. if [ -n "${sys_call}" ]
  49. then
  50. sys_desc="$(printf '%s' "${sys_call}" | jsonfilter -e '@.release.description')"
  51. sys_model="$(printf '%s' "${sys_call}" | jsonfilter -e '@.model')"
  52. sys_ver="$(cat /etc/turris-version 2>/dev/null)"
  53. if [ -n "${sys_ver}" ]
  54. then
  55. sys_desc="${sys_desc}/${sys_ver}"
  56. fi
  57. adb_sysver="${sys_model}, ${sys_desc}"
  58. fi
  59. # check hash utility
  60. #
  61. if [ ! -x "${adb_hashutil}" ]
  62. then
  63. adb_hashutil="$(command -v md5sum)"
  64. fi
  65. # source in system libraries
  66. #
  67. if [ -r "/lib/functions.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
  68. then
  69. . "/lib/functions.sh"
  70. . "/usr/share/libubox/jshn.sh"
  71. else
  72. f_log "err" "system libraries not found"
  73. fi
  74. # parse 'global' and 'extra' section by callback
  75. #
  76. config_cb()
  77. {
  78. local type="${1}"
  79. if [ "${type}" = "adblock" ]
  80. then
  81. option_cb()
  82. {
  83. local option="${1}"
  84. local value="${2}"
  85. eval "${option}=\"${value}\""
  86. }
  87. else
  88. reset_cb
  89. fi
  90. }
  91. # parse 'source' typed sections
  92. #
  93. parse_config()
  94. {
  95. local value opt section="${1}" options="enabled adb_src adb_src_rset adb_src_cat"
  96. eval "adb_sources=\"${adb_sources} ${section}\""
  97. for opt in ${options}
  98. do
  99. config_get value "${section}" "${opt}"
  100. if [ -n "${value}" ]
  101. then
  102. eval "${opt}_${section}=\"${value}\""
  103. fi
  104. done
  105. }
  106. # load adblock config
  107. #
  108. config_load adblock
  109. config_foreach parse_config source
  110. # check dns backend
  111. #
  112. case "${adb_dns}" in
  113. dnsmasq)
  114. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  115. adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
  116. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  117. adb_dnsheader=""
  118. adb_dnsdeny="awk '{print \"server=/\"\$0\"/\"}'"
  119. adb_dnsallow="awk '{print \"server=/\"\$0\"/#\"}'"
  120. adb_dnshalt="server=/#/"
  121. ;;
  122. unbound)
  123. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  124. adb_dnsuser="${adb_dnsuser:-"unbound"}"
  125. adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
  126. adb_dnsheader=""
  127. adb_dnsdeny="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
  128. adb_dnsallow="awk '{print \"local-zone: \042\"\$0\"\042 transparent\"}'"
  129. adb_dnshalt="local-zone: \".\" static"
  130. ;;
  131. named)
  132. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  133. adb_dnsuser="${adb_dnsuser:-"bind"}"
  134. adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
  135. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  136. adb_dnsdeny="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  137. adb_dnsallow="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  138. adb_dnshalt="* CNAME ."
  139. ;;
  140. kresd)
  141. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  142. adb_dnsuser="${adb_dnsuser:-"root"}"
  143. adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
  144. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  145. adb_dnsdeny="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  146. adb_dnsallow="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  147. adb_dnshalt="* CNAME ."
  148. ;;
  149. dnscrypt-proxy)
  150. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  151. adb_dnsuser="${adb_dnsuser:-"nobody"}"
  152. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  153. adb_dnsheader=""
  154. adb_dnsdeny="awk '{print \$0}'"
  155. adb_dnsallow=""
  156. adb_dnshalt=""
  157. ;;
  158. esac
  159. # check adblock status
  160. #
  161. if [ ${adb_enabled} -eq 0 ]
  162. then
  163. f_extconf
  164. f_temp
  165. f_rmdns
  166. f_jsnup
  167. f_log "info" "adblock is currently disabled, please set adb_enabled to '1' to use this service"
  168. exit 0
  169. fi
  170. if [ -d "${adb_dnsdir}" ] && [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
  171. then
  172. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  173. fi
  174. if [ "${adb_action}" = "start" ] && [ "${adb_trigger}" = "timed" ]
  175. then
  176. sleep ${adb_triggerdelay}
  177. fi
  178. while [ ${cnt} -le 30 ]
  179. do
  180. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
  181. if [ "${dns_up}" = "true" ]
  182. then
  183. break
  184. fi
  185. sleep 1
  186. cnt=$((cnt+1))
  187. done
  188. if [ "${dns_up}" != "true" ] || [ -z "${adb_dns}" ] || [ ! -x "$(command -v ${adb_dns})" ]
  189. then
  190. f_log "err" "'${adb_dns}' not running or not executable"
  191. elif [ ! -d "${adb_dnsdir}" ]
  192. then
  193. f_log "err" "'${adb_dnsdir}' backend directory not found"
  194. fi
  195. }
  196. # check environment
  197. #
  198. f_envcheck()
  199. {
  200. local ssl_lib
  201. # check external uci config files
  202. #
  203. f_extconf
  204. # check fetch utility
  205. #
  206. case "${adb_fetchutil}" in
  207. uclient-fetch)
  208. if [ -f "/lib/libustream-ssl.so" ]
  209. then
  210. adb_fetchparm="${adb_fetchparm:-"--timeout=10 --no-check-certificate -O"}"
  211. ssl_lib="libustream-ssl"
  212. else
  213. adb_fetchparm="${adb_fetchparm:-"--timeout=10 -O"}"
  214. fi
  215. ;;
  216. wget)
  217. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"}"
  218. ssl_lib="built-in"
  219. ;;
  220. wget-nossl)
  221. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=10 -O"}"
  222. ;;
  223. busybox)
  224. adb_fetchparm="${adb_fetchparm:-"-O"}"
  225. ;;
  226. curl)
  227. adb_fetchparm="${adb_fetchparm:-"--connect-timeout 10 --insecure -o"}"
  228. ssl_lib="built-in"
  229. ;;
  230. aria2c)
  231. adb_fetchparm="${adb_fetchparm:-"--timeout=10 --allow-overwrite=true --auto-file-renaming=false --check-certificate=false -o"}"
  232. ssl_lib="built-in"
  233. ;;
  234. esac
  235. adb_fetchutil="$(command -v "${adb_fetchutil}")"
  236. if [ ! -x "${adb_fetchutil}" ] || [ -z "${adb_fetchutil}" ] || [ -z "${adb_fetchparm}" ]
  237. then
  238. f_log "err" "download utility not found, please install 'uclient-fetch' with 'libustream-mbedtls' or the full 'wget' package"
  239. fi
  240. adb_fetchinfo="${adb_fetchutil} (${ssl_lib:-"-"})"
  241. f_temp
  242. f_jsnup "running"
  243. f_log "info" "start adblock processing (${adb_action})"
  244. }
  245. # create temporary files and directories
  246. #
  247. f_temp()
  248. {
  249. if [ -z "${adb_tmpdir}" ]
  250. then
  251. adb_tmpdir="$(mktemp -p /tmp -d)"
  252. adb_tmpload="$(mktemp -p ${adb_tmpdir} -tu)"
  253. adb_tmpfile="$(mktemp -p ${adb_tmpdir} -tu)"
  254. fi
  255. if [ ! -s "${adb_pidfile}" ]
  256. then
  257. printf '%s' "${$}" > "${adb_pidfile}"
  258. fi
  259. }
  260. # remove temporary files and directories
  261. #
  262. f_rmtemp()
  263. {
  264. if [ -d "${adb_tmpdir}" ]
  265. then
  266. rm -rf "${adb_tmpdir}"
  267. fi
  268. > "${adb_pidfile}"
  269. }
  270. # remove dns related files and directories
  271. #
  272. f_rmdns()
  273. {
  274. if [ -n "${adb_dns}" ]
  275. then
  276. f_hash
  277. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  278. > "${adb_dnsdir}/.${adb_dnsfile}"
  279. > "${adb_rtfile}"
  280. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  281. f_hash
  282. if [ ${?} -eq 1 ]
  283. then
  284. f_dnsup
  285. fi
  286. f_rmtemp
  287. fi
  288. f_log "debug" "f_rmdns::: dns: ${adb_dns}, dns_dir: ${adb_dnsdir}, dns_prefix: ${adb_dnsprefix}, dns_file: ${adb_dnsfile}, rt_file: ${adb_rtfile}, backup_dir: ${adb_backupdir}"
  289. }
  290. # commit uci changes
  291. #
  292. f_uci()
  293. {
  294. local change config="${1}"
  295. if [ -n "${config}" ]
  296. then
  297. change="$(uci -q changes "${config}" | awk '{ORS=" "; print $0}')"
  298. if [ -n "${change}" ]
  299. then
  300. uci -q commit "${config}"
  301. case "${config}" in
  302. firewall)
  303. /etc/init.d/firewall reload >/dev/null 2>&1
  304. ;;
  305. *)
  306. /etc/init.d/"${adb_dns}" reload >/dev/null 2>&1
  307. ;;
  308. esac
  309. fi
  310. fi
  311. f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
  312. }
  313. # list/overall count
  314. #
  315. f_count()
  316. {
  317. local mode="${1}"
  318. adb_cnt=0
  319. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ] && ([ -z "${mode}" ] || [ "${mode}" = "final" ])
  320. then
  321. adb_cnt="$(( $(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}") - $(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add_whitelist") ))"
  322. if [ "${adb_dns}" = "named" ] || [ "${adb_dns}" = "kresd" ]
  323. then
  324. adb_cnt="$(( (${adb_cnt} - $(printf '%s' "${adb_dnsheader}" | grep -c "^")) / 2 ))"
  325. fi
  326. elif [ -s "${adb_tmpfile}" ]
  327. then
  328. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpfile}")"
  329. fi
  330. }
  331. # set external config options
  332. #
  333. f_extconf()
  334. {
  335. local uci_config port port_list="53 853 5353"
  336. case "${adb_dns}" in
  337. dnsmasq)
  338. uci_config="dhcp"
  339. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci -q get dhcp.@dnsmasq[${adb_dnsinstance}].serversfile | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  340. then
  341. uci -q set dhcp.@dnsmasq[${adb_dnsinstance}].serversfile="${adb_dnsdir}/${adb_dnsfile}"
  342. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci -q get dhcp.@dnsmasq[${adb_dnsinstance}].serversfile | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  343. then
  344. uci -q delete dhcp.@dnsmasq[${adb_dnsinstance}].serversfile
  345. fi
  346. ;;
  347. kresd)
  348. uci_config="resolver"
  349. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci -q get resolver.kresd.rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  350. then
  351. uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  352. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci -q get resolver.kresd.rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  353. then
  354. uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  355. fi
  356. if [ ${adb_enabled} -eq 1 ] && [ ${adb_dnsflush} -eq 0 ] && [ "$(uci -q get resolver.kresd.keep_cache)" != "1" ]
  357. then
  358. uci -q set resolver.kresd.keep_cache="1"
  359. elif [ ${adb_enabled} -eq 0 ] || ([ ${adb_dnsflush} -eq 1 ] && [ "$(uci -q get resolver.kresd.keep_cache)" = "1" ])
  360. then
  361. uci -q set resolver.kresd.keep_cache="0"
  362. fi
  363. ;;
  364. esac
  365. f_uci "${uci_config}"
  366. uci_config="firewall"
  367. if [ ${adb_enabled} -eq 1 ] && [ ${adb_forcedns} -eq 1 ] && \
  368. [ -z "$(uci -q get firewall.adblock_dns_53)" ] && [ $(/etc/init.d/firewall enabled; printf '%u' ${?}) -eq 0 ]
  369. then
  370. for port in ${port_list}
  371. do
  372. uci_add firewall "redirect" "adblock_dns_${port}"
  373. uci_set firewall "adblock_dns_${port}" "name" "Adblock DNS, port ${port}"
  374. uci_set firewall "adblock_dns_${port}" "src" "lan"
  375. uci_set firewall "adblock_dns_${port}" "proto" "tcp udp"
  376. uci_set firewall "adblock_dns_${port}" "src_dport" "${port}"
  377. uci_set firewall "adblock_dns_${port}" "dest_port" "${port}"
  378. uci_set firewall "adblock_dns_${port}" "target" "DNAT"
  379. done
  380. elif [ -n "$(uci -q get firewall.adblock_dns_53)" ] && ([ ${adb_enabled} -eq 0 ] || [ ${adb_forcedns} -eq 0 ])
  381. then
  382. for port in ${port_list}
  383. do
  384. uci_remove firewall "adblock_dns_${port}"
  385. done
  386. fi
  387. f_uci "${uci_config}"
  388. }
  389. # restart of the dns backend
  390. #
  391. f_dnsup()
  392. {
  393. local dns_up cache_util cache_rc cnt=0
  394. if [ ${adb_dnsflush} -eq 0 ] && [ ${adb_enabled} -eq 1 ] && [ "${adb_rc}" -eq 0 ]
  395. then
  396. case "${adb_dns}" in
  397. dnsmasq)
  398. killall -q -HUP "${adb_dns}"
  399. cache_rc=${?}
  400. ;;
  401. unbound)
  402. cache_util="$(command -v unbound-control)"
  403. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}"/unbound.conf ]
  404. then
  405. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf dump_cache > "${adb_tmpdir}"/adb_cache.dump 2>/dev/null
  406. fi
  407. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  408. ;;
  409. kresd)
  410. cache_util="keep_cache"
  411. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  412. cache_rc=${?}
  413. ;;
  414. named)
  415. cache_util="$(command -v rndc)"
  416. if [ -x "${cache_util}" ] && [ -f /etc/bind/rndc.conf ]
  417. then
  418. "${cache_util}" -c /etc/bind/rndc.conf reload >/dev/null 2>&1
  419. cache_rc=${?}
  420. else
  421. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  422. fi
  423. ;;
  424. *)
  425. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  426. ;;
  427. esac
  428. else
  429. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  430. fi
  431. adb_rc=1
  432. while [ ${cnt} -le 10 ]
  433. do
  434. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
  435. if [ "${dns_up}" = "true" ]
  436. then
  437. case "${adb_dns}" in
  438. unbound)
  439. cache_util="$(command -v unbound-control)"
  440. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}"/adb_cache.dump ]
  441. then
  442. while [ ${cnt} -le 10 ]
  443. do
  444. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf load_cache < "${adb_tmpdir}"/adb_cache.dump >/dev/null 2>&1
  445. cache_rc=${?}
  446. if [ ${cache_rc} -eq 0 ]
  447. then
  448. break
  449. fi
  450. cnt=$((cnt+1))
  451. sleep 1
  452. done
  453. fi
  454. ;;
  455. esac
  456. adb_rc=0
  457. break
  458. fi
  459. cnt=$((cnt+1))
  460. sleep 1
  461. done
  462. f_log "debug" "f_dnsup::: cache_util: ${cache_util:-"-"}, cache_rc: ${cache_rc:-"-"}, cache_flush: ${adb_dnsflush}, cache_cnt: ${cnt}, rc: ${adb_rc}"
  463. return ${adb_rc}
  464. }
  465. # backup/restore/remove blocklists
  466. #
  467. f_list()
  468. {
  469. local file mode="${1}" in_rc="${adb_rc}"
  470. case "${mode}" in
  471. backup)
  472. if [ -d "${adb_backupdir}" ]
  473. then
  474. gzip -cf "${adb_tmpfile}" 2>/dev/null > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  475. adb_rc=${?}
  476. fi
  477. ;;
  478. restore)
  479. if [ -d "${adb_backupdir}" ] && [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  480. then
  481. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null > "${adb_tmpfile}"
  482. adb_rc=${?}
  483. fi
  484. ;;
  485. remove)
  486. if [ -d "${adb_backupdir}" ]
  487. then
  488. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  489. fi
  490. adb_rc=${?}
  491. ;;
  492. merge)
  493. for file in "${adb_tmpfile}".*
  494. do
  495. cat "${file}" 2>/dev/null >> "${adb_tmpdir}/${adb_dnsfile}"
  496. if [ ${?} -ne 0 ]
  497. then
  498. adb_rc=${?}
  499. break
  500. fi
  501. rm -f "${file}"
  502. done
  503. adb_tmpfile="${adb_tmpdir}/${adb_dnsfile}"
  504. ;;
  505. final)
  506. > "${adb_dnsdir}/${adb_dnsfile}"
  507. if [ -s "${adb_tmpdir}/tmp.add_whitelist" ]
  508. then
  509. cat "${adb_tmpdir}/tmp.add_whitelist" >> "${adb_dnsdir}/${adb_dnsfile}"
  510. fi
  511. if [ -s "${adb_tmpdir}/tmp.rem_whitelist" ]
  512. then
  513. grep -vf "${adb_tmpdir}/tmp.rem_whitelist" "${adb_tmpdir}/${adb_dnsfile}" | eval "${adb_dnsdeny}" >> "${adb_dnsdir}/${adb_dnsfile}"
  514. else
  515. eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >> "${adb_dnsdir}/${adb_dnsfile}"
  516. fi
  517. if [ ${?} -eq 0 ] && [ -n "${adb_dnsheader}" ]
  518. then
  519. printf '%s\n' "${adb_dnsheader}" | cat - "${adb_dnsdir}/${adb_dnsfile}" > "${adb_tmpdir}/${adb_dnsfile}"
  520. cat "${adb_tmpdir}/${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  521. fi
  522. adb_rc=${?}
  523. ;;
  524. esac
  525. f_count "${mode}"
  526. f_log "debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${adb_rc}"
  527. }
  528. # top level domain compression
  529. #
  530. f_tld()
  531. {
  532. local cnt cnt_srt cnt_tld source="${1}" temp="${1}.tld"
  533. cnt="$(wc -l 2>/dev/null < "${source}")"
  534. sort -u "${source}" > "${temp}"
  535. if [ ${?} -eq 0 ]
  536. then
  537. cnt_srt="$(wc -l 2>/dev/null < "${temp}")"
  538. awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${temp}" > "${source}"
  539. if [ ${?} -eq 0 ]
  540. then
  541. sort "${source}" > "${temp}"
  542. if [ ${?} -eq 0 ]
  543. then
  544. awk '{if(NR==1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "${temp}" > "${source}"
  545. if [ ${?} -eq 0 ]
  546. then
  547. awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${source}" > "${temp}"
  548. if [ ${?} -eq 0 ]
  549. then
  550. sort "${temp}" > "${source}"
  551. if [ ${?} -eq 0 ]
  552. then
  553. cnt_tld="$(wc -l 2>/dev/null < "${source}")"
  554. else
  555. cat "${temp}" > "${source}"
  556. fi
  557. fi
  558. else
  559. cat "${temp}" > "${source}"
  560. fi
  561. fi
  562. else
  563. cat "${temp}" > "${source}"
  564. fi
  565. fi
  566. rm -f "${temp}"
  567. f_log "debug" "f_tld ::: source: ${source}, cnt: ${cnt:-"-"}, cnt_srt: ${cnt_srt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
  568. }
  569. # blocklist hash compare
  570. #
  571. f_hash()
  572. {
  573. local hash hash_rc=1
  574. if [ -x "${adb_hashutil}" ] && [ -f "${adb_dnsdir}/${adb_dnsfile}" ]
  575. then
  576. hash="$(${adb_hashutil} "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null | awk '{print $1}')"
  577. if [ -z "${adb_hashold}" ] && [ -n "${hash}" ]
  578. then
  579. adb_hashold="${hash}"
  580. elif [ -z "${adb_hashnew}" ] && [ -n "${hash}" ]
  581. then
  582. adb_hashnew="${hash}"
  583. fi
  584. if [ -n "${adb_hashold}" ] && [ -n "${adb_hashnew}" ]
  585. then
  586. if [ "${adb_hashold}" = "${adb_hashnew}" ]
  587. then
  588. hash_rc=0
  589. fi
  590. adb_hashold=""
  591. adb_hashnew=""
  592. fi
  593. fi
  594. f_log "debug" "f_hash ::: hash_util: ${adb_hashutil}, hash: ${hash}, out_rc: ${hash_rc}"
  595. return ${hash_rc}
  596. }
  597. # suspend/resume adblock processing
  598. #
  599. f_switch()
  600. {
  601. local mode="${1}"
  602. if [ ! -s "${adb_dnsdir}/.${adb_dnsfile}" ] && [ "${mode}" = "suspend" ]
  603. then
  604. f_hash
  605. cat "${adb_dnsdir}/${adb_dnsfile}" > "${adb_dnsdir}/.${adb_dnsfile}"
  606. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  607. f_hash
  608. elif [ -s "${adb_dnsdir}/.${adb_dnsfile}" ] && [ "${mode}" = "resume" ]
  609. then
  610. f_hash
  611. cat "${adb_dnsdir}/.${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  612. > "${adb_dnsdir}/.${adb_dnsfile}"
  613. f_hash
  614. fi
  615. if [ ${?} -eq 1 ]
  616. then
  617. f_temp
  618. f_dnsup
  619. f_jsnup "${mode}"
  620. f_log "info" "${mode} adblock processing"
  621. f_rmtemp
  622. exit 0
  623. fi
  624. }
  625. # query blocklist for certain (sub-)domains
  626. #
  627. f_query()
  628. {
  629. local search result prefix suffix field domain="${1}" tld="${1#*.}"
  630. if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  631. then
  632. printf '%s\n' "::: invalid domain input, please submit a single domain, e.g. 'doubleclick.net'"
  633. else
  634. case "${adb_dns}" in
  635. dnsmasq)
  636. prefix=".*[\/\.]"
  637. suffix="(\/)"
  638. field=2
  639. ;;
  640. unbound)
  641. prefix=".*[\"\.]"
  642. suffix="(static)"
  643. field=3
  644. ;;
  645. named)
  646. prefix="[^\*].*[\.]"
  647. suffix="( \.)"
  648. field=1
  649. ;;
  650. kresd)
  651. prefix="[^\*].*[\.]"
  652. suffix="( \.)"
  653. field=1
  654. ;;
  655. dnscrypt-proxy)
  656. prefix=".*[\.]"
  657. suffix=""
  658. field=1
  659. ;;
  660. esac
  661. while [ "${domain}" != "${tld}" ]
  662. do
  663. search="${domain//./\.}"
  664. result="$(awk -F '/|\"| ' "/^($search|${prefix}+${search}.*${suffix}$)/{i++;{printf(\" + %s\n\",\$${field})};if(i>9){printf(\" + %s\n\",\"[...]\");exit}}" "${adb_dnsdir}/${adb_dnsfile}")"
  665. printf '%s\n' "::: results for domain '${domain}'"
  666. printf '%s\n' "${result:-" - no match"}"
  667. domain="${tld}"
  668. tld="${domain#*.}"
  669. done
  670. fi
  671. }
  672. # update runtime information
  673. #
  674. f_jsnup()
  675. {
  676. local bg_pid rundate status="${1:-"enabled"}" mode="normal mode" no_mail=0
  677. if [ ${adb_rc} -gt 0 ]
  678. then
  679. status="error"
  680. rundate="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  681. fi
  682. if [ ${adb_enabled} -eq 0 ]
  683. then
  684. status="disabled"
  685. fi
  686. if [ "${status}" = "enabled" ]
  687. then
  688. rundate="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  689. fi
  690. if [ "${status}" = "suspend" ]
  691. then
  692. status="paused"
  693. fi
  694. if [ "${status}" = "resume" ]
  695. then
  696. no_mail=1
  697. status="enabled"
  698. fi
  699. if [ ${adb_backup_mode} -eq 1 ]
  700. then
  701. mode="backup mode"
  702. fi
  703. if [ -s "${adb_rtfile}" ]
  704. then
  705. json_load "$(cat "${adb_rtfile}" 2>/dev/null)"
  706. json_select data
  707. if [ -z "${adb_fetchinfo}" ] && [ -s "${adb_rtfile}" ]
  708. then
  709. json_get_var adb_fetchinfo "fetch_utility"
  710. fi
  711. if [ -z "${rundate}" ]
  712. then
  713. json_get_var rundate "last_rundate"
  714. fi
  715. if [ -z "${adb_cnt}" ]
  716. then
  717. json_get_var adb_cnt "overall_domains"
  718. adb_cnt="${adb_cnt%% *}"
  719. fi
  720. fi
  721. json_init
  722. json_add_object "data"
  723. json_add_string "adblock_status" "${status}"
  724. json_add_string "adblock_version" "${adb_ver}"
  725. json_add_string "overall_domains" "${adb_cnt:-0} (${mode})"
  726. json_add_string "fetch_utility" "${adb_fetchinfo:-"-"}"
  727. json_add_string "dns_backend" "${adb_dns} (${adb_dnsdir})"
  728. json_add_string "last_rundate" "${rundate:-"-"}"
  729. json_add_string "system_release" "${adb_sysver}"
  730. json_close_object
  731. json_dump > "${adb_rtfile}"
  732. if [ ${adb_notify} -eq 1 ] && [ ${no_mail} -eq 0 ] && [ -x /etc/adblock/adblock.notify ] && \
  733. ([ "${status}" = "error" ] || ([ "${status}" = "enabled" ] && [ ${adb_cnt} -le ${adb_notifycnt} ]))
  734. then
  735. (/etc/adblock/adblock.notify >/dev/null 2>&1) &
  736. bg_pid=${!}
  737. fi
  738. f_log "debug" "f_jsnup::: status: ${status}, mode: ${mode}, cnt: ${adb_cnt}, notify: ${adb_notify}, notify_cnt: ${adb_notifycnt}, notify_pid: ${bg_pid:-"-"}"
  739. }
  740. # write to syslog
  741. #
  742. f_log()
  743. {
  744. local class="${1}" log_msg="${2}"
  745. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  746. then
  747. logger -p "${class}" -t "adblock-[${adb_ver}]" "${log_msg}"
  748. if [ "${class}" = "err" ]
  749. then
  750. f_rmdns
  751. f_jsnup
  752. logger -p "${class}" -t "adblock-[${adb_ver}]" "Please also check 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md'"
  753. exit 1
  754. fi
  755. fi
  756. }
  757. # main function for blocklist processing
  758. #
  759. f_main()
  760. {
  761. local tmp_load tmp_file src_name src_rset src_url src_log src_arc src_cat cat list entry suffix mem_total mem_free enabled cnt=1
  762. mem_total="$(awk '/^MemTotal/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  763. mem_free="$(awk '/^MemFree/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  764. tmp_load="${adb_tmpload}"
  765. tmp_file="${adb_tmpfile}"
  766. > "${adb_dnsdir}/.${adb_dnsfile}"
  767. > "${adb_tmpdir}/tmp.raw_whitelist"
  768. > "${adb_tmpdir}/tmp.add_whitelist"
  769. > "${adb_tmpdir}/tmp.rem_whitelist"
  770. f_log "debug" "f_main ::: dns: ${adb_dns}, fetch_util: ${adb_fetchinfo}, backup: ${adb_backup}, backup_mode: ${adb_backup_mode}, dns_jail: ${adb_jail}, force_srt: ${adb_forcesrt}, force_dns: ${adb_forcedns}, mem_total: ${mem_total:-0}, mem_free: ${mem_free:-0}, max_queue: ${adb_maxqueue}"
  771. # prepare whitelist entries
  772. #
  773. if [ -s "${adb_whitelist}" ]
  774. then
  775. adb_whitelist_rset="/^([^([:space:]|\#|\*|\/).]+\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  776. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.raw_whitelist"
  777. f_tld "${adb_tmpdir}/tmp.raw_whitelist"
  778. adb_whitelist_rset="/^([^([:space:]|\#|\*|\/).]+\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\.\",\"\\\.\",\$1);print tolower(\"^\"\$1\"\\\|\\\.\"\$1)}"
  779. awk "${adb_whitelist_rset}" "${adb_tmpdir}/tmp.raw_whitelist" > "${adb_tmpdir}/tmp.rem_whitelist"
  780. if [ -n "${adb_dnsallow}" ]
  781. then
  782. eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw_whitelist" > "${adb_tmpdir}/tmp.add_whitelist"
  783. fi
  784. fi
  785. # build 'dnsjail' list
  786. #
  787. if [ ${adb_jail} -eq 1 ]
  788. then
  789. cat "${adb_tmpdir}/tmp.add_whitelist" > "/tmp/${adb_dnsjail}"
  790. printf '%s\n' "${adb_dnshalt}" >> "/tmp/${adb_dnsjail}"
  791. if [ -n "${adb_dnsheader}" ]
  792. then
  793. printf '%s\n' "${adb_dnsheader}" | cat - "/tmp/${adb_dnsjail}" > "${adb_tmpdir}/tmp.dnsjail"
  794. cat "${adb_tmpdir}/tmp.dnsjail" > "/tmp/${adb_dnsjail}"
  795. fi
  796. fi
  797. # main loop
  798. #
  799. for src_name in ${adb_sources}
  800. do
  801. enabled="$(eval printf '%s' \"\${enabled_${src_name}\}\")"
  802. src_url="$(eval printf '%s' \"\${adb_src_${src_name}\}\")"
  803. src_rset="$(eval printf '%s' \"\${adb_src_rset_${src_name}\}\")"
  804. src_cat="$(eval printf '%s' \"\${adb_src_cat_${src_name}\}\")"
  805. adb_tmpload="${tmp_load}.${src_name}"
  806. adb_tmpfile="${tmp_file}.${src_name}"
  807. # basic pre-checks
  808. #
  809. f_log "debug" "f_main ::: name: ${src_name}, enabled: ${enabled}"
  810. if [ "${enabled}" != "1" ] || [ -z "${src_url}" ] || [ -z "${src_rset}" ]
  811. then
  812. f_list remove
  813. continue
  814. fi
  815. # backup mode
  816. #
  817. if [ ${adb_backup_mode} -eq 1 ] && [ "${adb_action}" = "start" ] && [ "${src_name}" != "blacklist" ]
  818. then
  819. f_list restore
  820. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  821. then
  822. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  823. then
  824. f_tld "${adb_tmpfile}"
  825. fi
  826. continue
  827. fi
  828. fi
  829. # download queue processing
  830. #
  831. if [ "${src_name}" = "blacklist" ]
  832. then
  833. if [ -s "${src_url}" ]
  834. then
  835. (
  836. src_log="$(cat "${src_url}" > "${adb_tmpload}" 2>&1)"
  837. adb_rc=${?}
  838. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  839. then
  840. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  841. adb_rc=${?}
  842. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  843. then
  844. rm -f "${adb_tmpload}"
  845. f_list download
  846. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  847. then
  848. f_tld "${adb_tmpfile}"
  849. fi
  850. fi
  851. else
  852. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  853. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  854. fi
  855. ) &
  856. else
  857. continue
  858. fi
  859. elif [ -n "${src_cat}" ]
  860. then
  861. (
  862. src_arc="${adb_tmpdir}/${src_url##*/}"
  863. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
  864. adb_rc=${?}
  865. if [ ${adb_rc} -eq 0 ] && [ -s "${src_arc}" ]
  866. then
  867. list="$(tar -tzf "${src_arc}")"
  868. suffix="$(eval printf '%s' \"\${adb_src_suffix_${src_name}:-\"domains\"\}\")"
  869. for cat in ${src_cat}
  870. do
  871. entry="$(printf '%s' "${list}" | grep -E "[\^/]+${cat}/${suffix}")"
  872. if [ -n "${entry}" ]
  873. then
  874. tar -xOzf "${src_arc}" "${entry}" >> "${adb_tmpload}"
  875. adb_rc=${?}
  876. if [ ${adb_rc} -ne 0 ]
  877. then
  878. break
  879. fi
  880. fi
  881. done
  882. else
  883. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  884. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  885. fi
  886. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  887. then
  888. rm -f "${src_arc}"
  889. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  890. adb_rc=${?}
  891. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  892. then
  893. rm -f "${adb_tmpload}"
  894. f_list download
  895. if [ ${adb_backup} -eq 1 ]
  896. then
  897. f_list backup
  898. fi
  899. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  900. then
  901. f_tld "${adb_tmpfile}"
  902. fi
  903. elif [ ${adb_backup} -eq 1 ]
  904. then
  905. f_list restore
  906. fi
  907. elif [ ${adb_backup} -eq 1 ]
  908. then
  909. f_list restore
  910. fi
  911. ) &
  912. else
  913. (
  914. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${adb_tmpload}" "${src_url}" 2>&1)"
  915. adb_rc=${?}
  916. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  917. then
  918. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  919. adb_rc=${?}
  920. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  921. then
  922. rm -f "${adb_tmpload}"
  923. f_list download
  924. if [ ${adb_backup} -eq 1 ]
  925. then
  926. f_list backup
  927. fi
  928. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  929. then
  930. f_tld "${adb_tmpfile}"
  931. fi
  932. elif [ ${adb_backup} -eq 1 ]
  933. then
  934. f_list restore
  935. fi
  936. else
  937. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  938. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  939. if [ ${adb_backup} -eq 1 ]
  940. then
  941. f_list restore
  942. fi
  943. fi
  944. ) &
  945. fi
  946. hold=$(( cnt % adb_maxqueue ))
  947. if [ ${hold} -eq 0 ]
  948. then
  949. wait
  950. fi
  951. cnt=$(( cnt + 1 ))
  952. done
  953. # list merge
  954. #
  955. wait
  956. src_name="overall"
  957. adb_tmpfile="${tmp_file}"
  958. f_list merge
  959. # overall sort and conditional dns restart
  960. #
  961. f_hash
  962. if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  963. then
  964. if ([ ${mem_total} -ge 64 ] && [ ${mem_free} -ge 40 ]) || [ ${adb_forcesrt} -eq 1 ]
  965. then
  966. f_tld "${adb_tmpdir}/${adb_dnsfile}"
  967. fi
  968. f_list final
  969. else
  970. > "${adb_dnsdir}/${adb_dnsfile}"
  971. fi
  972. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  973. f_hash
  974. if [ ${?} -eq 1 ]
  975. then
  976. f_dnsup
  977. fi
  978. f_jsnup
  979. if [ ${?} -eq 0 ]
  980. then
  981. f_log "info" "blocklist with overall ${adb_cnt} domains loaded successfully (${adb_sysver})"
  982. else
  983. f_log "err" "dns backend restart with active blocklist failed"
  984. fi
  985. f_rmtemp
  986. exit ${adb_rc}
  987. }
  988. # handle different adblock actions
  989. #
  990. f_envload
  991. case "${adb_action}" in
  992. stop)
  993. f_rmdns
  994. ;;
  995. restart)
  996. f_rmdns
  997. f_envcheck
  998. f_main
  999. ;;
  1000. suspend)
  1001. f_switch suspend
  1002. ;;
  1003. resume)
  1004. f_switch resume
  1005. ;;
  1006. query)
  1007. f_query "${2}"
  1008. ;;
  1009. start|reload)
  1010. f_envcheck
  1011. f_main
  1012. ;;
  1013. esac