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.

1713 lines
53 KiB

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