Skip to content

Instantly share code, notes, and snippets.

@leshniak
Last active September 6, 2022 00:06
Show Gist options
  • Save leshniak/9d534a6c1da352254133dd9c53590f54 to your computer and use it in GitHub Desktop.
Save leshniak/9d534a6c1da352254133dd9c53590f54 to your computer and use it in GitHub Desktop.
A simple script that overrides /etc/resolv.conf to custom one on per-app basis (Linux only)
#!/bin/sh
set -e
trap clean TERM INT EXIT
tmp_resolv_conf=""
clean() {
rm -f -- "$tmp_resolv_conf"
}
split() {
local IFS="$1"
read array <<EOF
$2
EOF
echo $array
}
generate_entries() {
printf "nameserver %s\n" "$@"
}
script_name=$(basename "$0")
if [ -z "$*" ]; then
echo "Usage: [ODNS_SERVERS=] [ODNS_OPTIONS=] $script_name <command>"
echo
echo "Overrides /etc/resolv.conf on per-app basis."
echo "Check it using \`$script_name cat /etc/resolv.conf\`."
echo
echo "Options:"
echo " - ODNS_SERVERS= environment variable, a comma-separated list of DNS"
echo " servers; defaults to \"9.9.9.9,149.112.112.112\""
echo " - ODNS_OPTIONS= environment variable, /etc/resolv.conf options;"
echo " defaults to \"edns0 single-request-reopen\""
exit 1
fi
tmp_resolv_conf=$(mktemp --suffix ".odns")
nameservers=$(split , "${ODNS_SERVERS:-9.9.9.9,149.112.112.112}")
cat >| "$tmp_resolv_conf" <<EOF
# Generated by odns
$(generate_entries $nameservers)\
$([ -z "${ODNS_OPTIONS+.}" ] && echo "\\noptions ${ODNS_OPTIONS:-edns0 single-request-reopen}")
EOF
unshare -rm sh -c "mount --bind \"$tmp_resolv_conf\" /etc/resolv.conf; \
exec unshare --map-user=$(id -ru) --map-group=$(id -rg) -- $*"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment