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.

1482 lines
56 KiB

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