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.

1641 lines
51 KiB

  1. #!/bin/sh
  2. # dns based ad/abuse domain blocking
  3. # Copyright (c) 2015-2020 Dirk Brenken (dev@brenken.org)
  4. # This is free software, licensed under the GNU General Public License v3.
  5. # set (s)hellcheck exceptions
  6. # shellcheck disable=1091,2016,2039,2059,2086,2143,2181,2188
  7. # set initial defaults
  8. #
  9. export LC_ALL=C
  10. export PATH="/usr/sbin:/usr/bin:/sbin:/bin"
  11. set -o pipefail
  12. adb_ver="4.0.4"
  13. adb_enabled=0
  14. adb_debug=0
  15. adb_forcedns=0
  16. adb_maxqueue=4
  17. adb_dnsfilereset=0
  18. adb_dnsflush=0
  19. adb_dnstimeout=20
  20. adb_safesearch=0
  21. adb_safesearchmod=0
  22. adb_report=0
  23. adb_trigger=""
  24. adb_triggerdelay=0
  25. adb_backup=1
  26. adb_mail=0
  27. adb_mailcnt=0
  28. adb_jail=0
  29. adb_dns=""
  30. adb_dnsprefix="adb_list"
  31. adb_tmpbase="/tmp"
  32. adb_backupdir="/tmp"
  33. adb_reportdir="/tmp"
  34. adb_jaildir="/tmp"
  35. adb_pidfile="/var/run/adblock.pid"
  36. adb_blacklist="/etc/adblock/adblock.blacklist"
  37. adb_whitelist="/etc/adblock/adblock.whitelist"
  38. adb_ubusservice="/etc/adblock/adblock.monitor"
  39. adb_mailservice="/etc/adblock/adblock.mail"
  40. adb_dnsfile="${adb_dnsprefix}.overall"
  41. adb_dnsjail="${adb_dnsprefix}.jail"
  42. adb_srcarc="/etc/adblock/adblock.sources.gz"
  43. adb_srcfile="${adb_tmpbase}/adb_sources.json"
  44. adb_rtfile="${adb_tmpbase}/adb_runtime.json"
  45. adb_loggercmd="$(command -v logger)"
  46. adb_dumpcmd="$(command -v tcpdump)"
  47. adb_lookupcmd="$(command -v nslookup)"
  48. adb_fetchutil=""
  49. adb_portlist="53 853 5353"
  50. adb_repiface=""
  51. adb_replisten="53"
  52. adb_repchunkcnt="5"
  53. adb_repchunksize="1"
  54. adb_lookupdomain="example.com"
  55. adb_action="${1:-"start"}"
  56. adb_packages=""
  57. adb_sources=""
  58. adb_cnt=""
  59. # load & check adblock environment
  60. #
  61. f_load()
  62. {
  63. adb_sysver="$(ubus -S call system board 2>/dev/null | jsonfilter -e '@.model' -e '@.release.description' | \
  64. "${adb_awk}" 'BEGIN{ORS=", "}{print $0}' | "${adb_awk}" '{print substr($0,1,length($0)-2)}')"
  65. f_conf
  66. if [ "${adb_action}" != "report" ]
  67. then
  68. f_dns
  69. f_fetch
  70. fi
  71. if [ "${adb_enabled}" -eq 0 ]
  72. then
  73. f_extconf
  74. f_temp
  75. f_rmdns
  76. f_bgserv "stop"
  77. f_jsnup "disabled"
  78. f_log "info" "adblock is currently disabled, please set the config option 'adb_enabled' to '1' to use this service"
  79. exit 0
  80. fi
  81. }
  82. # check & set environment
  83. #
  84. f_env()
  85. {
  86. adb_starttime="$(date "+%s")"
  87. f_log "info" "adblock instance started ::: action: ${adb_action}, priority: ${adb_nice:-"0"}, pid: ${$}"
  88. f_jsnup "running"
  89. f_extconf
  90. f_temp
  91. if [ "${adb_dnsflush}" -eq 1 ]
  92. then
  93. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  94. f_dnsup
  95. fi
  96. if [ ! -r "${adb_srcfile}" ]
  97. then
  98. if [ -r "${adb_srcarc}" ]
  99. then
  100. zcat "${adb_srcarc}" > "${adb_srcfile}"
  101. else
  102. f_log "err" "adblock source archive not found"
  103. fi
  104. fi
  105. if [ -r "${adb_srcfile}" ]
  106. then
  107. json_load_file "${adb_srcfile}"
  108. else
  109. f_log "err" "adblock source file not found"
  110. fi
  111. }
  112. # load adblock config
  113. #
  114. f_conf()
  115. {
  116. local cnt=0 cnt_max=10
  117. if [ ! -r "/etc/config/adblock" ] || [ -n "$(uci -q show adblock.@source[0])" ]
  118. then
  119. if [ -r "/etc/config/adblock-opkg" ] && [ -z "$(uci -q show adblock-opkg.@source[0])" ]
  120. then
  121. if [ -r "/etc/config/adblock" ]
  122. then
  123. cp -pf "/etc/config/adblock" "/etc/config/adblock-backup"
  124. fi
  125. cp -pf "/etc/config/adblock-opkg" "/etc/config/adblock"
  126. f_log "info" "missing or old adblock config replaced with new valid default config"
  127. else
  128. f_log "err" "unrecoverable adblock config error, please re-install the package via opkg with the '--force-reinstall --force-maintainer' options"
  129. fi
  130. fi
  131. config_cb()
  132. {
  133. option_cb()
  134. {
  135. local option="${1}"
  136. local value="${2}"
  137. eval "${option}=\"${value}\""
  138. }
  139. list_cb()
  140. {
  141. local option="${1}"
  142. local value="${2}"
  143. eval "${option}=\"$(printf "%s" "${adb_sources}") ${value}\""
  144. }
  145. }
  146. config_load adblock
  147. if [ -z "${adb_fetchutil}" ] || [ -z "${adb_dns}" ]
  148. then
  149. while [ -z "${adb_packages}" ] && [ "${cnt}" -le "${cnt_max}" ]
  150. do
  151. adb_packages="$(opkg list-installed 2>/dev/null)"
  152. cnt=$((cnt+1))
  153. sleep 1
  154. done
  155. if [ -z "${adb_packages}" ]
  156. then
  157. f_log "err" "local opkg package repository is not available, please set 'adb_fetchutil' and 'adb_dns' manually"
  158. fi
  159. fi
  160. }
  161. # load dns backend config
  162. #
  163. f_dns()
  164. {
  165. local util utils dns_up cnt=0
  166. if [ -z "${adb_dns}" ]
  167. then
  168. utils="knot-resolver named unbound dnsmasq raw"
  169. for util in ${utils}
  170. do
  171. if [ "${util}" = "raw" ] || [ -n "$(printf "%s" "${adb_packages}" | grep "^${util}")" ]
  172. then
  173. if [ "${util}" = "knot-resolver" ]
  174. then
  175. util="kresd"
  176. fi
  177. if [ "${util}" = "raw" ] || [ -x "$(command -v "${util}")" ]
  178. then
  179. adb_dns="${util}"
  180. uci_set adblock global adb_dns "${util}"
  181. f_uci "adblock"
  182. break
  183. fi
  184. fi
  185. done
  186. elif [ "${adb_dns}" != "raw" ] && [ ! -x "$(command -v "${adb_dns}")" ]
  187. then
  188. unset adb_dns
  189. fi
  190. if [ -n "${adb_dns}" ]
  191. then
  192. case "${adb_dns}" in
  193. "dnsmasq")
  194. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  195. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  196. adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
  197. adb_dnsdir="${adb_dnsdir:-"/tmp/dnsmasq.d"}"
  198. adb_dnsheader="${adb_dnsheader}"
  199. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"address=/\"\$0\"/\"}'"}"
  200. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"local=/\"\$0\"/#\"}'"}"
  201. adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"address=/\"\$0\"/\"item\"\"}'"}"
  202. adb_dnsstop="${adb_dnsstop:-"address=/#/"}"
  203. ;;
  204. "unbound")
  205. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  206. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  207. adb_dnsuser="${adb_dnsuser:-"unbound"}"
  208. adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
  209. adb_dnsheader="${adb_dnsheader}"
  210. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 static\"}'"}"
  211. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 transparent\"}'"}"
  212. adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{type=\"AAAA\";if(match(item,/^([0-9]{1,3}\.){3}[0-9]{1,3}$/)){type=\"A\"}}{print \"local-data: \\042\"\$0\" \"type\" \"item\"\\042\"}'"}"
  213. adb_dnsstop="${adb_dnsstop:-"local-zone: \".\" static"}"
  214. ;;
  215. "named")
  216. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  217. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  218. adb_dnsuser="${adb_dnsuser:-"bind"}"
  219. adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
  220. adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n IN NS localhost.\n"}"
  221. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
  222. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
  223. adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"\"\$0\" CNAME \"item\".\\n*.\"\$0\" CNAME \"item\".\"}'"}"
  224. adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
  225. ;;
  226. "kresd")
  227. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  228. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  229. adb_dnsuser="${adb_dnsuser:-"root"}"
  230. adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
  231. adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n IN NS localhost.\n"}"
  232. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
  233. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
  234. adb_dnssafesearch="${adb_dnssafesearch:-"0"}"
  235. adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
  236. ;;
  237. "raw")
  238. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  239. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  240. adb_dnsuser="${adb_dnsuser:-"root"}"
  241. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  242. adb_dnsheader="${adb_dnsheader}"
  243. adb_dnsdeny="${adb_dnsdeny:-"0"}"
  244. adb_dnsallow="${adb_dnsallow:-"1"}"
  245. adb_dnssafesearch="${adb_dnssafesearch:-"0"}"
  246. adb_dnsstop="${adb_dnsstop:-"0"}"
  247. ;;
  248. esac
  249. fi
  250. if [ "${adb_dns}" != "raw" ] && { [ -z "${adb_dns}" ] || [ ! -x "$(command -v "${adb_dns}")" ]; }
  251. then
  252. f_log "err" "dns backend not found, please set 'adb_dns' manually"
  253. fi
  254. if [ "${adb_dns}" != "raw" ] && { [ "${adb_dnsdir}" = "${adb_tmpbase}" ] || [ "${adb_dnsdir}" = "${adb_backupdir}" ] || \
  255. [ "${adb_dnsdir}" = "${adb_reportdir}" ] || [ "${adb_dnsdir}" = "${adb_jaildir}" ]; }
  256. then
  257. f_log "err" "dns directory '${adb_dnsdir}' has been misconfigured, it must not point to the 'adb_tmpbase', 'adb_backupdir', 'adb_reportdir' or 'adb_jaildir'"
  258. fi
  259. if [ "${adb_action}" = "start" ] && [ -z "${adb_trigger}" ]
  260. then
  261. sleep ${adb_triggerdelay}
  262. fi
  263. if [ "${adb_dns}" != "raw" ] && [ "${adb_action}" != "stop" ]
  264. then
  265. while [ "${cnt}" -le 30 ]
  266. do
  267. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
  268. if [ "${dns_up}" = "true" ]
  269. then
  270. break
  271. fi
  272. sleep 1
  273. cnt=$((cnt+1))
  274. done
  275. if [ -n "${adb_dnsdir}" ] && [ ! -d "${adb_dnsdir}" ]
  276. then
  277. mkdir -p "${adb_dnsdir}"
  278. if [ "${?}" -eq 0 ]
  279. then
  280. f_log "info" "dns backend directory '${adb_dnsdir}' created"
  281. else
  282. f_log "err" "dns backend directory '${adb_dnsdir}' could not be created"
  283. fi
  284. fi
  285. if [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
  286. then
  287. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  288. fi
  289. if [ "${dns_up}" != "true" ]
  290. then
  291. f_dnsup 4
  292. if [ "${?}" -ne 0 ]
  293. then
  294. f_log "err" "dns backend '${adb_dns}' not running or executable"
  295. fi
  296. fi
  297. if [ "${adb_backup}" -eq 1 ] && [ -n "${adb_backupdir}" ] && [ ! -d "${adb_backupdir}" ]
  298. then
  299. mkdir -p "${adb_backupdir}"
  300. if [ "${?}" -eq 0 ]
  301. then
  302. f_log "info" "backup directory '${adb_backupdir}' created"
  303. else
  304. f_log "err" "backup backend directory '${adb_backupdir}' could not be created"
  305. fi
  306. fi
  307. if [ -n "${adb_jaildir}" ] && [ ! -d "${adb_jaildir}" ]
  308. then
  309. mkdir -p "${adb_jaildir}"
  310. if [ "${?}" -eq 0 ]
  311. then
  312. f_log "info" "jail directory '${adb_jaildir}' created"
  313. else
  314. f_log "err" "jail directory '${adb_jaildir}' could not be created"
  315. fi
  316. fi
  317. fi
  318. f_log "debug" "f_dns ::: dns: ${adb_dns}, dns_dir: ${adb_dnsdir}, dns_file: ${adb_dnsfile}, dns_user: ${adb_dnsuser}, dns_inotify: ${adb_dnsinotify}, dns_instance: ${adb_dnsinstance}, backup: ${adb_backup}, backup_dir: ${adb_backupdir}, jail_dir: ${adb_jaildir}"
  319. }
  320. # load fetch utility
  321. #
  322. f_fetch()
  323. {
  324. local util utils cnt=0
  325. if [ -z "${adb_fetchutil}" ]
  326. then
  327. utils="aria2c curl wget uclient-fetch"
  328. for util in ${utils}
  329. do
  330. if { [ "${util}" = "uclient-fetch" ] && [ -n "$(printf "%s" "${adb_packages}" | grep "^libustream-")" ]; } || \
  331. { [ "${util}" = "wget" ] && [ -n "$(printf "%s" "${adb_packages}" | grep "^wget -")" ]; } || \
  332. [ "${util}" = "curl" ] || [ "${util}" = "aria2c" ]
  333. then
  334. if [ -x "$(command -v "${util}")" ]
  335. then
  336. adb_fetchutil="${util}"
  337. uci_set adblock global adb_fetchutil "${util}"
  338. f_uci "adblock"
  339. break
  340. fi
  341. fi
  342. done
  343. elif [ ! -x "$(command -v "${adb_fetchutil}")" ]
  344. then
  345. unset adb_fetchutil
  346. fi
  347. case "${adb_fetchutil}" in
  348. "aria2c")
  349. adb_fetchparm="${adb_fetchparm:-"--timeout=20 --allow-overwrite=true --auto-file-renaming=false --check-certificate=true --dir= -o"}"
  350. ;;
  351. "curl")
  352. adb_fetchparm="${adb_fetchparm:-"--connect-timeout 20 --silent --show-error --location -o"}"
  353. ;;
  354. "uclient-fetch")
  355. adb_fetchparm="${adb_fetchparm:-"--timeout=20 -O"}"
  356. ;;
  357. "wget")
  358. adb_fetchparm="${adb_fetchparm:-"--no-cache --no-cookies --max-redirect=0 --timeout=20 -O"}"
  359. ;;
  360. esac
  361. if [ -n "${adb_fetchutil}" ] && [ -n "${adb_fetchparm}" ]
  362. then
  363. adb_fetchutil="$(command -v "${adb_fetchutil}")"
  364. else
  365. f_log "err" "download utility with SSL support not found, please install 'uclient-fetch' with a 'libustream-*' variant or another download utility like 'wget', 'curl' or 'aria2'"
  366. fi
  367. f_log "debug" "f_fetch ::: fetch_util: ${adb_fetchutil:-"-"}, fetch_parm: ${adb_fetchparm:-"-"}"
  368. }
  369. # create temporary files, directories and set dependent options
  370. #
  371. f_temp()
  372. {
  373. local cpu core cores
  374. cpu="$(grep -c '^processor' /proc/cpuinfo 2>/dev/null)"
  375. core="$(grep -cm1 '^core id' /proc/cpuinfo 2>/dev/null)"
  376. if [ "${cpu}" -eq 0 ]
  377. then
  378. cpu=1
  379. fi
  380. if [ "${core}" -eq 0 ]
  381. then
  382. core=1
  383. fi
  384. cores=$((cpu*core))
  385. if [ -d "${adb_tmpbase}" ]
  386. then
  387. adb_tmpdir="$(mktemp -p "${adb_tmpbase}" -d)"
  388. adb_tmpload="$(mktemp -p "${adb_tmpdir}" -tu)"
  389. adb_tmpfile="$(mktemp -p "${adb_tmpdir}" -tu)"
  390. adb_srtopts="--temporary-directory=${adb_tmpdir} --compress-program=gzip --batch-size=32 --parallel=${cores}"
  391. else
  392. f_log "err" "the temp base directory '${adb_tmpbase}' does not exist/is not mounted yet, please create the directory or raise the 'adb_triggerdelay' to defer the adblock start"
  393. fi
  394. if [ ! -s "${adb_pidfile}" ]
  395. then
  396. printf "%s" "${$}" > "${adb_pidfile}"
  397. fi
  398. f_log "debug" "f_temp ::: tmp_base: ${adb_tmpbase:-"-"}, tmp_dir: ${adb_tmpdir:-"-"}, cores: ${cores:-"-"}, sort_options: ${adb_srtopts}, pid_file: ${adb_pidfile:-"-"}"
  399. }
  400. # remove temporary files and directories
  401. #
  402. f_rmtemp()
  403. {
  404. if [ -d "${adb_tmpdir}" ]
  405. then
  406. rm -rf "${adb_tmpdir}"
  407. fi
  408. rm -f "${adb_srcfile}"
  409. > "${adb_pidfile}"
  410. f_log "debug" "f_rmtemp ::: tmp_dir: ${adb_tmpdir:-"-"}, src_file: ${adb_srcfile:-"-"}, pid_file: ${adb_pidfile:-"-"}"
  411. }
  412. # remove dns related files
  413. #
  414. f_rmdns()
  415. {
  416. local status
  417. status="$(ubus -S call service list '{"name":"adblock"}' 2>/dev/null | jsonfilter -l1 -e '@["adblock"].instances.*.running' 2>/dev/null)"
  418. if [ "${adb_dns}" = "raw" ] || { [ -n "${adb_dns}" ] && [ -n "${status}" ]; }
  419. then
  420. > "${adb_rtfile}"
  421. if [ "${adb_backup}" -eq 1 ]
  422. then
  423. rm -f "${adb_backupdir}/${adb_dnsprefix}".*.gz
  424. fi
  425. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  426. f_dnsup 4
  427. fi
  428. f_rmtemp
  429. f_log "debug" "f_rmdns ::: dns: ${adb_dns}, status: ${status:-"-"}, dns_dir: ${adb_dnsdir}, dns_file: ${adb_dnsfile}, rt_file: ${adb_rtfile}, backup_dir: ${adb_backupdir:-"-"}"
  430. }
  431. # commit uci changes
  432. #
  433. f_uci()
  434. {
  435. local change config="${1}"
  436. if [ -n "${config}" ]
  437. then
  438. change="$(uci -q changes "${config}" | "${adb_awk}" '{ORS=" "; print $0}')"
  439. if [ -n "${change}" ]
  440. then
  441. uci_commit "${config}"
  442. case "${config}" in
  443. "firewall")
  444. "/etc/init.d/firewall" reload >/dev/null 2>&1
  445. ;;
  446. "resolver")
  447. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  448. f_count
  449. f_jsnup "running"
  450. "/etc/init.d/${adb_dns}" reload >/dev/null 2>&1
  451. ;;
  452. esac
  453. fi
  454. f_log "debug" "f_uci ::: config: ${config}, change: ${change}"
  455. fi
  456. }
  457. # get list counter
  458. #
  459. f_count()
  460. {
  461. local file mode="${1}" name="${2}"
  462. adb_cnt=0
  463. case "${mode}" in
  464. "blacklist")
  465. if [ -s "${adb_tmpfile}.${name}" ]
  466. then
  467. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpfile}.${name}")"
  468. fi
  469. ;;
  470. "whitelist")
  471. if [ -s "${adb_tmpdir}/tmp.raw.${name}" ]
  472. then
  473. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.raw.${name}")"
  474. rm -f "${adb_tmpdir}/tmp.raw.${name}"
  475. fi
  476. ;;
  477. "safesearch")
  478. if [ -s "${adb_tmpdir}/tmp.safesearch.${name}" ]
  479. then
  480. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.safesearch.${name}")"
  481. fi
  482. ;;
  483. "merge")
  484. if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  485. then
  486. adb_cnt="$(wc -l 2>/dev/null < "${adb_tmpdir}/${adb_dnsfile}")"
  487. fi
  488. ;;
  489. "download"|"backup"|"restore")
  490. if [ -s "${src_tmpfile}" ]
  491. then
  492. adb_cnt="$(wc -l 2>/dev/null < "${src_tmpfile}")"
  493. fi
  494. ;;
  495. "final")
  496. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
  497. then
  498. adb_cnt="$(wc -l 2>/dev/null < "${adb_dnsdir}/${adb_dnsfile}")"
  499. if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]
  500. then
  501. adb_cnt=$((adb_cnt-$(wc -l 2>/dev/null < "${adb_tmpdir}/tmp.add.whitelist")))
  502. fi
  503. for file in "${adb_tmpdir}/tmp.safesearch".*
  504. do
  505. if [ -r "${file}" ]
  506. then
  507. adb_cnt=$((adb_cnt-$(wc -l 2>/dev/null < "${file}")))
  508. fi
  509. done
  510. if [ -n "${adb_dnsheader}" ]
  511. then
  512. adb_cnt=$(((adb_cnt-$(printf "${adb_dnsheader}" | grep -c "^"))/2))
  513. fi
  514. fi
  515. ;;
  516. esac
  517. }
  518. # set external config options
  519. #
  520. f_extconf()
  521. {
  522. local config config_dir config_file port fwcfg
  523. case "${adb_dns}" in
  524. "dnsmasq")
  525. config="dhcp"
  526. config_dir="$(uci_get dhcp "@dnsmasq[${adb_dnsinstance}]" confdir | grep -Fo "${adb_dnsdir}")"
  527. if [ "${adb_enabled}" -eq 1 ] && [ -z "${config_dir}" ]
  528. then
  529. uci_set dhcp "@dnsmasq[${adb_dnsinstance}]" confdir "${adb_dnsdir}" 2>/dev/null
  530. fi
  531. ;;
  532. "kresd")
  533. config="resolver"
  534. config_file="$(uci_get resolver kresd rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
  535. if [ "${adb_enabled}" -eq 1 ] && [ -z "${config_file}" ]
  536. then
  537. uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  538. elif [ "${adb_enabled}" -eq 0 ] && [ -n "${config_file}" ]
  539. then
  540. uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  541. fi
  542. ;;
  543. esac
  544. f_uci "${config}"
  545. config="firewall"
  546. fwcfg="$(uci -qNX show "${config}")"
  547. if [ "${adb_enabled}" -eq 1 ] && [ "${adb_forcedns}" -eq 1 ] && \
  548. [ "$(/etc/init.d/firewall enabled; printf "%u" ${?})" -eq 0 ]
  549. then
  550. for port in ${adb_portlist}
  551. do
  552. if [ -z "$(printf "%s" "${fwcfg}" | grep -Fo -m1 "adblock_dns_${port}")" ]
  553. then
  554. uci -q batch <<-EOC
  555. set firewall."adblock_dns_${port}"="redirect"
  556. set firewall."adblock_dns_${port}".name="Adblock DNS, port ${port}"
  557. set firewall."adblock_dns_${port}".src="lan"
  558. set firewall."adblock_dns_${port}".proto="tcp udp"
  559. set firewall."adblock_dns_${port}".src_dport="${port}"
  560. set firewall."adblock_dns_${port}".dest_port="${port}"
  561. set firewall."adblock_dns_${port}".target="DNAT"
  562. EOC
  563. fi
  564. done
  565. elif [ "${adb_enabled}" -eq 0 ] || [ "${adb_forcedns}" -eq 0 ]
  566. then
  567. for port in ${adb_portlist}
  568. do
  569. if [ -n "$(printf "%s" "${fwcfg}" | grep -Fo -m1 "adblock_dns_${port}")" ]
  570. then
  571. uci_remove firewall "adblock_dns_${port}"
  572. fi
  573. done
  574. fi
  575. f_uci "${config}"
  576. }
  577. # restart dns backend
  578. #
  579. f_dnsup()
  580. {
  581. local dns_service dns_up dns_pid dns_procfile restart_rc cnt=0 out_rc=4 in_rc="${1:-0}"
  582. if [ "${adb_dns}" = "raw" ] || { [ "${in_rc}" -eq 0 ] && [ "${adb_dnsinotify}" -eq 1 ]; }
  583. then
  584. out_rc=0
  585. else
  586. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  587. restart_rc="${?}"
  588. fi
  589. if [ "${restart_rc}" = "0" ]
  590. then
  591. while [ "${cnt}" -le "${adb_dnstimeout}" ]
  592. do
  593. dns_service="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}")"
  594. dns_up="$(printf "%s" "${dns_service}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
  595. dns_pid="$(printf "%s" "${dns_service}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.pid")"
  596. dns_procfile="$(ls -l "/proc/${dns_pid}/fd" 2>/dev/null | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")"
  597. if [ "${dns_up}" = "true" ] && [ -n "${dns_pid}" ] && [ -z "${dns_procfile}" ]
  598. then
  599. if [ -x "${adb_lookupcmd}" ] && [ "${adb_lookupdomain}" != "false" ]
  600. then
  601. "${adb_lookupcmd}" "${adb_lookupdomain}" >/dev/null 2>&1
  602. if [ "${?}" -eq 0 ]
  603. then
  604. out_rc=0
  605. break
  606. fi
  607. else
  608. sleep ${adb_dnstimeout}
  609. cnt=${adb_dnstimeout}
  610. out_rc=0
  611. break
  612. fi
  613. fi
  614. cnt=$((cnt+1))
  615. sleep 1
  616. done
  617. fi
  618. f_log "debug" "f_dnsup ::: lookup_util: ${adb_lookupcmd:-"-"}, lookup_domain: ${adb_lookupdomain:-"-"}, restart_rc: ${restart_rc:-"-"}, dns_timeout: ${adb_dnstimeout}, dns_cnt: ${cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
  619. return "${out_rc}"
  620. }
  621. # backup/restore/remove blocklists
  622. #
  623. f_list()
  624. {
  625. local hold file rset item array safe_url safe_ips safe_cname safe_domains out_rc mode="${1}" src_name="${2:-"${src_name}"}" in_rc="${src_rc:-0}" cnt=1 ffiles="-maxdepth 1 -name ${adb_dnsprefix}.*.gz"
  626. case "${mode}" in
  627. "blacklist"|"whitelist")
  628. src_name="${mode}"
  629. if [ "${src_name}" = "blacklist" ] && [ -s "${adb_blacklist}" ]
  630. then
  631. rset="/^([[:alnum:]_-]+\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  632. "${adb_awk}" "${rset}" "${adb_blacklist}" | \
  633. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${adb_tmpdir}/tmp.raw.${src_name}"
  634. sort ${adb_srtopts} -u "${adb_tmpdir}/tmp.raw.${src_name}" 2>/dev/null > "${adb_tmpfile}.${src_name}"
  635. out_rc="${?}"
  636. rm -f "${adb_tmpdir}/tmp.raw.${src_name}"
  637. elif [ "${src_name}" = "whitelist" ] && [ -s "${adb_whitelist}" ]
  638. then
  639. rset="/^([[:alnum:]_-]+\\.)+[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  640. "${adb_awk}" "${rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.raw.${src_name}"
  641. out_rc="${?}"
  642. if [ "${out_rc}" -eq 0 ]
  643. then
  644. rset="/^([[:alnum:]_-]+\\.)+[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\\.\",\"\\\\.\",\$1);print tolower(\"^(|.*\\\\.)\"\$1\"$\")}"
  645. "${adb_awk}" "${rset}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.rem.${src_name}"
  646. out_rc="${?}"
  647. if [ "${out_rc}" -eq 0 ] && [ "${adb_dnsallow}" != "1" ]
  648. then
  649. eval "${adb_dnsallow}" "${adb_tmpdir}/tmp.raw.${src_name}" > "${adb_tmpdir}/tmp.add.${src_name}"
  650. out_rc="${?}"
  651. if [ "${out_rc}" -eq 0 ] && [ "${adb_jail}" = "1" ] && [ "${adb_dnsstop}" != "0" ]
  652. then
  653. > "${adb_jaildir}/${adb_dnsjail}"
  654. if [ -n "${adb_dnsheader}" ]
  655. then
  656. printf "${adb_dnsheader}" >> "${adb_jaildir}/${adb_dnsjail}"
  657. fi
  658. cat "${adb_tmpdir}/tmp.add.${src_name}" >> "${adb_jaildir}/${adb_dnsjail}"
  659. printf "%s\n" "${adb_dnsstop}" >> "${adb_jaildir}/${adb_dnsjail}"
  660. fi
  661. fi
  662. fi
  663. fi
  664. ;;
  665. "safesearch")
  666. case "${src_name}" in
  667. "google")
  668. rset="/^(\\.[[:alnum:]_-]+\\.)+[[:alpha:]]+([[:space:]]|$)/{printf \"%s\n%s\n\",tolower(\"www\"\$1),tolower(substr(\$1,2,length(\$1)))}"
  669. safe_url="https://www.google.com/supported_domains"
  670. safe_ips="216.239.38.120 2001:4860:4802:32::78"
  671. safe_cname="forcesafesearch.google.com"
  672. safe_domains="${adb_tmpdir}/tmp.load.safesearch.${src_name}"
  673. if [ "${adb_backup}" -eq 1 ] && [ -s "${adb_backupdir}/safesearch.${src_name}.gz" ]
  674. then
  675. zcat "${adb_backupdir}/safesearch.${src_name}.gz" > "${safe_domains}"
  676. out_rc="${?}"
  677. else
  678. "${adb_fetchutil}" ${adb_fetchparm} "${safe_domains}" "${safe_url}" 2>/dev/null
  679. out_rc="${?}"
  680. if [ "${adb_backup}" -eq 1 ] && [ "${out_rc}" -eq 0 ]
  681. then
  682. gzip -cf "${safe_domains}" > "${adb_backupdir}/safesearch.${src_name}.gz"
  683. fi
  684. fi
  685. if [ "${out_rc}" -eq 0 ]
  686. then
  687. "${adb_awk}" "${rset}" "${safe_domains}" > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  688. out_rc="${?}"
  689. fi
  690. ;;
  691. "bing")
  692. safe_ips="204.79.197.220 ::FFFF:CC4F:C5DC"
  693. safe_cname="strict.bing.com"
  694. safe_domains="www.bing.com"
  695. printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  696. out_rc="${?}"
  697. ;;
  698. "duckduckgo")
  699. safe_ips="50.16.250.179 54.208.102.2 52.204.96.252"
  700. safe_cname="safe.duckduckgo.com"
  701. safe_domains="duckduckgo.com"
  702. printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  703. out_rc="${?}"
  704. ;;
  705. "pixabay")
  706. safe_ips="104.18.82.97 2606:4700::6812:8d57 2606:4700::6812:5261"
  707. safe_cname="safesearch.pixabay.com"
  708. safe_domains="pixabay.com"
  709. printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  710. out_rc="${?}"
  711. ;;
  712. "yandex")
  713. safe_ips="213.180.193.56"
  714. safe_cname="familysearch.yandex.ru"
  715. safe_domains="ya.ru yandex.ru yandex.com yandex.com.tr yandex.ua yandex.by yandex.ee yandex.lt yandex.lv yandex.md yandex.uz yandex.tm yandex.tj yandex.az"
  716. printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  717. out_rc="${?}"
  718. ;;
  719. "youtube")
  720. if [ "${adb_safesearchmod}" -eq 0 ]
  721. then
  722. safe_ips="216.239.38.120 2001:4860:4802:32::78"
  723. safe_cname="restrict.youtube.com"
  724. else
  725. safe_ips="216.239.38.119 2001:4860:4802:32::77"
  726. safe_cname="restrictmoderate.youtube.com"
  727. fi
  728. safe_domains="www.youtube.com m.youtube.com youtubei.googleapis.com youtube.googleapis.com www.youtube-nocookie.com"
  729. printf "%s\n" ${safe_domains} > "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  730. out_rc="${?}"
  731. ;;
  732. esac
  733. if [ "${out_rc}" -eq 0 ]
  734. then
  735. > "${adb_tmpdir}/tmp.safesearch.${src_name}"
  736. if [ "${adb_dns}" = "named" ] || [ "${adb_dns}" = "kresd" ]
  737. then
  738. array="${safe_cname}"
  739. else
  740. array="${safe_ips}"
  741. fi
  742. for item in ${array}
  743. do
  744. eval "${adb_dnssafesearch}" "${adb_tmpdir}/tmp.raw.safesearch.${src_name}" >> "${adb_tmpdir}/tmp.safesearch.${src_name}"
  745. if [ "${?}" -ne 0 ]
  746. then
  747. rm -f "${adb_tmpdir}/tmp.safesearch.${src_name}"
  748. break
  749. fi
  750. done
  751. out_rc="${?}"
  752. rm -f "${adb_tmpdir}/tmp.raw.safesearch.${src_name}"
  753. fi
  754. ;;
  755. "backup")
  756. (
  757. gzip -cf "${src_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  758. out_rc="${?}"
  759. )&
  760. ;;
  761. "restore")
  762. if [ -n "${src_name}" ] && [ -s "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  763. then
  764. zcat "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${src_tmpfile}"
  765. out_rc="${?}"
  766. elif [ -z "${src_name}" ]
  767. then
  768. for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz
  769. do
  770. if [ -r "${file}" ]
  771. then
  772. name="${file##*/}"
  773. name="${name%.*}"
  774. zcat "${file}" > "${adb_tmpfile}.${name}" &
  775. hold=$((cnt%adb_maxqueue))
  776. if [ "${hold}" -eq 0 ]
  777. then
  778. wait
  779. fi
  780. cnt=$((cnt+1))
  781. fi
  782. done
  783. wait
  784. out_rc="${?}"
  785. else
  786. out_rc=4
  787. fi
  788. if [ "${adb_action}" != "start" ] && [ "${adb_action}" != "resume" ] && [ -n "${src_name}" ] && [ "${out_rc}" -ne 0 ]
  789. then
  790. adb_sources="${adb_sources/${src_name}}"
  791. fi
  792. ;;
  793. "remove")
  794. if [ "${adb_backup}" -eq 1 ]
  795. then
  796. rm "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" 2>/dev/null
  797. fi
  798. out_rc="${?}"
  799. adb_sources="${adb_sources/${src_name}}"
  800. ;;
  801. "merge")
  802. if [ "${adb_backup}" -eq 1 ]
  803. then
  804. for src_name in ${adb_sources}
  805. do
  806. ffiles="${ffiles} -a ! -name ${adb_dnsprefix}.${src_name}.gz"
  807. done
  808. if [ "${adb_safesearch}" -eq 1 ] && [ "${adb_dnssafesearch}" != "0" ]
  809. then
  810. ffiles="${ffiles} -a ! -name safesearch.google.gz"
  811. fi
  812. find "${adb_backupdir}" ${ffiles} -print0 2>/dev/null | xargs -0 rm 2>/dev/null
  813. fi
  814. unset src_name
  815. sort ${adb_srtopts} -mu "${adb_tmpfile}".* 2>/dev/null > "${adb_tmpdir}/${adb_dnsfile}"
  816. out_rc="${?}"
  817. rm -f "${adb_tmpfile}".*
  818. ;;
  819. "final")
  820. unset src_name
  821. if [ -n "${adb_dnsheader}" ]
  822. then
  823. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  824. else
  825. > "${adb_dnsdir}/${adb_dnsfile}"
  826. fi
  827. if [ -s "${adb_tmpdir}/tmp.add.whitelist" ]
  828. then
  829. cat "${adb_tmpdir}/tmp.add.whitelist" >> "${adb_dnsdir}/${adb_dnsfile}"
  830. fi
  831. for file in "${adb_tmpdir}/tmp.safesearch".*
  832. do
  833. if [ -r "${file}" ]
  834. then
  835. cat "${file}" >> "${adb_dnsdir}/${adb_dnsfile}"
  836. fi
  837. done
  838. if [ "${adb_dnsdeny}" != "0" ]
  839. then
  840. eval "${adb_dnsdeny}" "${adb_tmpdir}/${adb_dnsfile}" >> "${adb_dnsdir}/${adb_dnsfile}"
  841. else
  842. mv "${adb_tmpdir}/${adb_dnsfile}" "${adb_dnsdir}/${adb_dnsfile}"
  843. fi
  844. out_rc="${?}"
  845. ;;
  846. esac
  847. f_count "${mode}" "${src_name}"
  848. out_rc="${out_rc:-"${in_rc}"}"
  849. f_log "debug" "f_list ::: name: ${src_name:-"-"}, mode: ${mode}, cnt: ${adb_cnt}, in_rc: ${in_rc}, out_rc: ${out_rc}"
  850. return "${out_rc}"
  851. }
  852. # top level domain compression
  853. #
  854. f_tld()
  855. {
  856. local cnt cnt_tld source="${1}" temp_tld="${1}.tld"
  857. "${adb_awk}" '{if(NR==1){tld=$NF};while(getline){if(index($NF,tld".")==0){print tld;tld=$NF}}print tld}' "${source}" | \
  858. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${temp_tld}"
  859. if [ "${?}" -eq 0 ]
  860. then
  861. mv -f "${temp_tld}" "${source}"
  862. cnt_tld="$(wc -l 2>/dev/null < "${source}")"
  863. else
  864. rm -f "${temp_tld}"
  865. fi
  866. f_log "debug" "f_tld ::: source: ${source}, cnt: ${adb_cnt:-"-"}, cnt_tld: ${cnt_tld:-"-"}"
  867. }
  868. # suspend/resume adblock processing
  869. #
  870. f_switch()
  871. {
  872. local status list entry done="false" mode="${1}"
  873. json_load_file "${adb_rtfile}" >/dev/null 2>&1
  874. json_select "data" >/dev/null 2>&1
  875. json_get_var status "adblock_status"
  876. if [ "${mode}" = "suspend" ] && [ "${status}" = "enabled" ]
  877. then
  878. f_env
  879. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  880. f_count
  881. done="true"
  882. elif [ "${mode}" = "resume" ] && [ "${status}" = "paused" ]
  883. then
  884. f_env
  885. f_main
  886. done="true"
  887. fi
  888. if [ "${done}" = "true" ]
  889. then
  890. if [ "${mode}" = "suspend" ]
  891. then
  892. f_bgserv "stop"
  893. f_dnsup
  894. fi
  895. if [ "${mode}" = "resume" ]
  896. then
  897. f_bgserv "start"
  898. fi
  899. f_jsnup "${mode}"
  900. f_log "info" "${mode} adblock processing"
  901. fi
  902. f_rmtemp
  903. }
  904. # query blocklist for certain (sub-)domains
  905. #
  906. f_query()
  907. {
  908. local search result prefix suffix field query_start query_end query_timeout=30 domain="${1}" tld="${1#*.}"
  909. if [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  910. then
  911. printf "%s\\n" "::: invalid input, please submit a single (sub-)domain :::"
  912. else
  913. case "${adb_dns}" in
  914. "dnsmasq")
  915. prefix=".*[\\/\\.]"
  916. suffix="(\\/)"
  917. field=2
  918. ;;
  919. "unbound")
  920. prefix=".*[\"\\.]"
  921. suffix="(static)"
  922. field=3
  923. ;;
  924. "named")
  925. prefix="[^\\*].*[\\.]"
  926. suffix="( \\.)"
  927. field=1
  928. ;;
  929. "kresd")
  930. prefix="[^\\*].*[\\.]"
  931. suffix="( \\.)"
  932. field=1
  933. ;;
  934. "raw")
  935. prefix=".*[\\.]"
  936. suffix=""
  937. field=1
  938. ;;
  939. esac
  940. query_start="$(date "+%s")"
  941. if [ "${adb_dnsfilereset}" -eq 0 ]
  942. then
  943. while [ "${domain}" != "${tld}" ]
  944. do
  945. search="${domain//[+*~%\$&\"\']/}"
  946. search="${search//./\\.}"
  947. result="$("${adb_awk}" -F '/|\"|\t| ' "/^(${search}|${prefix}+${search}.*${suffix})$/{i++;if(i<=9){printf \" + %s\\n\",\$${field}}else if(i==10){printf \" + %s\\n\",\"[...]\";exit}}" "${adb_dnsdir}/${adb_dnsfile}")"
  948. printf "%s\\n%s\\n%s\\n" ":::" "::: domain '${domain}' in active blocklist" ":::"
  949. printf "%s\\n\\n" "${result:-" - no match"}"
  950. domain="${tld}"
  951. tld="${domain#*.}"
  952. done
  953. fi
  954. if [ "${adb_backup}" -eq 1 ] && [ -d "${adb_backupdir}" ]
  955. then
  956. search="${1//[+*~%\$&\"\']/}"
  957. search="${search//./\\.}"
  958. printf "%s\\n%s\\n%s\\n" ":::" "::: domain '${1}' in backups and black-/whitelist" ":::"
  959. for file in "${adb_backupdir}/${adb_dnsprefix}".*.gz "${adb_blacklist}" "${adb_whitelist}"
  960. do
  961. suffix="${file##*.}"
  962. if [ "${suffix}" = "gz" ]
  963. then
  964. zcat "${file}" 2>/dev/null | \
  965. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' | "${adb_awk}" -v f="${file##*/}" "BEGIN{rc=1};/^($search|.*\\.${search})$/{i++;if(i<=3){printf \" + %-30s%s\\n\",f,\$1;rc=0}else if(i==4){printf \" + %-30s%s\\n\",f,\"[...]\"}};END{exit rc}"
  966. else
  967. "${adb_awk}" -v f="${file##*/}" "BEGIN{rc=1};/^($search|.*\\.${search})$/{i++;if(i<=3){printf \" + %-30s%s\\n\",f,\$1;rc=0}else if(i==4){printf \" + %-30s%s\\n\",f,\"[...]\"}};END{exit rc}" "${file}"
  968. fi
  969. if [ "${?}" -eq 0 ]
  970. then
  971. result="true"
  972. query_end="$(date "+%s")"
  973. if [ "$((query_end-query_start))" -gt "${query_timeout}" ]
  974. then
  975. printf "%s\\n\\n" " - [...]"
  976. break
  977. fi
  978. fi
  979. done
  980. if [ "${result}" != "true" ]
  981. then
  982. printf "%s\\n\\n" " - no match"
  983. fi
  984. fi
  985. fi
  986. }
  987. # update runtime information
  988. #
  989. f_jsnup()
  990. {
  991. local runtime utils memory bg_pid status="${1:-"enabled"}"
  992. case "${status}" in
  993. "enabled"|"error")
  994. adb_endtime="$(date "+%s")"
  995. memory="$("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null | "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
  996. if [ "$(( (adb_endtime-adb_starttime)/60 ))" -lt 60 ]
  997. then
  998. runtime="${adb_action}, $(( (adb_endtime-adb_starttime)/60 ))m $(( (adb_endtime-adb_starttime)%60 ))s, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
  999. else
  1000. runtime="${adb_action}, n/a, ${memory:-0}, $(date "+%d.%m.%Y %H:%M:%S")"
  1001. fi
  1002. if [ "${status}" = "error" ]
  1003. then
  1004. adb_cnt=0
  1005. fi
  1006. ;;
  1007. "suspend")
  1008. status="paused"
  1009. ;;
  1010. "resume")
  1011. status=""
  1012. ;;
  1013. esac
  1014. json_load_file "${adb_rtfile}" >/dev/null 2>&1
  1015. json_select "data" >/dev/null 2>&1
  1016. if [ "${?}" -eq 0 ]
  1017. then
  1018. if [ -z "${adb_fetchutil}" ] || [ -z "${adb_awk}" ]
  1019. then
  1020. json_get_var utils "utilities"
  1021. else
  1022. utils="${adb_fetchutil}, ${adb_awk}"
  1023. fi
  1024. if [ -z "${adb_cnt}" ]
  1025. then
  1026. json_get_var adb_cnt "blocked_domains"
  1027. adb_cnt="${adb_cnt%% *}"
  1028. fi
  1029. if [ -z "${runtime}" ]
  1030. then
  1031. json_get_var runtime "last_run"
  1032. fi
  1033. fi
  1034. > "${adb_rtfile}"
  1035. json_load_file "${adb_rtfile}" >/dev/null 2>&1
  1036. json_init
  1037. json_add_object "data"
  1038. json_add_string "adblock_status" "${status:-"enabled"}"
  1039. json_add_string "adblock_version" "${adb_ver}"
  1040. json_add_string "blocked_domains" "${adb_cnt:-0}"
  1041. json_add_array "active_sources"
  1042. for entry in ${adb_sources}
  1043. do
  1044. json_add_object
  1045. json_add_string "source" "${entry}"
  1046. json_close_object
  1047. done
  1048. json_close_array
  1049. json_add_string "dns_backend" "${adb_dns:-"-"}, ${adb_dnsdir:-"-"}"
  1050. json_add_string "run_utils" "${utils:-"-"}"
  1051. json_add_string "run_ifaces" "trigger: ${adb_trigger:-"-"}, report: ${adb_repiface:-"-"}"
  1052. json_add_string "run_directories" "base: ${adb_tmpbase}, backup: ${adb_backupdir}, report: ${adb_reportdir}, jail: ${adb_jaildir}"
  1053. json_add_string "run_flags" "backup: ${adb_backup}, reset: ${adb_dnsfilereset}, flush: ${adb_dnsflush}, force: ${adb_forcedns}, search: ${adb_safesearch}, report: ${adb_report}, mail: ${adb_mail}, jail: ${adb_jail}"
  1054. json_add_string "last_run" "${runtime:-"-"}"
  1055. json_add_string "system" "${adb_sysver}"
  1056. json_close_object
  1057. json_dump > "${adb_rtfile}"
  1058. if [ "${adb_mail}" -eq 1 ] && [ -x "${adb_mailservice}" ] && \
  1059. { [ "${status}" = "error" ] || { [ "${status}" = "enabled" ] && [ "${adb_cnt}" -le "${adb_mailcnt}" ]; } }
  1060. then
  1061. ( "${adb_mailservice}" "${adb_ver}" >/dev/null 2>&1 )&
  1062. bg_pid="${!}"
  1063. fi
  1064. f_log "debug" "f_jsnup ::: status: ${status:-"-"}, cnt: ${adb_cnt}, mail: ${adb_mail}, mail_service: ${adb_mailservice}, mail_cnt: ${adb_mailcnt}, mail_pid: ${bg_pid:-"-"}"
  1065. }
  1066. # write to syslog
  1067. #
  1068. f_log()
  1069. {
  1070. local class="${1}" log_msg="${2}"
  1071. if [ -n "${log_msg}" ] && { [ "${class}" != "debug" ] || [ "${adb_debug}" -eq 1 ]; }
  1072. then
  1073. if [ -x "${adb_loggercmd}" ]
  1074. then
  1075. "${adb_loggercmd}" -p "${class}" -t "adblock-${adb_ver}[${$}]" "${log_msg}"
  1076. else
  1077. printf "%s %s %s\\n" "${class}" "adblock-${adb_ver}[${$}]" "${log_msg}"
  1078. fi
  1079. if [ "${class}" = "err" ]
  1080. then
  1081. f_rmdns
  1082. f_bgserv "stop"
  1083. f_jsnup "error"
  1084. exit 1
  1085. fi
  1086. fi
  1087. }
  1088. # start ubus monitor service to trace dns backend events
  1089. #
  1090. f_bgserv()
  1091. {
  1092. local bg_pid status="${1}"
  1093. bg_pid="$(pgrep -f "^/bin/sh ${adb_ubusservice}.*|^/bin/ubus -S -M r -m invoke monitor|^grep -qF \"method\":\"set\",\"data\":\\{\"name\":\"${adb_dns}\"" | "${adb_awk}" '{ORS=" "; print $1}')"
  1094. if [ "${adb_dns}" != "raw" ] && [ -z "${bg_pid}" ] && [ "${status}" = "start" ] \
  1095. && [ -x "${adb_ubusservice}" ] && [ "${adb_dnsfilereset}" -eq 1 ]
  1096. then
  1097. ( "${adb_ubusservice}" "${adb_ver}" & )
  1098. elif [ -n "${bg_pid}" ] && [ "${status}" = "stop" ]
  1099. then
  1100. kill -HUP "${bg_pid}" 2>/dev/null
  1101. fi
  1102. f_log "debug" "f_bgserv ::: status: ${status:-"-"}, bg_pid: ${bg_pid:-"-"}, dns_filereset: ${adb_dnsfilereset:-"-"}, ubus_service: ${adb_ubusservice:-"-"}"
  1103. }
  1104. # main function for blocklist processing
  1105. #
  1106. f_main()
  1107. {
  1108. local src_tmpload src_tmpfile src_name src_rset src_url src_log src_arc src_cat src_item src_list src_entries src_suffix src_rc entry keylist memory cnt=1
  1109. memory="$("${adb_awk}" '/^MemTotal|^MemFree|^MemAvailable/{ORS="/"; print int($2/1000)}' "/proc/meminfo" 2>/dev/null | "${adb_awk}" '{print substr($0,1,length($0)-1)}')"
  1110. f_log "debug" "f_main ::: memory: ${memory:-0}, max_queue: ${adb_maxqueue}, safe_search: ${adb_safesearch}, force_dns: ${adb_forcedns}, awk: ${adb_awk}"
  1111. # white- and blacklist preparation
  1112. #
  1113. list="blacklist whitelist"
  1114. for entry in ${list}
  1115. do
  1116. ( f_list "${entry}" "${entry}" )&
  1117. done
  1118. # safe search preparation
  1119. #
  1120. if [ "${adb_safesearch}" -eq 1 ] && [ "${adb_dnssafesearch}" != "0" ]
  1121. then
  1122. list="google bing duckduckgo pixabay yandex youtube"
  1123. for entry in ${list}
  1124. do
  1125. ( f_list safesearch "${entry}" )&
  1126. done
  1127. fi
  1128. wait
  1129. # main loop
  1130. #
  1131. for src_name in ${adb_sources}
  1132. do
  1133. json_select "${src_name}" >/dev/null 2>&1
  1134. if [ "${?}" -ne 0 ]
  1135. then
  1136. adb_sources="${adb_sources/${src_name}}"
  1137. continue
  1138. fi
  1139. json_get_var src_url "url" >/dev/null 2>&1
  1140. json_get_var src_rset "rule" >/dev/null 2>&1
  1141. json_get_values src_cat "categories" >/dev/null 2>&1
  1142. json_select ..
  1143. src_tmpload="${adb_tmpload}.${src_name}.load"
  1144. src_tmpsort="${adb_tmpload}.${src_name}.sort"
  1145. src_tmpfile="${adb_tmpfile}.${src_name}"
  1146. src_rc=4
  1147. # basic pre-checks
  1148. #
  1149. if [ -z "${src_url}" ] || [ -z "${src_rset}" ]
  1150. then
  1151. f_list remove
  1152. continue
  1153. fi
  1154. # backup mode
  1155. #
  1156. if [ "${adb_backup}" -eq 1 ] && { [ "${adb_action}" = "start" ] || [ "${adb_action}" = "resume" ]; }
  1157. then
  1158. f_list restore
  1159. if [ "${?}" -eq 0 ] && [ -s "${src_tmpfile}" ]
  1160. then
  1161. continue
  1162. fi
  1163. fi
  1164. # download queue processing
  1165. #
  1166. if [ -n "${src_cat}" ]
  1167. then
  1168. (
  1169. src_arc="${adb_tmpdir}/${src_url##*/}"
  1170. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
  1171. src_rc="${?}"
  1172. if [ "${src_rc}" -eq 0 ] && [ -s "${src_arc}" ]
  1173. then
  1174. unset src_entries
  1175. src_suffix="$(eval printf "%s" \"\$\{adb_src_suffix_${src_name}:-\"domains\"\}\")"
  1176. src_list="$(tar -tzf "${src_arc}" 2>/dev/null)"
  1177. for src_item in ${src_cat}
  1178. do
  1179. src_entries="${src_entries} $(printf "%s" "${src_list}" | grep -E "${src_item}/${src_suffix}$")"
  1180. done
  1181. if [ -n "${src_entries}" ]
  1182. then
  1183. tar -xOzf "${src_arc}" ${src_entries} 2>/dev/null > "${src_tmpload}"
  1184. src_rc="${?}"
  1185. fi
  1186. rm -f "${src_arc}"
  1187. else
  1188. src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
  1189. f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
  1190. fi
  1191. if [ "${src_rc}" -eq 0 ] && [ -s "${src_tmpload}" ]
  1192. then
  1193. if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]
  1194. then
  1195. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1196. grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1197. else
  1198. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1199. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1200. fi
  1201. rm -f "${src_tmpload}"
  1202. sort ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
  1203. src_rc="${?}"
  1204. rm -f "${src_tmpsort}"
  1205. if [ "${src_rc}" -eq 0 ] && [ -s "${src_tmpfile}" ]
  1206. then
  1207. f_list download
  1208. if [ "${adb_backup}" -eq 1 ]
  1209. then
  1210. f_list backup
  1211. fi
  1212. elif [ "${adb_backup}" -eq 1 ] && [ "${adb_action}" != "start" ]
  1213. then
  1214. f_log "info" "archive preparation of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
  1215. f_list restore
  1216. rm -f "${src_tmpfile}"
  1217. fi
  1218. elif [ "${adb_backup}" -eq 1 ] && [ "${adb_action}" != "start" ]
  1219. then
  1220. f_log "info" "archive extraction of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
  1221. f_list restore
  1222. fi
  1223. )&
  1224. continue
  1225. else
  1226. (
  1227. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpload}" "${src_url}" 2>&1)"
  1228. src_rc="${?}"
  1229. if [ "${src_rc}" -eq 0 ] && [ -s "${src_tmpload}" ]
  1230. then
  1231. if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]
  1232. then
  1233. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1234. grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1235. else
  1236. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1237. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1238. fi
  1239. rm -f "${src_tmpload}"
  1240. sort ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
  1241. src_rc="${?}"
  1242. rm -f "${src_tmpsort}"
  1243. if [ "${src_rc}" -eq 0 ] && [ -s "${src_tmpfile}" ]
  1244. then
  1245. f_list download
  1246. if [ "${adb_backup}" -eq 1 ]
  1247. then
  1248. f_list backup
  1249. fi
  1250. elif [ "${adb_backup}" -eq 1 ] && [ "${adb_action}" != "start" ]
  1251. then
  1252. f_log "info" "preparation of '${src_name}' failed, rc: ${src_rc}"
  1253. f_list restore
  1254. rm -f "${src_tmpfile}"
  1255. fi
  1256. else
  1257. src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
  1258. f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
  1259. if [ "${adb_backup}" -eq 1 ] && [ "${adb_action}" != "start" ]
  1260. then
  1261. f_list restore
  1262. fi
  1263. fi
  1264. )&
  1265. fi
  1266. hold=$((cnt%adb_maxqueue))
  1267. if [ "${hold}" -eq 0 ]
  1268. then
  1269. wait
  1270. fi
  1271. cnt=$((cnt+1))
  1272. done
  1273. wait
  1274. f_list merge
  1275. # tld compression and dns restart
  1276. #
  1277. if [ "${?}" -eq 0 ] && [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  1278. then
  1279. f_tld "${adb_tmpdir}/${adb_dnsfile}"
  1280. f_list final
  1281. else
  1282. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  1283. fi
  1284. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  1285. f_dnsup
  1286. if [ "${?}" -eq 0 ]
  1287. then
  1288. if [ "${adb_action}" != "resume" ]
  1289. then
  1290. f_jsnup "enabled"
  1291. fi
  1292. if [ "${adb_dns}" != "raw" ] && [ "${adb_dnsfilereset}" -eq 1 ]
  1293. then
  1294. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  1295. f_log "info" "blocklist with overall ${adb_cnt} blocked domains loaded successfully and reset afterwards (${adb_sysver})"
  1296. f_bgserv "start"
  1297. else
  1298. f_log "info" "blocklist with overall ${adb_cnt} blocked domains loaded successfully (${adb_sysver})"
  1299. fi
  1300. else
  1301. f_log "err" "dns backend restart with adblock blocklist failed"
  1302. fi
  1303. f_rmtemp
  1304. }
  1305. # trace dns queries via tcpdump and prepare a report
  1306. #
  1307. f_report()
  1308. {
  1309. local iface bg_pid status total start end blocked percent top_list top array item index hold ports cnt=0 search="${1}" count="${2}" process="${3}" print="${4}"
  1310. if [ "${adb_report}" -eq 1 ] && [ ! -x "${adb_dumpcmd}" ]
  1311. then
  1312. f_log "info" "Please install the package 'tcpdump' or 'tcpdump-mini' to use the reporting feature"
  1313. elif [ "${adb_report}" -eq 0 ] && [ "${adb_action}" = "report" ]
  1314. then
  1315. f_log "info" "Please enable the 'DNS Report' option to use the reporting feature"
  1316. fi
  1317. if [ -x "${adb_dumpcmd}" ]
  1318. then
  1319. bg_pid="$(pgrep -f "^${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
  1320. if [ "${adb_report}" -eq 0 ] || { [ -n "${bg_pid}" ] && { [ "${adb_action}" = "stop" ] || [ "${adb_action}" = "restart" ]; } }
  1321. then
  1322. if [ -n "${bg_pid}" ]
  1323. then
  1324. kill -HUP "${bg_pid}" 2>/dev/null
  1325. while $(kill -0 "${bg_pid}" 2>/dev/null)
  1326. do
  1327. sleep 1
  1328. done
  1329. unset bg_pid
  1330. fi
  1331. fi
  1332. fi
  1333. if [ -x "${adb_dumpcmd}" ] && [ "${adb_report}" -eq 1 ]
  1334. then
  1335. if [ -z "${bg_pid}" ] && [ "${adb_action}" != "report" ] && [ "${adb_action}" != "stop" ]
  1336. then
  1337. for port in ${adb_replisten}
  1338. do
  1339. if [ -z "${ports}" ]
  1340. then
  1341. ports="port ${port}"
  1342. else
  1343. ports="${ports} or port ${port}"
  1344. fi
  1345. done
  1346. if [ -z "${adb_repiface}" ]
  1347. then
  1348. network_get_device iface "lan"
  1349. if [ -n "${iface}" ]
  1350. then
  1351. adb_repiface="${iface}"
  1352. else
  1353. network_get_physdev iface "lan"
  1354. if [ -n "${iface}" ]
  1355. then
  1356. adb_repiface="${iface}"
  1357. fi
  1358. fi
  1359. if [ -n "${adb_repiface}" ]
  1360. then
  1361. uci_set adblock global adb_repiface "${adb_repiface}"
  1362. f_uci "adblock"
  1363. fi
  1364. fi
  1365. if [ -n "${adb_reportdir}" ] && [ ! -d "${adb_reportdir}" ]
  1366. then
  1367. mkdir -p "${adb_reportdir}"
  1368. f_log "info" "report directory '${adb_reportdir}' created"
  1369. fi
  1370. if [ -n "${adb_repiface}" ] && [ -d "${adb_reportdir}" ]
  1371. then
  1372. ( "${adb_dumpcmd}" -nn -s0 -l -i ${adb_repiface} ${ports} -C${adb_repchunksize} -W${adb_repchunkcnt} -w "${adb_reportdir}/adb_report.pcap" >/dev/null 2>&1 & )
  1373. bg_pid="$(pgrep -f "^${adb_dumpcmd}.*adb_report\\.pcap$" | "${adb_awk}" '{ORS=" "; print $1}')"
  1374. else
  1375. f_log "info" "Please set the name of the reporting network device 'adb_repiface' manually"
  1376. fi
  1377. fi
  1378. if [ "${adb_action}" = "report" ] && [ "${process}" = "true" ]
  1379. then
  1380. > "${adb_reportdir}/adb_report.raw"
  1381. for file in "${adb_reportdir}/adb_report.pcap"*
  1382. do
  1383. (
  1384. "${adb_dumpcmd}" -tttt -r "${file}" 2>/dev/null | \
  1385. "${adb_awk}" -v cnt="${cnt}" '!/\.lan\. |PTR\? | SOA\? /&&/ A[\? ]+|NXDomain|0\.0\.0\.0/{a=$1;b=substr($2,0,8);c=$4;sub(/\.[0-9]+$/,"",c);d=cnt $7;sub(/\*$/,"",d);
  1386. e=$(NF-1);sub(/[0-9]\/[0-9]\/[0-9]|0\.0\.0\.0/,"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",d,e,a,b,c}' >> "${adb_reportdir}/adb_report.raw"
  1387. )&
  1388. hold=$((cnt%adb_maxqueue))
  1389. if [ "${hold}" -eq 0 ]
  1390. then
  1391. wait
  1392. fi
  1393. cnt=$((cnt+1))
  1394. done
  1395. wait
  1396. if [ -s "${adb_reportdir}/adb_report.raw" ]
  1397. then
  1398. sort ${adb_srtopts} -k1 -k3 -k4 -k5 -k1 -ur "${adb_reportdir}/adb_report.raw" | \
  1399. "${adb_awk}" '{currA=($1+0);currB=$1;currC=substr($1,length($1),1);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}}' | \
  1400. sort ${adb_srtopts} -k1 -k2 -k3 -k4 -ur > "${adb_reportdir}/adb_report.srt"
  1401. rm -f "${adb_reportdir}/adb_report.raw"
  1402. fi
  1403. if [ -s "${adb_reportdir}/adb_report.srt" ]
  1404. then
  1405. start="$("${adb_awk}" 'END{printf "%s_%s",$1,$2}' "${adb_reportdir}/adb_report.srt")"
  1406. end="$("${adb_awk}" 'NR==1{printf "%s_%s",$1,$2}' "${adb_reportdir}/adb_report.srt")"
  1407. total="$(wc -l < "${adb_reportdir}/adb_report.srt")"
  1408. blocked="$("${adb_awk}" '{if($5=="NX")cnt++}END{printf "%s",cnt}' "${adb_reportdir}/adb_report.srt")"
  1409. percent="$("${adb_awk}" -v t="${total}" -v b="${blocked}" 'BEGIN{printf "%.2f%s",b/t*100,"%"}')"
  1410. > "${adb_reportdir}/adb_report.json"
  1411. printf "%s" "{ \"data\": { " >> "${adb_reportdir}/adb_report.json"
  1412. printf "%s" "\"start_date\": \"${start%_*}\", " >> "${adb_reportdir}/adb_report.json"
  1413. printf "%s" "\"start_time\": \"${start#*_}\", " >> "${adb_reportdir}/adb_report.json"
  1414. printf "%s" "\"end_date\": \"${end%_*}\", " >> "${adb_reportdir}/adb_report.json"
  1415. printf "%s" "\"end_time\": \"${end#*_}\", " >> "${adb_reportdir}/adb_report.json"
  1416. printf "%s" "\"total\": \"${total}\", " >> "${adb_reportdir}/adb_report.json"
  1417. printf "%s" "\"blocked\": \"${blocked}\", " >> "${adb_reportdir}/adb_report.json"
  1418. printf "%s" "\"percent\": \"${percent}\", " >> "${adb_reportdir}/adb_report.json"
  1419. top_list="top_clients top_domains top_blocked"
  1420. for top in ${top_list}
  1421. do
  1422. printf "%s" " \"${top}\": [ " >> "${adb_reportdir}/adb_report.json"
  1423. case "${top}" in
  1424. "top_clients")
  1425. "${adb_awk}" '{print $3}' "${adb_reportdir}/adb_report.srt" | sort ${adb_srtopts} | uniq -c | \
  1426. sort ${adb_srtopts} -nr | "${adb_awk}" '{ORS=" ";if(NR==1)printf "{ \"count\": \"%s\", \"address\": \"%s\" }",$1,$2; else if(NR<10)printf ", { \"count\": \"%s\", \"address\": \"%s\" }",$1,$2}' >> "${adb_reportdir}/adb_report.json"
  1427. ;;
  1428. "top_domains")
  1429. "${adb_awk}" '{if($5!="NX")print $4}' "${adb_reportdir}/adb_report.srt" | sort ${adb_srtopts} | uniq -c | \
  1430. sort ${adb_srtopts} -nr | "${adb_awk}" '{ORS=" ";if(NR==1)printf "{ \"count\": \"%s\", \"address\": \"%s\" }",$1,$2; else if(NR<10)printf ", { \"count\": \"%s\", \"address\": \"%s\" }",$1,$2}' >> "${adb_reportdir}/adb_report.json"
  1431. ;;
  1432. "top_blocked")
  1433. "${adb_awk}" '{if($5=="NX")print $4}' "${adb_reportdir}/adb_report.srt" | sort ${adb_srtopts} | uniq -c | \
  1434. sort ${adb_srtopts} -nr | "${adb_awk}" '{ORS=" ";if(NR==1)printf "{ \"count\": \"%s\", \"address\": \"%s\" }",$1,$2; else if(NR<10)printf ", { \"count\": \"%s\", \"address\": \"%s\" }",$1,$2}' >> "${adb_reportdir}/adb_report.json"
  1435. ;;
  1436. esac
  1437. printf "%s" " ], " >> "${adb_reportdir}/adb_report.json"
  1438. done
  1439. search="${search//./\\.}"
  1440. search="${search//[+*~%\$&\"\' ]/}"
  1441. "${adb_awk}" "BEGIN{i=0;printf \"\\\"requests\\\": [ \" }/(${search})/{i++;if(i==1)printf \"{ \\\"date\\\": \\\"%s\\\", \\\"time\\\": \\\"%s\\\", \\\"client\\\": \\\"%s\\\", \\\"domain\\\": \\\"%s\\\", \\\"rc\\\": \\\"%s\\\" }\",\$1,\$2,\$3,\$4,\$5;else if(i<=${count})printf \", { \\\"date\\\": \\\"%s\\\", \\\"time\\\": \\\"%s\\\", \\\"client\\\": \\\"%s\\\", \\\"domain\\\": \\\"%s\\\", \\\"rc\\\": \\\"%s\\\" }\",\$1,\$2,\$3,\$4,\$5}END{printf \" ] } }\n\"}" "${adb_reportdir}/adb_report.srt" >> "${adb_reportdir}/adb_report.json"
  1442. rm -f "${adb_reportdir}/adb_report.srt"
  1443. fi
  1444. fi
  1445. if [ -s "${adb_reportdir}/adb_report.json" ]
  1446. then
  1447. if [ "${print}" = "cli" ]
  1448. then
  1449. printf "%s\\n%s\\n%s\\n" ":::" "::: Adblock DNS-Query Report" ":::"
  1450. json_load_file "${adb_reportdir}/adb_report.json"
  1451. json_select "data"
  1452. json_get_keys keylist
  1453. for key in ${keylist}
  1454. do
  1455. json_get_var value "${key}"
  1456. eval "${key}=\"${value}\""
  1457. done
  1458. printf " + %s\\n + %s\\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}"
  1459. printf " + %s\\n + %s %s\\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})"
  1460. top_list="top_clients top_domains top_blocked requests"
  1461. for top in ${top_list}
  1462. do
  1463. case "${top}" in
  1464. "top_clients")
  1465. item="::: Top 10 Clients"
  1466. ;;
  1467. "top_domains")
  1468. item="::: Top 10 Domains"
  1469. ;;
  1470. "top_blocked")
  1471. item="::: Top 10 Blocked Domains"
  1472. ;;
  1473. esac
  1474. if json_get_type status "${top}" && [ "${top}" != "requests" ] && [ "${status}" = "array" ]
  1475. then
  1476. printf "%s\\n%s\\n%s\\n" ":::" "${item}" ":::"
  1477. json_select "${top}"
  1478. index=1
  1479. while json_get_type status "${index}" && [ "${status}" = "object" ]
  1480. do
  1481. json_get_values item "${index}"
  1482. printf " + %-9s::: %s\\n" ${item}
  1483. index=$((index+1))
  1484. done
  1485. elif json_get_type status "${top}" && [ "${top}" = "requests" ] && [ "${status}" = "array" ]
  1486. then
  1487. printf "%s\\n%s\\n%s\\n" ":::" "::: Latest DNS Queries" ":::"
  1488. printf "%-15s%-15s%-45s%-50s%s\\n" "Date" "Time" "Client" "Domain" "Answer"
  1489. json_select "${top}"
  1490. index=1
  1491. while json_get_type status "${index}" && [ "${status}" = "object" ]
  1492. do
  1493. json_get_values item "${index}"
  1494. printf "%-15s%-15s%-45s%-50s%s\\n" ${item}
  1495. index=$((index+1))
  1496. done
  1497. fi
  1498. json_select ".."
  1499. done
  1500. elif [ "${print}" = "json" ]
  1501. then
  1502. cat "${adb_reportdir}/adb_report.json"
  1503. fi
  1504. fi
  1505. fi
  1506. f_log "debug" "f_report ::: action: ${adb_action}, report: ${adb_report}, search: ${1}, count: ${2}, process: ${3}, print: ${4}, dump_util: ${adb_dumpcmd}, repdir: ${adb_reportdir}, repiface: ${adb_repiface:-"-"}, replisten: ${adb_replisten}, repchunksize: ${adb_repchunksize}, repchunkcnt: ${adb_repchunkcnt}, bg_pid: ${bg_pid}"
  1507. }
  1508. # awk selection
  1509. #
  1510. adb_awk="$(command -v gawk)"
  1511. if [ -z "${adb_awk}" ]
  1512. then
  1513. adb_awk="$(command -v awk)"
  1514. fi
  1515. # source required system libraries
  1516. #
  1517. if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
  1518. then
  1519. . "/lib/functions.sh"
  1520. . "/lib/functions/network.sh"
  1521. . "/usr/share/libubox/jshn.sh"
  1522. else
  1523. f_log "err" "system libraries not found"
  1524. fi
  1525. # handle different adblock actions
  1526. #
  1527. f_load
  1528. case "${adb_action}" in
  1529. "stop")
  1530. f_bgserv "stop"
  1531. f_report "+" "50" "false" "false"
  1532. f_rmdns
  1533. ;;
  1534. "restart")
  1535. f_bgserv "stop"
  1536. f_report "+" "50" "false" "false"
  1537. f_rmdns
  1538. f_env
  1539. f_main
  1540. ;;
  1541. "suspend")
  1542. if [ "${adb_dns}" != "raw" ]
  1543. then
  1544. f_switch suspend
  1545. fi
  1546. ;;
  1547. "resume")
  1548. if [ "${adb_dns}" != "raw" ]
  1549. then
  1550. f_switch resume
  1551. fi
  1552. ;;
  1553. "report")
  1554. f_report "${2}" "${3}" "${4}" "${5}"
  1555. ;;
  1556. "query")
  1557. f_query "${2}"
  1558. ;;
  1559. "start"|"reload")
  1560. f_bgserv "stop"
  1561. f_report "+" "50" "false" "false"
  1562. f_env
  1563. f_main
  1564. ;;
  1565. esac