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.

1076 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.3"
  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 temporay 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 temporay 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
  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)" ] && [ $(/etc/init.d/firewall enabled; printf '%u' ${?}) -eq 0 ]
  369. then
  370. uci -q batch <<-EOF
  371. set firewall.adblock_dns="redirect"
  372. set firewall.adblock_dns.name="Adblock DNS"
  373. set firewall.adblock_dns.src="lan"
  374. set firewall.adblock_dns.proto="tcp udp"
  375. set firewall.adblock_dns.src_dport="53"
  376. set firewall.adblock_dns.dest_port="53"
  377. set firewall.adblock_dns.target="DNAT"
  378. EOF
  379. elif [ -n "$(uci -q get firewall.adblock_dns)" ] && ([ ${adb_enabled} -eq 0 ] || [ ${adb_forcedns} -eq 0 ])
  380. then
  381. uci -q delete firewall.adblock_dns
  382. fi
  383. f_uci "${uci_config}"
  384. }
  385. # restart of the dns backend
  386. #
  387. f_dnsup()
  388. {
  389. local dns_up cache_util cache_rc cnt=0
  390. if [ ${adb_dnsflush} -eq 0 ] && [ ${adb_enabled} -eq 1 ] && [ "${adb_rc}" -eq 0 ]
  391. then
  392. case "${adb_dns}" in
  393. dnsmasq)
  394. killall -q -HUP "${adb_dns}"
  395. cache_rc=${?}
  396. ;;
  397. unbound)
  398. cache_util="$(command -v unbound-control)"
  399. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}"/unbound.conf ]
  400. then
  401. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf dump_cache > "${adb_tmpdir}"/adb_cache.dump 2>/dev/null
  402. fi
  403. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  404. ;;
  405. kresd)
  406. cache_util="keep_cache"
  407. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  408. cache_rc=${?}
  409. ;;
  410. named)
  411. cache_util="$(command -v rndc)"
  412. if [ -x "${cache_util}" ] && [ -f /etc/bind/rndc.conf ]
  413. then
  414. "${cache_util}" -c /etc/bind/rndc.conf reload >/dev/null 2>&1
  415. cache_rc=${?}
  416. else
  417. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  418. fi
  419. ;;
  420. *)
  421. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  422. ;;
  423. esac
  424. else
  425. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  426. fi
  427. adb_rc=1
  428. while [ ${cnt} -le 10 ]
  429. do
  430. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
  431. if [ "${dns_up}" = "true" ]
  432. then
  433. case "${adb_dns}" in
  434. unbound)
  435. cache_util="$(command -v unbound-control)"
  436. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}"/adb_cache.dump ]
  437. then
  438. while [ ${cnt} -le 10 ]
  439. do
  440. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf load_cache < "${adb_tmpdir}"/adb_cache.dump >/dev/null 2>&1
  441. cache_rc=${?}
  442. if [ ${cache_rc} -eq 0 ]
  443. then
  444. break
  445. fi
  446. cnt=$((cnt+1))
  447. sleep 1
  448. done
  449. fi
  450. ;;
  451. esac
  452. adb_rc=0
  453. break
  454. fi
  455. cnt=$((cnt+1))
  456. sleep 1
  457. done
  458. f_log "debug" "f_dnsup::: cache_util: ${cache_util:-"-"}, cache_rc: ${cache_rc:-"-"}, cache_flush: ${adb_dnsflush}, cache_cnt: ${cnt}, rc: ${adb_rc}"
  459. return ${adb_rc}
  460. }
  461. # backup/restore/remove blocklists
  462. #
  463. f_list()
  464. {
  465. local file mode="${1}" in_rc="${adb_rc}"
  466. case "${mode}" in
  467. backup)
  468. if [ -d "${adb_backupdir}" ]
  469. then
  470. gzip -cf "${adb_tmpfile}" 2>/dev/null > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  471. adb_rc=${?}
  472. fi
  473. ;;
  474. restore)
  475. if [ -d "${adb_backupdir}" ] && [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  476. then
  477. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null > "${adb_tmpfile}"
  478. adb_rc=${?}
  479. fi
  480. ;;
  481. remove)
  482. if [ -d "${adb_backupdir}" ]
  483. then
  484. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  485. fi
  486. adb_rc=${?}
  487. ;;
  488. merge)
  489. for file in "${adb_tmpfile}".*
  490. do
  491. cat "${file}" 2>/dev/null >> "${adb_tmpdir}/${adb_dnsfile}"
  492. if [ ${?} -ne 0 ]
  493. then
  494. adb_rc=${?}
  495. break
  496. fi
  497. rm -f "${file}"
  498. done
  499. adb_tmpfile="${adb_tmpdir}/${adb_dnsfile}"
  500. ;;
  501. final)
  502. > "${adb_dnsdir}/${adb_dnsfile}"
  503. if [ -s "${adb_tmpdir}/tmp.add_whitelist" ]
  504. then
  505. cat "${adb_tmpdir}/tmp.add_whitelist" >> "${adb_dnsdir}/${adb_dnsfile}"
  506. fi
  507. if [ -s "${adb_tmpdir}/tmp.rem_whitelist" ]
  508. then
  509. grep -vf "${adb_tmpdir}/tmp.rem_whitelist" "${adb_tmpdir}/${adb_dnsfile}" | eval "${adb_dnsdeny}" >> "${adb_dnsdir}/${adb_dnsfile}"
  510. else
  511. eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >> "${adb_dnsdir}/${adb_dnsfile}"
  512. fi
  513. if [ ${?} -eq 0 ] && [ -n "${adb_dnsheader}" ]
  514. then
  515. printf '%s\n' "${adb_dnsheader}" | cat - "${adb_dnsdir}/${adb_dnsfile}" > "${adb_tmpdir}/${adb_dnsfile}"
  516. cat "${adb_tmpdir}/${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  517. fi
  518. adb_rc=${?}
  519. ;;
  520. esac
  521. f_count "${mode}"
  522. f_log "debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${adb_rc}"
  523. }
  524. # top level domain compression
  525. #
  526. f_tld()
  527. {
  528. local cnt cnt_srt cnt_tld source="${1}" temp="${1}.tld"
  529. cnt="$(wc -l 2>/dev/null < "${source}")"
  530. sort -u "${source}" > "${temp}"
  531. if [ ${?} -eq 0 ]
  532. then
  533. cnt_srt="$(wc -l 2>/dev/null < "${temp}")"
  534. awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${temp}" > "${source}"
  535. if [ ${?} -eq 0 ]
  536. then
  537. sort "${source}" > "${temp}"
  538. if [ ${?} -eq 0 ]
  539. then
  540. awk '{if(NR==1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "${temp}" > "${source}"
  541. if [ ${?} -eq 0 ]
  542. then
  543. awk -F "." '{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${source}" > "${temp}"
  544. if [ ${?} -eq 0 ]
  545. then
  546. sort "${temp}" > "${source}"
  547. if [ ${?} -eq 0 ]
  548. then
  549. cnt_tld="$(wc -l 2>/dev/null < "${source}")"
  550. else
  551. cat "${temp}" > "${source}"
  552. fi
  553. fi
  554. else
  555. cat "${temp}" > "${source}"
  556. fi
  557. fi
  558. else
  559. cat "${temp}" > "${source}"
  560. fi
  561. fi
  562. rm -f "${temp}"
  563. f_log "debug" "f_tld ::: source: ${source}, cnt: ${cnt:-"-"}, cnt_srt: ${cnt_srt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
  564. }
  565. # blocklist hash compare
  566. #
  567. f_hash()
  568. {
  569. local hash hash_rc=1
  570. if [ -x "${adb_hashutil}" ] && [ -f "${adb_dnsdir}/${adb_dnsfile}" ]
  571. then
  572. hash="$(${adb_hashutil} "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null | awk '{print $1}')"
  573. if [ -z "${adb_hashold}" ] && [ -n "${hash}" ]
  574. then
  575. adb_hashold="${hash}"
  576. elif [ -z "${adb_hashnew}" ] && [ -n "${hash}" ]
  577. then
  578. adb_hashnew="${hash}"
  579. fi
  580. if [ -n "${adb_hashold}" ] && [ -n "${adb_hashnew}" ]
  581. then
  582. if [ "${adb_hashold}" = "${adb_hashnew}" ]
  583. then
  584. hash_rc=0
  585. fi
  586. adb_hashold=""
  587. adb_hashnew=""
  588. fi
  589. fi
  590. f_log "debug" "f_hash ::: hash_util: ${adb_hashutil}, hash: ${hash}, out_rc: ${hash_rc}"
  591. return ${hash_rc}
  592. }
  593. # suspend/resume adblock processing
  594. #
  595. f_switch()
  596. {
  597. local mode="${1}"
  598. if [ ! -s "${adb_dnsdir}/.${adb_dnsfile}" ] && [ "${mode}" = "suspend" ]
  599. then
  600. f_hash
  601. cat "${adb_dnsdir}/${adb_dnsfile}" > "${adb_dnsdir}/.${adb_dnsfile}"
  602. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  603. f_hash
  604. elif [ -s "${adb_dnsdir}/.${adb_dnsfile}" ] && [ "${mode}" = "resume" ]
  605. then
  606. f_hash
  607. cat "${adb_dnsdir}/.${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  608. > "${adb_dnsdir}/.${adb_dnsfile}"
  609. f_hash
  610. fi
  611. if [ ${?} -eq 1 ]
  612. then
  613. f_temp
  614. f_dnsup
  615. f_jsnup "${mode}"
  616. f_log "info" "${mode} adblock processing"
  617. f_rmtemp
  618. exit 0
  619. fi
  620. }
  621. # query blocklist for certain (sub-)domains
  622. #
  623. f_query()
  624. {
  625. local search result prefix suffix field domain="${1}" tld="${1#*.}"
  626. if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  627. then
  628. printf '%s\n' "::: invalid domain input, please submit a single domain, e.g. 'doubleclick.net'"
  629. else
  630. case "${adb_dns}" in
  631. dnsmasq)
  632. prefix=".*[\/\.]"
  633. suffix="(\/)"
  634. field=2
  635. ;;
  636. unbound)
  637. prefix=".*[\"\.]"
  638. suffix="(static)"
  639. field=3
  640. ;;
  641. named)
  642. prefix="[^\*].*[\.]"
  643. suffix="( \.)"
  644. field=1
  645. ;;
  646. kresd)
  647. prefix="[^\*].*[\.]"
  648. suffix="( \.)"
  649. field=1
  650. ;;
  651. dnscrypt-proxy)
  652. prefix=".*[\.]"
  653. suffix=""
  654. field=1
  655. ;;
  656. esac
  657. while [ "${domain}" != "${tld}" ]
  658. do
  659. search="${domain//./\.}"
  660. result="$(awk -F '/|\"| ' "/^($search|${prefix}+${search}.*${suffix}$)/{i++;{printf(\" + %s\n\",\$${field})};if(i>9){printf(\" + %s\n\",\"[...]\");exit}}" "${adb_dnsdir}/${adb_dnsfile}")"
  661. printf '%s\n' "::: results for domain '${domain}'"
  662. printf '%s\n' "${result:-" - no match"}"
  663. domain="${tld}"
  664. tld="${domain#*.}"
  665. done
  666. fi
  667. }
  668. # update runtime information
  669. #
  670. f_jsnup()
  671. {
  672. local bg_pid rundate status="${1:-"enabled"}" mode="normal mode" no_mail=0
  673. if [ ${adb_rc} -gt 0 ]
  674. then
  675. status="error"
  676. rundate="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  677. fi
  678. if [ ${adb_enabled} -eq 0 ]
  679. then
  680. status="disabled"
  681. fi
  682. if [ "${status}" = "enabled" ]
  683. then
  684. rundate="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  685. fi
  686. if [ "${status}" = "suspend" ]
  687. then
  688. status="paused"
  689. fi
  690. if [ "${status}" = "resume" ]
  691. then
  692. no_mail=1
  693. status="enabled"
  694. fi
  695. if [ ${adb_backup_mode} -eq 1 ]
  696. then
  697. mode="backup mode"
  698. fi
  699. if [ -s "${adb_rtfile}" ]
  700. then
  701. json_load "$(cat "${adb_rtfile}" 2>/dev/null)"
  702. json_select data
  703. if [ -z "${adb_fetchinfo}" ] && [ -s "${adb_rtfile}" ]
  704. then
  705. json_get_var adb_fetchinfo "fetch_utility"
  706. fi
  707. if [ -z "${rundate}" ]
  708. then
  709. json_get_var rundate "last_rundate"
  710. fi
  711. if [ -z "${adb_cnt}" ]
  712. then
  713. json_get_var adb_cnt "overall_domains"
  714. adb_cnt="${adb_cnt%% *}"
  715. fi
  716. fi
  717. json_init
  718. json_add_object "data"
  719. json_add_string "adblock_status" "${status}"
  720. json_add_string "adblock_version" "${adb_ver}"
  721. json_add_string "overall_domains" "${adb_cnt:-0} (${mode})"
  722. json_add_string "fetch_utility" "${adb_fetchinfo:-"-"}"
  723. json_add_string "dns_backend" "${adb_dns} (${adb_dnsdir})"
  724. json_add_string "last_rundate" "${rundate:-"-"}"
  725. json_add_string "system_release" "${adb_sysver}"
  726. json_close_object
  727. json_dump > "${adb_rtfile}"
  728. if [ ${adb_notify} -eq 1 ] && [ ${no_mail} -eq 0 ] && [ -x /etc/adblock/adblock.notify ] && \
  729. ([ "${status}" = "error" ] || ([ "${status}" = "enabled" ] && [ ${adb_cnt} -le ${adb_notifycnt} ]))
  730. then
  731. (/etc/adblock/adblock.notify >/dev/null 2>&1) &
  732. bg_pid=${!}
  733. fi
  734. f_log "debug" "f_jsnup::: status: ${status}, mode: ${mode}, cnt: ${adb_cnt}, notify: ${adb_notify}, notify_cnt: ${adb_notifycnt}, notify_pid: ${bg_pid:-"-"}"
  735. }
  736. # write to syslog
  737. #
  738. f_log()
  739. {
  740. local class="${1}" log_msg="${2}"
  741. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  742. then
  743. logger -p "${class}" -t "adblock-[${adb_ver}]" "${log_msg}"
  744. if [ "${class}" = "err" ]
  745. then
  746. f_rmdns
  747. f_jsnup
  748. logger -p "${class}" -t "adblock-[${adb_ver}]" "Please also check 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md'"
  749. exit 1
  750. fi
  751. fi
  752. }
  753. # main function for blocklist processing
  754. #
  755. f_main()
  756. {
  757. 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
  758. mem_total="$(awk '/^MemTotal/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  759. mem_free="$(awk '/^MemFree/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  760. tmp_load="${adb_tmpload}"
  761. tmp_file="${adb_tmpfile}"
  762. > "${adb_dnsdir}/.${adb_dnsfile}"
  763. > "${adb_tmpdir}/tmp.raw_whitelist"
  764. > "${adb_tmpdir}/tmp.add_whitelist"
  765. > "${adb_tmpdir}/tmp.rem_whitelist"
  766. 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}"
  767. # prepare whitelist entries
  768. #
  769. if [ -s "${adb_whitelist}" ]
  770. then
  771. adb_whitelist_rset="/^([^([:space:]|\#|\*|\/).]+\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  772. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.raw_whitelist"
  773. f_tld "${adb_tmpdir}/tmp.raw_whitelist"
  774. adb_whitelist_rset="/^([^([:space:]|\#|\*|\/).]+\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\.\",\"\\\.\",\$1);print tolower(\"^\"\$1\"\\\|\\\.\"\$1)}"
  775. awk "${adb_whitelist_rset}" "${adb_tmpdir}/tmp.raw_whitelist" > "${adb_tmpdir}/tmp.rem_whitelist"
  776. if [ -n "${adb_dnsallow}" ]
  777. then
  778. eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw_whitelist" > "${adb_tmpdir}/tmp.add_whitelist"
  779. fi
  780. fi
  781. # build 'dnsjail' list
  782. #
  783. if [ ${adb_jail} -eq 1 ]
  784. then
  785. cat "${adb_tmpdir}/tmp.add_whitelist" > "/tmp/${adb_dnsjail}"
  786. printf '%s\n' "${adb_dnshalt}" >> "/tmp/${adb_dnsjail}"
  787. if [ -n "${adb_dnsheader}" ]
  788. then
  789. printf '%s\n' "${adb_dnsheader}" | cat - "/tmp/${adb_dnsjail}" > "${adb_tmpdir}/tmp.dnsjail"
  790. cat "${adb_tmpdir}/tmp.dnsjail" > "/tmp/${adb_dnsjail}"
  791. fi
  792. fi
  793. # main loop
  794. #
  795. for src_name in ${adb_sources}
  796. do
  797. enabled="$(eval printf '%s' \"\${enabled_${src_name}\}\")"
  798. src_url="$(eval printf '%s' \"\${adb_src_${src_name}\}\")"
  799. src_rset="$(eval printf '%s' \"\${adb_src_rset_${src_name}\}\")"
  800. src_cat="$(eval printf '%s' \"\${adb_src_cat_${src_name}\}\")"
  801. adb_tmpload="${tmp_load}.${src_name}"
  802. adb_tmpfile="${tmp_file}.${src_name}"
  803. # basic pre-checks
  804. #
  805. f_log "debug" "f_main ::: name: ${src_name}, enabled: ${enabled}"
  806. if [ "${enabled}" != "1" ] || [ -z "${src_url}" ] || [ -z "${src_rset}" ]
  807. then
  808. f_list remove
  809. continue
  810. fi
  811. # backup mode
  812. #
  813. if [ ${adb_backup_mode} -eq 1 ] && [ "${adb_action}" = "start" ] && [ "${src_name}" != "blacklist" ]
  814. then
  815. f_list restore
  816. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  817. then
  818. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  819. then
  820. f_tld "${adb_tmpfile}"
  821. fi
  822. continue
  823. fi
  824. fi
  825. # download queue processing
  826. #
  827. if [ "${src_name}" = "blacklist" ]
  828. then
  829. if [ -s "${src_url}" ]
  830. then
  831. (
  832. src_log="$(cat "${src_url}" > "${adb_tmpload}" 2>&1)"
  833. adb_rc=${?}
  834. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  835. then
  836. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  837. adb_rc=${?}
  838. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  839. then
  840. rm -f "${adb_tmpload}"
  841. f_list download
  842. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  843. then
  844. f_tld "${adb_tmpfile}"
  845. fi
  846. fi
  847. else
  848. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  849. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  850. fi
  851. ) &
  852. else
  853. continue
  854. fi
  855. elif [ -n "${src_cat}" ]
  856. then
  857. (
  858. src_arc="${adb_tmpdir}/${src_url##*/}"
  859. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
  860. adb_rc=${?}
  861. if [ ${adb_rc} -eq 0 ] && [ -s "${src_arc}" ]
  862. then
  863. list="$(tar -tzf "${src_arc}")"
  864. suffix="$(eval printf '%s' \"\${adb_src_suffix_${src_name}:-\"domains\"\}\")"
  865. for cat in ${src_cat}
  866. do
  867. entry="$(printf '%s' "${list}" | grep -E "[\^/]+${cat}/${suffix}")"
  868. if [ -n "${entry}" ]
  869. then
  870. tar -xOzf "${src_arc}" "${entry}" >> "${adb_tmpload}"
  871. adb_rc=${?}
  872. if [ ${adb_rc} -ne 0 ]
  873. then
  874. break
  875. fi
  876. fi
  877. done
  878. else
  879. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  880. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  881. fi
  882. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  883. then
  884. rm -f "${src_arc}"
  885. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  886. adb_rc=${?}
  887. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  888. then
  889. rm -f "${adb_tmpload}"
  890. f_list download
  891. if [ ${adb_backup} -eq 1 ]
  892. then
  893. f_list backup
  894. fi
  895. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  896. then
  897. f_tld "${adb_tmpfile}"
  898. fi
  899. elif [ ${adb_backup} -eq 1 ]
  900. then
  901. f_list restore
  902. fi
  903. elif [ ${adb_backup} -eq 1 ]
  904. then
  905. f_list restore
  906. fi
  907. ) &
  908. else
  909. (
  910. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${adb_tmpload}" "${src_url}" 2>&1)"
  911. adb_rc=${?}
  912. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  913. then
  914. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  915. adb_rc=${?}
  916. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  917. then
  918. rm -f "${adb_tmpload}"
  919. f_list download
  920. if [ ${adb_backup} -eq 1 ]
  921. then
  922. f_list backup
  923. fi
  924. if ([ ${mem_total} -lt 64 ] || [ ${mem_free} -lt 40 ]) && [ ${adb_forcesrt} -eq 0 ]
  925. then
  926. f_tld "${adb_tmpfile}"
  927. fi
  928. elif [ ${adb_backup} -eq 1 ]
  929. then
  930. f_list restore
  931. fi
  932. else
  933. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  934. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  935. if [ ${adb_backup} -eq 1 ]
  936. then
  937. f_list restore
  938. fi
  939. fi
  940. ) &
  941. fi
  942. hold=$(( cnt % adb_maxqueue ))
  943. if [ ${hold} -eq 0 ]
  944. then
  945. wait
  946. fi
  947. cnt=$(( cnt + 1 ))
  948. done
  949. # list merge
  950. #
  951. wait
  952. src_name="overall"
  953. adb_tmpfile="${tmp_file}"
  954. f_list merge
  955. # overall sort and conditional dns restart
  956. #
  957. f_hash
  958. if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  959. then
  960. if ([ ${mem_total} -ge 64 ] && [ ${mem_free} -ge 40 ]) || [ ${adb_forcesrt} -eq 1 ]
  961. then
  962. f_tld "${adb_tmpdir}/${adb_dnsfile}"
  963. fi
  964. f_list final
  965. else
  966. > "${adb_dnsdir}/${adb_dnsfile}"
  967. fi
  968. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  969. f_hash
  970. if [ ${?} -eq 1 ]
  971. then
  972. f_dnsup
  973. fi
  974. f_jsnup
  975. if [ ${?} -eq 0 ]
  976. then
  977. f_log "info" "blocklist with overall ${adb_cnt} domains loaded successfully (${adb_sysver})"
  978. else
  979. f_log "err" "dns backend restart with active blocklist failed"
  980. fi
  981. f_rmtemp
  982. exit ${adb_rc}
  983. }
  984. # handle different adblock actions
  985. #
  986. f_envload
  987. case "${adb_action}" in
  988. stop)
  989. f_rmdns
  990. ;;
  991. restart)
  992. f_rmdns
  993. f_envcheck
  994. f_main
  995. ;;
  996. suspend)
  997. f_switch suspend
  998. ;;
  999. resume)
  1000. f_switch resume
  1001. ;;
  1002. query)
  1003. f_query "${2}"
  1004. ;;
  1005. start|reload)
  1006. f_envcheck
  1007. f_main
  1008. ;;
  1009. esac