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.

1034 lines
32 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.1"
  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=0
  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. if [ ${adb_jail} -eq 1 ]
  120. then
  121. adb_dnsallow="awk '{print \"server=/\"\$0\"/#\"}'"
  122. adb_dnshalt="server=/#/"
  123. fi
  124. ;;
  125. unbound)
  126. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  127. adb_dnsuser="${adb_dnsuser:-"unbound"}"
  128. adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
  129. adb_dnsheader=""
  130. adb_dnsdeny="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
  131. if [ ${adb_jail} -eq 1 ]
  132. then
  133. adb_dnsallow="awk '{print \"local-zone: \042\"\$0\"\042 transparent\"}'"
  134. adb_dnshalt="local-zone: \".\" static"
  135. fi
  136. ;;
  137. named)
  138. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  139. adb_dnsuser="${adb_dnsuser:-"bind"}"
  140. adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
  141. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  142. adb_dnsdeny="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  143. if [ ${adb_jail} -eq 1 ]
  144. then
  145. adb_dnsallow="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  146. adb_dnshalt="* CNAME ."
  147. fi
  148. ;;
  149. kresd)
  150. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  151. adb_dnsuser="${adb_dnsuser:-"root"}"
  152. adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
  153. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  154. adb_dnsdeny="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  155. if [ ${adb_jail} -eq 1 ]
  156. then
  157. adb_dnsallow="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  158. adb_dnshalt="* CNAME ."
  159. fi
  160. ;;
  161. dnscrypt-proxy)
  162. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  163. adb_dnsuser="${adb_dnsuser:-"nobody"}"
  164. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  165. adb_dnsheader=""
  166. adb_dnsdeny="awk '{print \$0}'"
  167. ;;
  168. esac
  169. # check adblock status
  170. #
  171. if [ ${adb_enabled} -eq 0 ]
  172. then
  173. f_extconf
  174. f_temp
  175. f_rmdns
  176. f_jsnup
  177. f_log "info" "adblock is currently disabled, please set adb_enabled to '1' to use this service"
  178. exit 0
  179. fi
  180. if [ -d "${adb_dnsdir}" ] && [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
  181. then
  182. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  183. fi
  184. if [ "${adb_action}" = "start" ] && [ "${adb_trigger}" = "timed" ]
  185. then
  186. sleep ${adb_triggerdelay}
  187. fi
  188. while [ ${cnt} -le 30 ]
  189. do
  190. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
  191. if [ "${dns_up}" = "true" ]
  192. then
  193. break
  194. fi
  195. sleep 1
  196. cnt=$((cnt+1))
  197. done
  198. if [ -z "${adb_dns}" ] || [ -z "${adb_dnsdeny}" ] || [ ! -x "$(command -v ${adb_dns})" ] || [ ! -d "${adb_dnsdir}" ]
  199. then
  200. f_log "err" "'${adb_dns}' not running, DNS backend not found"
  201. fi
  202. }
  203. # check environment
  204. #
  205. f_envcheck()
  206. {
  207. local ssl_lib
  208. # check external uci config files
  209. #
  210. f_extconf
  211. # check fetch utility
  212. #
  213. case "${adb_fetchutil}" in
  214. uclient-fetch)
  215. if [ -f "/lib/libustream-ssl.so" ]
  216. then
  217. adb_fetchparm="${adb_fetchparm:-"--timeout=10 --no-check-certificate -O"}"
  218. ssl_lib="libustream-ssl"
  219. else
  220. adb_fetchparm="${adb_fetchparm:-"--timeout=10 -O"}"
  221. fi
  222. ;;
  223. wget)
  224. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"}"
  225. ssl_lib="built-in"
  226. ;;
  227. wget-nossl)
  228. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=10 -O"}"
  229. ;;
  230. busybox)
  231. adb_fetchparm="${adb_fetchparm:-"-O"}"
  232. ;;
  233. curl)
  234. adb_fetchparm="${adb_fetchparm:-"--connect-timeout 10 --insecure -o"}"
  235. ssl_lib="built-in"
  236. ;;
  237. aria2c)
  238. adb_fetchparm="${adb_fetchparm:-"--timeout=10 --allow-overwrite=true --auto-file-renaming=false --check-certificate=false -o"}"
  239. ssl_lib="built-in"
  240. ;;
  241. esac
  242. adb_fetchutil="$(command -v "${adb_fetchutil}")"
  243. if [ ! -x "${adb_fetchutil}" ] || [ -z "${adb_fetchutil}" ] || [ -z "${adb_fetchparm}" ]
  244. then
  245. f_log "err" "download utility not found, please install 'uclient-fetch' with 'libustream-mbedtls' or the full 'wget' package"
  246. fi
  247. adb_fetchinfo="${adb_fetchutil} (${ssl_lib:-"-"})"
  248. f_temp
  249. f_jsnup "running"
  250. f_log "info" "start adblock processing (${adb_action})"
  251. }
  252. # create temporay files and directories
  253. #
  254. f_temp()
  255. {
  256. if [ -z "${adb_tmpdir}" ]
  257. then
  258. adb_tmpdir="$(mktemp -p /tmp -d)"
  259. adb_tmpload="$(mktemp -p ${adb_tmpdir} -tu)"
  260. adb_tmpfile="$(mktemp -p ${adb_tmpdir} -tu)"
  261. fi
  262. if [ ! -s "${adb_pidfile}" ]
  263. then
  264. printf '%s' "${$}" > "${adb_pidfile}"
  265. fi
  266. }
  267. # remove temporay files and directories
  268. #
  269. f_rmtemp()
  270. {
  271. if [ -d "${adb_tmpdir}" ]
  272. then
  273. rm -rf "${adb_tmpdir}"
  274. fi
  275. > "${adb_pidfile}"
  276. }
  277. # remove dns related files and directories
  278. #
  279. f_rmdns()
  280. {
  281. if [ -n "${adb_dns}" ]
  282. then
  283. f_hash
  284. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  285. > "${adb_dnsdir}/.${adb_dnsfile}"
  286. > "${adb_rtfile}"
  287. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  288. f_hash
  289. if [ ${?} -eq 1 ]
  290. then
  291. f_dnsup
  292. fi
  293. f_rmtemp
  294. fi
  295. 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}"
  296. }
  297. # commit uci changes
  298. #
  299. f_uci()
  300. {
  301. local change config="${1}"
  302. if [ -n "${config}" ]
  303. then
  304. change="$(uci -q changes "${config}" | awk '{ORS=" "; print $0}')"
  305. if [ -n "${change}" ]
  306. then
  307. uci -q commit "${config}"
  308. case "${config}" in
  309. firewall)
  310. /etc/init.d/firewall reload >/dev/null 2>&1
  311. ;;
  312. *)
  313. /etc/init.d/"${adb_dns}" reload >/dev/null 2>&1
  314. ;;
  315. esac
  316. fi
  317. fi
  318. f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
  319. }
  320. # list/overall count
  321. #
  322. f_count()
  323. {
  324. local mode="${1}"
  325. adb_cnt=0
  326. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ] && ([ -z "${mode}" ] || [ "${mode}" = "final" ])
  327. then
  328. if [ "${adb_dns}" = "named" ] || [ "${adb_dns}" = "kresd" ]
  329. then
  330. adb_cnt="$(( ($(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}") - $(printf "%s" "${adb_dnsheader}" | grep -c "^")) / 2 ))"
  331. else
  332. adb_cnt="$(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}")"
  333. fi
  334. elif [ "${mode}" = "whitelist" ] && [ -s "${adb_tmpdir}/tmp.whitelist" ]
  335. then
  336. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.whitelist")"
  337. elif [ -s "${adb_tmpfile}" ]
  338. then
  339. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpfile}")"
  340. fi
  341. }
  342. # set external config options
  343. #
  344. f_extconf()
  345. {
  346. local uci_config
  347. case "${adb_dns}" in
  348. dnsmasq)
  349. uci_config="dhcp"
  350. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci -q get dhcp.@dnsmasq[${adb_dnsinstance}].serversfile | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  351. then
  352. uci -q set dhcp.@dnsmasq[${adb_dnsinstance}].serversfile="${adb_dnsdir}/${adb_dnsfile}"
  353. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci -q get dhcp.@dnsmasq[${adb_dnsinstance}].serversfile | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  354. then
  355. uci -q delete dhcp.@dnsmasq[${adb_dnsinstance}].serversfile
  356. fi
  357. ;;
  358. kresd)
  359. uci_config="resolver"
  360. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci -q get resolver.kresd.rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  361. then
  362. uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  363. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci -q get resolver.kresd.rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  364. then
  365. uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  366. fi
  367. if [ ${adb_enabled} -eq 1 ] && [ ${adb_dnsflush} -eq 0 ] && [ "$(uci -q get resolver.kresd.keep_cache)" != "1" ]
  368. then
  369. uci -q set resolver.kresd.keep_cache="1"
  370. elif [ ${adb_enabled} -eq 0 ] || ([ ${adb_dnsflush} -eq 1 ] && [ "$(uci -q get resolver.kresd.keep_cache)" = "1" ])
  371. then
  372. uci -q set resolver.kresd.keep_cache="0"
  373. fi
  374. ;;
  375. esac
  376. f_uci "${uci_config}"
  377. uci_config="firewall"
  378. if [ ${adb_enabled} -eq 1 ] && [ ${adb_forcedns} -eq 1 ] && \
  379. [ -z "$(uci -q get firewall.adblock_dns)" ] && [ $(/etc/init.d/firewall enabled; printf "%u" ${?}) -eq 0 ]
  380. then
  381. uci -q set firewall.adblock_dns="redirect"
  382. uci -q set firewall.adblock_dns.name="Adblock DNS"
  383. uci -q set firewall.adblock_dns.src="lan"
  384. uci -q set firewall.adblock_dns.proto="tcp udp"
  385. uci -q set firewall.adblock_dns.src_dport="53"
  386. uci -q set firewall.adblock_dns.dest_port="53"
  387. uci -q set firewall.adblock_dns.target="DNAT"
  388. elif [ -n "$(uci -q get firewall.adblock_dns)" ] && ([ ${adb_enabled} -eq 0 ] || [ ${adb_forcedns} -eq 0 ])
  389. then
  390. uci -q delete firewall.adblock_dns
  391. fi
  392. f_uci "${uci_config}"
  393. }
  394. # restart of the dns backend
  395. #
  396. f_dnsup()
  397. {
  398. local dns_up cache_util cache_rc cnt=0
  399. if [ ${adb_dnsflush} -eq 0 ] && [ ${adb_enabled} -eq 1 ] && [ "${adb_rc}" -eq 0 ]
  400. then
  401. case "${adb_dns}" in
  402. dnsmasq)
  403. killall -q -HUP "${adb_dns}"
  404. cache_rc=${?}
  405. ;;
  406. unbound)
  407. cache_util="$(command -v unbound-control)"
  408. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}"/unbound.conf ]
  409. then
  410. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf dump_cache > "${adb_tmpdir}"/adb_cache.dump 2>/dev/null
  411. fi
  412. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  413. ;;
  414. kresd)
  415. cache_util="keep_cache"
  416. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  417. cache_rc=${?}
  418. ;;
  419. named)
  420. cache_util="$(command -v rndc)"
  421. if [ -x "${cache_util}" ] && [ -f /etc/bind/rndc.conf ]
  422. then
  423. "${cache_util}" -c /etc/bind/rndc.conf reload >/dev/null 2>&1
  424. cache_rc=${?}
  425. else
  426. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  427. fi
  428. ;;
  429. *)
  430. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  431. ;;
  432. esac
  433. else
  434. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  435. fi
  436. adb_rc=1
  437. while [ ${cnt} -le 10 ]
  438. do
  439. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
  440. if [ "${dns_up}" = "true" ]
  441. then
  442. case "${adb_dns}" in
  443. unbound)
  444. cache_util="$(command -v unbound-control)"
  445. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}"/adb_cache.dump ]
  446. then
  447. while [ ${cnt} -le 10 ]
  448. do
  449. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf load_cache < "${adb_tmpdir}"/adb_cache.dump >/dev/null 2>&1
  450. cache_rc=${?}
  451. if [ ${cache_rc} -eq 0 ]
  452. then
  453. break
  454. fi
  455. cnt=$((cnt+1))
  456. sleep 1
  457. done
  458. fi
  459. ;;
  460. esac
  461. adb_rc=0
  462. break
  463. fi
  464. cnt=$((cnt+1))
  465. sleep 1
  466. done
  467. f_log "debug" "f_dnsup::: cache_util: ${cache_util:-"-"}, cache_rc: ${cache_rc:-"-"}, cache_flush: ${adb_dnsflush}, cache_cnt: ${cnt}, rc: ${adb_rc}"
  468. return ${adb_rc}
  469. }
  470. # backup/restore/remove blocklists
  471. #
  472. f_list()
  473. {
  474. local file mode="${1}" in_rc="${adb_rc}"
  475. case "${mode}" in
  476. backup)
  477. if [ -d "${adb_backupdir}" ]
  478. then
  479. gzip -cf "${adb_tmpfile}" 2>/dev/null > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  480. adb_rc=${?}
  481. fi
  482. ;;
  483. restore)
  484. if [ -d "${adb_backupdir}" ] && [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  485. then
  486. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null > "${adb_tmpfile}"
  487. adb_rc=${?}
  488. fi
  489. ;;
  490. remove)
  491. if [ -d "${adb_backupdir}" ]
  492. then
  493. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  494. fi
  495. adb_rc=${?}
  496. ;;
  497. merge)
  498. for file in "${adb_tmpfile}".*
  499. do
  500. cat "${file}" 2>/dev/null >> "${adb_tmpdir}/${adb_dnsfile}"
  501. if [ ${?} -ne 0 ]
  502. then
  503. adb_rc=${?}
  504. break
  505. fi
  506. rm -f "${file}"
  507. done
  508. adb_tmpfile="${adb_tmpdir}/${adb_dnsfile}"
  509. ;;
  510. final)
  511. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  512. then
  513. grep -vf "${adb_tmpdir}/tmp.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 field=1 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. field=2
  637. ;;
  638. unbound)
  639. field=3
  640. ;;
  641. esac
  642. while [ "${domain}" != "${tld}" ]
  643. do
  644. search="${domain//./\.}"
  645. result="$(awk -F '/|\"| ' "/^($search|[^\*].*[\/\"\. ]+${search})/{i++;{printf(\" + %s\n\",\$${field})};if(i>9){printf(\" + %s\n\",\"[...]\");exit}}" "${adb_dnsdir}/${adb_dnsfile}")"
  646. printf "%s\n" "::: results for domain '${domain}'"
  647. printf "%s\n" "${result:-" - no match"}"
  648. domain="${tld}"
  649. tld="${domain#*.}"
  650. done
  651. fi
  652. }
  653. # update runtime information
  654. #
  655. f_jsnup()
  656. {
  657. local bg_pid rundate="$(/bin/date "+%d.%m.%Y %H:%M:%S")" status="${1:-"enabled"}" mode="normal mode" no_mail=0
  658. if [ ${adb_rc} -gt 0 ]
  659. then
  660. status="error"
  661. fi
  662. if [ ${adb_enabled} -eq 0 ]
  663. then
  664. status="disabled"
  665. fi
  666. if [ "${status}" = "suspend" ]
  667. then
  668. status="paused"
  669. fi
  670. if [ "${status}" = "resume" ]
  671. then
  672. no_mail=1
  673. status="enabled"
  674. fi
  675. if [ "${status}" = "enabled" ]
  676. then
  677. f_count
  678. fi
  679. if [ ${adb_backup_mode} -eq 1 ]
  680. then
  681. mode="backup mode"
  682. fi
  683. if [ -z "${adb_fetchinfo}" ] && [ -s "${adb_rtfile}" ]
  684. then
  685. json_load "$(cat "${adb_rtfile}" 2>/dev/null)"
  686. json_select data
  687. json_get_var adb_fetchinfo "fetch_utility"
  688. fi
  689. json_init
  690. json_add_object "data"
  691. json_add_string "adblock_status" "${status}"
  692. json_add_string "adblock_version" "${adb_ver}"
  693. json_add_string "overall_domains" "${adb_cnt} (${mode})"
  694. json_add_string "fetch_utility" "${adb_fetchinfo:-"-"}"
  695. json_add_string "dns_backend" "${adb_dns} (${adb_dnsdir})"
  696. json_add_string "last_rundate" "${rundate:-"-"}"
  697. json_add_string "system_release" "${adb_sysver}"
  698. json_close_object
  699. json_dump > "${adb_rtfile}"
  700. if [ ${adb_notify} -eq 1 ] && [ ${no_mail} -eq 0 ] && [ -x /etc/adblock/adblock.notify ] && \
  701. ([ "${status}" = "error" ] || ([ "${status}" = "enabled" ] && [ ${adb_cnt} -le ${adb_notifycnt} ]))
  702. then
  703. (/etc/adblock/adblock.notify >/dev/null 2>&1) &
  704. bg_pid=${!}
  705. fi
  706. f_log "debug" "f_jsnup::: status: ${status}, mode: ${mode}, cnt: ${adb_cnt}, notify: ${adb_notify}, notify_cnt: ${adb_notifycnt}, notify_pid: ${bg_pid:-"-"}"
  707. }
  708. # write to syslog
  709. #
  710. f_log()
  711. {
  712. local class="${1}" log_msg="${2}"
  713. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  714. then
  715. logger -p "${class}" -t "adblock-[${adb_ver}]" "${log_msg}"
  716. if [ "${class}" = "err" ]
  717. then
  718. f_rmdns
  719. f_jsnup
  720. logger -p "${class}" -t "adblock-[${adb_ver}]" "Please also check 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md' (${adb_sysver})"
  721. exit 1
  722. fi
  723. fi
  724. }
  725. # main function for blocklist processing
  726. #
  727. f_main()
  728. {
  729. local tmp_load tmp_file src_name src_rset src_arc src_log mem_total mem_free enabled url cnt=1
  730. mem_total="$(awk '/^MemTotal/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  731. mem_free="$(awk '/^MemFree/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  732. tmp_load="${adb_tmpload}"
  733. tmp_file="${adb_tmpfile}"
  734. > "${adb_dnsdir}/.${adb_dnsfile}"
  735. > "${adb_tmpdir}/tmp.whitelist"
  736. 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}"
  737. # prepare whitelist entries
  738. #
  739. if [ -s "${adb_whitelist}" ]
  740. then
  741. adb_whitelist_rset="/^([^([:space:]|\#|\*|\/).]+\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\.\",\"\\\.\",\$1);print tolower(\"^\"\$1\"\\\|\\\.\"\$1)}"
  742. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
  743. f_list whitelist
  744. if [ ${adb_jail} -eq 1 ] && [ "${adb_dns}" != "dnscrypt-proxy" ]
  745. then
  746. adb_whitelist_rset="/^([^([:space:]|\#|\*|\/).]+\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  747. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.dnsjail"
  748. fi
  749. fi
  750. # build 'dnsjail' list
  751. #
  752. if [ ${adb_jail} -eq 1 ] && [ "${adb_dns}" != "dnscrypt-proxy" ]
  753. then
  754. f_tld "${adb_tmpdir}/tmp.dnsjail"
  755. eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.dnsjail" > "/tmp/${adb_dnsjail}"
  756. printf '%s\n' "${adb_dnshalt}" >> "/tmp/${adb_dnsjail}"
  757. if [ -n "${adb_dnsheader}" ]
  758. then
  759. printf '%s\n' "${adb_dnsheader}" | cat - "/tmp/${adb_dnsjail}" > "${adb_tmpdir}/tmp.dnsjail"
  760. cat "${adb_tmpdir}/tmp.dnsjail" > "/tmp/${adb_dnsjail}"
  761. fi
  762. fi
  763. # main loop
  764. #
  765. for src_name in ${adb_sources}
  766. do
  767. eval "enabled=\"\${enabled_${src_name}}\""
  768. eval "url=\"\${adb_src_${src_name}}\""
  769. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  770. adb_tmpload="${tmp_load}.${src_name}"
  771. adb_tmpfile="${tmp_file}.${src_name}"
  772. # basic pre-checks
  773. #
  774. f_log "debug" "f_main ::: name: ${src_name}, enabled: ${enabled}"
  775. if [ "${enabled}" != "1" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  776. then
  777. f_list remove
  778. continue
  779. fi
  780. # backup mode
  781. #
  782. if [ ${adb_backup_mode} -eq 1 ] && [ "${adb_action}" = "start" ] && [ "${src_name}" != "blacklist" ]
  783. then
  784. f_list restore
  785. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  786. then
  787. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  788. then
  789. f_tld "${adb_tmpfile}"
  790. fi
  791. continue
  792. fi
  793. fi
  794. # download queue processing
  795. #
  796. if [ "${src_name}" = "blacklist" ]
  797. then
  798. if [ -s "${url}" ]
  799. then
  800. (
  801. src_log="$(cat "${url}" > "${adb_tmpload}" 2>&1)"
  802. adb_rc=${?}
  803. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  804. then
  805. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  806. adb_rc=${?}
  807. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  808. then
  809. rm -f "${adb_tmpload}"
  810. f_list download
  811. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  812. then
  813. f_tld "${adb_tmpfile}"
  814. fi
  815. fi
  816. else
  817. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  818. f_log "debug" "f_main ::: name: ${src_name}, url: ${url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  819. fi
  820. ) &
  821. else
  822. continue
  823. fi
  824. elif [ "${src_name}" = "shalla" ]
  825. then
  826. (
  827. src_arc="${adb_tmpdir}"/shallalist.tar.gz
  828. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${url}" 2>&1)"
  829. adb_rc=${?}
  830. if [ ${adb_rc} -eq 0 ] && [ -s "${src_arc}" ]
  831. then
  832. for category in ${adb_src_cat_shalla}
  833. do
  834. tar -xOzf "${src_arc}" "BL/${category}/domains" >> "${adb_tmpload}"
  835. adb_rc=${?}
  836. if [ ${adb_rc} -ne 0 ]
  837. then
  838. break
  839. fi
  840. done
  841. else
  842. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  843. f_log "debug" "f_main ::: name: ${src_name}, url: ${url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  844. fi
  845. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  846. then
  847. rm -f "${src_arc}"
  848. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  849. adb_rc=${?}
  850. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  851. then
  852. rm -f "${adb_tmpload}"
  853. f_list download
  854. if [ ${adb_backup} -eq 1 ]
  855. then
  856. f_list backup
  857. fi
  858. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  859. then
  860. f_tld "${adb_tmpfile}"
  861. fi
  862. elif [ ${adb_backup} -eq 1 ]
  863. then
  864. f_list restore
  865. fi
  866. elif [ ${adb_backup} -eq 1 ]
  867. then
  868. f_list restore
  869. fi
  870. ) &
  871. else
  872. (
  873. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${adb_tmpload}" "${url}" 2>&1)"
  874. adb_rc=${?}
  875. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  876. then
  877. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  878. adb_rc=${?}
  879. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  880. then
  881. rm -f "${adb_tmpload}"
  882. f_list download
  883. if [ ${adb_backup} -eq 1 ]
  884. then
  885. f_list backup
  886. fi
  887. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  888. then
  889. f_tld "${adb_tmpfile}"
  890. fi
  891. elif [ ${adb_backup} -eq 1 ]
  892. then
  893. f_list restore
  894. fi
  895. else
  896. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  897. f_log "debug" "f_main ::: name: ${src_name}, url: ${url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  898. if [ ${adb_backup} -eq 1 ]
  899. then
  900. f_list restore
  901. fi
  902. fi
  903. ) &
  904. fi
  905. hold=$(( cnt % adb_maxqueue ))
  906. if [ ${hold} -eq 0 ]
  907. then
  908. wait
  909. fi
  910. cnt=$(( cnt + 1 ))
  911. done
  912. # list merge
  913. #
  914. wait
  915. src_name="overall"
  916. adb_tmpfile="${tmp_file}"
  917. f_list merge
  918. # overall sort and conditional dns restart
  919. #
  920. f_hash
  921. if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  922. then
  923. if ([ ${mem_total} -ge 64 ] && [ ${mem_free} -ge 40 ]) || [ ${adb_forcesrt} -eq 1 ]
  924. then
  925. f_tld "${adb_tmpdir}/${adb_dnsfile}"
  926. fi
  927. f_list final
  928. else
  929. > "${adb_dnsdir}/${adb_dnsfile}"
  930. fi
  931. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  932. f_hash
  933. if [ ${?} -eq 1 ]
  934. then
  935. f_dnsup
  936. fi
  937. f_jsnup
  938. if [ ${?} -eq 0 ]
  939. then
  940. f_log "info" "blocklist with overall ${adb_cnt} domains loaded successfully (${adb_sysver})"
  941. else
  942. f_log "err" "dns backend restart with active blocklist failed"
  943. fi
  944. f_rmtemp
  945. exit ${adb_rc}
  946. }
  947. # handle different adblock actions
  948. #
  949. f_envload
  950. case "${adb_action}" in
  951. stop)
  952. f_rmdns
  953. ;;
  954. restart)
  955. f_rmdns
  956. f_envcheck
  957. f_main
  958. ;;
  959. suspend)
  960. f_switch suspend
  961. ;;
  962. resume)
  963. f_switch resume
  964. ;;
  965. query)
  966. f_query "${2}"
  967. ;;
  968. start|reload)
  969. f_envcheck
  970. f_main
  971. ;;
  972. esac