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.

1888 lines
58 KiB

  1. #!/bin/sh
  2. # dns based ad/abuse domain blocking
  3. # Copyright (c) 2015-2022 Dirk Brenken (dev@brenken.org)
  4. # This is free software, licensed under the GNU General Public License v3.
  5. # set (s)hellcheck exceptions
  6. # shellcheck disable=1091,2010,2016,2034,2039,2059,2086,2091,2129,2143,2154,2181,2183,2188,3040,3043,3060
  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_stb_sources" ]
  207. then
  208. eval "${option}=\"$(printf "%s" "${adb_stb_sources}") ${value}\""
  209. elif [ "${option}" = "adb_utc_sources" ]
  210. then
  211. eval "${option}=\"$(printf "%s" "${adb_utc_sources}") ${value}\""
  212. elif [ "${option}" = "adb_denyip" ]
  213. then
  214. eval "${option}=\"$(printf "%s" "${adb_denyip}") ${value}\""
  215. elif [ "${option}" = "adb_allowip" ]
  216. then
  217. eval "${option}=\"$(printf "%s" "${adb_allowip}") ${value}\""
  218. elif [ "${option}" = "adb_safesearchlist" ]
  219. then
  220. eval "${option}=\"$(printf "%s" "${adb_safesearchlist}") ${value}\""
  221. elif [ "${option}" = "adb_zonelist" ]
  222. then
  223. eval "${option}=\"$(printf "%s" "${adb_zonelist}") ${value}\""
  224. elif [ "${option}" = "adb_portlist" ]
  225. then
  226. eval "${option}=\"$(printf "%s" "${adb_portlist}") ${value}\""
  227. fi
  228. }
  229. }
  230. config_load adblock
  231. if [ -z "${adb_fetchutil}" ] || [ -z "${adb_dns}" ]
  232. then
  233. while [ -z "${adb_packages}" ] && [ "${cnt}" -le "${cnt_max}" ]
  234. do
  235. adb_packages="$(opkg list-installed 2>/dev/null)"
  236. cnt=$((cnt+1))
  237. sleep 1
  238. done
  239. if [ -z "${adb_packages}" ]
  240. then
  241. f_log "err" "local opkg package repository is not available, please set 'adb_fetchutil' and 'adb_dns' manually"
  242. fi
  243. fi
  244. }
  245. # status helper function
  246. #
  247. f_char()
  248. {
  249. local result input="${1}"
  250. if [ "${input}" = "1" ]
  251. then
  252. result="✔"
  253. else
  254. result="✘"
  255. fi
  256. printf "%s" "${result}"
  257. }
  258. # load dns backend config
  259. #
  260. f_dns()
  261. {
  262. local util utils dns_up cnt=0
  263. if [ -z "${adb_dns}" ]
  264. then
  265. utils="knot-resolver bind unbound dnsmasq raw"
  266. for util in ${utils}
  267. do
  268. if [ "${util}" = "raw" ] || [ -n "$(printf "%s" "${adb_packages}" | grep "^${util}")" ]
  269. then
  270. if [ "${util}" = "knot-resolver" ]
  271. then
  272. util="kresd"
  273. elif [ "${util}" = "bind" ]
  274. then
  275. util="named"
  276. fi
  277. if [ "${util}" = "raw" ] || [ -x "$(command -v "${util}")" ]
  278. then
  279. adb_dns="${util}"
  280. uci_set adblock global adb_dns "${util}"
  281. f_uci "adblock"
  282. break
  283. fi
  284. fi
  285. done
  286. elif [ "${adb_dns}" != "raw" ] && [ ! -x "$(command -v "${adb_dns}")" ]
  287. then
  288. unset adb_dns
  289. fi
  290. if [ -n "${adb_dns}" ]
  291. then
  292. case "${adb_dns}" in
  293. "dnsmasq")
  294. adb_dnscachecmd="-"
  295. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  296. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  297. adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
  298. adb_dnsdir="${adb_dnsdir:-"/tmp/dnsmasq.d"}"
  299. adb_dnsheader="${adb_dnsheader:-""}"
  300. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"address=/\"\$0\"/\"}'"}"
  301. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"local=/\"\$0\"/#\"}'"}"
  302. adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"address=/\"\$0\"/\"item\"\"}'"}"
  303. adb_dnsstop="${adb_dnsstop:-"address=/#/"}"
  304. ;;
  305. "unbound")
  306. adb_dnscachecmd="$(command -v unbound-control || printf "%s" "-")"
  307. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  308. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  309. adb_dnsuser="${adb_dnsuser:-"unbound"}"
  310. adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
  311. adb_dnsheader="${adb_dnsheader:-""}"
  312. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 static\"}'"}"
  313. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"local-zone: \\042\"\$0\"\\042 transparent\"}'"}"
  314. 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\"}'"}"
  315. adb_dnsstop="${adb_dnsstop:-"local-zone: \".\" static"}"
  316. ;;
  317. "named")
  318. adb_dnscachecmd="$(command -v rndc || printf "%s" "-")"
  319. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  320. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  321. adb_dnsuser="${adb_dnsuser:-"bind"}"
  322. adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
  323. adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n IN NS localhost.\n"}"
  324. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
  325. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
  326. adb_dnsdenyip="${adb_dnsdenyip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME .\"}'"}"
  327. adb_dnsallowip="${adb_dnsallowip:-"${adb_awk} '{print \"\"\$0\".rpz-client-ip CNAME rpz-passthru.\"}'"}"
  328. adb_dnssafesearch="${adb_dnssafesearch:-"${adb_awk} -v item=\"\$item\" '{print \"\"\$0\" CNAME \"item\".\\n*.\"\$0\" CNAME \"item\".\"}'"}"
  329. adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
  330. ;;
  331. "kresd")
  332. adb_dnscachecmd="-"
  333. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  334. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  335. adb_dnsuser="${adb_dnsuser:-"root"}"
  336. adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
  337. adb_dnsheader="${adb_dnsheader:-"\$TTL 2h\n@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)\n"}"
  338. adb_dnsdeny="${adb_dnsdeny:-"${adb_awk} '{print \"\"\$0\" CNAME .\\n*.\"\$0\" CNAME .\"}'"}"
  339. adb_dnsallow="${adb_dnsallow:-"${adb_awk} '{print \"\"\$0\" CNAME rpz-passthru.\\n*.\"\$0\" CNAME rpz-passthru.\"}'"}"
  340. 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\"\"}'"}"
  341. adb_dnsstop="${adb_dnsstop:-"* CNAME ."}"
  342. ;;
  343. "raw")
  344. adb_dnscachecmd="-"
  345. adb_dnsinotify="${adb_dnsinotify:-"0"}"
  346. adb_dnsinstance="${adb_dnsinstance:-"0"}"
  347. adb_dnsuser="${adb_dnsuser:-"root"}"
  348. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  349. adb_dnsheader="${adb_dnsheader:-""}"
  350. adb_dnsdeny="${adb_dnsdeny:-"0"}"
  351. adb_dnsallow="${adb_dnsallow:-"1"}"
  352. adb_dnssafesearch="${adb_dnssafesearch:-"0"}"
  353. adb_dnsstop="${adb_dnsstop:-"0"}"
  354. ;;
  355. esac
  356. fi
  357. if [ "${adb_dns}" != "raw" ] && { [ -z "${adb_dns}" ] || [ ! -x "$(command -v "${adb_dns}")" ]; }
  358. then
  359. f_log "err" "dns backend not found, please set 'adb_dns' manually"
  360. fi
  361. if [ "${adb_dns}" != "raw" ] && { [ "${adb_dnsdir}" = "${adb_tmpbase}" ] || [ "${adb_dnsdir}" = "${adb_backupdir}" ] || [ "${adb_dnsdir}" = "${adb_reportdir}" ]; }
  362. then
  363. f_log "err" "dns directory '${adb_dnsdir}' has been misconfigured, it must not point to the 'adb_tmpbase', 'adb_backupdir', 'adb_reportdir'"
  364. fi
  365. if [ "${adb_action}" = "start" ] && [ -z "${adb_trigger}" ]
  366. then
  367. sleep ${adb_triggerdelay}
  368. fi
  369. if [ "${adb_dns}" != "raw" ] && [ "${adb_action}" != "stop" ]
  370. then
  371. while [ "${cnt}" -le 30 ]
  372. do
  373. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
  374. if [ "${dns_up}" = "true" ]
  375. then
  376. break
  377. fi
  378. sleep 1
  379. cnt=$((cnt+1))
  380. done
  381. fi
  382. if [ "${adb_action}" != "stop" ]
  383. then
  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 -Iseconds)"
  1241. else
  1242. runtime="${adb_action}, n/a, ${memory:-0}, $(date -Iseconds)"
  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}" = "utcapitole" ] && [ -n "${adb_utc_sources}" ]
  1418. then
  1419. src_cat="${adb_utc_sources}"
  1420. if [ -n "${src_cat}" ]
  1421. then
  1422. (
  1423. src_arc="${adb_tmpdir}/${src_url##*/}"
  1424. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_arc}" "${src_url}" 2>&1)"
  1425. src_rc="${?}"
  1426. if [ "${src_rc}" = "0" ] && [ -s "${src_arc}" ]
  1427. then
  1428. src_suffix="$(eval printf "%s" \"\$\{adb_src_suffix_${src_name}:-\"domains\"\}\")"
  1429. src_list="$(tar -tzf "${src_arc}" 2>/dev/null)"
  1430. for src_item in ${src_cat}
  1431. do
  1432. src_entries="${src_entries} $(printf "%s" "${src_list}" | grep -E "${src_item}/${src_suffix}$")"
  1433. done
  1434. if [ -n "${src_entries}" ]
  1435. then
  1436. tar -xOzf "${src_arc}" ${src_entries} 2>/dev/null > "${src_tmpload}"
  1437. src_rc="${?}"
  1438. fi
  1439. > "${src_arc}"
  1440. else
  1441. src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
  1442. f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
  1443. fi
  1444. if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]
  1445. then
  1446. if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]
  1447. then
  1448. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1449. grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1450. else
  1451. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1452. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1453. fi
  1454. > "${src_tmpload}"
  1455. "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
  1456. src_rc="${?}"
  1457. > "${src_tmpsort}"
  1458. if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]
  1459. then
  1460. f_list download
  1461. if [ "${adb_backup}" = "1" ]
  1462. then
  1463. f_list backup
  1464. fi
  1465. elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
  1466. then
  1467. f_log "info" "archive preparation of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
  1468. f_list restore
  1469. rm -f "${src_tmpfile}"
  1470. fi
  1471. elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
  1472. then
  1473. f_log "info" "archive extraction of '${src_name}' failed, categories: ${src_cat:-"-"}, entries: ${src_entries}, rc: ${src_rc}"
  1474. f_list restore
  1475. fi
  1476. )&
  1477. fi
  1478. else
  1479. if [ "${src_name}" = "energized" ] && [ -n "${adb_eng_sources}" ]
  1480. then
  1481. src_cat="${adb_eng_sources}"
  1482. elif [ "${src_name}" = "stevenblack" ] && [ -n "${adb_stb_sources}" ]
  1483. then
  1484. src_cat="${adb_stb_sources}"
  1485. elif { [ "${src_name}" = "energized" ] && [ -z "${adb_eng_sources}" ]; } || \
  1486. { [ "${src_name}" = "stevenblack" ] && [ -z "${adb_stb_sources}" ]; }
  1487. then
  1488. continue
  1489. fi
  1490. (
  1491. for suffix in ${src_cat:-${src_url}}
  1492. do
  1493. if [ "${src_url}" != "${suffix}" ]
  1494. then
  1495. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpcat}" "${src_url}${suffix}" 2>&1)"
  1496. src_rc="${?}"
  1497. if [ "${src_rc}" = "0" ] && [ -s "${src_tmpcat}" ]
  1498. then
  1499. cat "${src_tmpcat}" >> "${src_tmpload}"
  1500. > "${src_tmpcat}"
  1501. fi
  1502. else
  1503. src_log="$("${adb_fetchutil}" ${adb_fetchparm} "${src_tmpload}" "${src_url}" 2>&1)"
  1504. src_rc="${?}"
  1505. fi
  1506. done
  1507. if [ "${src_rc}" = "0" ] && [ -s "${src_tmpload}" ]
  1508. then
  1509. if [ -s "${adb_tmpdir}/tmp.rem.whitelist" ]
  1510. then
  1511. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1512. grep -Evf "${adb_tmpdir}/tmp.rem.whitelist" | "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1513. else
  1514. "${adb_awk}" "${src_rset}" "${src_tmpload}" | sed "s/\r//g" | \
  1515. "${adb_awk}" 'BEGIN{FS="."}{for(f=NF;f>1;f--)printf "%s.",$f;print $1}' > "${src_tmpsort}"
  1516. fi
  1517. > "${src_tmpload}"
  1518. "${adb_sort}" ${adb_srtopts} -u "${src_tmpsort}" 2>/dev/null > "${src_tmpfile}"
  1519. src_rc="${?}"
  1520. > "${src_tmpsort}"
  1521. if [ "${src_rc}" = "0" ] && [ -s "${src_tmpfile}" ]
  1522. then
  1523. f_list download
  1524. if [ "${adb_backup}" = "1" ]
  1525. then
  1526. f_list backup
  1527. fi
  1528. elif [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
  1529. then
  1530. f_log "info" "preparation of '${src_name}' failed, rc: ${src_rc}"
  1531. f_list restore
  1532. rm -f "${src_tmpfile}"
  1533. fi
  1534. else
  1535. src_log="$(printf "%s" "${src_log}" | "${adb_awk}" '{ORS=" ";print $0}')"
  1536. f_log "info" "download of '${src_name}' failed, url: ${src_url}, rule: ${src_rset:-"-"}, categories: ${src_cat:-"-"}, rc: ${src_rc}, log: ${src_log:-"-"}"
  1537. if [ "${adb_backup}" = "1" ] && [ "${adb_action}" != "start" ]
  1538. then
  1539. f_list restore
  1540. fi
  1541. fi
  1542. )&
  1543. fi
  1544. hold=$((cnt%adb_maxqueue))
  1545. if [ "${hold}" = "0" ]
  1546. then
  1547. wait
  1548. fi
  1549. cnt=$((cnt+1))
  1550. done
  1551. wait
  1552. f_list merge
  1553. # tld compression and dns restart
  1554. #
  1555. if [ "${?}" = "0" ] && [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  1556. then
  1557. f_tld "${adb_tmpdir}/${adb_dnsfile}"
  1558. f_list final
  1559. else
  1560. printf "${adb_dnsheader}" > "${adb_dnsdir}/${adb_dnsfile}"
  1561. fi
  1562. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  1563. f_dnsup
  1564. if [ "${?}" = "0" ]
  1565. then
  1566. if [ "${adb_action}" != "resume" ]
  1567. then
  1568. f_jsnup "enabled"
  1569. fi
  1570. f_log "info" "blocklist with overall ${adb_cnt} blocked domains loaded successfully (${adb_sysver})"
  1571. else
  1572. f_log "err" "dns backend restart with adblock blocklist failed"
  1573. fi
  1574. f_rmtemp
  1575. }
  1576. # trace dns queries via tcpdump and prepare a report
  1577. #
  1578. f_report()
  1579. {
  1580. 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:-"+"}"
  1581. report_raw="${adb_reportdir}/adb_report.raw"
  1582. report_srt="${adb_reportdir}/adb_report.srt"
  1583. report_jsn="${adb_reportdir}/adb_report.json"
  1584. report_txt="${adb_reportdir}/adb_mailreport.txt"
  1585. # build json file
  1586. #
  1587. if [ "${action}" != "json" ]
  1588. then
  1589. > "${report_raw}"
  1590. > "${report_srt}"
  1591. > "${report_txt}"
  1592. > "${report_jsn}"
  1593. if [ "${adb_represolve}" = "1" ]
  1594. then
  1595. resolve=""
  1596. fi
  1597. for file in "${adb_reportdir}/adb_report.pcap"*
  1598. do
  1599. (
  1600. "${adb_dumpcmd}" "${resolve}" -tttt -r "${file}" 2>/dev/null | \
  1601. "${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);
  1602. 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}"
  1603. )&
  1604. hold=$((cnt%adb_maxqueue))
  1605. if [ "${hold}" = "0" ]
  1606. then
  1607. wait
  1608. fi
  1609. cnt=$((cnt+1))
  1610. done
  1611. wait
  1612. if [ -s "${report_raw}" ]
  1613. then
  1614. "${adb_sort}" ${adb_srtopts} -k1 -k3 -k4 -k5 -k1 -ur "${report_raw}" | \
  1615. "${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}}' | \
  1616. "${adb_sort}" ${adb_srtopts} -k1 -k2 -k3 -k4 -ur > "${report_srt}"
  1617. rm -f "${report_raw}"
  1618. fi
  1619. if [ -s "${report_srt}" ]
  1620. then
  1621. start="$("${adb_awk}" 'END{printf "%s_%s",$1,$2}' "${report_srt}")"
  1622. end="$("${adb_awk}" 'NR==1{printf "%s_%s",$1,$2}' "${report_srt}")"
  1623. total="$(wc -l < "${report_srt}")"
  1624. blocked="$("${adb_awk}" '{if($5=="NX")cnt++}END{printf "%s",cnt}' "${report_srt}")"
  1625. percent="$("${adb_awk}" -v t="${total}" -v b="${blocked}" 'BEGIN{printf "%.2f%s",b/t*100,"%"}')"
  1626. > "${report_jsn}"
  1627. printf "%s\n" "{ " >> "${report_jsn}"
  1628. printf "\t%s\n" "\"start_date\": \"${start%_*}\", " >> "${report_jsn}"
  1629. printf "\t%s\n" "\"start_time\": \"${start#*_}\", " >> "${report_jsn}"
  1630. printf "\t%s\n" "\"end_date\": \"${end%_*}\", " >> "${report_jsn}"
  1631. printf "\t%s\n" "\"end_time\": \"${end#*_}\", " >> "${report_jsn}"
  1632. printf "\t%s\n" "\"total\": \"${total}\", " >> "${report_jsn}"
  1633. printf "\t%s\n" "\"blocked\": \"${blocked}\", " >> "${report_jsn}"
  1634. printf "\t%s\n" "\"percent\": \"${percent}\", " >> "${report_jsn}"
  1635. top_list="top_clients top_domains top_blocked"
  1636. for top in ${top_list}
  1637. do
  1638. printf "\t%s" "\"${top}\": [ " >> "${report_jsn}"
  1639. case "${top}" in
  1640. "top_clients")
  1641. "${adb_awk}" '{print $3}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c | \
  1642. "${adb_sort}" ${adb_srtopts} -nr | \
  1643. "${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}"
  1644. ;;
  1645. "top_domains")
  1646. "${adb_awk}" '{if($5!="NX")print $4}' "${report_srt}" | "${adb_sort}" ${adb_srtopts} | uniq -c | \
  1647. "${adb_sort}" ${adb_srtopts} -nr | \
  1648. "${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}"
  1649. ;;
  1650. "top_blocked")
  1651. "${adb_awk}" '{if($5=="NX")print $4}' "${report_srt}" | \
  1652. "${adb_sort}" ${adb_srtopts} | uniq -c | "${adb_sort}" ${adb_srtopts} -nr | \
  1653. "${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}"
  1654. ;;
  1655. esac
  1656. printf "\n\t%s\n" "]," >> "${report_jsn}"
  1657. done
  1658. search="${search//./\\.}"
  1659. search="${search//[+*~%\$&\"\' ]/}"
  1660. "${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}"
  1661. rm -f "${report_srt}"
  1662. fi
  1663. fi
  1664. # output preparation
  1665. #
  1666. if [ -s "${report_jsn}" ] && { [ "${action}" = "cli" ] || [ "${action}" = "mail" ]; }
  1667. then
  1668. printf "%s\n%s\n%s\n" ":::" "::: Adblock DNS-Query Report" ":::" >> "${report_txt}"
  1669. json_init
  1670. json_load_file "${report_jsn}"
  1671. json_get_keys key_list
  1672. for key in ${key_list}
  1673. do
  1674. json_get_var value "${key}"
  1675. eval "${key}=\"${value}\""
  1676. done
  1677. printf " + %s\n + %s\n" "Start ::: ${start_date}, ${start_time}" "End ::: ${end_date}, ${end_time}" >> "${report_txt}"
  1678. printf " + %s\n + %s %s\n" "Total ::: ${total}" "Blocked ::: ${blocked}" "(${percent})" >> "${report_txt}"
  1679. top_list="top_clients top_domains top_blocked requests"
  1680. for top in ${top_list}
  1681. do
  1682. case "${top}" in
  1683. "top_clients")
  1684. item="::: Top 10 Clients"
  1685. ;;
  1686. "top_domains")
  1687. item="::: Top 10 Domains"
  1688. ;;
  1689. "top_blocked")
  1690. item="::: Top 10 Blocked Domains"
  1691. ;;
  1692. esac
  1693. if json_get_type status "${top}" && [ "${top}" != "requests" ] && [ "${status}" = "array" ]
  1694. then
  1695. printf "%s\n%s\n%s\n" ":::" "${item}" ":::" >> "${report_txt}"
  1696. json_select "${top}"
  1697. index=1
  1698. item=""
  1699. while json_get_type status "${index}" && [ "${status}" = "object" ]
  1700. do
  1701. json_get_values item "${index}"
  1702. printf " + %-9s::: %s\n" ${item} >> "${report_txt}"
  1703. index=$((index+1))
  1704. done
  1705. elif json_get_type status "${top}" && [ "${top}" = "requests" ] && [ "${status}" = "array" ]
  1706. then
  1707. printf "%s\n%s\n%s\n" ":::" "::: Latest DNS Queries" ":::" >> "${report_txt}"
  1708. printf "%-15s%-15s%-45s%-80s%s\n" "Date" "Time" "Client" "Domain" "Answer" >> "${report_txt}"
  1709. json_select "${top}"
  1710. index=1
  1711. while json_get_type status "${index}" && [ "${status}" = "object" ]
  1712. do
  1713. json_get_values item "${index}"
  1714. printf "%-15s%-15s%-45s%-80s%s\n" ${item} >> "${report_txt}"
  1715. index=$((index+1))
  1716. done
  1717. fi
  1718. json_select ".."
  1719. done
  1720. content="$(cat "${report_txt}" 2>/dev/null)"
  1721. rm -f "${report_txt}"
  1722. fi
  1723. # report output
  1724. #
  1725. if [ "${action}" = "cli" ]
  1726. then
  1727. printf "%s\n" "${content}"
  1728. elif [ "${action}" = "json" ]
  1729. then
  1730. cat "${report_jsn}"
  1731. elif [ "${action}" = "mail" ] && [ "${adb_mail}" = "1" ] && [ -x "${adb_mailservice}" ]
  1732. then
  1733. ( "${adb_mailservice}" "${adb_ver}" "${content}" >/dev/null 2>&1 )&
  1734. bg_pid="${!}"
  1735. fi
  1736. 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}"
  1737. }
  1738. # source required system libraries
  1739. #
  1740. if [ -r "/lib/functions.sh" ] && [ -r "/lib/functions/network.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
  1741. then
  1742. . "/lib/functions.sh"
  1743. . "/lib/functions/network.sh"
  1744. . "/usr/share/libubox/jshn.sh"
  1745. else
  1746. f_log "err" "system libraries not found"
  1747. fi
  1748. # version information
  1749. #
  1750. if [ "${adb_action}" = "version" ]
  1751. then
  1752. printf "%s\n" "${adb_ver}"
  1753. exit 0
  1754. fi
  1755. # awk check
  1756. #
  1757. adb_awk="$(command -v gawk)"
  1758. if [ ! -x "${adb_awk}" ]
  1759. then
  1760. adb_awk="$(command -v awk)"
  1761. if [ ! -x "${adb_awk}" ]
  1762. then
  1763. f_log "err" "awk not found or not executable"
  1764. fi
  1765. fi
  1766. # sort check
  1767. #
  1768. adb_sort="$(command -v sort)"
  1769. if [ ! -x "${adb_sort}" ] || [ "$("${adb_sort}" --version 2>/dev/null | grep -c "coreutils")" = "0" ]
  1770. then
  1771. f_log "err" "coreutils sort not found or not executable"
  1772. fi
  1773. # handle different adblock actions
  1774. #
  1775. f_load
  1776. case "${adb_action}" in
  1777. "stop")
  1778. f_rmdns
  1779. ;;
  1780. "restart")
  1781. f_rmdns
  1782. f_env
  1783. f_main
  1784. ;;
  1785. "suspend")
  1786. if [ "${adb_dns}" != "raw" ]
  1787. then
  1788. f_switch suspend
  1789. fi
  1790. ;;
  1791. "resume")
  1792. if [ "${adb_dns}" != "raw" ]
  1793. then
  1794. f_switch resume
  1795. fi
  1796. ;;
  1797. "report")
  1798. f_report "${2}" "${3}" "${4}"
  1799. ;;
  1800. "query")
  1801. f_query "${2}"
  1802. ;;
  1803. "start"|"reload")
  1804. f_env
  1805. f_main
  1806. ;;
  1807. esac