adblock.sh 57 KB

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