summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xwg-netns-exec50
1 files changed, 41 insertions, 9 deletions
diff --git a/wg-netns-exec b/wg-netns-exec
index bfeb010..73550e0 100755
--- a/wg-netns-exec
+++ b/wg-netns-exec
@@ -9,14 +9,44 @@ die() {
[[ -n "${SUDO_USER}" ]] || die 'SUDO_USER is not set'
+if [[ -t 1 ]]; then
+ C_INFO='\e[90m'
+ C_STDIN='\e[36m'
+ C_RESET='\e[0m'
+else
+ C_INFO=
+ C_STDIN=
+ C_RESET=
+fi
+
+qargs() {
+ local arg sep=
+ for arg; do
+ [[ "${arg:-*}" =~ [^A-Za-z0-9%+./:=@_-] ]] && arg="${arg@Q}"
+ printf '%s%s' "${sep}" "${arg}"
+ sep=' '
+ done
+ printf '\n'
+}
+
+STDERR=
run() {
- if [[ -t 1 ]]; then
- printf '\e[90m[*] %s\e[0m\n' "$*"
+ local prefix='[*]'
+ ((DRY_RUN)) && prefix='[DRY]'
+ printf "${C_INFO}%s %s${C_RESET}\n" "${prefix}" "$(qargs "$@")" >&2
+
+ if ((DRY_RUN)); then
+ if [[ ! -t 0 ]]; then
+ while IFS= read -r line; do
+ printf " ${C_STDIN}| %s${C_RESET}\n" \
+ "${line}" >&2
+ done
+ fi
+ elif [[ -n "${STDERR}" ]]; then
+ "$@" 2>"${STDERR}"
else
- printf '[*] %s\n' "$*"
+ "$@"
fi
-
- "$@"
}
wg_conf=
@@ -41,6 +71,9 @@ while (($#)); do
--dnat)
dnat_rules+=("${2}")
shift 2 ;;
+ --dry-run)
+ DRY_RUN=1
+ shift ;;
--)
shift
break ;;
@@ -55,7 +88,6 @@ done
[[ "${wg_conf}" =~ ^[A-Za-z0-9+.=_-]{1,15}$ ]] &&
wg_conf="/etc/wg-netns-exec/${wg_conf}.conf"
[[ -e "${wg_conf}" ]] || die "config file does not exist: ${wg_conf}"
-echo "config: $wg_conf"
: ${netns:=$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c 8)}
wg_if="wg-${netns}"
@@ -167,7 +199,7 @@ if ((${#dnat_rules[@]})); then
nft_pre+='}'
fi
-run ip netns del "${netns}" 2>/dev/null
+STDERR=/dev/null run ip netns del "${netns}"
run ip netns add "${netns}"
trap 'run ip netns del "${netns}"' EXIT
@@ -180,8 +212,8 @@ for i in $(awk '
' "${wg_conf}"); do
run ip -n "${netns}" addr add "${i}" dev "${wg_if}"
done
-run ip netns exec "${netns}" wg setconf "${wg_if}" <(
- wg-quick strip "${wg_conf}")
+run wg-quick strip "${wg_conf}" |
+ run ip netns exec "${netns}" wg setconf "${wg_if}" /dev/stdin
run ip -n "${netns}" link set "${wg_if}" up
run ip -n "${netns}" -4 route add default dev "${wg_if}"
run ip -n "${netns}" -6 route add default dev "${wg_if}"