#!/bin/sh
# cmuvpn.sh
# copyright (c) 2003 Patrick Wagstrom
# email pwagstro at andrew dawt cmu dawt edu
#
# distributed under the terms of the GNU General Public License V2
#

SITES="www.library.cmu.edu ieeexplore.ieee.org portal.acm.org"
SITES="$SITES unicorn.library.cmu.edu"
IFACE=ppp0
CONNECTION=CMU

# ---
# --- shouldn't need to change stuff underneath here
# ---

COMMAND=$1

add_route () {
	NETWORK=$1
	NETMASK=$2

	echo "Adding network $NETWORK/$NETMASK to routing tables"

	route add -net $NETWORK netmask $NETMASK dev $IFACE

	iptables --insert OUTPUT 1 --source 0.0.0.0/0.0.0.0 \
	--destination $NETWORK/$NETMASK --jump ACCEPT --out-interface $IFACE

	iptables --insert INPUT 1 --source $NETWORK/$NETMASK \
	--destination 0.0.0.0/0.0.0.0 --jump ACCEPT --in-interface $IFACE

	iptables --insert FORWARD 1 --source 0.0.0.0/0.0.0.0 \
	--destination $NETWORK/$NETMASK --jump ACCEPT --out-interface $IFACE

	iptables --insert FORWARD 1 --source $NETWORK/$NETMASK \
	--destination 0.0.0.0/0.0.0.0 --jump ACCEPT
}

get_host() {
	ADDR=`gethostip $1 | awk '{ print $2; }' | cut -d . -f 1-3`
	echo -n $ADDR.0
}

start_connection() {
	pppd call CMU
	# give the connection a chance to start up
	sleep 5
	iptables -F
	
	NETWORKS=""
	for x in $SITES; do
		THISNET=`get_host $x`
		NETWORKS="$NETWORKS $THISNET"
	done
	NETWORKS=`echo $NETWORKS | tr ' ' \\\\n | sort | uniq`
	
	for x in $NETWORKS; do
		add_route $x 255.255.255.0
	done
	iptables --append FORWARD --protocol tcp \
	--tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu
}

stop_connection() {
	PID=`head -n 1 /var/run/ppp-$CONNECTION.pid`
	kill $PID
	rm /var/run/ppp-$CONNECTION.pid
	iptables -F
}

print_help() {
	echo "Simple CMU VPN Script"
	echo "USAGE: "
	echo "cmuvpn.sh [start | stop]"
	echo
	echo "Comments?  email pwagstro@andrew"
}

if [ $USER != 'root' ]; then
  echo "You must be root to run this script"
  exit
fi


case $COMMAND in
	start)
		start_connection
	;;

	stop)
		stop_connection
	;;

	*)
		print_help
	;;
esac

