checkwan () {
# Using Google's 8.8.8.8 server to test for WAN connectivity over verified SSL Handshake
Connectivity=1
wandownbreakertrip=0
vpnresettripped=0
WAN_ELAPSED_TIME=0
testssl=8.8.8.8
# Show that we're testing the WAN connection
if [ $1 == "Loop" ]
then
printf "${CGreen}\r[Checking WAN Connectivity]..."
elif [ $1 = "Reset" ]
then
printf "${CGreen}\rChecking WAN Connectivity..."
fi
while [ $Connectivity == "1" ]; do
# Start a timer to see how long this takes to add to the TX/RX Calculations
WAN_START_TIME=$(date +%s)
# Check the actual WAN State from NVRAM before running connectivity test
if [ "$(nvram get wan0_state_t)" -ne 2 ] && [ "$(nvram get wan1_state_t)" -ne 2 ]
then
# The WAN is most likely down, and keep looping through until NVRAM reports that it's back up
wandownbreakertrip=1
while [ $wandownbreakertrip == "1" ]; do
# Continue to test for WAN connectivity while in this loop. If it comes back up, break out of the loop and reset VPN
if [ "$(nvram get wan0_state_t)" -ne 2 ] || [ "$(nvram get wan1_state_t)" -ne 2 ]
then
# Continue to loop and retest the WAN every 15 seconds
echo -e "$(date) - VPNMON-R2 ----------> ERROR: WAN DOWN" >> $LOGFILE
# clear screen
clear && clear
echo -e "${CRed}-----------------> ERROR: WAN DOWN <-----------------"
echo ""
echo -e "${CRed}VPNMON-R2 is unable to detect a stable WAN connection."
echo -e "Trying to verify connection every $SPIN seconds...${CClear}\n"
echo ""
echo -e "${CRed}Please check with your ISP, or reset your modem to "
echo -e "${CRed}re-establish a connection.${CClear}\n"
spinner
wandownbreakertrip=1
else
wandownbreakertrip=2
fi
done
else
# If the WAN was down, and now it has just reset, then run a VPN Reset, and try to establish a new VPN connection
if [ $wandownbreakertrip == "2" ]
then
wandownbreakertrip=0
vpnresettripped=1
echo ""
echo -e "${CGReen}WAN Connection Detected... waiting 30 seconds for connection to stabilize."
echo -e "$(date) - VPNMON-R2 - WAN Connection Re-established -- Resetting VPN" >> $LOGFILE
SPIN=30
spinner
clear && clear
vpnreset
fi
# Else test the connection on active WAN using 443 and verifying a handshake... if this fails, then the WAN connection is most likely down... or Google is down ;)
if nc -w1 $testssl 443 && echo |openssl s_client -connect $testssl:443 2>&1 |awk 'handshake && $1 == "Verification" { if ($2=="OK") exit; exit 1 } $1 $2 == "SSLhandshake" { handshake = 1 }'
then
if [ $1 == "Loop" ]
then
printf "${CGreen}\r[Checking WAN Connectivity]...ACTIVE"
sleep 1
printf "\33[2K\r"
elif [ $1 = "Reset" ]
then
printf "${CGreen}\rChecking WAN Connectivity...ACTIVE"
sleep 1
echo -e "\n"
fi
WAN_END_TIME=$(date +%s)
WAN_ELAPSED_TIME=$(( WAN_END_TIME - WAN_START_TIME ))
return
else
wandownbreakertrip=1
fi
fi
done
}