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.

1294 lines
35 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.6.3"
  12. adb_sysver="unknown"
  13. adb_enabled=0
  14. adb_debug=0
  15. adb_forcedns=0
  16. adb_jail=0
  17. adb_maxqueue=8
  18. adb_notify=0
  19. adb_notifycnt=0
  20. adb_triggerdelay=0
  21. adb_backup=0
  22. adb_backup_mode=0
  23. adb_backupdir="/mnt"
  24. adb_fetchutil="uclient-fetch"
  25. adb_dns="dnsmasq"
  26. adb_dnsprefix="adb_list"
  27. adb_dnsfile="${adb_dnsprefix}.overall"
  28. adb_dnsjail="${adb_dnsprefix}.jail"
  29. adb_dnsflush=0
  30. adb_whitelist="/etc/adblock/adblock.whitelist"
  31. adb_rtfile="/tmp/adb_runtime.json"
  32. adb_hashutil="$(command -v sha256sum)"
  33. adb_hashold=""
  34. adb_hashnew=""
  35. adb_report=0
  36. adb_repiface="br-lan"
  37. adb_replisten="53"
  38. adb_repdir="/tmp"
  39. adb_reputil="$(command -v tcpdump)"
  40. adb_repchunkcnt="5"
  41. adb_repchunksize="1"
  42. adb_cnt=""
  43. adb_rc=0
  44. adb_action="${1:-"start"}"
  45. adb_pidfile="/var/run/adblock.pid"
  46. # load adblock environment
  47. #
  48. f_envload()
  49. {
  50. local dns_up sys_call sys_desc sys_model cnt=0
  51. # get system information
  52. #
  53. sys_call="$(ubus -S call system board 2>/dev/null)"
  54. if [ -n "${sys_call}" ]
  55. then
  56. sys_desc="$(printf '%s' "${sys_call}" | jsonfilter -e '@.release.description')"
  57. sys_model="$(printf '%s' "${sys_call}" | jsonfilter -e '@.model')"
  58. adb_sysver="${sys_model}, ${sys_desc}"
  59. fi
  60. # check hash utility
  61. #
  62. if [ ! -x "${adb_hashutil}" ]
  63. then
  64. adb_hashutil="$(command -v md5sum)"
  65. fi
  66. # parse 'global' and 'extra' section by callback
  67. #
  68. config_cb()
  69. {
  70. local type="${1}"
  71. if [ "${type}" = "adblock" ]
  72. then
  73. option_cb()
  74. {
  75. local option="${1}"
  76. local value="${2}"
  77. eval "${option}=\"${value}\""
  78. }
  79. else
  80. reset_cb
  81. fi
  82. }
  83. # parse 'source' typed sections
  84. #
  85. parse_config()
  86. {
  87. local value opt section="${1}" options="enabled adb_src adb_src_rset adb_src_cat"
  88. eval "adb_sources=\"${adb_sources} ${section}\""
  89. for opt in ${options}
  90. do
  91. config_get value "${section}" "${opt}"
  92. if [ -n "${value}" ]
  93. then
  94. eval "${opt}_${section}=\"${value}\""
  95. fi
  96. done
  97. }
  98. # load adblock config
  99. #
  100. config_load adblock
  101. config_foreach parse_config source
  102. # check dns backend
  103. #
  104. case "${adb_dns}" in
  105. dnsmasq)
  106. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  107. adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
  108. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  109. adb_dnsheader=""
  110. adb_dnsdeny="awk '{print \"server=/\"\$0\"/\"}'"
  111. adb_dnsallow="awk '{print \"server=/\"\$0\"/#\"}'"
  112. adb_dnshalt="server=/#/"
  113. ;;
  114. unbound)
  115. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  116. adb_dnsuser="${adb_dnsuser:-"unbound"}"
  117. adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
  118. adb_dnsheader=""
  119. adb_dnsdeny="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
  120. adb_dnsallow="awk '{print \"local-zone: \042\"\$0\"\042 transparent\"}'"
  121. adb_dnshalt="local-zone: \".\" static"
  122. ;;
  123. named)
  124. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  125. adb_dnsuser="${adb_dnsuser:-"bind"}"
  126. adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
  127. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  128. adb_dnsdeny="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  129. adb_dnsallow="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  130. adb_dnshalt="* CNAME ."
  131. ;;
  132. kresd)
  133. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  134. adb_dnsuser="${adb_dnsuser:-"root"}"
  135. adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
  136. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  137. adb_dnsdeny="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  138. adb_dnsallow="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  139. adb_dnshalt="* CNAME ."
  140. ;;
  141. dnscrypt-proxy)
  142. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  143. adb_dnsuser="${adb_dnsuser:-"nobody"}"
  144. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  145. adb_dnsheader=""
  146. adb_dnsdeny="awk '{print \$0}'"
  147. adb_dnsallow=""
  148. adb_dnshalt=""
  149. ;;
  150. esac
  151. # check adblock status
  152. #
  153. if [ ${adb_enabled} -eq 0 ]
  154. then
  155. f_extconf
  156. f_temp
  157. f_rmdns
  158. f_jsnup "disabled"
  159. f_log "info" "adblock is currently disabled, please set adb_enabled to '1' to use this service"
  160. exit 0
  161. fi
  162. if [ -d "${adb_dnsdir}" ] && [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
  163. then
  164. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  165. fi
  166. if [ "${adb_action}" = "start" ] && [ "${adb_trigger}" = "timed" ]
  167. then
  168. sleep ${adb_triggerdelay}
  169. fi
  170. while [ ${cnt} -le 30 ]
  171. do
  172. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
  173. if [ "${dns_up}" = "true" ]
  174. then
  175. break
  176. fi
  177. sleep 1
  178. cnt=$((cnt+1))
  179. done
  180. if [ "${dns_up}" != "true" ] || [ -z "${adb_dns}" ] || [ ! -x "$(command -v ${adb_dns})" ]
  181. then
  182. f_log "err" "'${adb_dns}' not running or not executable"
  183. elif [ ! -d "${adb_dnsdir}" ]
  184. then
  185. f_log "err" "'${adb_dnsdir}' backend directory not found"
  186. fi
  187. }
  188. # check environment
  189. #
  190. f_envcheck()
  191. {
  192. local ssl_lib
  193. # startup message
  194. #
  195. f_log "info" "adblock instance started ::: action: ${adb_action}, priority: ${adb_nice:-"0"}, pid: ${$}"
  196. f_jsnup "running"
  197. # check external uci config files
  198. #
  199. f_extconf
  200. # check fetch utility
  201. #
  202. case "${adb_fetchutil}" in
  203. uclient-fetch)
  204. if [ -f "/lib/libustream-ssl.so" ]
  205. then
  206. adb_fetchparm="${adb_fetchparm:-"--timeout=10 --no-check-certificate -O"}"
  207. ssl_lib="libustream-ssl"
  208. else
  209. adb_fetchparm="${adb_fetchparm:-"--timeout=10 -O"}"
  210. fi
  211. ;;
  212. wget)
  213. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"}"
  214. ssl_lib="built-in"
  215. ;;
  216. wget-nossl)
  217. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=10 -O"}"
  218. ;;
  219. busybox)
  220. adb_fetchparm="${adb_fetchparm:-"-O"}"
  221. ;;
  222. curl)
  223. adb_fetchparm="${adb_fetchparm:-"--connect-timeout 10 --insecure -o"}"
  224. ssl_lib="built-in"
  225. ;;
  226. aria2c)
  227. adb_fetchparm="${adb_fetchparm:-"--timeout=10 --allow-overwrite=true --auto-file-renaming=false --check-certificate=false -o"}"
  228. ssl_lib="built-in"
  229. ;;
  230. esac
  231. adb_fetchutil="$(command -v "${adb_fetchutil}")"
  232. if [ ! -x "${adb_fetchutil}" ] || [ -z "${adb_fetchutil}" ] || [ -z "${adb_fetchparm}" ]
  233. then
  234. f_log "err" "download utility not found, please install 'uclient-fetch' with 'libustream-mbedtls' or the full 'wget' package"
  235. fi
  236. adb_fetchinfo="${adb_fetchutil} (${ssl_lib:-"-"})"
  237. f_temp
  238. }
  239. # create temporary files and directories
  240. #
  241. f_temp()
  242. {
  243. if [ -z "${adb_tmpdir}" ]
  244. then
  245. adb_tmpdir="$(mktemp -p /tmp -d)"
  246. adb_tmpload="$(mktemp -p ${adb_tmpdir} -tu)"
  247. adb_tmpfile="$(mktemp -p ${adb_tmpdir} -tu)"
  248. fi
  249. if [ ! -s "${adb_pidfile}" ]
  250. then
  251. printf '%s' "${$}" > "${adb_pidfile}"
  252. fi
  253. }
  254. # remove temporary files and directories
  255. #
  256. f_rmtemp()
  257. {
  258. if [ -d "${adb_tmpdir}" ]
  259. then
  260. rm -rf "${adb_tmpdir}"
  261. fi
  262. > "${adb_pidfile}"
  263. }
  264. # remove dns related files and directories
  265. #
  266. f_rmdns()
  267. {
  268. if [ -n "${adb_dns}" ]
  269. then
  270. f_hash
  271. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  272. > "${adb_dnsdir}/.${adb_dnsfile}"
  273. > "${adb_rtfile}"
  274. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  275. f_hash
  276. if [ ${?} -eq 1 ]
  277. then
  278. f_dnsup
  279. fi
  280. f_rmtemp
  281. fi
  282. 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}"
  283. }
  284. # commit uci changes
  285. #
  286. f_uci()
  287. {
  288. local change config="${1}"
  289. if [ -n "${config}" ]
  290. then
  291. change="$(uci -q changes "${config}" | awk '{ORS=" "; print $0}')"
  292. if [ -n "${change}" ]
  293. then
  294. uci_commit "${config}"
  295. case "${config}" in
  296. firewall)
  297. /etc/init.d/firewall reload >/dev/null 2>&1
  298. ;;
  299. *)
  300. /etc/init.d/"${adb_dns}" reload >/dev/null 2>&1
  301. ;;
  302. esac
  303. fi
  304. fi
  305. f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
  306. }
  307. # list/overall count
  308. #
  309. f_count()
  310. {
  311. local mode="${1}"
  312. adb_cnt=0
  313. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ] && ([ -z "${mode}" ] || [ "${mode}" = "final" ])
  314. then
  315. adb_cnt="$(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}")"
  316. if [ -s "${adb_tmpdir}/tmp.add_whitelist" ]
  317. then
  318. adb_cnt="$(( ${adb_cnt} - $(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add_whitelist") ))"
  319. fi
  320. if [ "${adb_dns}" = "named" ] || [ "${adb_dns}" = "kresd" ]
  321. then
  322. adb_cnt="$(( (${adb_cnt} - $(printf '%s' "${adb_dnsheader}" | grep -c "^")) / 2 ))"
  323. fi
  324. elif [ -s "${adb_tmpfile}" ]
  325. then
  326. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpfile}")"
  327. fi
  328. }
  329. # set external config options
  330. #
  331. f_extconf()
  332. {
  333. local uci_config port port_list="53 853 5353"
  334. case "${adb_dns}" in
  335. dnsmasq)
  336. uci_config="dhcp"
  337. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci_get dhcp "@dnsmasq[${adb_dnsinstance}]" serversfile | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  338. then
  339. uci_set dhcp "@dnsmasq[${adb_dnsinstance}]" serversfile "${adb_dnsdir}/${adb_dnsfile}"
  340. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci_get dhcp "@dnsmasq[${adb_dnsinstance}]" serversfile | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  341. then
  342. uci_remove dhcp "@dnsmasq[${adb_dnsinstance}]" serversfile
  343. fi
  344. ;;
  345. kresd)
  346. uci_config="resolver"
  347. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci_get resolver kresd rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  348. then
  349. uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  350. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci_get resolver kresd rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  351. then
  352. uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  353. fi
  354. if [ ${adb_enabled} -eq 1 ] && [ ${adb_dnsflush} -eq 0 ] && [ "$(uci_get resolver kresd keep_cache)" != "1" ]
  355. then
  356. uci_set resolver kresd keep_cache "1"
  357. elif [ ${adb_enabled} -eq 0 ] || ([ ${adb_dnsflush} -eq 1 ] && [ "$(uci_get resolver kresd keep_cache)" = "1" ])
  358. then
  359. uci_set resolver kresd keep_cache "0"
  360. fi
  361. ;;
  362. esac
  363. f_uci "${uci_config}"
  364. uci_config="firewall"
  365. if [ ${adb_enabled} -eq 1 ] && [ ${adb_forcedns} -eq 1 ] && \
  366. [ -z "$(uci_get firewall adblock_dns_53)" ] && [ $(/etc/init.d/firewall enabled; printf '%u' ${?}) -eq 0 ]
  367. then
  368. for port in ${port_list}
  369. do
  370. uci_add firewall "redirect" "adblock_dns_${port}"
  371. uci_set firewall "adblock_dns_${port}" "name" "Adblock DNS, port ${port}"
  372. uci_set firewall "adblock_dns_${port}" "src" "lan"
  373. uci_set firewall "adblock_dns_${port}" "proto" "tcp udp"
  374. uci_set firewall "adblock_dns_${port}" "src_dport" "${port}"
  375. uci_set firewall "adblock_dns_${port}" "dest_port" "${port}"
  376. uci_set firewall "adblock_dns_${port}" "target" "DNAT"
  377. done
  378. elif [ -n "$(uci_get firewall adblock_dns_53)" ] && ([ ${adb_enabled} -eq 0 ] || [ ${adb_forcedns} -eq 0 ])
  379. then
  380. for port in ${port_list}
  381. do
  382. uci_remove firewall "adblock_dns_${port}"
  383. done
  384. fi
  385. f_uci "${uci_config}"
  386. }
  387. # restart of the dns backend
  388. #
  389. f_dnsup()
  390. {
  391. local dns_up cache_util cache_rc cnt=0
  392. if [ ${adb_dnsflush} -eq 0 ] && [ ${adb_enabled} -eq 1 ] && [ "${adb_rc}" -eq 0 ]
  393. then
  394. case "${adb_dns}" in
  395. dnsmasq)
  396. killall -q -HUP "${adb_dns}"
  397. cache_rc=${?}
  398. ;;
  399. unbound)
  400. cache_util="$(command -v unbound-control)"
  401. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -f "${adb_dnsdir}"/unbound.conf ]
  402. then
  403. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf dump_cache > "${adb_tmpdir}"/adb_cache.dump 2>/dev/null
  404. fi
  405. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  406. ;;
  407. kresd)
  408. cache_util="keep_cache"
  409. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  410. cache_rc=${?}
  411. ;;
  412. named)
  413. cache_util="$(command -v rndc)"
  414. if [ -x "${cache_util}" ] && [ -f /etc/bind/rndc.conf ]
  415. then
  416. "${cache_util}" -c /etc/bind/rndc.conf reload >/dev/null 2>&1
  417. cache_rc=${?}
  418. else
  419. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  420. fi
  421. ;;
  422. *)
  423. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  424. ;;
  425. esac
  426. else
  427. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  428. fi
  429. adb_rc=1
  430. while [ ${cnt} -le 10 ]
  431. do
  432. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
  433. if [ "${dns_up}" = "true" ]
  434. then
  435. case "${adb_dns}" in
  436. unbound)
  437. cache_util="$(command -v unbound-control)"
  438. if [ -x "${cache_util}" ] && [ -d "${adb_tmpdir}" ] && [ -s "${adb_tmpdir}"/adb_cache.dump ]
  439. then
  440. while [ ${cnt} -le 10 ]
  441. do
  442. "${cache_util}" -c "${adb_dnsdir}"/unbound.conf load_cache < "${adb_tmpdir}"/adb_cache.dump >/dev/null 2>&1
  443. cache_rc=${?}
  444. if [ ${cache_rc} -eq 0 ]
  445. then
  446. break
  447. fi
  448. cnt=$((cnt+1))
  449. sleep 1
  450. done
  451. fi
  452. ;;
  453. esac
  454. adb_rc=0
  455. break
  456. fi
  457. cnt=$((cnt+1))
  458. sleep 1
  459. done
  460. f_log "debug" "f_dnsup ::: cache_util: ${cache_util:-"-"}, cache_rc: ${cache_rc:-"-"}, cache_flush: ${adb_dnsflush}, cache_cnt: ${cnt}, rc: ${adb_rc}"
  461. return ${adb_rc}
  462. }
  463. # backup/restore/remove blocklists
  464. #
  465. f_list()
  466. {
  467. local file mode="${1}" in_rc="${adb_rc}"
  468. case "${mode}" in
  469. backup)
  470. if [ -d "${adb_backupdir}" ]
  471. then
  472. gzip -cf "${adb_tmpfile}" 2>/dev/null > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  473. adb_rc=${?}
  474. fi
  475. ;;
  476. restore)
  477. if [ -d "${adb_backupdir}" ] && [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  478. then
  479. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null > "${adb_tmpfile}"
  480. adb_rc=${?}
  481. fi
  482. ;;
  483. remove)
  484. if [ -d "${adb_backupdir}" ]
  485. then
  486. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  487. fi
  488. adb_rc=${?}
  489. ;;
  490. merge)
  491. for file in "${adb_tmpfile}".*
  492. do
  493. cat "${file}" 2>/dev/null >> "${adb_tmpdir}/${adb_dnsfile}"
  494. if [ ${?} -ne 0 ]
  495. then
  496. adb_rc=${?}
  497. break
  498. fi
  499. rm -f "${file}"
  500. done
  501. adb_tmpfile="${adb_tmpdir}/${adb_dnsfile}"
  502. ;;
  503. final)
  504. > "${adb_dnsdir}/${adb_dnsfile}"
  505. if [ -s "${adb_tmpdir}/tmp.add_whitelist" ]
  506. then
  507. cat "${adb_tmpdir}/tmp.add_whitelist" >> "${adb_dnsdir}/${adb_dnsfile}"
  508. fi
  509. if [ -s "${adb_tmpdir}/tmp.rem_whitelist" ]
  510. then
  511. grep -vf "${adb_tmpdir}/tmp.rem_whitelist" "${adb_tmpdir}/${adb_dnsfile}" | eval "${adb_dnsdeny}" >> "${adb_dnsdir}/${adb_dnsfile}"
  512. else
  513. eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >> "${adb_dnsdir}/${adb_dnsfile}"
  514. fi
  515. if [ ${?} -eq 0 ] && [ -n "${adb_dnsheader}" ]
  516. then
  517. printf '%s\n' "${adb_dnsheader}" | cat - "${adb_dnsdir}/${adb_dnsfile}" > "${adb_tmpdir}/${adb_dnsfile}"
  518. mv -f "${adb_tmpdir}/${adb_dnsfile}" "${adb_dnsdir}/${adb_dnsfile}"
  519. fi
  520. adb_rc=${?}
  521. ;;
  522. esac
  523. f_count "${mode}"
  524. f_log "debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${adb_rc}"
  525. }
  526. # top level domain compression
  527. #
  528. f_tld()
  529. {
  530. local cnt cnt_srt cnt_tld source="${1}" temp_src="${1}.src.gz" temp_tld="${1}.tld" tld_ok="false"
  531. gzip -cf "${source}" 2>/dev/null > "${temp_src}"
  532. if [ ${?} -eq 0 ]
  533. then
  534. cnt="$(wc -l 2>/dev/null < "${source}")"
  535. awk 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${source}" > "${temp_tld}"
  536. if [ ${?} -eq 0 ]
  537. then
  538. sort -u "${temp_tld}" > "${source}"
  539. if [ ${?} -eq 0 ]
  540. then
  541. cnt_srt="$(wc -l 2>/dev/null < "${source}")"
  542. awk '{if(NR==1){tld=$NF};while(getline){if($NF!~tld"\\."){print tld;tld=$NF}}print tld}' "${source}" > "${temp_tld}"
  543. if [ ${?} -eq 0 ]
  544. then
  545. awk 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' "${temp_tld}" > "${source}"
  546. if [ ${?} -eq 0 ]
  547. then
  548. rm -f "${temp_src}" "${temp_tld}"
  549. cnt_tld="$(wc -l 2>/dev/null < "${source}")"
  550. tld_ok="true"
  551. fi
  552. fi
  553. fi
  554. fi
  555. fi
  556. if [ "${tld_ok}" = "false" ]
  557. then
  558. rm -f "${temp_tld}"
  559. gunzip -cf "${temp_src}" 2>/dev/null > "${source}"
  560. if [ ${?} -ne 0 ]
  561. then
  562. rm -f "${temp_src}"
  563. > "${source}"
  564. fi
  565. fi
  566. f_log "debug" "f_tld ::: source: ${source}, cnt: ${cnt:-"-"}, cnt_srt: ${cnt_srt:-"-"}, cnt_tld: ${cnt_tld:-"-"}, tld_ok: ${tld_ok}"
  567. }
  568. # blocklist hash compare
  569. #
  570. f_hash()
  571. {
  572. local hash hash_rc=1
  573. if [ -x "${adb_hashutil}" ] && [ -f "${adb_dnsdir}/${adb_dnsfile}" ]
  574. then
  575. hash="$(${adb_hashutil} "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null | awk '{print $1}')"
  576. if [ -z "${adb_hashold}" ] && [ -n "${hash}" ]
  577. then
  578. adb_hashold="${hash}"
  579. elif [ -z "${adb_hashnew}" ] && [ -n "${hash}" ]
  580. then
  581. adb_hashnew="${hash}"
  582. fi
  583. if [ -n "${adb_hashold}" ] && [ -n "${adb_hashnew}" ]
  584. then
  585. if [ "${adb_hashold}" = "${adb_hashnew}" ]
  586. then
  587. hash_rc=0
  588. fi
  589. adb_hashold=""
  590. adb_hashnew=""
  591. fi
  592. fi
  593. f_log "debug" "f_hash ::: hash_util: ${adb_hashutil}, hash: ${hash}, out_rc: ${hash_rc}"
  594. return ${hash_rc}
  595. }
  596. # suspend/resume adblock processing
  597. #
  598. f_switch()
  599. {
  600. local status cnt mode="${1}"
  601. json_load_file "${adb_rtfile}" >/dev/null 2>&1
  602. json_select "data"
  603. json_get_var status "adblock_status"
  604. json_get_var cnt "overall_domains"
  605. if [ "${mode}" = "suspend" ] && [ "${status}" = "enabled" ]
  606. then
  607. if [ ${cnt%% *} -gt 0 ] && [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
  608. then
  609. f_hash
  610. cat "${adb_dnsdir}/${adb_dnsfile}" > "${adb_dnsdir}/.${adb_dnsfile}"
  611. printf '%s\n' "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  612. f_hash
  613. fi
  614. elif [ "${mode}" = "resume" ] && [ "${status}" = "paused" ]
  615. then
  616. if [ ${cnt%% *} -gt 0 ] && [ -s "${adb_dnsdir}/.${adb_dnsfile}" ]
  617. then
  618. f_hash
  619. cat "${adb_dnsdir}/.${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  620. > "${adb_dnsdir}/.${adb_dnsfile}"
  621. f_hash
  622. fi
  623. fi
  624. if [ ${?} -eq 1 ]
  625. then
  626. f_temp
  627. f_dnsup
  628. f_jsnup "${mode}"
  629. f_log "info" "${mode} adblock processing"
  630. f_rmtemp
  631. exit 0
  632. fi
  633. }
  634. # query blocklist for certain (sub-)domains
  635. #
  636. f_query()
  637. {
  638. local search result prefix suffix field domain="${1}" tld="${1#*.}"
  639. if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  640. then
  641. printf '%s\n' "::: invalid domain input, please submit a single domain, e.g. 'doubleclick.net'"
  642. else
  643. case "${adb_dns}" in
  644. dnsmasq)
  645. prefix=".*[\/\.]"
  646. suffix="(\/)"
  647. field=2
  648. ;;
  649. unbound)
  650. prefix=".*[\"\.]"
  651. suffix="(static)"
  652. field=3
  653. ;;
  654. named)
  655. prefix="[^\*].*[\.]"
  656. suffix="( \.)"
  657. field=1
  658. ;;
  659. kresd)
  660. prefix="[^\*].*[\.]"
  661. suffix="( \.)"
  662. field=1
  663. ;;
  664. dnscrypt-proxy)
  665. prefix=".*[\.]"
  666. suffix=""
  667. field=1
  668. ;;
  669. esac
  670. while [ "${domain}" != "${tld}" ]
  671. do
  672. search="${domain//./\\.}"
  673. search="${search//[+*~%\$&\"\']/}"
  674. result="$(awk -F '/|\"| ' "/^(${search}|${prefix}+${search}.*${suffix}$)/{i++;{printf(\" + %s\n\",\$${field})};if(i>9){printf(\" + %s\n\",\"[...]\");exit}}" "${adb_dnsdir}/${adb_dnsfile}")"
  675. printf '%s\n%s\n%s\n' ":::" "::: results for domain '${domain}'" ":::"
  676. printf '%s\n' "${result:-" - no match"}"
  677. domain="${tld}"
  678. tld="${domain#*.}"
  679. done
  680. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
  681. then
  682. search="${1//./\\.}"
  683. search="${search//[+*~%\$&\"\']/}"
  684. printf '%s\n%s\n%s\n' ":::" "::: results for domain '${1}' in backups" ":::"
  685. for file in ${adb_backupdir}/${adb_dnsprefix}.*.gz
  686. do
  687. zcat "${file}" 2>/dev/null | awk -v f="${file##*/}" "/^($search|.*\.${search})/{i++;{printf(\" + %-30s%s\n\",f,\$1)};if(i>=3){printf(\" + %-30s%s\n\",f,\"[...]\");exit}}"
  688. done
  689. fi
  690. fi
  691. }
  692. # update runtime information
  693. #
  694. f_jsnup()
  695. {
  696. local run_time bg_pid status="${1:-"enabled"}" mode="normal mode" no_mail=0
  697. if [ ${adb_rc} -gt 0 ]
  698. then
  699. status="error"
  700. run_time="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  701. fi
  702. if [ "${status}" = "enabled" ]
  703. then
  704. run_time="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  705. fi
  706. if [ "${status}" = "suspend" ]
  707. then
  708. status="paused"
  709. fi
  710. if [ "${status}" = "resume" ]
  711. then
  712. no_mail=1
  713. status="enabled"
  714. fi
  715. if [ ${adb_backup_mode} -eq 1 ]
  716. then
  717. mode="backup mode"
  718. fi
  719. json_load_file "${adb_rtfile}" >/dev/null 2>&1
  720. json_select "data" >/dev/null 2>&1
  721. if [ ${?} -eq 0 ]
  722. then
  723. if [ -z "${adb_fetchinfo}" ]
  724. then
  725. json_get_var adb_fetchinfo "fetch_utility"
  726. fi
  727. if [ -z "${adb_cnt}" ]
  728. then
  729. json_get_var adb_cnt "overall_domains"
  730. adb_cnt="${adb_cnt%% *}"
  731. fi
  732. if [ -z "${run_time}" ]
  733. then
  734. json_get_var run_time "last_rundate"
  735. fi
  736. fi
  737. > "${adb_rtfile}"
  738. json_load_file "${adb_rtfile}" >/dev/null 2>&1
  739. json_init
  740. json_add_object "data"
  741. json_add_string "adblock_status" "${status}"
  742. json_add_string "adblock_version" "${adb_ver}"
  743. json_add_string "overall_domains" "${adb_cnt:-0} (${mode})"
  744. json_add_string "fetch_utility" "${adb_fetchinfo:-"-"}"
  745. json_add_string "dns_backend" "${adb_dns} (${adb_dnsdir})"
  746. json_add_string "last_rundate" "${run_time:-"-"}"
  747. json_add_string "system_release" "${adb_sysver}"
  748. json_close_object
  749. json_dump > "${adb_rtfile}"
  750. if [ ${adb_notify} -eq 1 ] && [ ${no_mail} -eq 0 ] && [ -x /etc/adblock/adblock.notify ] && \
  751. ([ "${status}" = "error" ] || ([ "${status}" = "enabled" ] && [ ${adb_cnt} -le ${adb_notifycnt} ]))
  752. then
  753. (/etc/adblock/adblock.notify >/dev/null 2>&1)&
  754. bg_pid=${!}
  755. fi
  756. f_log "debug" "f_jsnup ::: status: ${status}, mode: ${mode}, cnt: ${adb_cnt}, notify: ${adb_notify}, notify_cnt: ${adb_notifycnt}, notify_pid: ${bg_pid:-"-"}"
  757. }
  758. # write to syslog
  759. #
  760. f_log()
  761. {
  762. local class="${1}" log_msg="${2}"
  763. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  764. then
  765. logger -p "${class}" -t "adblock-${adb_ver}[${$}]" "${log_msg}"
  766. if [ "${class}" = "err" ]
  767. then
  768. f_rmdns
  769. f_jsnup
  770. logger -p "${class}" -t "adblock-${adb_ver}[${$}]" "Please also check 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md'"
  771. exit 1
  772. fi
  773. fi
  774. }
  775. # main function for blocklist processing
  776. #
  777. f_main()
  778. {
  779. 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
  780. mem_total="$(awk '/^MemTotal/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  781. mem_free="$(awk '/^MemFree/ {print int($2/1000)}' "/proc/meminfo" 2>/dev/null)"
  782. tmp_load="${adb_tmpload}"
  783. tmp_file="${adb_tmpfile}"
  784. > "${adb_dnsdir}/.${adb_dnsfile}"
  785. > "${adb_tmpdir}/tmp.raw_whitelist"
  786. > "${adb_tmpdir}/tmp.add_whitelist"
  787. > "${adb_tmpdir}/tmp.rem_whitelist"
  788. 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_dns: ${adb_forcedns}, mem_total: ${mem_total:-0}, mem_free: ${mem_free:-0}, max_queue: ${adb_maxqueue}"
  789. # prepare whitelist entries
  790. #
  791. if [ -s "${adb_whitelist}" ]
  792. then
  793. adb_whitelist_rset="/^([[:alnum:]_-]+\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  794. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.raw_whitelist"
  795. f_tld "${adb_tmpdir}/tmp.raw_whitelist"
  796. adb_whitelist_rset="/^([[:alnum:]_-]+\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\.\",\"\\\.\",\$1);print tolower(\"^\"\$1\"\\\|\\\.\"\$1)}"
  797. awk "${adb_whitelist_rset}" "${adb_tmpdir}/tmp.raw_whitelist" > "${adb_tmpdir}/tmp.rem_whitelist"
  798. if [ -n "${adb_dnsallow}" ]
  799. then
  800. eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw_whitelist" > "${adb_tmpdir}/tmp.add_whitelist"
  801. fi
  802. fi
  803. # build 'dnsjail' list
  804. #
  805. if [ ${adb_jail} -eq 1 ]
  806. then
  807. cat "${adb_tmpdir}/tmp.add_whitelist" > "/tmp/${adb_dnsjail}"
  808. printf '%s\n' "${adb_dnshalt}" >> "/tmp/${adb_dnsjail}"
  809. if [ -n "${adb_dnsheader}" ]
  810. then
  811. printf '%s\n' "${adb_dnsheader}" | cat - "/tmp/${adb_dnsjail}" > "${adb_tmpdir}/tmp.dnsjail"
  812. cat "${adb_tmpdir}/tmp.dnsjail" > "/tmp/${adb_dnsjail}"
  813. fi
  814. fi
  815. # main loop
  816. #
  817. for src_name in ${adb_sources}
  818. do
  819. enabled="$(eval printf '%s' \"\${enabled_${src_name}\}\")"
  820. src_url="$(eval printf '%s' \"\${adb_src_${src_name}\}\")"
  821. src_rset="$(eval printf '%s' \"\${adb_src_rset_${src_name}\}\")"
  822. src_cat="$(eval printf '%s' \"\${adb_src_cat_${src_name}\}\")"
  823. adb_tmpload="${tmp_load}.${src_name}"
  824. adb_tmpfile="${tmp_file}.${src_name}"
  825. # basic pre-checks
  826. #
  827. f_log "debug" "f_main ::: name: ${src_name}, enabled: ${enabled}"
  828. if [ "${enabled}" != "1" ] || [ -z "${src_url}" ] || [ -z "${src_rset}" ]
  829. then
  830. f_list remove
  831. continue
  832. fi
  833. # backup mode
  834. #
  835. if [ ${adb_backup_mode} -eq 1 ] && [ "${adb_action}" = "start" ] && [ "${src_name}" != "blacklist" ]
  836. then
  837. f_list restore
  838. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  839. then
  840. continue
  841. fi
  842. fi
  843. # download queue processing
  844. #
  845. if [ "${src_name}" = "blacklist" ]
  846. then
  847. if [ -s "${src_url}" ]
  848. then
  849. (
  850. src_log="$(cat "${src_url}" > "${adb_tmpload}" 2>&1)"
  851. adb_rc=${?}
  852. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  853. then
  854. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  855. adb_rc=${?}
  856. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  857. then
  858. rm -f "${adb_tmpload}"
  859. f_list download
  860. fi
  861. else
  862. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  863. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  864. fi
  865. ) &
  866. else
  867. continue
  868. fi
  869. elif [ -n "${src_cat}" ]
  870. then
  871. (
  872. src_arc="${adb_tmpdir}/${src_url##*/}"
  873. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
  874. adb_rc=${?}
  875. if [ ${adb_rc} -eq 0 ] && [ -s "${src_arc}" ]
  876. then
  877. list="$(tar -tzf "${src_arc}")"
  878. suffix="$(eval printf '%s' \"\${adb_src_suffix_${src_name}:-\"domains\"\}\")"
  879. for cat in ${src_cat}
  880. do
  881. entry="$(printf '%s' "${list}" | grep -E "[\^/]+${cat}/${suffix}")"
  882. if [ -n "${entry}" ]
  883. then
  884. tar -xOzf "${src_arc}" "${entry}" >> "${adb_tmpload}"
  885. adb_rc=${?}
  886. if [ ${adb_rc} -ne 0 ]
  887. then
  888. break
  889. fi
  890. fi
  891. done
  892. else
  893. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  894. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  895. fi
  896. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  897. then
  898. rm -f "${src_arc}"
  899. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  900. adb_rc=${?}
  901. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  902. then
  903. rm -f "${adb_tmpload}"
  904. f_list download
  905. if [ ${adb_backup} -eq 1 ]
  906. then
  907. f_list backup
  908. fi
  909. elif [ ${adb_backup} -eq 1 ]
  910. then
  911. f_list restore
  912. fi
  913. elif [ ${adb_backup} -eq 1 ]
  914. then
  915. f_list restore
  916. fi
  917. ) &
  918. else
  919. (
  920. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${adb_tmpload}" "${src_url}" 2>&1)"
  921. adb_rc=${?}
  922. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  923. then
  924. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  925. adb_rc=${?}
  926. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  927. then
  928. rm -f "${adb_tmpload}"
  929. f_list download
  930. if [ ${adb_backup} -eq 1 ]
  931. then
  932. f_list backup
  933. fi
  934. elif [ ${adb_backup} -eq 1 ]
  935. then
  936. f_list restore
  937. fi
  938. else
  939. src_log="$(printf '%s' "${src_log}" | awk '{ORS=" ";print $0}')"
  940. f_log "debug" "f_main ::: name: ${src_name}, url: ${src_url}, rc: ${adb_rc}, log: ${src_log:-"-"}"
  941. if [ ${adb_backup} -eq 1 ]
  942. then
  943. f_list restore
  944. fi
  945. fi
  946. ) &
  947. fi
  948. hold=$(( cnt % adb_maxqueue ))
  949. if [ ${hold} -eq 0 ]
  950. then
  951. wait
  952. fi
  953. cnt=$(( cnt + 1 ))
  954. done
  955. # list merge
  956. #
  957. wait
  958. src_name="overall"
  959. adb_tmpfile="${tmp_file}"
  960. f_list merge
  961. # overall sort and conditional dns restart
  962. #
  963. f_hash
  964. if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  965. then
  966. f_tld "${adb_tmpdir}/${adb_dnsfile}"
  967. f_list final
  968. else
  969. > "${adb_dnsdir}/${adb_dnsfile}"
  970. fi
  971. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  972. f_hash
  973. if [ ${?} -eq 1 ]
  974. then
  975. f_dnsup
  976. fi
  977. f_jsnup
  978. if [ ${?} -eq 0 ]
  979. then
  980. f_log "info" "blocklist with overall ${adb_cnt} domains loaded successfully (${adb_sysver})"
  981. else
  982. f_log "err" "dns backend restart with active blocklist failed"
  983. fi
  984. f_rmtemp
  985. exit ${adb_rc}
  986. }
  987. # trace dns queries via tcpdump and prepare a report
  988. #
  989. f_report()
  990. {
  991. local bg_pid total blocked percent rep_clients rep_domains rep_blocked index hold ports cnt=0 search="${1}" count="${2}" filter="${3}" print="${4}"
  992. if [ ! -x "${adb_reputil}" ]
  993. then
  994. f_log "info" "Please install the package 'tcpdump-mini' manually to use the adblock reporting feature!"
  995. return 0
  996. fi
  997. bg_pid="$(pgrep -f "^${adb_reputil}.*adb_report\.pcap$" | awk '{ORS=" "; print $1}')"
  998. if [ ${adb_report} -eq 0 ] || ([ -n "${bg_pid}" ] && ([ "${adb_action}" = "stop" ] || [ "${adb_action}" = "restart" ]))
  999. then
  1000. if [ -n "${bg_pid}" ]
  1001. then
  1002. kill -HUP ${bg_pid}
  1003. while $(kill -0 ${bg_pid} 2>/dev/null)
  1004. do
  1005. sleep 1
  1006. done
  1007. unset bg_pid
  1008. fi
  1009. fi
  1010. if [ -z "${bg_pid}" ] && [ "${adb_action}" != "report" ] && [ "${adb_action}" != "stop" ]
  1011. then
  1012. for port in ${adb_replisten}
  1013. do
  1014. if [ -z "${ports}" ]
  1015. then
  1016. ports="port ${port}"
  1017. else
  1018. ports="${ports} or port ${port}"
  1019. fi
  1020. done
  1021. ("${adb_reputil}" -nn -s0 -l -i ${adb_repiface} ${ports} -C${adb_repchunksize} -W${adb_repchunkcnt} -w "${adb_repdir}/adb_report.pcap" >/dev/null 2>&1 &)
  1022. fi
  1023. if [ "${adb_action}" = "report" ] && [ "${filter}" = "false" ]
  1024. then
  1025. > "${adb_repdir}/adb_report.raw"
  1026. for file in "${adb_repdir}"/adb_report.pcap*
  1027. do
  1028. (
  1029. "${adb_reputil}" -tttt -r $file 2>/dev/null | \
  1030. awk -v cnt=${cnt} '!/\.lan\. /&&/ A[\? ]+|NXDomain/{a=$1;b=substr($2,0,8);c=$4;sub(/\.[0-9]+$/,"",c); \
  1031. d=cnt $7;e=$(NF-1);sub(/[0-9]\/[0-9]\/[0-9]/,"NX",e);sub(/\.$/,"",e);sub(/([0-9]{1,3}\.){3}[0-9]{1,3}/,"OK",e);printf("%s\t%s\t%s\t%s\t%s\n", a,b,c,d,e)}' >> "${adb_repdir}/adb_report.raw"
  1032. )&
  1033. hold=$(( cnt % adb_maxqueue ))
  1034. if [ ${hold} -eq 0 ]
  1035. then
  1036. wait
  1037. fi
  1038. cnt=$(( cnt + 1 ))
  1039. done
  1040. wait
  1041. if [ -s "${adb_repdir}/adb_report.raw" ]
  1042. then
  1043. awk '{printf("%s\t%s\t%s\t%s\t%s\t%s\n", $4,$5,$1,$2,$3,$4)}' "${adb_repdir}/adb_report.raw" | \
  1044. sort -ur | uniq -uf2 | awk '{currA=($6+0);currB=$6;currC=substr($6,length($6),1); \
  1045. if(reqA==currB){reqA=0;printf("%s\t%s\n",d,$2)}else if(currC=="+"){reqA=currA;d=$3"\t"$4"\t"$5"\t"$2}}' | sort -ur > "${adb_repdir}/adb_report"
  1046. fi
  1047. if [ -s "${adb_repdir}/adb_report" ]
  1048. then
  1049. total="$(wc -l < ${adb_repdir}/adb_report)"
  1050. blocked="$(awk '{if($5=="NX")print $4}' ${adb_repdir}/adb_report | wc -l)"
  1051. percent="$(awk -v t=${total} -v b=${blocked} 'BEGIN{printf("%.2f %s\n",b/t*100, "%")}')"
  1052. rep_clients="$(awk '{print $3}' ${adb_repdir}/adb_report | sort | uniq -c | sort -r | awk '{ORS=" ";if(NR<=10) printf("%s_%s ",$1,$2)}')"
  1053. rep_domains="$(awk '{if($5!="NX")print $4}' ${adb_repdir}/adb_report | sort | uniq -c | sort -r | awk '{ORS=" ";if(NR<=10)printf("%s_%s ",$1,$2)}')"
  1054. rep_blocked="$(awk '{if($5=="NX")print $4}' ${adb_repdir}/adb_report | sort | uniq -c | sort -r | awk '{ORS=" ";if(NR<=10)printf("%s_%s ",$1,$2)}')"
  1055. > "${adb_repdir}/adb_report.json"
  1056. json_load_file "${adb_repdir}/adb_report.json" >/dev/null 2>&1
  1057. json_init
  1058. json_add_object "data"
  1059. json_add_string "start_date" "$(awk 'END{printf("%s",$1)}' ${adb_repdir}/adb_report)"
  1060. json_add_string "start_time" "$(awk 'END{printf("%s",$2)}' ${adb_repdir}/adb_report)"
  1061. json_add_string "end_date" "$(awk 'NR==1{printf("%s",$1)}' ${adb_repdir}/adb_report)"
  1062. json_add_string "end_time" "$(awk 'NR==1{printf("%s",$2)}' ${adb_repdir}/adb_report)"
  1063. json_add_string "total" "${total}"
  1064. json_add_string "blocked" "${blocked}"
  1065. json_add_string "percent" "${percent}"
  1066. json_close_array
  1067. json_add_array "top_clients"
  1068. for client in ${rep_clients}
  1069. do
  1070. json_add_object
  1071. json_add_string "count" "${client%_*}"
  1072. json_add_string "address" "${client#*_}"
  1073. json_close_object
  1074. done
  1075. json_close_array
  1076. json_add_array "top_domains"
  1077. for domain in ${rep_domains}
  1078. do
  1079. json_add_object
  1080. json_add_string "count" "${domain%_*}"
  1081. json_add_string "address" "${domain#*_}"
  1082. json_close_object
  1083. done
  1084. json_close_array
  1085. json_add_array "top_blocked"
  1086. for block in ${rep_blocked}
  1087. do
  1088. json_add_object
  1089. json_add_string "count" "${block%_*}"
  1090. json_add_string "address" "${block#*_}"
  1091. json_close_object
  1092. done
  1093. json_close_object
  1094. json_dump > "${adb_repdir}/adb_report.json"
  1095. fi
  1096. rm -f "${adb_repdir}/adb_report.raw"
  1097. fi
  1098. if [ -s "${adb_repdir}/adb_report" ]
  1099. then
  1100. search="${search//./\\.}"
  1101. search="${search//[+*~%\$&\"\' ]/}"
  1102. > "${adb_repdir}/adb_report.final"
  1103. awk "BEGIN{i=0}/(${search})/{i++;if(i<=${count}){printf \"%s\t%s\t%s\t%s\t%s\n\",\$1,\$2,\$3,\$4,\$5}}" "${adb_repdir}/adb_report" > "${adb_repdir}/adb_report.final"
  1104. if [ ! -s "${adb_repdir}/adb_report.final" ]
  1105. then
  1106. printf "%s\t%s\t%s\t%s\t%s\n" "-" "-" "-" "-" "-" > "${adb_repdir}/adb_report.final"
  1107. fi
  1108. fi
  1109. if [ "${print}" = "true" ]
  1110. then
  1111. if [ -s "${adb_repdir}/adb_report.json" ]
  1112. then
  1113. printf "%s\n%s\n%s\n" ":::" "::: Adblock DNS-Query Report" ":::"
  1114. json_load_file "${adb_repdir}/adb_report.json"
  1115. json_select "data"
  1116. json_get_keys keylist
  1117. for key in ${keylist}
  1118. do
  1119. json_get_var value "${key}"
  1120. eval "${key}=\"${value}\""
  1121. done
  1122. printf " + %s\n + %s\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}"
  1123. printf " + %s\n + %s %s\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})"
  1124. json_select ".."
  1125. if json_get_type Status "top_clients" && [ "${Status}" = "array" ]
  1126. then
  1127. printf "%s\n%s\n%s\n" ":::" "::: Top 10 Clients" ":::"
  1128. json_select "top_clients"
  1129. index=1
  1130. while json_get_type Status ${index} && [ "${Status}" = "object" ]
  1131. do
  1132. json_get_values client ${index}
  1133. printf " + %-9s::: %s\n" ${client}
  1134. index=$((index + 1))
  1135. done
  1136. fi
  1137. json_select ".."
  1138. if json_get_type Status "top_domains" && [ "${Status}" = "array" ]
  1139. then
  1140. printf "%s\n%s\n%s\n" ":::" "::: Top 10 Domains" ":::"
  1141. json_select "top_domains"
  1142. index=1
  1143. while json_get_type Status ${index} && [ "${Status}" = "object" ]
  1144. do
  1145. json_get_values domain ${index}
  1146. printf " + %-9s::: %s\n" ${domain}
  1147. index=$((index + 1))
  1148. done
  1149. fi
  1150. json_select ".."
  1151. if json_get_type Status "top_blocked" && [ "${Status}" = "array" ]
  1152. then
  1153. printf "%s\n%s\n%s\n" ":::" "::: Top 10 Blocked Domains" ":::"
  1154. json_select "top_blocked"
  1155. index=1
  1156. while json_get_type Status ${index} && [ "${Status}" = "object" ]
  1157. do
  1158. json_get_values blocked ${index}
  1159. printf " + %-9s::: %s\n" ${blocked}
  1160. index=$((index + 1))
  1161. done
  1162. fi
  1163. if [ -s "${adb_repdir}/adb_report.final" ]
  1164. then
  1165. printf "%s\n%s\n%s\n" ":::" "::: Latest DNS Queries" ":::"
  1166. printf "%-15s%-15s%-45s%-50s%s\n" "Date" "Time" "Client" "Domain" "Answer"
  1167. awk '{printf "%-15s%-15s%-45s%-50s%s\n",$1,$2,$3,$4,$5}' "${adb_repdir}/adb_report.final"
  1168. fi
  1169. else
  1170. printf "%s\n%s\n%s\n" ":::" "::: no reporting data available yet" ":::"
  1171. fi
  1172. fi
  1173. f_log "debug" "f_report ::: action: ${adb_action}, report: ${adb_report}, search: ${1}, count: ${2}, filter: ${3}, print: ${4}, reputil: ${adb_reputil}, repdir: ${adb_repdir}, repiface: ${adb_repiface}, replisten: ${adb_replisten}, repchunksize: ${adb_repchunksize}, repchunkcnt: ${adb_repchunkcnt}, bg_pid: ${bg_pid}"
  1174. }
  1175. # source required system libraries
  1176. #
  1177. if [ -r "/lib/functions.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
  1178. then
  1179. . "/lib/functions.sh"
  1180. . "/usr/share/libubox/jshn.sh"
  1181. else
  1182. f_log "err" "system libraries not found"
  1183. fi
  1184. # handle different adblock actions
  1185. #
  1186. f_envload
  1187. case "${adb_action}" in
  1188. stop)
  1189. f_report "+" "50" "false" "false"
  1190. f_rmdns
  1191. ;;
  1192. restart)
  1193. f_report "+" "50" "false" "false"
  1194. f_rmdns
  1195. f_envcheck
  1196. f_main
  1197. ;;
  1198. suspend)
  1199. f_switch suspend
  1200. ;;
  1201. resume)
  1202. f_switch resume
  1203. ;;
  1204. report)
  1205. f_report "${2}" "${3}" "${4}" "${5}"
  1206. ;;
  1207. query)
  1208. f_query "${2}"
  1209. ;;
  1210. start|reload)
  1211. f_report "+" "50" "false" "false"
  1212. f_envcheck
  1213. f_main
  1214. ;;
  1215. esac