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.

1873 lines
58 KiB

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