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.

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