#!/bin/sh ECHOPING_TIMEOUT=10 VPNC_RETRY=3 VPNC_WAIT=5 VPNC_CONNECT_WAIT=2 test_wpa() { /etc/rc.d/wpa_supplicant status >/dev/null || return 1 /usr/sbin/wpa_cli status | grep '^wpa_state=COMPLETED$' >/dev/null } do_vpn() { ap=$(/usr/sbin/wpa_cli status | sed -n 's/^ssid=//p') case $ap in *IMAG*) conf=ensimag ;; *CROUS*) conf=crous ;; *) conf= ;; esac if [ -n "$conf" ]; then n=$VPNC_RETRY while ! /usr/pkg/sbin/vpnc $conf && [ $n -gt 0 ]; do sleep $VPNC_WAIT n=$(($n-1)) done # wait for VPNC to set up things correctly sleep $VPNC_CONNECT_WAIT if [ $n -ne 0 ]; then return 0 else logger -p local0.warning 'VPN connection failed' return 1 fi fi return 0 } die() { rm -f /var/run/do_wifi.pid if [ -n "$1" ]; then echo "$1" >&2 exit 1 else exit fi } # Only one process at a time if [ -f /var/run/do_wifi.pid ]; then if ps -p $(cat /var/run/do_wifi.pid) | grep do_wifi >/dev/null; then die 'Another do_wifi process is running; exiting.' fi fi echo $$ >/var/run/do_wifi.pid # Handle reboot all if [ "$1" = all ]; then /etc/rc.d/wpa_supplicant restart; sleep 1 /etc/rc.d/dhclient restart; sleep 1 /usr/pkg/bin/vpnc-disconnect 2>&1 >/dev/null; sleep 1 do_vpn; sleep 1 pkill -f '^ssh -F /etc/ssh/sshtunnel_config'; sleep 1 /usr/local/sbin/do_sshtunnel die fi # Kill selected services (so they can be restarted) for i; do case "$i" in wpa) /etc/rc.d/wpa_supplicant stop ;; dhcp) /etc/rc.d/dhclient stop ;; vpn) /usr/pkg/bin/vpnc-disconnect 2>&1 >/dev/null ;; ssh) pkill -f '^ssh -F /etc/ssh/sshtunnel_config' ;; esac done # Reconnect on Wifi/VPN failures if ! pgrep '^vpnc$' >/dev/null; then logger -p local0.notice 'VPN connection lost; restarting vpnc' if ! test_wpa || ! do_vpn; then /etc/rc.d/wpa_supplicant restart /etc/rc.d/dhclient restart do_vpn || die 'VPN connection failed' fi elif ! /usr/sbin/wpa_cli status | grep '^wpa_state=COMPLETED$' >/dev/null || \ ! /usr/pkg/bin/echoping -n 1 -t $ECHOPING_TIMEOUT \ -R -h / home >/dev/null; then logger -p local0.notice \ 'wireless connection seems lost; restarting wpa_supplicant' /etc/rc.d/wpa_supplicant restart fi # Change out-of-date DNS # if ! echoping -n 1 -t $ECHOPING_TIMEOUT -R -h / google.com >/dev/null; then # /usr/pkg/bin/vpnc-disconnect 2>&1 >/dev/null # do_vpn # fi # Restore SSH tunnel if ! pgrep -f '^ssh -F /etc/ssh/sshtunnel_config' >/dev/null; then logger -p local0.notice 'SSH tunnel lost; rebuilding SSH tunnel' /usr/local/sbin/do_sshtunnel fi # All is well, or is it die