aboutsummaryrefslogtreecommitdiff
path: root/files/usr/local/libexec/idm-update-unbound-blocklists.idm_server
blob: 381032db58ce08425043c64d077c82ec3a42ed9a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/sh

set -eu -o pipefail

prog=$(basename "$(readlink -f "$0")")
usage="${prog} URL_FILE WHITELIST_FILE BLOCKLIST_DIR"

die() {
  printf '%s: %s\n' "$prog" "$*" 1>&2
  exit 1
}

usage(){
  printf 'usage: %s\n' "$usage" 1>&2
  exit 2
}

case ${1:-} in
  -h|--help) usage ;;
esac

[ $# -eq 3 ] || usage

url_file=$1
whitelist_file=$2
blocklist_dir=$3

[ -d "$blocklist_dir" ] || die "not a directory: ${blocklist_dir}"

cd "$blocklist_dir"

# Delete any existing zone files.
find . -maxdepth 1 -type f -exec rm {} +

if grep -q '[^[:space:]]' "$whitelist_file"; then
  # If the whitelist file is non empty, compute a regex.
  while read -r pattern; do
    [ -n "$pattern" ] || continue
    whitelist_regex="${whitelist_regex:+"${whitelist_regex}|"}${pattern}"
  done < "$whitelist_file"

  # For each blocklist url, download the blocklist and filter out the whitelist.
  while read -r name url; do
    [ -n "$url" ] && curl -sSfL "$url" | grep -Ev "^(.*\\.)?(${whitelist_regex})[[:space:]]" > "${name}.zone"
  done < "$url_file"
else
  # If no whitelist configured, just download each blocklist.
  while read -r name url; do
    [ -n "$url" ] && curl -sSfL -o "${name}.zone" "$url"
  done < "$url_file"
fi

# Try to reload unbound.
unbound_pidfile=$(/usr/local/sbin/unbound-checkconf -o pidfile /usr/local/etc/unbound/unbound.conf)
kill -HUP "$(cat "$unbound_pidfile")" ||: