eibgrad

merlin-ovpn-sync-routes-66726.sh

Sep 25th, 2021 (edited)
1,309
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/sh
  2. # version: 1.2.0, 28-sep-2021, by eibgrad
  3. # href: https://tinyurl.com/2jenwbe5
  4.  
  5. SCRIPTS_DIR='/jffs/scripts'
  6. SCRIPT="$SCRIPTS_DIR/openvpn-event"
  7.  
  8. mkdir -p $SCRIPTS_DIR
  9.  
  10. create_script() {
  11. cat << "EOF" > $SCRIPT
  12. #!/bin/sh
  13. set -x # uncomment/comment to enable/disable debug mode
  14. {
  15. # required for serialization when reentry is possible
  16. LOCK="/tmp/$(basename $0).lock"
  17. acquire_lock() { while ! mkdir $LOCK &>/dev/null; do sleep 2; done; }
  18. release_lock() { rmdir $LOCK &>/dev/null; }
  19.  
  20. # exit (any concurrent instance(s) may now run)
  21. exit_0() { release_lock; exit 0; }
  22.  
  23. # one instance at a time
  24. acquire_lock
  25.  
  26. # only relevant for routed (tun) openvpn server route-up event
  27. [[ "${dev:0:4}" == 'tun2' && "$script_type" == 'up' ]] || exit_0
  28.  
  29. # ensure every openvpn client's routing policy table ...
  30. for i in 1 2 3 4 5; do
  31.     [ "$(ip route show table ovpnc${i})" ] || continue
  32.  
  33.     # ... contains the server's ip network on the tunnel
  34.     while read route; do
  35.         ip route add $route table ovpnc${i} 2>/dev/null && routing_changed=
  36.     done << EOR
  37.     $(ip route | grep $dev)
  38. EOR
  39. done
  40.  
  41. # force routing system to recognize any changes
  42. [ ${routing_changed+x} ] && ip route flush cache
  43.  
  44. exit_0
  45. } 2>&1 | logger -t $(basename $0)[$$]
  46. EOF
  47. chmod +x $SCRIPT
  48. }
  49.  
  50. if [ -f $SCRIPT ]; then
  51.     echo "error: $SCRIPT already exists; requires manual installation"
  52. else
  53.     create_script
  54.     echo 'Done.'
  55. fi
RAW Paste Data