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.

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