#!/system/bin/sh
#
# USB RNDIS tether setup
# shade@chemlab.org (cyanogen)
#
# extended by Stefan Tomanek (stefan@pico.ruhr.de)

# values specified here may be overridden by the config file
CONF="/etc/tether.conf"

# the bridge device
TETHER=tether

# a list of devices through which to get internet connectivity
OUT="rmnet0 tun+ tap+ ppp0 `getprop wifi.interface`"
ADDR=192.168.77.254
MASK=255.255.255.0

# configure the DHCP range
RANGE_START=192.168.77.100
RANGE_END=192.168.77.105

USB_TOGGLE=/sys/devices/virtual/usb_composite/rndis/enable
USB_DEV=usb0

# pand is required for bluetooth connectivity
PAND=pand
# this script is started by pand after a connection is established
PAND_UP=/system/xbin/pand-up.sh
PAND_PID=/data/misc/pand.pid

# dund is used for virtual dial up networking
DUND=dund
PPPD=/system/bin/pppd
DUND_PID=/data/misc/dund.pid
DUN_ADDRESS=192.168.77.106
DUN_CHATSCRIPT=/system/xbin/dun-chat.awk

ENABLE_USB=1
ENABLE_BT_PAN=1
ENABLE_BT_DUN=1

SYSCTL_FWD=net.ipv4.ip_forward

DNSMASQ=dnsmasq
DNSMASQ_PID=/data/misc/dnsmasq.pid

IPTABLES_CHAIN=tether

# load configuration file if present
if [ -e "$CONF" ]; then
    . "$CONF"
fi

logmsg() {
    local MSG="$*"
    # print message to STDOUT and logcat
    echo "$MSG"
    log -t tether "$MSG"
}

start_dnsmasq() {
    logmsg "Starting dnsmasq"
    $DNSMASQ \
        --interface "$TETHER" \
        --no-resolv \
        --no-poll \
        --no-negcache \
        --server 4.2.2.2 \
        --server 4.2.2.3 \
        --dhcp-authoritative \
        --dhcp-range=${RANGE_START},${RANGE_END},12h \
        --dhcp-leasefile=/data/misc/dnsmasq.leases \
        --pid-file="${DNSMASQ_PID}" \
        --user=dhcp
}

stop_dnsmasq() {
    if [ -e "${DNSMASQ_PID}" ]; then
        logmsg "Killing dnsmasq"
        # for some reason, dnsmasq doesn't terminate on SIGTERM
        kill -9 $(cat "${DNSMASQ_PID}")
        rm "${DNSMASQ_PID}"
    fi
}

start_usb() {
    logmsg "Activating USB tether"
    # add USB interface to it
    ifconfig $USB_DEV up
    brctl addif $TETHER $USB_DEV
    echo 1 > $USB_TOGGLE
}

stop_usb() {
    # bring down USB networking
    brctl delif $TETHER $USB_DEV
    ifconfig $USB_DEV down
    echo 0 > $USB_TOGGLE
}

start_bt_pan() {
    logmsg "Activating Bluetooth PAN tether"
    # launch PAND
    $PAND -P "$PAND_PID" --devup "$PAND_UP" -M -rNAP -S -s
}

start_bt_dun() {
    logmsg "Activating Bluetooth DUN tether"
    # launch DUND
    $DUND --persist -u -M -S --pppd "$PPPD" \
        local \
        connect ${DUN_CHATSCRIPT} \
        linkname tether \
        ipparam $IPTABLES_CHAIN \
        ${ADDR}:${DUN_ADDRESS} \
        noauth \
        ms-dns 4.2.2.2  &
    echo $! > "$DUND_PID"
}


stop_bt_pan() {
    # kill PAN connections
    $PAND -K
    # sometimes SIGTERM is not enough
    kill -9 $(cat "$PAND_PID")
    rm "$PAND_PID"
}

stop_bt_dun() {
    # kill DUN connections
    $DUND -K
    kill -9 $(cat "$DUND_PID")
    rm "$DUND_PID"
    # some children are naughty...
    killall dund
}

start_iptables() {
    # create (or at least empty) chain for forwarded packets
    iptables -N $IPTABLES_CHAIN
    iptables -F $IPTABLES_CHAIN
    # we let packets pass belonging to connections that are already established
    iptables -A $IPTABLES_CHAIN -m state --state RELATED,ESTABLISHED -j ACCEPT
    # other packets originating from the inner device are also allowed to pass
    iptables -A $IPTABLES_CHAIN -i $TETHER -j ACCEPT

    # hook the tether rules into the FORWARDING chain
    # send all packets that are send or received by the tethered network
    # through the filter chain
    iptables -A FORWARD -i $TETHER -j $IPTABLES_CHAIN
    iptables -A FORWARD -o $TETHER -j $IPTABLES_CHAIN

    # enable masquerading for all outgoing devices
    for DEV in $OUT; do
        iptables -t nat -A POSTROUTING -o $DEV -j MASQUERADE
    done
}

stop_iptables() {
    # disable masquerading
    for DEV in $OUT; do
        iptables -t nat -D POSTROUTING -o $DEV -j MASQUERADE
    done

    # remove references to the $IPTABLES_CHAIN chain
    iptables -D FORWARD -i $TETHER -j $IPTABLES_CHAIN
    iptables -D FORWARD -o $TETHER -j $IPTABLES_CHAIN

    # destroy the $IPTABLES_CHAIN chain
    iptables -F $IPTABLES_CHAIN
    iptables -X $IPTABLES_CHAIN
}

case "$1" in
   start)
      logmsg "Setting up tethering bridge"
      # create bridge for tethering
      brctl addbr $TETHER
      ifconfig $TETHER up $ADDR netmask $MASK

      start_iptables
      
      sysctl -w ${SYSCTL_FWD}=1
      
      # enable tethering subsystems
      [ "$ENABLE_USB" -eq 1 ] && start_usb
      [ "$ENABLE_BT_PAN" -eq 1 ] && start_bt_pan
      [ "$ENABLE_BT_DUN" -eq 1 ] && start_bt_dun
      
      start_dnsmasq

      setprop tethering.enabled 1
   ;;
   
   stop)
      stop_dnsmasq
      
      # shut down usb tethering if it is active
      [ -e "/sys/class/net/${TETHER}/brif/${USB_DEV}" ] && stop_usb
      # shut down bluetooth networking
      [ -e "$PAND_PID" ] && stop_bt_pan
      [ -e "$DUND_PID" ] && stop_bt_dun
     
      sysctl -w ${SYSCTL_FWD}=0

      stop_iptables

      # shut down the bridge device
      ifconfig $TETHER down
      brctl delbr $TETHER
      
      logmsg "Tethering bridge shut down"
      
      setprop tethering.enabled 0
   ;;

   restart)
      $0 stop
      $0 start
   ;;

   *)
      echo "Usage: $0 {start|stop|restart}"
      exit 1
esac

exit 0

