#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          networking
# Required-Start:    mountkernfs ifupdown $local_fs
# Required-Stop:     ifupdown $local_fs
# Default-Start:     S
# Default-Stop:      0 6
# Short-Description: Raise network interfaces.
### END INIT INFO

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"

[ -x /sbin/ifup ] || exit 0

. /lib/lsb/init-functions

spoofprotect_rp_filter() {
    [ -e /proc/sys/net/ipv4/conf/all/rp_filter ] || return 1
    RC=0
    for f in /proc/sys/net/ipv4/conf/*/rp_filter; do
	echo 1 > $f || RC=1
    done
    return $RC
}

spoofprotect() {
    log_action_begin_msg "Setting up IP spoofing protection"
    if spoofprotect_rp_filter; then
	log_action_end_msg 0 "rp_filter"
    else
	log_action_end_msg 1
    fi
}

ip_forward() {
    log_action_begin_msg "Enabling packet forwarding"
    if echo 1 > /proc/sys/net/ipv4/ip_forward; then
        log_action_end_msg 0
    else
	log_action_end_msg 1
    fi
}

syncookies() {
    log_action_begin_msg "Enabling TCP SYN cookies"
    if echo 1 > /proc/sys/net/ipv4/tcp_syncookies; then
        log_action_end_msg 0
    else
	log_action_end_msg 1
    fi
}

doopt() {
    optname=$1
    default=$2
    opt=`grep "^$optname=" /etc/network/options || true`
    if [ -z "$opt" ]; then
	opt="$optname=$default"
    fi
    optval=${opt#$optname=}
    if [ "$optval" = "yes" ]; then
	eval $optname
    fi
}

process_options() {
    [ -e /etc/network/options ] || return 0
    log_warning_msg "/etc/network/options is deprecated (see README.Debian of netbase)."
    doopt spoofprotect yes
    doopt syncookies no
    doopt ip_forward no
}

case "$1" in
start)
	process_options
	log_action_begin_msg "Configuring network interfaces"
	if ifup -a; then
	    log_action_end_msg $?
	else
	    log_action_end_msg $?
	fi
	;;

stop)
	if sed -n 's/^[^ ]* \([^ ]*\) \([^ ]*\) .*$/\2/p' /proc/mounts | 
		grep -qE '^(nfs[1234]?|smbfs|ncp|ncpfs|coda|cifs)$'; then
	    log_warning_msg "not deconfiguring network interfaces: network shares still mounted."
	    exit 0
	fi

	log_action_begin_msg "Deconfiguring network interfaces"
	if ifdown -a --exclude=lo; then
	    log_action_end_msg $?
	else
	    log_action_end_msg $?
	fi
	;;

force-reload|restart)
	process_options
	log_action_begin_msg "Reconfiguring network interfaces"
	ifdown -a --exclude=lo || true
	if ifup -a --exclude=lo; then
	    log_action_end_msg $?
	else
	    log_action_end_msg $?
	fi
	;;

*)
	echo "Usage: /etc/init.d/networking {start|stop|restart|force-reload}"
	exit 1
	;;
esac

exit 0

