I post my solution here, maybe it can help someone.
I code a script, that would try to query the MAC address of my home router, if success(meaning that I'm home), stop to connect the VPN.
And then modify the systemd service file(vpn-to-home.service), add a line ExecStartPre=/usr/local/bin/stop-if-lan.sh
.
The script stop-if-lan.sh:
#!/bin/bash
/usr/bin/ping -4n -c 1 -q -W 1 IP_OF_ROUTER > /dev/null
MAC_ADDRESS=`arp -n | awk '/IP_OF_ROUTER/{print $3;exit}'`
if [ "$MAC_ADDRESS" == "MAC_OF_ROUTER" ] ; then
# echo "We are already at home."
exit 1
fi
exit 0
The vpn-to-home.service of systemd:
[Unit]
Requisite=network-online.target
After=syslog.target network-online.target
[Service]
Type=idle
RuntimeDirectory=openvpn-client
WorkingDirectory=/run/openvpn-client
PrivateTmp=true
CapabilityBoundingSet=CAP_IPC_LOCK CAP_NET_ADMIN CAP_NET_RAW CAP_SETGID CAP_SETUID CAP_SYS_CHROOT CAP_DAC_OVERRIDE
ExecStartPre=/usr/local/bin/check-if-lan.sh
ExecStart=/usr/sbin/openvpn --config /etc/openvpn/client/client-to-home.ovpn
LimitNPROC=10
DeviceAllow=/dev/null rw
DeviceAllow=/dev/net/tun rw
ProtectSystem=true
ProtectHome=true
KillMode=process
[Install]
WantedBy=multi-user.target