#!/bin/sh
#
# Compiled firewall script generated by Shorewall 4.4.14 - Mon Nov 29 23:36:39 2010
#
#!/bin/sh
#
#     This program is under GPL [http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt]
#
#     (c) 1999-2010 - Tom Eastep (teastep@shorewall.net)
#
#	Options are:
#
#	    -n				  Don't alter Routing
#	    -v and -q			  Standard Shorewall Verbosity control
#           -t                            Timestamp progress messages
#           -p                            Purge conntrack table
#           -r                            Recover from failed start/restart
#           -V <verbosity>                Set verbosity level explicitly
#           -R <restore>                  Overrides RESTOREFILE setting
#
#	Commands are:
#
#	   start			  Starts the firewall
#          refresh                        Refresh the firewall
#	   restart			  Restarts the firewall
#	   reload			  Reload the firewall
#	   clear			  Removes all firewall rules
#	   stop				  Stops the firewall
#	   status			  Displays firewall status
#	   version			  Displays the version of Shorewall that
#	   				  generated this program
#
################################################################################
# Functions imported from /usr/share/shorewall/prog.header
################################################################################
#
# Conditionally produce message
#
progress_message() # $* = Message
{
    local timestamp
    timestamp=

    if [ $VERBOSITY -gt 1 ]; then
	[ -n "$g_timestamp" ] && timestamp="$(date +%H:%M:%S) "
	echo "${timestamp}$@"
    fi

    if [ $LOG_VERBOSITY -gt 1 ]; then
        timestamp="$(date +'%b %_d %T') "
        echo "${timestamp}$@" >> $STARTUP_LOG
    fi
}

progress_message2() # $* = Message
{
    local timestamp
    timestamp=

    if [ $VERBOSITY -gt 0 ]; then
	[ -n "$g_timestamp" ] && timestamp="$(date +%H:%M:%S) "
	echo "${timestamp}$@"
    fi

    if [ $LOG_VERBOSITY -gt 0 ]; then
        timestamp="$(date +'%b %_d %T') "
        echo "${timestamp}$@" >> $STARTUP_LOG
    fi
}

progress_message3() # $* = Message
{
    local timestamp
    timestamp=

    if [ $VERBOSITY -ge 0 ]; then
	[ -n "$g_timestamp" ] && timestamp="$(date +%H:%M:%S) "
	echo "${timestamp}$@"
    fi

    if [ $LOG_VERBOSITY -ge 0 ]; then
        timestamp="$(date +'%b %_d %T') "
        echo "${timestamp}$@" >> $STARTUP_LOG
    fi
}

#
# Set a standard chain's policy
#
setpolicy() # $1 = name of chain, $2 = policy
{
    run_iptables -P $1 $2
}

#
# Generate a list of all network interfaces on the system
#
find_all_interfaces() {
    ${IP:-ip} link list | egrep '^[[:digit:]]+:' | cut -d ' ' -f2 | sed -r 's/(@.*)?:$//'
}

#
# Generate a list of all network interfaces on the system that have an ipv4 address
#
find_all_interfaces1() {
    ${IP:-ip} -4 addr list | egrep '^[[:digit:]]+:' | cut -d ' ' -f2 | sed -r 's/(@.*)?:$//'
}

#
# Find the value 'dev' in the passed arguments then echo the next value
#

find_device() {
    while [ $# -gt 1 ]; do
	[ "x$1" = xdev ] && echo $2 && return
	shift
    done
}

#
# Find the value 'via' in the passed arguments then echo the next value
#

find_gateway() {
    while [ $# -gt 1 ]; do
	[ "x$1" = xvia ] && echo $2 && return
	shift
    done
}

#
# Find the value 'mtu' in the passed arguments then echo the next value
#

find_mtu() {
    while [ $# -gt 1 ]; do
	[ "x$1" = xmtu ] && echo $2 && return
	shift
    done
}

#
# Find the value 'peer' in the passed arguments then echo the next value up to
# "/"
#

find_peer() {
    while [ $# -gt 1 ]; do
	[ "x$1" = xpeer ] && echo ${2%/*} && return
	shift
    done
}

#
# Find the interfaces that have a route to the passed address - the default
# route is not used.
#

find_rt_interface() {
    $IP -4 route list | while read addr rest; do
	case $addr in
	    */*)
		in_network ${1%/*} $addr && echo $(find_device $rest)
		;;
	    default)
		;;
	    *)
		if [ "$addr" = "$1" -o "$addr/32" = "$1" ]; then
		    echo $(find_device $rest)
		fi
		;;
	esac
    done
}

#
# Try to find the gateway through an interface looking for 'nexthop'

find_nexthop() # $1 = interface
{
    echo $(find_gateway `$IP -4 route list | grep "[[:space:]]nexthop.* $1"`)
}

#
# Find the default route's interface
#
find_default_interface() {
    $IP -4 route list | while read first rest; do
	[ "$first" = default ] && echo $(find_device $rest) && return
    done
}

#
# Echo the name of the interface(s) that will be used to send to the
# passed address
#

find_interface_by_address() {
    local dev
    dev="$(find_rt_interface $1)"
    local first
    local rest

    [ -z "$dev" ] && dev=$(find_default_interface)

    [ -n "$dev" ] && echo $dev
}

#
# Determine if Interface is up
#
interface_is_up() {
    [ -n "$($IP link list dev $1 2> /dev/null | grep -e '[<,]UP[,>]')" ]
}

#
# Determine if interface is usable from a Netfilter prespective
#
interface_is_usable() # $1 = interface
{
    [ "$1" = lo ] && return 0
    interface_is_up $1 && [ "$(find_first_interface_address_if_any $1)" != 0.0.0.0 ] && run_isusable_exit $1
}

#
# Find interface addresses--returns the set of addresses assigned to the passed
# device
#
find_interface_addresses() # $1 = interface
{
    $IP -f inet addr show $1 2> /dev/null | grep inet\  | sed 's/\s*inet //;s/\/.*//;s/ peer.*//'
}

#
#  echo the list of networks routed out of a given interface
#
get_routed_networks() # $1 = interface name, $2-n = Fatal error message
{
    local address
    local rest

    $IP -4 route show dev $1 2> /dev/null |
	while read address rest; do
	    case "$address" in
		default)
		    if [ $# -gt 1 ]; then
			shift
			fatal_error "$@"
		    else
			echo "WARNING: default route ignored on interface $1" >&2
		    fi
		    ;;
		multicast|broadcast|prohibit|nat|throw|nexthop)
		    ;;
		*)
		    [ "$address" = "${address%/*}" ] && address="${address}/32"
		    echo $address
		    ;;
	    esac
        done
}

#
# Get the broadcast addresses associated with an interface
#
get_interface_bcasts() # $1 = interface
{
    local addresses
    addresses=

    $IP -f inet addr show dev $1 2> /dev/null | grep 'inet.*brd' | sed 's/inet.*brd //; s/scope.*//;' | sort -u
}

#
# Delete IP address
#
del_ip_addr() # $1 = address, $2 = interface
{
    [ $(find_first_interface_address_if_any $2) = $1 ] || qt $IP addr del $1 dev $2
}

# Add IP Aliases
#
add_ip_aliases() # $* = List of addresses
{
    local local
    local addresses
    local external
    local interface
    local inet
    local cidr
    local rest
    local val
    local arping
    arping=$(mywhich arping)

    address_details()
    {
	#
	# Folks feel uneasy if they don't see all of the same
	# decoration on these IP addresses that they see when their
	# distro's net config tool adds them. In an attempt to reduce
	# the anxiety level, we have the following code which sets
	# the VLSM and BRD from an existing address in the same networks
	#
	# Get all of the lines that contain inet addresses with broadcast
	#
	$IP -f inet addr show $interface 2> /dev/null | grep 'inet.*brd' | while read inet cidr rest ; do
	    case $cidr in
		*/*)
		    if in_network $external $cidr; then
			echo "/${cidr#*/} brd $(broadcastaddress $cidr)"
			break
		    fi
		    ;;
	    esac
	done
    }

    do_one()
    {
	val=$(address_details)

	$IP addr add ${external}${val} dev $interface $label
	[ -n "$arping" ] && qt $arping -U -c 2 -I $interface $external
	echo "$external $interface" >> $VARDIR/nat
	[ -n "$label" ] && label="with $label"
	progress_message "   IP Address $external added to interface $interface $label"
    }

    progress_message "Adding IP Addresses..."

    while [ $# -gt 0 ]; do
	external=$1
	interface=$2
	label=

	if [ "$interface" != "${interface%:*}" ]; then
	    label="${interface#*:}"
	    interface="${interface%:*}"
	    label="label $interface:$label"
	fi

	shift 2

	list_search $external $(find_interface_addresses $interface) || do_one
    done
}

#
# Detect the gateway through a PPP or DHCP-configured interface
#
detect_dynamic_gateway() { # $1 = interface
    local interface
    interface=$1
    local GATEWAYS
    GATEWAYS=
    local gateway

    gateway=$(run_findgw_exit $1);

    if [ -z "$gateway" ]; then
	gateway=$( find_peer $($IP addr list $interface ) )
    fi

    if [ -z "$gateway" -a -f /var/lib/dhcpcd/dhcpcd-${1}.info ]; then
	eval $(grep ^GATEWAYS=  /var/lib/dhcpcd/dhcpcd-${1}.info 2> /dev/null)
	[ -n "$GATEWAYS" ] && GATEWAYS=${GATEWAYS%,*} && gateway=$GATEWAYS
    fi

    if [ -z "$gateway" -a -f /var/lib/dhcp/dhclient-${1}.lease ]; then
	gateway=$(grep 'option routers' /var/lib/dhcp/dhclient-${1}.lease | tail -n 1 | while read j1 j2 gateway; do echo $gateway ; return 0; done)
    fi

    [ -n "$gateway" ] && echo $gateway
}

#
# Detect the gateway through an interface
#
detect_gateway() # $1 = interface
{
    local interface
    interface=$1
    local gateway
    #
    # First assume that this is some sort of dynamic interface
    #
    gateway=$( detect_dynamic_gateway $interface )
    #
    # Maybe there's a default route through this gateway already
    #
    [ -n "$gateway" ] || gateway=$(find_gateway $($IP -4 route list dev $interface | grep ^default))
    #
    # Last hope -- is there a load-balancing route through the interface?
    #
    [ -n "$gateway" ] || gateway=$(find_nexthop $interface)
    #
    # Be sure we found one
    #
    [ -n "$gateway" ] && echo $gateway
}

#
# Disable IPV6
#
disable_ipv6() {
    local foo
    foo="$($IP -f inet6 addr list 2> /dev/null)"

    if [ -n "$foo" ]; then
	if [ -x "$IP6TABLES" ]; then
	    $IP6TABLES -P FORWARD DROP
	    $IP6TABLES -P INPUT DROP
	    $IP6TABLES -P OUTPUT DROP
	    $IP6TABLES -F
	    $IP6TABLES -X
	    $IP6TABLES -A OUTPUT -o lo -j ACCEPT
	    $IP6TABLES -A INPUT -i lo -j ACCEPT
	else
	    error_message "WARNING: DISABLE_IPV6=Yes in shorewall.conf but this system does not appear to have ip6tables"
	fi
    fi
}

#
# Clear the current traffic shaping configuration
#

delete_tc1()
{
    clear_one_tc() {
        $TC qdisc del dev $1 root 2> /dev/null
        $TC qdisc del dev $1 ingress 2> /dev/null

    }

    run_tcclear_exit

    run_ip link list | \
    while read inx interface details; do
        case $inx in
            [0-9]*)
                clear_one_tc ${interface%:}
                ;;
            *)
                ;;
        esac
    done
}

#
# Detect a device's MTU -- echos the passed device's MTU
#
get_device_mtu() # $1 = device
{
    local output
    output="$($IP link list dev $1 2> /dev/null)" # quotes required for /bin/ash

    if [ -n "$output" ]; then
	echo $(find_mtu $output)
    else
	echo 1500
    fi
}

#
# Version of the above that doesn't generate any output for MTU 1500.
# Generates 'mtu <mtu+>' otherwise, where <mtu+> is the device's MTU + 100
#
get_device_mtu1() # $1 = device
{
    local output
    output="$($IP link list dev $1 2> /dev/null)" # quotes required for /bin/ash
    local mtu

    if [ -n "$output" ]; then
	mtu=$(find_mtu $output)
	if [ -n "$mtu" ]; then
	    [ $mtu = 1500 ] || echo mtu $(($mtu + 100))
	fi
    fi

}

#
# Undo changes to routing
#
undo_routing() {

    if [ -z "$g_noroutes"  ]; then
	#
	# Restore rt_tables database
	#
	if [ -f ${VARDIR}/rt_tables ]; then
	    [ -w /etc/iproute2/rt_table -a -z "$KEEP_RT_TABLES" ] && cp -f ${VARDIR}/rt_tables /etc/iproute2/ && progress_message "/etc/iproute2/rt_tables database restored"
	    rm -f ${VARDIR}/rt_tables
	fi
	#
	# Restore the rest of the routing table
	#
	if [ -f ${VARDIR}/undo_routing ]; then
	    . ${VARDIR}/undo_routing
	    progress_message "Shorewall-generated routing tables and routing rules removed"
	    rm -f ${VARDIR}/undo_routing
	fi
    fi

}

#
# Restore the default route that was in place before the initial 'shorewall start'
#
restore_default_route() {
    local result

    if [ -z "$g_noroutes" -a -f ${VARDIR}/default_route ]; then
	local default_route
	default_route=
	local route
	result=1

	while read route ; do
	    case $route in
		default*)
		    if [ -n "$default_route" ]; then
			case "$default_route" in
			    *metric*)
		                #
		                # Don't restore a route with a metric -- we only replace the one with metric == 0
		                #
				qt $IP -4 route delete default metric 0 && \
				    progress_message "Default Route with metric 0 deleted"
				;;
			    *)
				qt $IP -4 route replace $default_route && \
				    result=0 && \
				    progress_message "Default Route (${default_route# }) restored"
				;;
			esac

			break
		    fi

		    default_route="$default_route $route"
		    ;;
		*)
		    default_route="$default_route $route"
		    ;;
	    esac
	done < ${VARDIR}/default_route

	rm -f ${VARDIR}/default_route
    fi

    return $result
}

#
# Determine the MAC address of the passed IP through the passed interface
#
find_mac() # $1 = IP address, $2 = interface
{
    if interface_is_usable $2 ; then
	qt ping -nc 1 -t 2 -I $2 $1

	local result
	result=$($IP neigh list |  awk "/^$1 / {print \$5}")

	case $result in
	    \<*\>)
		;;
	    *)
		[ -n "$result" ] && echo $result
		;;
	esac
    fi
}

#
# Flush the conntrack table if $g_purge is non-empty
#
conditionally_flush_conntrack() {

    if [ -n "$g_purge" ]; then
	if [ -n $(mywhich conntrack) ]; then
            conntrack -F
	else
            error_message "WARNING: The '-p' option requires the conntrack utility which does not appear to be installed on this system"
	fi
    fi
}

#
# Clear Proxy Arp
#
delete_proxyarp() {
    if [ -f ${VARDIR}/proxyarp ]; then
	while read address interface external haveroute; do
	    qt arp -i $external -d $address pub
	    [ -z "${haveroute}${g_noroutes}" ] && qt $IP -4 route del $address dev $interface
	    f=/proc/sys/net/ipv4/conf/$interface/proxy_arp
	    [ -f $f ] && echo 0 > $f
	done < ${VARDIR}/proxyarp

	rm -f ${VARDIR}/proxyarp
    fi
}

#
# Remove all Shorewall-added rules
#
clear_firewall() {
    stop_firewall

    setpolicy INPUT ACCEPT
    setpolicy FORWARD ACCEPT
    setpolicy OUTPUT ACCEPT

    run_iptables -F
    qt $IPTABLES -t raw -F

    echo 1 > /proc/sys/net/ipv4/ip_forward

    if [ -n "$DISABLE_IPV6" ]; then
	if [ -x $IP6TABLES ]; then
    	    $IP6TABLES -P INPUT   ACCEPT 2> /dev/null
	    $IP6TABLES -P OUTPUT  ACCEPT 2> /dev/null
	    $IP6TABLES -P FORWARD ACCEPT 2> /dev/null
	fi
    fi

    run_clear_exit

    set_state "Cleared"

    logger -p kern.info "$g_product Cleared"
}

#
# Issue a message and stop/restore the firewall
#
fatal_error()
{
    echo "   ERROR: $@" >&2

    if [ $LOG_VERBOSITY -ge 0 ]; then
        timestamp="$(date +'%_b %d %T') "
        echo "${timestamp}  ERROR: $@" >> $STARTUP_LOG
    fi

    stop_firewall
    [ -n "$TEMPFILE" ] && rm -f $TEMPFILE
    exit 2
}

#
# Issue a message and stop
#
startup_error() # $* = Error Message
{
    echo "   ERROR: $@: Firewall state not changed" >&2

    if [ $LOG_VERBOSITY -ge 0 ]; then
        timestamp="$(date +'%_b %d %T') "
        echo "${timestamp}  ERROR: $@" >> $STARTUP_LOG
    fi

    case $COMMAND in
        start)
	    logger -p kern.err "ERROR:$g_product start failed:Firewall state not changed"
	    ;;
	restart)
	    logger -p kern.err "ERROR:$g_product restart failed:Firewall state not changed"
	    ;;
	restore)
	    logger -p kern.err "ERROR:$g_product restore failed:Firewall state not changed"
	    ;;
    esac

    if [ $LOG_VERBOSITY -ge 0 ]; then
        timestamp="$(date +'%_b %d %T') "

	case $COMMAND in
	    start)
		echo "${timestamp}  ERROR:$g_product start failed:Firewall state not changed" >> $STARTUP_LOG
		;;
	    restart)
		echo "${timestamp}  ERROR:$g_product restart failed:Firewall state not changed" >> $STARTUP_LOG
		;;
	    restore)
		echo "${timestamp}  ERROR:$g_product restore failed:Firewall state not changed" >> $STARTUP_LOG
		;;
	esac
    fi

    kill $$
    exit 2
}

#
# Run iptables and if an error occurs, stop/restore the firewall
#
run_iptables()
{
    local status

    while [ 1 ]; do
	$IPTABLES $@
	status=$?
	[ $status -ne 4 ] && break
    done

    if [ $status -ne 0 ]; then
        error_message "ERROR: Command \"$IPTABLES $@\" Failed"
	stop_firewall
        exit 2
    fi
}

#
# Run iptables retrying exit status 4
#
do_iptables()
{
    local status

    while [ 1 ]; do
	$IPTABLES $@
	status=$?
	[ $status -ne 4 ] && return $status;
    done
}

#
# Run iptables and if an error occurs, stop/restore the firewall
#
run_ip()
{
    if ! $IP -4 $@; then
	error_message "ERROR: Command \"$IP -4 $@\" Failed"
	stop_firewall
	exit 2
    fi
}

#
# Run tc and if an error occurs, stop/restore the firewall
#
run_tc() {
    if ! $TC $@ ; then
	error_message "ERROR: Command \"$TC $@\" Failed"
	stop_firewall
	exit 2
    fi
}

#
# Get a list of all configured broadcast addresses on the system
#
get_all_bcasts()
{
    $IP -f inet addr show 2> /dev/null | grep 'inet.*brd' | grep -v '/32 ' | sed 's/inet.*brd //; s/scope.*//;' | sort -u
}

#
# Run the .iptables_restore_input as a set of discrete iptables commands
#
debug_restore_input() {
    local first second rest table chain
    #
    # Clear the ruleset
    #
    qt1 $IPTABLES -t mangle -F
    qt1 $IPTABLES -t mangle -X

    for chain in PREROUTING INPUT FORWARD POSTROUTING; do
	qt1 $IPTABLES -t mangle -P $chain ACCEPT
    done

    qt1 $IPTABLES -t raw    -F
    qt1 $IPTABLES -t raw    -X

    for chain in PREROUTING OUTPUT; do
	qt1 $IPTABLES -t raw -P $chain ACCEPT
    done

    run_iptables -t nat -F
    run_iptables -t nat -X

    for chain in PREROUTING POSTROUTING OUTPUT; do
	qt1 $IPTABLES -t nat -P $chain ACCEPT
    done

    qt1 $IPTABLES -t filter -F
    qt1 $IPTABLES -t filter -X

    for chain in INPUT FORWARD OUTPUT; do
	qt1 $IPTABLES -t filter -P $chain -P ACCEPT
    done

    while read first second rest; do
	case $first in
	    -*)
		#
		# We can't call run_iptables() here because the rules may contain quoted strings
		#
		eval $IPTABLES -t $table $first $second $rest

		if [ $? -ne 0 ]; then
		    error_message "ERROR: Command \"$IPTABLES $first $second $rest\" Failed"
		    stop_firewall
		    exit 2
		fi
		;;
	    :*)
		chain=${first#:}

		if [ "x$second" = x- ]; then
		    do_iptables -t $table -N $chain
		else
		    do_iptables -t $table -P $chain $second
		fi

		if [ $? -ne 0 ]; then
		    error_message "ERROR: Command \"$IPTABLES $first $second $rest\" Failed"
		    stop_firewall
		    exit 2
		fi
		;;
	    #
	    # This grotesque hack with the table names works around a bug/feature with ash
	    #
	    '*'raw)
		table=raw
		;;
	    '*'mangle)
		table=mangle
		;;
	    '*'nat)
		table=nat
		;;
	    '*'filter)
		table=filter
		;;
	esac
    done
}

################################################################################
# End of functions in /usr/share/shorewall/prog.header
################################################################################
################################################################################
#   Functions imported from /usr/share/shorewall/lib.common
################################################################################

#
# Get the Shorewall version of the passed script
#
get_script_version() { # $1 = script
    local temp
    local version
    local ifs
    local digits
    local verbosity

    verbosity="$VERBOSITY"
    VERBOSITY=0

    temp=$( $SHOREWALL_SHELL $1 version | sed 's/-.*//' )

    if [ $? -ne 0 ]; then
	version=0
    else
	ifs=$IFS
	IFS=.
	temp=$(echo $temp)
	IFS=$ifs
	digits=0

	for temp in $temp; do
	    version=${version}$(printf '%02d' $temp)
	    digits=$(($digits + 1))
	    [ $digits -eq 3 ] && break
	done
    fi

    echo $version

    VERBOSITY="$verbosity"
}

#
# Do required exports or create the required option string and run the passed script using
# $SHOREWALL_SHELL
#
run_it() {
    local script
    local options
    local version

    export VARDIR

    script=$1
    shift

    version=$(get_script_version $script)

    if [ $version -lt 040408 ]; then
	#
	# Old script that doesn't understand 4.4.8 script options
	#
	export RESTOREFILE
	export VERBOSITY
	export NOROUTES=$g_noroutes
	export PURGE=$g_purge
	export TIMESTAMP=$g_timestamp
	export RECOVERING=$g_recovering

	if [ "$g_product" != Shorewall ]; then
	    #
	    # Shorewall Lite
	    #
	    export LOGFORMAT
	    export IPTABLES
	fi
    else
	#
	# 4.4.8 or later -- no additional exports required
	#
	if [ x$1 = xtrace -o x$1 = xdebug ]; then
	    options="$1 -"
	    shift;
	else
	    options='-'
	fi

	[ -n "$g_noroutes" ]   && options=${options}n
	[ -n "$g_timestamp" ]  && options=${options}t
	[ -n "$g_purge" ]      && options=${options}p
	[ -n "$g_recovering" ] && options=${options}r

	options="${options}V $VERBOSITY"

	[ -n "$RESTOREFILE" ] && options="${options} -R $RESTOREFILE"
    fi

    $SHOREWALL_SHELL $script $options $@
}

#
# Message to stderr
#
error_message() # $* = Error Message
{
   echo "   $@" >&2
}

#
# Split a colon-separated list into a space-separated list
#
split() {
    local ifs
    ifs=$IFS
    IFS=:
    echo $*
    IFS=$ifs
}

#
# Search a list looking for a match -- returns zero if a match found
# 1 otherwise
#
list_search() # $1 = element to search for , $2-$n = list
{
    local e
    e=$1

    while [ $# -gt 1 ]; do
	shift
	[ "x$e" = "x$1" ] && return 0
    done

    return 1
}

#
# Suppress all output for a command
#
qt()
{
    "$@" >/dev/null 2>&1
}

qt1()
{
    local status

    while [ 1 ]; do
	"$@" >/dev/null 2>&1
	status=$?
	[ $status -ne 4 ] && return $status
    done
}

#
# Determine if Shorewall is "running"
#
shorewall_is_started() {
    qt $IPTABLES -L shorewall -n
}

#
# Echos the fully-qualified name of the calling shell program
#
my_pathname() {
    cd $(dirname $0)
    echo $PWD/$(basename $0)
}

#
# Source a user exit file if it exists
#
run_user_exit() # $1 = file name
{
    local user_exit
    user_exit=$(find_file $1)

    if [ -f $user_exit ]; then
	progress_message "Processing $user_exit ..."
	. $user_exit
    fi
}

#
# Load a Kernel Module -- assumes that the variable 'moduledirectories' contains
#                         a space-separated list of directories to search for
#                         the module and that 'moduleloader' contains the
#                         module loader command.
#
loadmodule() # $1 = module name, $2 - * arguments
{
    local modulename
    modulename=$1
    local modulefile
    local suffix

    if ! list_search $modulename $DONT_LOAD $MODULES; then
	shift

	for suffix in $MODULE_SUFFIX ; do
	    for directory in $moduledirectories; do
		modulefile=$directory/${modulename}.${suffix}

		if [ -f $modulefile ]; then
		    case $moduleloader in
			insmod)
			    insmod $modulefile $*
			    ;;
			*)
			    modprobe $modulename $*
			    ;;
		    esac
		    break 2
		fi
	    done
	done
    fi
}

#
# Reload the Modules
#
reload_kernel_modules() {

    local save_modules_dir
    save_modules_dir=$MODULESDIR
    local directory
    local moduledirectories
    moduledirectories=
    local moduleloader
    moduleloader=modprobe
    local uname

    if ! qt mywhich modprobe; then
	moduleloader=insmod
    fi

    [ -n "${MODULE_SUFFIX:=o gz ko o.gz ko.gz}" ]

    [ -z "$MODULESDIR" ] && \
	uname=$(uname -r) && \
	MODULESDIR=/lib/modules/$uname/kernel/net/ipv4/netfilter:/lib/modules/$uname/kernel/net/netfilter:/lib/modules/$uname/kernel/net/sched:/lib/modules/$uname/extra:/lib/modules/$uname/extra/ipset

    MODULES=$(lsmod | cut -d ' ' -f1)

    for directory in $(split $MODULESDIR); do
	[ -d $directory ] && moduledirectories="$moduledirectories $directory"
    done

    [ -n "$moduledirectories" ] && while read command; do
	eval $command
    done

    MODULESDIR=$save_modules_dir
}

#
# Load kernel modules required for Shorewall
#
load_kernel_modules() # $1 = Yes, if we are to save moduleinfo in $VARDIR
{
    local save_modules_dir
    save_modules_dir=$MODULESDIR
    local directory
    local moduledirectories
    moduledirectories=
    local moduleloader
    moduleloader=modprobe
    local savemoduleinfo
    savemoduleinfo=${1:-Yes} # So old compiled scripts still work
    local uname

    if ! qt mywhich modprobe; then
	moduleloader=insmod
    fi

    [ -n "${MODULE_SUFFIX:=o gz ko o.gz ko.gz}" ]

    [ -z "$MODULESDIR" ] && \
	uname=$(uname -r) && \
	MODULESDIR=/lib/modules/$uname/kernel/net/ipv4/netfilter:/lib/modules/$uname/kernel/net/netfilter:/lib/modules/$uname/kernel/net/sched:/lib/modules/$uname/extra:/lib/modules/$uname/extra/ipset

    for directory in $(split $MODULESDIR); do
	[ -d $directory ] && moduledirectories="$moduledirectories $directory"
    done

    [ -n "$LOAD_HELPERS_ONLY" ] && modules=$(find_file helpers) || modules=$(find_file modules)

    if [ -f $modules -a -n "$moduledirectories" ]; then
	MODULES=$(lsmod | cut -d ' ' -f1)
	progress_message "Loading Modules..."
	. $modules
	if [ $savemoduleinfo = Yes ]; then
	    [ -d ${VARDIR} ] || mkdir -p ${VARDIR}
	    echo MODULESDIR="$MODULESDIR" > ${VARDIR}/.modulesdir
	    cp -f $modules ${VARDIR}/.modules
	fi
    elif [ $savemoduleinfo = Yes ]; then
	[ -d ${VARDIR} ] || mkdir -p ${VARDIR}
	> ${VARDIR}/.modulesdir
	> ${VARDIR}/.modules
    fi

    MODULESDIR=$save_modules_dir
}

#
#  Note: The following set of IP address manipulation functions have anomalous
#        behavior when the shell only supports 32-bit signed arithmetic and
#        the IP address is 128.0.0.0 or 128.0.0.1.
#

LEFTSHIFT='<<'

#
# Convert an IP address in dot quad format to an integer
#
decodeaddr() {
    local x
    local temp
    temp=0
    local ifs
    ifs=$IFS

    IFS=.

    for x in $1; do
	temp=$(( $(( $temp $LEFTSHIFT 8 )) | $x ))
    done

    echo $temp

    IFS=$ifs
}

#
# convert an integer to dot quad format
#
encodeaddr() {
    addr=$1
    local x
    local y
    y=$(($addr & 255))

    for x in 1 2 3 ; do
	addr=$(($addr >> 8))
	y=$(($addr & 255)).$y
    done

    echo $y
}

#
# Netmask from CIDR
#
ip_netmask() {
    local vlsm
    vlsm=${1#*/}

    [ $vlsm -eq 0 ] && echo 0 || echo $(( -1 $LEFTSHIFT $(( 32 - $vlsm )) ))
}

#
# Network address from CIDR
#
ip_network() {
    local decodedaddr
    decodedaddr=$(decodeaddr ${1%/*})
    local netmask
    netmask=$(ip_netmask $1)

    echo $(encodeaddr $(($decodedaddr & $netmask)))
}

#
# The following hack is supplied to compensate for the fact that many of
# the popular light-weight Bourne shell derivatives don't support XOR ("^").
#
ip_broadcast() {
    local x
    x=$(( 32 - ${1#*/} ))

    [ $x -eq 32 ] && echo -1 || echo $(( $(( 1 $LEFTSHIFT $x )) - 1 ))
}

#
# Calculate broadcast address from CIDR
#
broadcastaddress() {
    local decodedaddr
    decodedaddr=$(decodeaddr ${1%/*})
    local netmask
    netmask=$(ip_netmask $1)
    local broadcast
    broadcast=$(ip_broadcast $1)

    echo $(encodeaddr $(( $(($decodedaddr & $netmask)) | $broadcast )))
}

#
# Test for network membership
#
in_network() # $1 = IP address, $2 = CIDR network
{
    local netmask
    netmask=$(ip_netmask $2)
    #
    # Use string comparison to work around a broken BusyBox ash in OpenWRT
    #
    test $(( $(decodeaddr $1) & $netmask)) = $(( $(decodeaddr ${2%/*}) & $netmask ))
}

#
# Find interface address--returns the first IP address assigned to the passed
# device
#
find_first_interface_address() # $1 = interface
{
    #
    # get the line of output containing the first IP address
    #
    addr=$(${IP:-ip} -f inet addr show $1 2> /dev/null | grep 'inet .* global' | head -n1)
    #
    # If there wasn't one, bail out now
    #
    [ -n "$addr" ] || startup_error "Can't determine the IP address of $1"
    #
    # Strip off the trailing VLSM mask (or the peer IP in case of a P-t-P link)
    # along with everything else on the line
    #
    echo $addr | sed 's/\s*inet //;s/\/.*//;s/ peer.*//'
}

find_first_interface_address_if_any() # $1 = interface
{
    #
    # get the line of output containing the first IP address
    #
    addr=$(${IP:-ip} -f inet addr show $1 2> /dev/null | grep 'inet .* global' | head -n1)
    #
    # Strip off the trailing VLSM mask (or the peer IP in case of a P-t-P link)
    # along with everything else on the line
    #
    [ -n "$addr" ] && echo $addr | sed 's/\s*inet //;s/\/.*//;s/ peer.*//' || echo 0.0.0.0
}

#
# Internal version of 'which'
#
mywhich() {
    local dir

    for dir in $(split $PATH); do
	if [ -x $dir/$1 ]; then
	    echo $dir/$1
	    return 0
	fi
    done

    return 2
}

#
# Query NetFilter about the existence of a filter chain
#
chain_exists() # $1 = chain name
{
    qt1 $IPTABLES -L $1 -n
}

#
# Find a File -- For relative file name, look in each ${CONFIG_PATH} then ${CONFDIR}
#
find_file()
{
    local saveifs
    saveifs=
    local directory

    case $1 in
	/*)
	    echo $1
	    ;;
	*)
	    for directory in $(split $CONFIG_PATH); do
		if [ -f $directory/$1 ]; then
		    echo $directory/$1
		    return
		fi
	    done

	    echo ${CONFDIR}/$1
	    ;;
    esac
}

#
# Set the Shorewall state
#
set_state () # $1 = state $2
{
    if [ $# -gt 1 ]; then
	echo "$1 ($(date)) from $2" > ${VARDIR}/state
    else
	echo "$1 ($(date))" > ${VARDIR}/state
    fi
}

#
# Perform variable substitution on the passed argument and echo the result
#
expand() # $@ = contents of variable which may be the name of another variable
{
    eval echo \"$@\"
}

#
# Function for including one file into another
#
INCLUDE() {
    . $(find_file $(expand $@))
}

# Function to truncate a string -- It uses 'cut -b -<n>'
# rather than ${v:first:last} because light-weight shells like ash and
# dash do not support that form of expansion.
#

truncate() # $1 = length
{
    cut -b -${1}
}

################################################################################
#   End of imports from /usr/share/shorewall/lib.common
################################################################################
################################################################################
# Functions to execute the various user exits (extension scripts)
################################################################################

run_init_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/init ...

    #
    # Shorewall version 4 - Init File
    #
    # /etc/shorewall/init
    #
    #	Add commands below that you want to be executed at the beginning of
    #	a "shorewall start" or "shorewall restart" command.
    #
    # For additional information, see
    # http://shorewall.net/shorewall_extension_scripts.htm
    #
    ###############################################################################
}

run_start_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/start ...

    #
    # Shorewall version 4 - Start File
    #
    # /etc/shorewall/start
    #
    #	Add commands below that you want to be executed after shorewall has
    #	been started or restarted.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
    return 0
}

run_tcclear_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/tcclear ...

    #
    # Shorewall version 4 - tcclear File
    #
    # /etc/shorewall/tcclear
    #
    #	Add commands below that you want to be executed before Shorewall
    #       clears the traffic shaping configuration.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_started_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/started ...

    #
    # Shorewall version 4 - Started File
    #
    # /etc/shorewall/started
    #
    #	Add commands below that you want to be executed after shorewall has
    #	been completely started or restarted. The difference between this
    #	extension script and /etc/shorewall/start is that this one is invoked
    #	after delayed loading of the blacklist (DELAYBLACKLISTLOAD=Yes) and
    #	after the 'shorewall' chain has been created (thus signaling that the
    #	firewall is completely up).
    #
    #	This script should not change the firewall configuration directly but
    #	may do so indirectly by running /sbin/shorewall with the 'nolock'
    #	option.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_stop_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/stop ...

    #
    # Shorewall version 4 - Stop File
    #
    # /etc/shorewall/stop
    #
    #	Add commands below that you want to be executed at the beginning of a
    #	"shorewall stop" command.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_stopped_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/stopped ...

    #
    # Shorewall version 4 - Stopped File
    #
    # /etc/shorewall/stopped
    #
    #	Add commands below that you want to be executed at the completion of a
    #	"shorewall stop" command.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_clear_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/clear ...

    #
    # Shorewall version 4 - clear File
    #
    # /etc/shorewall/clear
    #
    #	Add commands below that you want to be executed after Shorewall
    #       has processed the 'clear' command.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_refresh_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/refresh ...

    #
    # Shorewall version 4 - refresh File
    #
    # /etc/shorewall/refresh
    #
    #	Add commands below that you want to be executed before Shorewall
    #       has processed the 'refresh' command.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_refreshed_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/refreshed ...

    #
    # Shorewall version 4 - refreshed File
    #
    # /etc/shorewall/refreshed
    #
    #	Add commands below that you want to be executed after Shorewall
    #       has processed the 'refresh' command.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_restored_exit() {
    
    progress_message2 Processing /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/restored ...

    #
    # Shorewall version 4 - Restored File
    #
    # /etc/shorewall/restored
    #
    #	Add commands below that you want to be executed after shorewall has
    #	completed a 'restore' command. 
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
}

run_isusable_exit() {
    #
    # Shorewall version 4 - isusable File
    #
    # /etc/shorewall/isusable
    #
    #	This script is called when Shorewall is attempting to determine
    #	if an interface named in /etc/shorewall/providers is usable.
    #
    #	The script is invoked inside a function that accepts an interface
    #	name as a single argument. The file below is designed to work with
    #	both swping and lsm as described at
    #	http://www.shorewall.net/MultiISP.html
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
    local status
    status=0

    [ -f ${VARDIR}/${1}.status ] && status=$(cat ${VARDIR}/${1}.status)

    return $status
}

run_findgw_exit() {
    #
    # Shorewall version 4 - Findgw File
    #
    # /etc/shorewall/findgw
    #
    #    The code in this file is executed when Shorewall is trying to detect the 
    #    gateway through an interface in /etc/shorewall/providers that has GATEWAY
    #    specified as 'detect'.
    #
    #    The function should echo the IP address of the gateway if it knows what 
    #    it is; the name of the interface is in $1.
    #
    # See http://shorewall.net/shorewall_extension_scripts.htm for additional
    # information.
    #
    ###############################################################################
    true
}
################################################################################
# End user exit functions
################################################################################

#
# Setup Common Rules (/proc)
#
setup_common_rules() {
    
    progress_message2 Setting up Route Filtering...

    for file in /proc/sys/net/ipv4/conf/*; do
	[ -f $file/rp_filter ] && echo 0 > $file/rp_filter
    done

    if [ -f /proc/sys/net/ipv4/conf/eth0/rp_filter ]; then
	echo 1 > /proc/sys/net/ipv4/conf/eth0/rp_filter
    else
	error_message "WARNING: Cannot set route filtering on eth0"
    fi

    echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter
    echo 0 > /proc/sys/net/ipv4/conf/default/rp_filter
    [ -n "$g_noroutes" ] || $IP -4 route flush cache
    
    progress_message2 Setting up Martian Logging...

    for file in /proc/sys/net/ipv4/conf/*; do
	[ -f $file/log_martians ] && echo 1 > $file/log_martians
    done

    echo 0 > /proc/sys/net/ipv4/conf/all/log_martians

    progress_message2 Setting up Proxy ARP...

    return 0
}

#
# Setup routing and traffic shaping
#
setup_routing_and_traffic_shaping() {
    
    if [ -z "$g_noroutes" ]; then
	
	undo_routing
	restore_default_route
    fi

    progress_message2 "Setting up Traffic Control..."

}

#
# This function initializes the global variables used by the program
#
initialize()
{
    #
    # Be sure that umask is sane
    #
    umask 077
    #
    # These variables are required by the library functions called in this script
    #
    SHAREDIR=/usr/share/shorewall-lite
    CONFDIR=/etc/shorewall-lite
    g_product="Shorewall Lite"
    [ -f ${CONFDIR}/vardir ] && . ${CONFDIR}/vardir
    CONFIG_PATH="/etc/shorewall-lite:/usr/share/shorewall-lite"
    [ -n "${VARDIR:=/var/lib/shorewall-lite}" ]
    TEMPFILE=
    DISABLE_IPV6=""
    MODULESDIR=""
    MODULE_SUFFIX="ko"
    LOAD_HELPERS_ONLY=""
    SUBSYSLOCK="/var/lock/subsys/shorewall"
    LOG_VERBOSITY="2"
    [ -n "${COMMAND:=restart}" ]
    [ -n "${VERBOSITY:=0}" ]
    [ -n "${RESTOREFILE:=restore}" ]
    SHOREWALL_VERSION="4.4.14"
    PATH="/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin"
    TERMINATOR=fatal_error
    DONT_LOAD=""
    STARTUP_LOG="/var/log/shorewall-lite-init.log"

    [ -z "$IPTABLES" ] && IPTABLES=$(mywhich iptables) # /sbin/shorewall exports IPTABLES
    [ -n "$IPTABLES" -a -x "$IPTABLES" ] || startup_error "Can't find iptables executable"

    case $IPTABLES in
	*/*)
	    ;;
	*)
	    IPTABLES=./$IPTABLES
	    ;;
    esac

    IP6TABLES=${IPTABLES%/*}/ip6tables
    IPTABLES_RESTORE=${IPTABLES}-restore
    [ -x "$IPTABLES_RESTORE" ] || startup_error "$IPTABLES_RESTORE does not exist or is not executable"
    IP=ip
    TC=tc
    IPSET=ipset

    g_stopping=

    #
    # The library requires that ${VARDIR} exist
    #
    [ -d ${VARDIR} ] || mkdir -p ${VARDIR}

}

#
# Set global variables holding detected IP information
#
detect_configuration()
{
    true

}

#
# Create the input to iptables-restore/ip6tables-restore and pass that input to the utility
#
setup_netfilter()
{
    
    progress_message2 Preparing iptables-restore input...

    exec 3>${VARDIR}/.iptables-restore-input

    cat >&3 << __EOF__
#
# Generated by Shorewall 4.4.14 - Mon Nov 29 23:36:39 2010
#
*raw
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
*nat
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:fortos - [0:0]
:tcfor - [0:0]
:tcin - [0:0]
:tcout - [0:0]
:tcpost - [0:0]
:tcpre - [0:0]
-A PREROUTING -j tcpre
-A INPUT -j tcin
-A FORWARD -j MARK --set-mark 0
-A FORWARD -j tcfor
-A FORWARD -j fortos
-A OUTPUT -j tcout
-A POSTROUTING -j tcpost
-A fortos -p 6 --dport 22 -j TOS --set-tos 16
-A fortos -p 6 --sport 22 -j TOS --set-tos 16
-A fortos -p 6 --dport 21 -j TOS --set-tos 16
-A fortos -p 6 --sport 21 -j TOS --set-tos 16
-A fortos -p 6 --sport 20 -j TOS --set-tos 8
-A fortos -p 6 --dport 20 -j TOS --set-tos 8
-A fortos -p 6 --sport 873 -j TOS --set-tos 8
-A fortos -p 6 --dport 873 -j TOS --set-tos 8
COMMIT
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:%Knock - [0:0]
:%rejNotSyn - [0:0]
:Drop - [0:0]
:Reject - [0:0]
:dropBcast - [0:0]
:dropInvalid - [0:0]
:dropNotSyn - [0:0]
:dynamic - [0:0]
:fw2net - [0:0]
:fw2vpn - [0:0]
:logdrop - [0:0]
:logflags - [0:0]
:logreject - [0:0]
:net2fw - [0:0]
:net2vpn - [0:0]
:reject - [0:0]
:smurflog - [0:0]
:smurfs - [0:0]
:tcpflags - [0:0]
:vpn2fw - [0:0]
:vpn2net - [0:0]
:vpn_frwd - [0:0]
-A INPUT -m conntrack --ctstate NEW,INVALID -j dynamic
-A INPUT -i eth0 -j net2fw
-A INPUT -i tap0 -j vpn2fw
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -j Reject
-A INPUT -g reject
-A FORWARD -m conntrack --ctstate NEW,INVALID -j dynamic
-A FORWARD -i eth0 -o tap0 -j net2vpn
-A FORWARD -i tap0 -j vpn_frwd
-A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -j Reject
-A FORWARD -g reject
-A OUTPUT -o eth0 -j fw2net
-A OUTPUT -o tap0 -j fw2vpn
-A OUTPUT -o lo -j ACCEPT
-A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT
-A %Knock -p tcp --dport 22     -m recent --rcheck --seconds 60 --name Knock-22          -j ACCEPT
-A %Knock -p tcp --dport 2221  -m recent                            --name Knock-22 --remove -j DROP
-A %Knock -p tcp --dport 2222      -m recent                            --name Knock-22 --set    -j DROP
-A %Knock -p tcp --dport 2223 -m recent                            --name Knock-22 --remove -j DROP
-A %rejNotSyn -p 6 ! --syn -j LOG --log-level 6 --log-prefix "Shorewall:rejNotSyn:REJECT:" 
-A %rejNotSyn -p 6 ! --syn -j REJECT --reject-with tcp-reset
-A Drop 
-A Drop -p 6 --dport 113 -j reject -m comment --comment "Auth"
-A Drop -j dropBcast
-A Drop -p 1 --icmp-type 3/4 -j ACCEPT -m comment --comment "Needed ICMP types"
-A Drop -p 1 --icmp-type 11 -j ACCEPT -m comment --comment "Needed ICMP types"
-A Drop -j dropInvalid
-A Drop -p 17 -m multiport --dports 135,445 -j DROP -m comment --comment "SMB"
-A Drop -p 17 --dport 137:139 -j DROP -m comment --comment "SMB"
-A Drop -p 17 --dport 1024:65535 --sport 137 -j DROP -m comment --comment "SMB"
-A Drop -p 6 -m multiport --dports 135,139,445 -j DROP -m comment --comment "SMB"
-A Drop -p 17 --dport 1900 -j DROP -m comment --comment "UPnP"
-A Drop -p 6 -j dropNotSyn
-A Drop -p 17 --sport 53 -j DROP -m comment --comment "Late DNS Replies"
-A Reject 
-A Reject -p 6 --dport 113 -j reject -m comment --comment "Auth"
-A Reject -j dropBcast
-A Reject -p 1 --icmp-type 3/4 -j ACCEPT -m comment --comment "Needed ICMP types"
-A Reject -p 1 --icmp-type 11 -j ACCEPT -m comment --comment "Needed ICMP types"
-A Reject -j dropInvalid
-A Reject -p 17 -m multiport --dports 135,445 -j reject -m comment --comment "SMB"
-A Reject -p 17 --dport 137:139 -j reject -m comment --comment "SMB"
-A Reject -p 17 --dport 1024:65535 --sport 137 -j reject -m comment --comment "SMB"
-A Reject -p 6 -m multiport --dports 135,139,445 -j reject -m comment --comment "SMB"
-A Reject -p 17 --dport 1900 -j DROP -m comment --comment "UPnP"
-A Reject -p 6 -j dropNotSyn
-A Reject -p 17 --sport 53 -j DROP -m comment --comment "Late DNS Replies"
-A dropBcast -m addrtype --dst-type BROADCAST -j DROP
-A dropBcast -d 224.0.0.0/4 -j DROP
-A dropInvalid -m conntrack --ctstate INVALID -j DROP
-A dropNotSyn -p 6 ! --syn -j DROP
__EOF__

    [ -f ${VARDIR}/.dynamic ] && cat ${VARDIR}/.dynamic >&3

    cat >&3 << __EOF__
-A fw2net -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A fw2net -p udp -d 217.150.130.114  --dport 1194 -j ACCEPT
-A fw2net -j %rejNotSyn
-A fw2net -j ACCEPT
-A fw2vpn -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A fw2vpn -j %rejNotSyn
-A fw2vpn -j ACCEPT
-A logdrop  -j DROP
-A logflags -j LOG --log-ip-options --log-level 6 --log-prefix "Shorewall:logflags:DROP:" 
-A logflags -j DROP
-A logreject  -j reject
-A net2fw -m conntrack --ctstate NEW,INVALID -j smurfs
-A net2fw -p tcp -j tcpflags
-A net2fw -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A net2fw -p udp -s 217.150.130.114  --sport 1194 -j ACCEPT
-A net2fw -j %rejNotSyn
-A net2fw -p 1 --icmp-type 8 -j ACCEPT -m comment --comment "Ping"
-A net2fw -p 17 --dport 33434:33524 -j ACCEPT -m comment --comment "Trcrt"
-A net2fw -p 1 --icmp-type 8 -j ACCEPT -m comment --comment "Trcrt"
-A net2fw -p 6 --dport 80 -j ACCEPT -m comment --comment "Web"
-A net2fw -p 6 --dport 443 -j ACCEPT -m comment --comment "Web"
-A net2fw -p 6 -m multiport --dports 20200,20201,20202,21200,21201,21202,21300,22200,22201,22202,22300 -j ACCEPT
-A net2fw -s 160.114.8.24 -j ACCEPT
-A net2fw -s 212.92.23.55 -j ACCEPT
-A net2fw -s 212.92.23.223 -j ACCEPT
-A net2fw -s 212.92.23.224 -j ACCEPT
-A net2fw -s 80.75.224.131 -j ACCEPT
-A net2fw -s 217.27.219.101 -j ACCEPT
-A net2fw -s 217.20.134.44 -j ACCEPT
-A net2fw -p 6 --dport 22 -s 160.114.8.24 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 212.92.23.55 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 212.92.23.223 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 212.92.23.224 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 80.75.224.131 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 217.27.219.101 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 217.20.134.44 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 --dport 22 -s 213.253.216.153 -j ACCEPT -m comment --comment "SSH"
-A net2fw -p 6 -m multiport --dports 22,2221,2222,2223 -j %Knock
-A net2fw -j Reject
-A net2fw -g reject
-A net2vpn -m conntrack --ctstate NEW,INVALID -j smurfs
-A net2vpn -p tcp -j tcpflags
-A net2vpn -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A net2vpn -j %rejNotSyn
-A net2vpn -j Reject
-A net2vpn -g reject
-A reject -m addrtype --src-type BROADCAST -j DROP
-A reject -s 224.0.0.0/4 -j DROP
-A reject -p 2 -j DROP
-A reject -p 6 -j REJECT --reject-with tcp-reset
-A reject -p 17 -j REJECT
-A reject -p 1 -j REJECT --reject-with icmp-host-unreachable
-A reject -j REJECT --reject-with icmp-host-prohibited
-A smurflog -j LOG --log-level 6 --log-prefix "Shorewall:smurfs:DROP:" 
-A smurflog -j DROP
-A smurfs -s 0.0.0.0 -j RETURN
-A smurfs -m addrtype --src-type BROADCAST -g smurflog
-A smurfs -s 224.0.0.0/4 -g smurflog
-A tcpflags -p tcp --tcp-flags ALL FIN,URG,PSH -g logflags
-A tcpflags -p tcp --tcp-flags ALL NONE -g logflags
-A tcpflags -p tcp --tcp-flags SYN,RST SYN,RST -g logflags
-A tcpflags -p tcp --tcp-flags SYN,FIN SYN,FIN -g logflags
-A tcpflags -p tcp --syn --sport 0 -g logflags
-A vpn2fw -m conntrack --ctstate NEW,INVALID -j smurfs
-A vpn2fw -p tcp -j tcpflags
-A vpn2fw -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A vpn2fw -j %rejNotSyn
-A vpn2fw -j ACCEPT
-A vpn2net -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A vpn2net -j %rejNotSyn
-A vpn2net -j Reject
-A vpn2net -g reject
-A vpn_frwd -m conntrack --ctstate NEW,INVALID -j smurfs
-A vpn_frwd -p tcp -j tcpflags
-A vpn_frwd -o eth0 -j vpn2net
-A vpn_frwd -o tap0 -j ACCEPT
COMMIT
__EOF__

    exec 3>&-

    [ -n "$DEBUG" ] && command=debug_restore_input || command=$IPTABLES_RESTORE

    progress_message2 "Running $command..."

    cat ${VARDIR}/.iptables-restore-input | $command # Use this nonsensical form to appease SELinux
    if [ $? != 0 ]; then
	fatal_error "iptables-restore Failed. Input is in ${VARDIR}/.iptables-restore-input"
    fi

}

chainlist_reload()
{
    
    progress_message2 Preparing iptables-restore input for chain mangle:...

    exec 3>${VARDIR}/.iptables-restore-input

    cat >&3 << __EOF__
*mangle
:fortos - [0:0]
:tcfor - [0:0]
:tcin - [0:0]
:tcout - [0:0]
:tcpost - [0:0]
:tcpre - [0:0]
-A fortos -p 6 --dport 22 -j TOS --set-tos 16
-A fortos -p 6 --sport 22 -j TOS --set-tos 16
-A fortos -p 6 --dport 21 -j TOS --set-tos 16
-A fortos -p 6 --sport 21 -j TOS --set-tos 16
-A fortos -p 6 --sport 20 -j TOS --set-tos 8
-A fortos -p 6 --dport 20 -j TOS --set-tos 8
-A fortos -p 6 --sport 873 -j TOS --set-tos 8
-A fortos -p 6 --dport 873 -j TOS --set-tos 8
COMMIT
__EOF__

    exec 3>&-

    progress_message2 "Running iptables-restore..."

    cat ${VARDIR}/.iptables-restore-input | $IPTABLES_RESTORE -n # Use this nonsensical form to appease SELinux
    if [ $? != 0 ]; then
	fatal_error "iptables-restore Failed. Input is in ${VARDIR}/.iptables-restore-input"
    fi

}

#
# Start/Restart the Firewall
#
define_firewall() {
    
    progress_message2 Initializing...

    load_kernel_modules Yes
    if [ "$COMMAND" = refresh ]; then
       run_refresh_exit
    else
	run_init_exit
    fi

    if [ "$COMMAND" = restart -o "$COMMAND" = refresh ]; then
	if chain_exists 'UPnP -t nat'; then
	    ${IPTABLES}-save -t nat | grep '^-A UPnP ' > ${VARDIR}/.UPnP
	else
	    rm -f ${VARDIR}/.UPnP
	fi
	
	if chain_exists forwardUPnP; then
	    ${IPTABLES}-save -t filter | grep '^-A forwardUPnP ' > ${VARDIR}/.forwardUPnP
	else
	    rm -f ${VARDIR}/.forwardUPnP
	fi
	
	if chain_exists dynamic; then
	    ${IPTABLES}-save -t filter | grep '^-A dynamic ' > ${VARDIR}/.dynamic
	else
	    rm -f ${VARDIR}/.dynamic
	fi

    else
	rm -f ${VARDIR}/.UPnP
	rm -f ${VARDIR}/.forwardUPnP
	
	if [ "$COMMAND" = stop -o "$COMMAND" = clear ]; then
	    if chain_exists dynamic; then
		${IPTABLES}-save -t filter | grep '^-A dynamic ' > ${VARDIR}/.dynamic
	    fi
	fi

    fi

    qt1 $IPTABLES -L shorewall -n && qt1 $IPTABLES -F shorewall && qt1 $IPTABLES -X shorewall

    delete_proxyarp

    if [ -f ${VARDIR}/nat ]; then
	while read external interface; do
	    del_ip_addr $external $interface
	done < ${VARDIR}/nat

	rm -f ${VARDIR}/nat
    fi

    delete_tc1

    setup_common_rules

    setup_routing_and_traffic_shaping

    cat > ${VARDIR}/proxyarp << __EOF__
__EOF__

    if [ "$COMMAND" != refresh ]; then
	cat > ${VARDIR}/zones << __EOF__
fw firewall
net ipv4 eth0:0.0.0.0/0
vpn ipv4 tap0:0.0.0.0/0
__EOF__
	cat > ${VARDIR}/policies << __EOF__
fw 	=>	net	ACCEPT using chain fw2net
fw 	=>	vpn	ACCEPT using chain fw2vpn
net 	=>	fw	REJECT using chain net2fw
net 	=>	vpn	REJECT using chain net2vpn
vpn 	=>	fw	ACCEPT using chain vpn2fw
vpn 	=>	net	REJECT using chain vpn2net
__EOF__
    fi

    > ${VARDIR}/nat

    if [ $COMMAND = restore ]; then
	iptables_save_file=${VARDIR}/$(basename $0)-iptables
	if [ -f $iptables_save_file ]; then
	    cat $iptables_save_file | $IPTABLES_RESTORE # Use this nonsensical form to appease SELinux
	else
	    fatal_error "$iptables_save_file does not exist"
	fi

	echo 1 > /proc/sys/net/ipv4/ip_forward
	progress_message2 IPv4 Forwarding Enabled

	set_state Started /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/
	run_restored_exit
    else
	if [ $COMMAND = refresh ]; then
	    chainlist_reload

	    echo 1 > /proc/sys/net/ipv4/ip_forward
	    progress_message2 IPv4 Forwarding Enabled

	    run_refreshed_exit
	    do_iptables -N shorewall
	    set_state Started /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/
	else
	    setup_netfilter
	    conditionally_flush_conntrack

	    echo 1 > /proc/sys/net/ipv4/ip_forward
	    progress_message2 IPv4 Forwarding Enabled

	    run_start_exit
	    do_iptables -N shorewall
	    set_state Started /home/lfarkas/work/lenux/shorewall/dev-5.armadina.hu/
	    run_started_exit
	fi
    

	[ $0 = ${VARDIR}/firewall ] || cp -f $(my_pathname) ${VARDIR}/firewall
    fi
    
    date > ${VARDIR}/restarted
    
    case $COMMAND in
	start)
	    logger -p kern.info "$g_product started"
	    ;;
	restart)
	    logger -p kern.info "$g_product restarted"
	    ;;
	refresh)
	    logger -p kern.info "$g_product refreshed"
	    ;;
	restore)
	    logger -p kern.info "$g_product restored"
	    ;;
    esac

}

#
# Stop/restore the firewall after an error or because of a 'stop' or 'clear' command
#
stop_firewall() {
    local hack

    deletechain() {
	qt $IPTABLES -L $1 -n && qt $IPTABLES -F $1 && qt $IPTABLES -X $1
    }

    case $COMMAND in
	stop|clear|restore)
	    if chain_exists dynamic; then
		${IPTABLES}-save -t filter | grep '^-A dynamic' > ${VARDIR}/.dynamic
	    fi
	    ;;
	*)
	    set +x

	    case $COMMAND in
		start)
		    logger -p kern.err "ERROR:$g_product start failed"
		    ;;
		restart)
		    logger -p kern.err "ERROR:$g_product restart failed"
		    ;;
		refresh)
		    logger -p kern.err "ERROR:$g_product refresh failed"
		    ;;
	    esac

	    if [ "$RESTOREFILE" = NONE ]; then
		COMMAND=clear
		clear_firewall
		echo "$g_product Cleared"

		kill $$
		exit 2
	    else
		g_restorepath=${VARDIR}/$RESTOREFILE

		if [ -x $g_restorepath ]; then
		    echo Restoring ${g_product:=Shorewall}...

		    g_recovering=Yes

		    if run_it $g_restorepath restore; then
			echo "$g_product restored from $g_restorepath"
			set_state "Restored from $g_restorepath"
		    else
			set_state "Unknown"
		    fi

		    kill $$
		    exit 2
		fi
	    fi
	    ;;
    esac

    if [ -n "$g_stopping" ]; then
	kill $$
	exit 1
    fi

    set_state "Stopping"

    g_stopping="Yes"

    deletechain shorewall

    run_stop_exit

    if [ -f ${VARDIR}/nat ]; then
	while read external interface; do
      	    del_ip_addr $external $interface
	done < ${VARDIR}/nat

	rm -f ${VARDIR}/nat
    fi

    if [ -f ${VARDIR}/proxyarp ]; then
	while read address interface external haveroute; do
	    qt arp -i $external -d $address pub
	    [ -z "${haveroute}${g_noroutes}" ] && qt $IP -4 route del $address dev $interface
	    f=/proc/sys/net/ipv4/conf/$interface/proxy_arp
	    [ -f $f ] && echo 0 > $f
	done < ${VARDIR}/proxyarp

	 rm -f ${VARDIR}/proxyarp
    fi


    delete_tc1
    undo_routing
    restore_default_route

    [ -n "$DEBUG" ] && command=debug_restore_input || command=$IPTABLES_RESTORE

    progress_message2 "Running $command..."

    $command <<__EOF__
#
# Generated by Shorewall 4.4.14 - Mon Nov 29 23:36:39 2010
#
*raw
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
*nat
:PREROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
*mangle
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
COMMIT
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A INPUT -i eth0  -s 160.114.8.24   -j ACCEPT
-A INPUT -i eth0  -s 212.92.23.55   -j ACCEPT
-A INPUT -i eth0  -s 212.92.23.223   -j ACCEPT
-A INPUT -i eth0  -s 212.92.23.224   -j ACCEPT
-A INPUT -i eth0  -s 80.75.224.131   -j ACCEPT
-A INPUT -i eth0  -s 217.27.219.101   -j ACCEPT
-A INPUT -i eth0  -s 217.20.134.44   -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 160.114.8.24  -d 212.92.23.55   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 160.114.8.24  -d 212.92.23.223   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 160.114.8.24  -d 212.92.23.224   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 160.114.8.24  -d 80.75.224.131   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 160.114.8.24  -d 217.27.219.101   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 160.114.8.24  -d 217.20.134.44   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.55  -d 160.114.8.24   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.55  -d 212.92.23.223   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.55  -d 212.92.23.224   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.55  -d 80.75.224.131   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.55  -d 217.27.219.101   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.55  -d 217.20.134.44   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.223  -d 160.114.8.24   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.223  -d 212.92.23.55   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.223  -d 212.92.23.224   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.223  -d 80.75.224.131   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.223  -d 217.27.219.101   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.223  -d 217.20.134.44   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.224  -d 160.114.8.24   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.224  -d 212.92.23.55   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.224  -d 212.92.23.223   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.224  -d 80.75.224.131   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.224  -d 217.27.219.101   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 212.92.23.224  -d 217.20.134.44   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 80.75.224.131  -d 160.114.8.24   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 80.75.224.131  -d 212.92.23.55   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 80.75.224.131  -d 212.92.23.223   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 80.75.224.131  -d 212.92.23.224   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 80.75.224.131  -d 217.27.219.101   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 80.75.224.131  -d 217.20.134.44   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.27.219.101  -d 160.114.8.24   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.27.219.101  -d 212.92.23.55   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.27.219.101  -d 212.92.23.223   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.27.219.101  -d 212.92.23.224   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.27.219.101  -d 80.75.224.131   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.27.219.101  -d 217.20.134.44   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.20.134.44  -d 160.114.8.24   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.20.134.44  -d 212.92.23.55   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.20.134.44  -d 212.92.23.223   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.20.134.44  -d 212.92.23.224   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.20.134.44  -d 80.75.224.131   -j ACCEPT
-A FORWARD -i eth0  -o eth0  -s 217.20.134.44  -d 217.27.219.101   -j ACCEPT
COMMIT
__EOF__

    if [ $? != 0 ]; then
	error_message "ERROR: $command Failed."
    fi

    echo 1 > /proc/sys/net/ipv4/ip_forward
    progress_message2 IPv4 Forwarding Enabled

    run_stopped_exit


    set_state "Stopped"
    logger -p kern.info "$g_product Stopped"

    case $COMMAND in
    stop|clear)
	;;
    *)
	#
	# The firewall is being stopped when we were trying to do something
	# else. Kill the shell in case we're running in a subshell
	#
	kill $$
	;;
    esac
}

#
# Handle the "up" and "down" commands
#
updown() # $1 = interface
{
    local state
    state=cleared

    progress_message3 "$g_product $COMMAND triggered by $1"

    if shorewall_is_started; then
	state=started
    elif [ -f ${VARDIR}/state ]; then
	case "$(cat ${VARDIR}/state)" in
	    Stopped*)
		state=stopped
		;;
	    Cleared*)
		;;
	    *)
		state=unknown
		;;
	esac
    else
	state=unknown
    fi

    case $1 in
	*)
	    case $state in
		started)
		    COMMAND=restart
		    progress_message3 "$g_product attempting restart"
		    detect_configuration
		    define_firewall
		    ;;
		*)
		    progress_message3 "$COMMAND on interface $1 ignored"
		    ;;
	    esac
    esac
}

###############################################################################
# Code imported from /usr/share/shorewall/prog.footer
###############################################################################
#
# Give Usage Information
#
usage() {
    echo "Usage: $0 [ options ] [ start|stop|clear|down|reset|refresh|restart|status|up|version ]"
    echo
    echo "Options are:"
    echo
    echo "   -v and -q        Standard Shorewall verbosity controls"
    echo "   -n               Don't unpdate routing configuration"
    echo "   -p               Purge Conntrack Table"
    echo "   -t               Timestamp progress Messages"
    echo "   -V <verbosity>   Set verbosity explicitly"
    echo "   -R <file>        Override RESTOREFILE setting"
    exit $1
}
################################################################################
# E X E C U T I O N    B E G I N S   H E R E				       #
################################################################################
#
# Start trace if first arg is "debug" or "trace"
#
if [ $# -gt 1 ]; then
    if [ "x$1" = "xtrace" ]; then
	set -x
	shift
    elif [ "x$1" = "xdebug" ]; then
	DEBUG=Yes
	shift
    fi
fi
#
# Map VERBOSE to VERBOSITY for compatibility with old Shorewall-lite installations
#
[ -z "$VERBOSITY" ] && [ -n "$VERBOSE" ] && VERBOSITY=$VERBOSE
#
# Map other old exported variables
#
g_purge=$PURGE
g_noroutes=$NOROUTES
g_timestamp=$TIMESTAMP
g_recovering=$RECOVERING

initialize

if [ -n "$STARTUP_LOG" ]; then
    touch $STARTUP_LOG
    chmod 0600 $STARTUP_LOG
    if [ ${SHOREWALL_INIT_SCRIPT:-0} -eq 1 ]; then
	#
	# We're being run by a startup script that isn't redirecting STDOUT
	# Redirect it to the log
	#
	exec 2>>$STARTUP_LOG
    fi
fi

finished=0

while [ $finished -eq 0 -a $# -gt 0 ]; do
    option=$1
    case $option in
	-*)
	    option=${option#-}

	    [ -z "$option" ] && usage 1

	    while [ -n "$option" ]; do
		case $option in
		    v*)
			[ $VERBOSITY -lt 2 ] && VERBOSITY=$(($VERBOSITY + 1 ))
			option=${option#v}
			;;
		    q*)
			[ $VERBOSITY -gt -1 ] && VERBOSITY=$(($VERBOSITY - 1 ))
			option=${option#q}
			;;
		    n*)
			g_noroutes=Yes
			option=${option#n}
			;;
		    t*)
			g_timestamp=Yes
			option=${option#t}
			;;
		    p*)
			g_purge=Yes
			option=${option#p}
			;;
		    r*)
			g_recovering=Yes
			option=${option#r}
			;;
		    V*)
			option=${option#V}

			if [ -z "$option" -a $# -gt 0 ]; then
			    shift
			    option=$1
			fi

			if [ -n "$option" ]; then
			    case $option in
				-1|0|1|2)
				    VERBOSITY=$option
				    option=
				    ;;
				*)
				    startup_error "Invalid -V option value ($option)"
				    ;;
			    esac
			else
			    startup_error "Missing -V option value"
			fi
			;;
		    R*)
			option=${option#R}

			if [ -z "$option" -a $# -gt 0 ]; then
			    shift
			    option=$1
			fi

			if [ -n "$option" ]; then
			    case $option in
				*/*)
	    			    startup_error "-R must specify a simple file name: $option"
				    ;;
				.safe|.try|NONE)
				    ;;
				.*)
				    error_message "ERROR: Reserved File Name: $RESTOREFILE"
				    exit 2
				    ;;
			    esac
			else
			    startup_error "Missing -R option value"
			fi

			RESTOREFILE=$option
			option=
			;;
		    *)
			usage 1
			;;
		esac
	    done
	    shift
	    ;;
	*)
	    finished=1
            ;;
    esac
done

COMMAND="$1"

case "$COMMAND" in
    start)
	[ $# -ne 1 ] && usage 2
	if shorewall_is_started; then
	    error_message "$g_product is already Running"
	    status=0
	else
	    progress_message3 "Starting $g_product...."
	    detect_configuration
	    define_firewall
	    status=$?
	    [ -n "$SUBSYSLOCK" -a $status -eq 0 ] && touch $SUBSYSLOCK
	    progress_message3 "done."
	fi
	;;
    stop)
	[ $# -ne 1 ] && usage 2
	progress_message3 "Stopping $g_product...."
	detect_configuration
	stop_firewall
	status=0
	[ -n "$SUBSYSLOCK" ] && rm -f $SUBSYSLOCK
	progress_message3 "done."
	;;
    reset)
	if ! shorewall_is_started ; then
	    error_message "$g_product is not running"
	    status=2
	elif [ $# -eq 1 ]; then
	    $IPTABLES -Z
	    $IPTABLES -t nat -Z
	    $IPTABLES -t mangle -Z
	    date > ${VARDIR}/restarted
	    status=0
	    progress_message3 "$g_product Counters Reset"
	else
	    shift
	    status=0
	    for chain in $@; do
		if chain_exists $chain; then
		    if qt $IPTABLES -Z $chain; then
			progress_message3 "Filter $chain Counters Reset"
		    else
			error_message "ERROR: Reset of chain $chain failed"
			status=2
			break
		    fi
		else
		    error_message "WARNING: Filter Chain $chain does not exist"
		fi
	    done
	fi
	;;
    restart)
	[ $# -ne 1 ] && usage 2
	if shorewall_is_started; then
	    progress_message3 "Restarting $g_product...."
	else
	    error_message "$g_product is not running"
	    progress_message3 "Starting $g_product...."
	    COMMAND=start
	fi

	detect_configuration
	define_firewall
	status=$?
	if [ -n "$SUBSYSLOCK" ]; then
 	    [ $status -eq 0 ] && touch $SUBSYSLOCK || rm -f $SUBSYSLOCK
        fi
	progress_message3 "done."
	;;
    refresh)
	[ $# -ne 1 ] && usage 2
	if shorewall_is_started; then
	    progress_message3 "Refreshing $g_product...."
	    detect_configuration
	    define_firewall
	    status=$?
	    progress_message3 "done."
	else
	    echo "$g_product is not running" >&2
	    status=2
	fi
	;;
    restore)
	[ $# -ne 1 ] && usage 2
	detect_configuration
	define_firewall
	status=$?
	if [ -n "$SUBSYSLOCK" ]; then
 	    [ $status -eq 0 ] && touch $SUBSYSLOCK || rm -f $SUBSYSLOCK
        fi
	;;
    clear)
	[ $# -ne 1 ] && usage 2
	progress_message3 "Clearing $g_product...."
	clear_firewall
	status=0
	if [ -n "$SUBSYSLOCK" ]; then
	    rm -f $SUBSYSLOCK
	fi
	progress_message3 "done."
	;;
    status)
	[ $# -ne 1 ] && usage 2
	echo "$g_product-$SHOREWALL_VERSION Status at $(hostname) - $(date)"
	echo
	if shorewall_is_started; then
	    echo "$g_product is running"
	    status=0
	else
	    echo "$g_product is stopped"
	    status=4
	fi

	if [ -f ${VARDIR}/state ]; then
	    state="$(cat ${VARDIR}/state)"
	    case $state in
		Stopped*|lClear*)
		    status=3
		    ;;
	    esac
	else
	    state=Unknown
	fi
	echo "State:$state"
	echo
	;;
    up|down)
	[ $# -eq 1 ] && exit 0
	shift
	[ $# -ne 1 ] && usage 2
	updown $@
	status=0;
	;;
    version)
	[ $# -ne 1 ] && usage 2
	echo $SHOREWALL_VERSION
	status=0
	;;
    help)
	[ $# -ne 1 ] && usage 2
	usage 0
	;;
    *)
	usage 2
	;;
esac

exit $status
