adblock.sh 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. #!/bin/sh
  2. # dns based ad/abuse domain blocking
  3. # written by Dirk Brenken (dev@brenken.org)
  4. # This is free software, licensed under the GNU General Public License v3.
  5. # You should have received a copy of the GNU General Public License
  6. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  7. # set initial defaults
  8. #
  9. LC_ALL=C
  10. PATH="/usr/sbin:/usr/bin:/sbin:/bin"
  11. adb_ver="3.1.1"
  12. adb_sysver="unknown"
  13. adb_enabled=0
  14. adb_debug=0
  15. adb_backup_mode=0
  16. adb_whitelist_mode=0
  17. adb_forcesrt=0
  18. adb_forcedns=0
  19. adb_triggerdelay=0
  20. adb_backup=0
  21. adb_backupdir="/mnt"
  22. adb_fetch="/usr/bin/wget"
  23. adb_fetchparm="--quiet --no-cache --no-cookies --max-redirect=0 --timeout=10 --no-check-certificate -O"
  24. adb_dns="dnsmasq"
  25. adb_dnsprefix="adb_list"
  26. adb_dnsfile="${adb_dnsprefix}.overall"
  27. adb_whitelist="/etc/adblock/adblock.whitelist"
  28. adb_rtfile="/tmp/adb_runtime.json"
  29. adb_hashsum="$(command -v sha256sum)"
  30. adb_action="${1:-"start"}"
  31. adb_cnt=0
  32. adb_rc=0
  33. # f_envload: load adblock environment
  34. #
  35. f_envload()
  36. {
  37. local dns_up sys_call sys_desc sys_model sys_ver cnt=0
  38. # get system information
  39. #
  40. sys_call="$(ubus -S call system board 2>/dev/null)"
  41. if [ -n "${sys_call}" ]
  42. then
  43. sys_desc="$(printf '%s' "${sys_call}" | jsonfilter -e '@.release.description')"
  44. sys_model="$(printf '%s' "${sys_call}" | jsonfilter -e '@.model')"
  45. sys_ver="$(cat /etc/turris-version 2>/dev/null)"
  46. if [ -n "${sys_ver}" ]
  47. then
  48. sys_desc="${sys_desc}/${sys_ver}"
  49. fi
  50. adb_sysver="${sys_model}, ${sys_desc}"
  51. fi
  52. # source in system libraries
  53. #
  54. if [ -r "/lib/functions.sh" ] && [ -r "/usr/share/libubox/jshn.sh" ]
  55. then
  56. . "/lib/functions.sh"
  57. . "/usr/share/libubox/jshn.sh"
  58. else
  59. f_log "error" "system libraries not found"
  60. fi
  61. # parse 'global' and 'extra' section by callback
  62. #
  63. config_cb()
  64. {
  65. local type="${1}"
  66. if [ "${type}" = "adblock" ]
  67. then
  68. option_cb()
  69. {
  70. local option="${1}"
  71. local value="${2}"
  72. eval "${option}=\"${value}\""
  73. }
  74. else
  75. reset_cb
  76. fi
  77. }
  78. # parse 'source' typed sections
  79. #
  80. parse_config()
  81. {
  82. local value opt section="${1}" options="enabled adb_src adb_src_rset adb_src_cat"
  83. eval "adb_sources=\"${adb_sources} ${section}\""
  84. for opt in ${options}
  85. do
  86. config_get value "${section}" "${opt}"
  87. if [ -n "${value}" ]
  88. then
  89. eval "${opt}_${section}=\"${value}\""
  90. fi
  91. done
  92. }
  93. # load adblock config
  94. #
  95. config_load adblock
  96. config_foreach parse_config source
  97. # set/check dns backend environment
  98. #
  99. case "${adb_dns}" in
  100. dnsmasq)
  101. adb_dnsuser="${adb_dnsuser:-"dnsmasq"}"
  102. adb_dnsdir="${adb_dnsdir:-"/tmp/dnsmasq.d"}"
  103. adb_dnsformat="awk '{print \"local=/\"\$0\"/\"}'"
  104. if [ ${adb_whitelist_mode} -eq 1 ]
  105. then
  106. adb_dnsformat="awk '{print \"local=/\"\$0\"/#\"}'"
  107. adb_dnsblock="local=/#/"
  108. fi
  109. ;;
  110. unbound)
  111. adb_dnsuser="${adb_dnsuser:-"unbound"}"
  112. adb_dnsdir="${adb_dnsdir:-"/var/lib/unbound"}"
  113. adb_dnsformat="awk '{print \"local-zone: \042\"\$0\"\042 static\"}'"
  114. if [ ${adb_whitelist_mode} -eq 1 ]
  115. then
  116. adb_dnsformat="awk '{print \"local-zone: \042\"\$0\"\042 transparent\"}'"
  117. adb_dnsblock="local-zone: \".\" static"
  118. fi
  119. ;;
  120. named)
  121. adb_dnsuser="${adb_dnsuser:-"bind"}"
  122. adb_dnsdir="${adb_dnsdir:-"/var/lib/bind"}"
  123. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  124. adb_dnsformat="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  125. if [ ${adb_whitelist_mode} -eq 1 ]
  126. then
  127. adb_dnsformat="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  128. adb_dnsblock="* CNAME ."
  129. fi
  130. ;;
  131. kresd)
  132. adb_dnsuser="${adb_dnsuser:-"root"}"
  133. adb_dnsdir="${adb_dnsdir:-"/etc/kresd"}"
  134. adb_dnsheader="\$TTL 2h"$'\n'"@ IN SOA localhost. root.localhost. (1 6h 1h 1w 2h)"$'\n'" IN NS localhost."
  135. adb_dnsformat="awk '{print \"\"\$0\" CNAME .\n*.\"\$0\" CNAME .\"}'"
  136. if [ ${adb_whitelist_mode} -eq 1 ]
  137. then
  138. adb_dnsformat="awk '{print \"\"\$0\" CNAME rpz-passthru.\n*.\"\$0\" CNAME rpz-passthru.\"}'"
  139. adb_dnsblock="* CNAME ."
  140. fi
  141. ;;
  142. dnscrypt-proxy)
  143. adb_dnsuser="${adb_dnsuser:-"nobody"}"
  144. adb_dnsdir="${adb_dnsdir:-"/tmp"}"
  145. adb_dnsformat="awk '{print \$0}'"
  146. ;;
  147. esac
  148. # check adblock status
  149. #
  150. if [ ${adb_enabled} -eq 0 ]
  151. then
  152. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
  153. then
  154. f_rmdns
  155. f_dnsrestart
  156. fi
  157. f_extconf
  158. f_jsnupdate
  159. f_log "info " "adblock is currently disabled, please set adb_enabled to '1' to use this service"
  160. exit 0
  161. fi
  162. if [ -d "${adb_dnsdir}" ] && [ ! -f "${adb_dnsdir}/${adb_dnsfile}" ]
  163. then
  164. > "${adb_dnsdir}/${adb_dnsfile}"
  165. fi
  166. case "${adb_action}" in
  167. start|restart|reload)
  168. > "${adb_rtfile}"
  169. if [ "${adb_action}" = "start" ] && [ "${adb_trigger}" = "timed" ]
  170. then
  171. sleep ${adb_triggerdelay}
  172. fi
  173. ;;
  174. esac
  175. while [ ${cnt} -le 30 ]
  176. do
  177. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" 2>/dev/null | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running" 2>/dev/null)"
  178. if [ "${dns_up}" = "true" ]
  179. then
  180. break
  181. fi
  182. sleep 1
  183. cnt=$((cnt+1))
  184. done
  185. if [ -z "${adb_dns}" ] || [ -z "${adb_dnsformat}" ] || [ ! -x "$(command -v ${adb_dns})" ] || [ ! -d "${adb_dnsdir}" ]
  186. then
  187. f_log "error" "'${adb_dns}' not running, DNS backend not found"
  188. fi
  189. }
  190. # f_envcheck: check/set environment prerequisites
  191. #
  192. f_envcheck()
  193. {
  194. local ssl_lib
  195. # check external uci config files
  196. #
  197. f_extconf
  198. # check fetch utility
  199. #
  200. ssl_lib="-"
  201. if [ -x "${adb_fetch}" ]
  202. then
  203. if [ "$(readlink -fn "${adb_fetch}")" = "/usr/bin/wget-nossl" ]
  204. then
  205. adb_fetchparm="--quiet --no-cache --no-cookies --max-redirect=0 --timeout=10 -O"
  206. elif [ "$(readlink -fn "${adb_fetch}")" = "/bin/busybox" ] ||
  207. ([ "$(readlink -fn "/bin/wget")" = "/bin/busybox" ] && [ "$(readlink -fn "${adb_fetch}")" != "/usr/bin/wget" ])
  208. then
  209. adb_fetch="/bin/busybox"
  210. adb_fetchparm="-q -O"
  211. else
  212. ssl_lib="built-in"
  213. fi
  214. fi
  215. if [ ! -x "${adb_fetch}" ] && [ "$(readlink -fn "/bin/wget")" = "/bin/uclient-fetch" ]
  216. then
  217. adb_fetch="/bin/uclient-fetch"
  218. if [ -f "/lib/libustream-ssl.so" ]
  219. then
  220. adb_fetchparm="-q --timeout=10 --no-check-certificate -O"
  221. ssl_lib="libustream-ssl"
  222. else
  223. adb_fetchparm="-q --timeout=10 -O"
  224. fi
  225. fi
  226. if [ ! -x "${adb_fetch}" ] || [ -z "${adb_fetch}" ] || [ -z "${adb_fetchparm}" ]
  227. then
  228. f_log "error" "no download utility found, please install 'uclient-fetch' with 'libustream-mbedtls' or the full 'wget' package"
  229. fi
  230. adb_fetchinfo="${adb_fetch##*/} (${ssl_lib})"
  231. # check hashsum utility
  232. #
  233. if [ ! -x "${adb_hashsum}" ]
  234. then
  235. adb_hashsum="$(command -v md5sum)"
  236. fi
  237. # initialize temp files and directories
  238. #
  239. adb_tmpload="$(mktemp -tu)"
  240. adb_tmpfile="$(mktemp -tu)"
  241. adb_tmpdir="$(mktemp -p /tmp -d)"
  242. > "${adb_tmpdir}/tmp.whitelist"
  243. }
  244. # f_extconf: set external config options
  245. #
  246. f_extconf()
  247. {
  248. # kresd related options
  249. #
  250. if [ "${adb_dns}" = "kresd" ]
  251. then
  252. if [ ${adb_enabled} -eq 1 ] && [ -z "$(uci -q get resolver.kresd.rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  253. then
  254. uci -q add_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  255. elif [ ${adb_enabled} -eq 0 ] && [ -n "$(uci -q get resolver.kresd.rpz_file | grep -Fo "${adb_dnsdir}/${adb_dnsfile}")" ]
  256. then
  257. uci -q del_list resolver.kresd.rpz_file="${adb_dnsdir}/${adb_dnsfile}"
  258. fi
  259. if [ -n "$(uci -q changes resolver)" ]
  260. then
  261. uci -q commit resolver
  262. fi
  263. fi
  264. # firewall related options
  265. #
  266. if [ ${adb_enabled} -eq 1 ] && [ ${adb_forcedns} -eq 1 ] && [ -z "$(uci -q get firewall.adblock_dns)" ]
  267. then
  268. uci -q set firewall.adblock_dns="redirect"
  269. uci -q set firewall.adblock_dns.name="Adblock DNS"
  270. uci -q set firewall.adblock_dns.src="lan"
  271. uci -q set firewall.adblock_dns.proto="tcp udp"
  272. uci -q set firewall.adblock_dns.src_dport="53"
  273. uci -q set firewall.adblock_dns.dest_port="53"
  274. uci -q set firewall.adblock_dns.target="DNAT"
  275. elif [ -n "$(uci -q get firewall.adblock_dns)" ] && ([ ${adb_enabled} -eq 0 ] || [ ${adb_forcedns} -eq 0 ])
  276. then
  277. uci -q delete firewall.adblock_dns
  278. fi
  279. if [ -n "$(uci -q changes firewall)" ]
  280. then
  281. uci -q commit firewall
  282. if [ $(/etc/init.d/firewall enabled; printf "%u" ${?}) -eq 0 ]
  283. then
  284. /etc/init.d/firewall reload >/dev/null 2>&1
  285. fi
  286. fi
  287. }
  288. # f_rmtemp: remove temporary files & directories
  289. #
  290. f_rmtemp()
  291. {
  292. if [ -d "${adb_tmpdir}" ]
  293. then
  294. rm -f "${adb_tmpload}"
  295. rm -f "${adb_tmpfile}"
  296. rm -rf "${adb_tmpdir}"
  297. fi
  298. }
  299. # f_rmdns: remove dns related files & directories
  300. #
  301. f_rmdns()
  302. {
  303. if [ -n "${adb_dns}" ]
  304. then
  305. > "${adb_dnsdir}/${adb_dnsfile}"
  306. > "${adb_rtfile}"
  307. rm -f "${adb_dnsdir}/.${adb_dnsfile}"
  308. rm -f "${adb_backupdir}/${adb_dnsprefix}"*.gz
  309. fi
  310. }
  311. # f_dnsrestart: restart the dns backend
  312. #
  313. f_dnsrestart()
  314. {
  315. local dns_up cnt=0
  316. "/etc/init.d/${adb_dns}" restart >/dev/null 2>&1
  317. while [ ${cnt} -le 10 ]
  318. do
  319. dns_up="$(ubus -S call service list "{\"name\":\"${adb_dns}\"}" | jsonfilter -l1 -e "@[\"${adb_dns}\"].instances.*.running")"
  320. if [ "${dns_up}" = "true" ]
  321. then
  322. return 0
  323. fi
  324. cnt=$((cnt+1))
  325. sleep 1
  326. done
  327. return 1
  328. }
  329. # f_list: backup/restore/remove blocklists
  330. #
  331. f_list()
  332. {
  333. local mode="${1}" in_rc="${adb_rc}" cnt=0
  334. case "${mode}" in
  335. backup)
  336. cnt="$(wc -l < "${adb_tmpfile}")"
  337. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ]
  338. then
  339. gzip -cf "${adb_tmpfile}" > "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  340. adb_rc=${?}
  341. fi
  342. ;;
  343. restore)
  344. if [ ${adb_backup} -eq 1 ] && [ -d "${adb_backupdir}" ] &&
  345. [ -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" ]
  346. then
  347. gunzip -cf "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz" > "${adb_tmpfile}"
  348. adb_rc=${?}
  349. fi
  350. ;;
  351. remove)
  352. if [ -d "${adb_backupdir}" ]
  353. then
  354. rm -f "${adb_backupdir}/${adb_dnsprefix}.${src_name}.gz"
  355. fi
  356. adb_rc=${?}
  357. ;;
  358. merge)
  359. if [ -s "${adb_tmpfile}" ]
  360. then
  361. cat "${adb_tmpfile}" >> "${adb_tmpdir}/${adb_dnsfile}"
  362. adb_rc=${?}
  363. fi
  364. ;;
  365. format)
  366. if [ -s "${adb_tmpdir}/tmp.whitelist" ]
  367. then
  368. grep -vf "${adb_tmpdir}/tmp.whitelist" "${adb_tmpdir}/${adb_dnsfile}" | eval "${adb_dnsformat}" > "${adb_dnsdir}/${adb_dnsfile}"
  369. else
  370. eval "${adb_dnsformat}" "${adb_tmpdir}/${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  371. fi
  372. if [ -n "${adb_dnsheader}" ]
  373. then
  374. printf '%s\n' "${adb_dnsheader}" | cat - "${adb_dnsdir}/${adb_dnsfile}" > "${adb_tmpdir}/${adb_dnsfile}"
  375. cat "${adb_tmpdir}/${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  376. fi
  377. adb_rc=${?}
  378. ;;
  379. esac
  380. f_log "debug" "name: ${src_name}, mode: ${mode}, count: ${cnt}, in_rc: ${in_rc}, out_rc: ${adb_rc}"
  381. }
  382. # f_tldcompression: top level domain compression
  383. #
  384. f_tldcompression()
  385. {
  386. local source="${1}" temp="${adb_tmpload}"
  387. awk -F "." '{for(f=NF;f > 1;f--) printf "%s.", $f;print $1}' "${source}" 2>/dev/null | sort -u > "${temp}"
  388. awk '{if(NR==1){tld=$NF};while(getline){if($NF !~ tld"\\."){print tld;tld=$NF}}print tld}' "${temp}" 2>/dev/null > "${source}"
  389. awk -F "." '{for(f=NF;f > 1;f--) printf "%s.", $f;print $1}' "${source}" 2>/dev/null > "${temp}"
  390. sort -u "${temp}" > "${source}"
  391. }
  392. # f_switch: suspend/resume adblock processing
  393. #
  394. f_switch()
  395. {
  396. local source target status mode="${1}"
  397. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ] && [ "${mode}" = "suspend" ]
  398. then
  399. source="${adb_dnsdir}/${adb_dnsfile}"
  400. target="${adb_dnsdir}/.${adb_dnsfile}"
  401. status="suspended"
  402. elif [ -s "${adb_dnsdir}/.${adb_dnsfile}" ] && [ "${mode}" = "resume" ]
  403. then
  404. source="${adb_dnsdir}/.${adb_dnsfile}"
  405. target="${adb_dnsdir}/${adb_dnsfile}"
  406. status="resumed"
  407. fi
  408. if [ -n "${status}" ]
  409. then
  410. cat "${source}" > "${target}"
  411. > "${source}"
  412. chown "${adb_dnsuser}" "${target}" 2>/dev/null
  413. f_dnsrestart
  414. f_jsnupdate
  415. f_log "info " "adblock processing ${status}"
  416. fi
  417. }
  418. # f_query: query blocklist for certain (sub-)domains
  419. #
  420. f_query()
  421. {
  422. local search result cnt
  423. local domain="${1}"
  424. local tld="${domain#*.}"
  425. if [ ! -s "${adb_dnsdir}/${adb_dnsfile}" ]
  426. then
  427. printf "%s\n" "::: no active blocklist found, please start / resume adblock first"
  428. elif [ -z "${domain}" ] || [ "${domain}" = "${tld}" ]
  429. then
  430. printf "%s\n" "::: invalid domain input, please submit a single domain, e.g. 'doubleclick.net'"
  431. else
  432. cd "${adb_dnsdir}"
  433. while [ "${domain}" != "${tld}" ]
  434. do
  435. search="${domain//./\.}"
  436. if [ "${adb_dns}" = "dnsmasq" ] || [ "${adb_dns}" = "unbound" ]
  437. then
  438. result="$(awk -F '/|\"' "/[\/\"\.]${search}/{i++;{printf(\" + %s\n\",\$2)};if(i>9){exit}}" "${adb_dnsfile}")"
  439. else
  440. result="$(awk "/(^[^\*][[:alpha:]]*[\.]+${search}|^${search})/{i++;{printf(\" + %s\n\",\$1)};if(i>9){exit}}" "${adb_dnsfile}")"
  441. fi
  442. printf "%s\n" "::: max. ten results for domain '${domain}'"
  443. printf "%s\n" "${result:-" - no match"}"
  444. domain="${tld}"
  445. tld="${domain#*.}"
  446. done
  447. fi
  448. }
  449. # f_jsnupdate: update runtime information
  450. #
  451. f_jsnupdate()
  452. {
  453. local status rundate="$(/bin/date "+%d.%m.%Y %H:%M:%S")"
  454. if [ ${adb_rc} -gt 0 ]
  455. then
  456. status="error"
  457. elif [ ${adb_enabled} -eq 0 ]
  458. then
  459. status="disabled"
  460. elif [ -s "${adb_dnsdir}/.${adb_dnsfile}" ]
  461. then
  462. status="paused"
  463. else
  464. status="enabled"
  465. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
  466. then
  467. if [ "${adb_dns}" = "named" ] || [ "${adb_dns}" = "kresd" ]
  468. then
  469. adb_cnt="$(( ( $(wc -l < "${adb_dnsdir}/${adb_dnsfile}") - $(printf "%s" "${adb_dnsheader}" | grep -c "^") ) / 2 ))"
  470. else
  471. adb_cnt="$(wc -l < "${adb_dnsdir}/${adb_dnsfile}")"
  472. fi
  473. fi
  474. fi
  475. if [ -z "${adb_fetchinfo}" ] && [ -s "${adb_rtfile}" ]
  476. then
  477. json_load "$(cat "${adb_rtfile}" 2>/dev/null)"
  478. json_select data
  479. json_get_var adb_fetchinfo "fetch_utility"
  480. fi
  481. json_init
  482. json_add_object "data"
  483. json_add_string "adblock_status" "${status}"
  484. json_add_string "adblock_version" "${adb_ver}"
  485. json_add_string "overall_domains" "${adb_cnt}"
  486. json_add_string "fetch_utility" "${adb_fetchinfo}"
  487. json_add_string "dns_backend" "${adb_dns} (${adb_dnsdir})"
  488. json_add_string "last_rundate" "${rundate}"
  489. json_add_string "system_release" "${adb_sysver}"
  490. json_close_object
  491. json_dump > "${adb_rtfile}"
  492. }
  493. # f_status: output runtime information
  494. #
  495. f_status()
  496. {
  497. local key keylist value
  498. if [ -s "${adb_rtfile}" ]
  499. then
  500. printf "%s\n" "::: adblock runtime information"
  501. json_load "$(cat "${adb_rtfile}" 2>/dev/null)"
  502. json_select data
  503. json_get_keys keylist
  504. for key in ${keylist}
  505. do
  506. json_get_var value "${key}"
  507. printf " + %-15s : %s\n" "${key}" "${value}"
  508. done
  509. fi
  510. }
  511. # f_log: write to syslog, exit on error
  512. #
  513. f_log()
  514. {
  515. local class="${1}" log_msg="${2}"
  516. if [ -n "${log_msg}" ] && ([ "${class}" != "debug" ] || [ ${adb_debug} -eq 1 ])
  517. then
  518. logger -t "adblock-[${adb_ver}] ${class}" "${log_msg}"
  519. if [ "${class}" = "error" ]
  520. then
  521. logger -t "adblock-[${adb_ver}] ${class}" "Please check 'https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md' (${adb_sysver})"
  522. f_rmtemp
  523. if [ -s "${adb_dnsdir}/${adb_dnsfile}" ]
  524. then
  525. f_rmdns
  526. f_dnsrestart
  527. fi
  528. adb_rc=1
  529. f_jsnupdate
  530. exit 1
  531. fi
  532. fi
  533. }
  534. # main function for blocklist processing
  535. #
  536. f_main()
  537. {
  538. local src_name src_rset shalla_archive enabled url hash_old hash_new
  539. local mem_total="$(awk '/^MemTotal/ {print int($2/1000)}' "/proc/meminfo")"
  540. f_log "info " "start adblock processing ..."
  541. f_log "debug" "action: ${adb_action}, dns: ${adb_dns}, fetch: ${adb_fetchinfo}, hashsum: ${adb_hashsum}, backup: ${adb_backup}, backup_mode: ${adb_backup_mode}, whitelist_mode: ${adb_whitelist_mode}, force_srt/_dns: ${adb_forcesrt}/${adb_forcedns}, mem_total: ${mem_total}"
  542. > "${adb_rtfile}"
  543. > "${adb_dnsdir}/.${adb_dnsfile}"
  544. # prepare whitelist entries
  545. #
  546. if [ -s "${adb_whitelist}" ]
  547. then
  548. if [ ${adb_whitelist_mode} -eq 1 ] && [ "${adb_dns}" != "dnscrypt-proxy" ]
  549. then
  550. adb_whitelist_rset="\$0~/^([[:alnum:]_-]+\.){1,}[[:alpha:]]+([[:space:]]|$)/{print tolower(\$1)}"
  551. else
  552. adb_whitelist_rset="\$0~/^([[:alnum:]_-]+\.){1,}[[:alpha:]]+([[:space:]]|$)/{gsub(\"\\\.\",\"\\\.\",\$1);print tolower(\"^\"\$1\"\\\|\\\.\"\$1)}"
  553. fi
  554. awk "${adb_whitelist_rset}" "${adb_whitelist}" > "${adb_tmpdir}/tmp.whitelist"
  555. fi
  556. # whitelist mode
  557. #
  558. if [ ${adb_whitelist_mode} -eq 1 ] && [ "${adb_dns}" != "dnscrypt-proxy" ]
  559. then
  560. f_tldcompression "${adb_tmpdir}/tmp.whitelist"
  561. eval "${adb_dnsformat}" "${adb_tmpdir}/tmp.whitelist" > "${adb_dnsdir}/${adb_dnsfile}"
  562. printf '%s\n' "${adb_dnsblock}" >> "${adb_dnsdir}/${adb_dnsfile}"
  563. if [ -n "${adb_dnsheader}" ]
  564. then
  565. printf '%s\n' "${adb_dnsheader}" | cat - "${adb_dnsdir}/${adb_dnsfile}" > "${adb_tmpdir}/${adb_dnsfile}"
  566. cat "${adb_tmpdir}/${adb_dnsfile}" > "${adb_dnsdir}/${adb_dnsfile}"
  567. fi
  568. f_dnsrestart
  569. if [ ${?} -eq 0 ]
  570. then
  571. f_jsnupdate "${adb_cnt}"
  572. f_log "info " "whitelist with overall ${adb_cnt} domains loaded successfully (${adb_sysver})"
  573. else
  574. f_log "error" "dns backend restart with active whitelist failed"
  575. fi
  576. return
  577. fi
  578. # normal & backup mode
  579. #
  580. for src_name in ${adb_sources}
  581. do
  582. eval "enabled=\"\${enabled_${src_name}}\""
  583. eval "url=\"\${adb_src_${src_name}}\""
  584. eval "src_rset=\"\${adb_src_rset_${src_name}}\""
  585. > "${adb_tmpload}"
  586. > "${adb_tmpfile}"
  587. adb_rc=4
  588. # basic pre-checks
  589. #
  590. f_log "debug" "name: ${src_name}, enabled: ${enabled}, url: ${url}, rset: ${src_rset}"
  591. if [ "${enabled}" != "1" ] || [ -z "${url}" ] || [ -z "${src_rset}" ]
  592. then
  593. f_list remove
  594. continue
  595. fi
  596. # backup mode
  597. #
  598. if [ ${adb_backup_mode} -eq 1 ] && [ "${adb_action}" = "start" ] && [ "${src_name}" != "blacklist" ]
  599. then
  600. f_list restore
  601. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  602. then
  603. f_list merge
  604. continue
  605. fi
  606. fi
  607. # download blocklist
  608. #
  609. if [ "${src_name}" = "blacklist" ] && [ -s "${url}" ]
  610. then
  611. cat "${url}" > "${adb_tmpload}"
  612. adb_rc=${?}
  613. elif [ "${src_name}" = "shalla" ]
  614. then
  615. shalla_archive="${adb_tmpdir}/shallalist.tar.gz"
  616. "${adb_fetch}" ${adb_fetchparm} "${shalla_archive}" "${url}" 2>/dev/null
  617. adb_rc=${?}
  618. if [ ${adb_rc} -eq 0 ]
  619. then
  620. for category in ${adb_src_cat_shalla}
  621. do
  622. tar -xOzf "${shalla_archive}" "BL/${category}/domains" >> "${adb_tmpload}"
  623. adb_rc=${?}
  624. if [ ${adb_rc} -ne 0 ]
  625. then
  626. break
  627. fi
  628. done
  629. fi
  630. rm -f "${shalla_archive}"
  631. rm -rf "${adb_tmpdir}/BL"
  632. else
  633. "${adb_fetch}" ${adb_fetchparm} "${adb_tmpload}" "${url}" 2>/dev/null
  634. adb_rc=${?}
  635. fi
  636. # check download result and prepare list output (incl. tld compression, list backup & restore)
  637. #
  638. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpload}" ]
  639. then
  640. awk "${src_rset}" "${adb_tmpload}" 2>/dev/null > "${adb_tmpfile}"
  641. if [ -s "${adb_tmpfile}" ]
  642. then
  643. f_tldcompression "${adb_tmpfile}"
  644. if [ "${src_name}" != "blacklist" ]
  645. then
  646. f_list backup
  647. fi
  648. else
  649. f_list restore
  650. fi
  651. else
  652. f_list restore
  653. fi
  654. # list merge
  655. #
  656. if [ ${adb_rc} -eq 0 ] && [ -s "${adb_tmpfile}" ]
  657. then
  658. f_list merge
  659. if [ ${adb_rc} -ne 0 ]
  660. then
  661. f_list remove
  662. fi
  663. else
  664. f_list remove
  665. fi
  666. done
  667. # hash preparation, whitelist removal and overall sort
  668. #
  669. if [ -x "${adb_hashsum}" ] && [ -f "${adb_dnsdir}/${adb_dnsfile}" ]
  670. then
  671. hash_old="$(${adb_hashsum} "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null | awk '{print $1}')"
  672. fi
  673. if [ -s "${adb_tmpdir}/${adb_dnsfile}" ]
  674. then
  675. if [ ${mem_total} -ge 64 ] || [ ${adb_forcesrt} -eq 1 ]
  676. then
  677. f_tldcompression "${adb_tmpdir}/${adb_dnsfile}"
  678. fi
  679. f_list format
  680. else
  681. > "${adb_dnsdir}/${adb_dnsfile}"
  682. fi
  683. chown "${adb_dnsuser}" "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null
  684. f_rmtemp
  685. # conditional restart of the dns backend and runtime information export
  686. #
  687. if [ -x "${adb_hashsum}" ] && [ -f "${adb_dnsdir}/${adb_dnsfile}" ]
  688. then
  689. hash_new="$(${adb_hashsum} "${adb_dnsdir}/${adb_dnsfile}" 2>/dev/null | awk '{print $1}')"
  690. fi
  691. if [ -z "${hash_old}" ] || [ -z "${hash_new}" ] || [ "${hash_old}" != "${hash_new}" ]
  692. then
  693. f_dnsrestart
  694. fi
  695. if [ ${?} -eq 0 ]
  696. then
  697. f_jsnupdate "${adb_cnt}"
  698. f_log "info " "blocklist with overall ${adb_cnt} domains loaded successfully (${adb_sysver})"
  699. else
  700. f_log "error" "dns backend restart with active blocklist failed"
  701. fi
  702. }
  703. # handle different adblock actions
  704. #
  705. f_envload
  706. case "${adb_action}" in
  707. stop)
  708. f_rmtemp
  709. f_rmdns
  710. f_dnsrestart
  711. ;;
  712. restart)
  713. f_rmtemp
  714. f_rmdns
  715. f_envcheck
  716. f_main
  717. ;;
  718. suspend)
  719. f_switch suspend
  720. ;;
  721. resume)
  722. f_switch resume
  723. ;;
  724. query)
  725. f_query "${2}"
  726. ;;
  727. status)
  728. f_status
  729. ;;
  730. *)
  731. f_envcheck
  732. f_main
  733. ;;
  734. esac
  735. exit 0