Skip to content

add iptables rules cleanup in ovpn_run when the docker use host network #631

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion bin/ovpn_run
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,33 @@ function setupIptablesAndRouting {
done
}

# clear iptables rules if they exist
function clearIptablesAndRouting {
iptables -t nat -C POSTROUTING -s $OVPN_SERVER -o $OVPN_NATDEVICE -j MASQUERADE 2>/dev/null && {
iptables -t nat -D POSTROUTING -s $OVPN_SERVER -o $OVPN_NATDEVICE -j MASQUERADE
}
for i in "${OVPN_ROUTES[@]}"; do
iptables -t nat -C POSTROUTING -s "$i" -o $OVPN_NATDEVICE -j MASQUERADE 2>/dev/null && {
iptables -t nat -D POSTROUTING -s "$i" -o $OVPN_NATDEVICE -j MASQUERADE
}
done
}

# forward SIGTERM to the child and then cleanup
function gracefully_shutdown {
kill -SIGTERM $child_pid
if [ "$OVPN_DEFROUTE" != "0" ] || [ "$OVPN_NAT" == "1" ] ; then
clearIptablesAndRouting
fi
}

# foward the signal
function forward_handler {
sig_type="$1"
# forward this signal to the child
kill -"$sig_type" $child_pid
}


addArg "--config" "$OPENVPN/openvpn.conf"

Expand Down Expand Up @@ -101,5 +128,23 @@ if [ $? = 0 ]; then
fi
fi

######## Do not exit immediately after this section #########
set +e
# Install the SIGTERM handler
trap gracefully_shutdown SIGTERM SIGINT
# Install other signals mentioned in the OpenVPN reference manual
for sig in SIGHUP SIGUSR1 SIGUSR2; do
trap "forward_handler $sig" "$sig"
done

echo "Running 'openvpn ${ARGS[@]} ${USER_ARGS[@]}'"
exec openvpn ${ARGS[@]} ${USER_ARGS[@]}
# Run it in the background and then wait it later
openvpn ${ARGS[@]} ${USER_ARGS[@]} &
child_pid=$!

# wait for the openvpn process to end
wait $child_pid
# keep wait for it if this process has not ended
while [[ "$?" -ne 0 ]]; do
wait $child_pid
done