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.

1372 lines
40 KiB

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