#!/bin/bash
#
# dhclient-script: Network interface configuration script run by
#                  dhclient based on DHCP client communication
#
# Copyright (C) 2008, 2009, 2010  Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): David Cantrell <dcantrell@redhat.com>
#
# ----------
# This script is a rewrite/reworking on dhclient-script originally
# included as part of dhcp-970306:
# dhclient-script for Linux. Dan Halbert, March, 1997.
# Updated for Linux 2.[12] by Brian J. Murrell, January 1999.
# Modified by David Cantrell <dcantrell@redhat.com> for Fedora and RHEL
# ----------
#
# 1/11/2016 modified by hfasching, Barracuda Networks AG
#

PATH=/bin:/usr/bin:/sbin
SAVEDIR=/var/lib/dhclient

LOGFACILITY="local7"
LOGLEVEL="notice"

ETCDIR="/etc/dhcp"

scriptname=${0##*/}

# Array to hold the interfaces for pefix delegation
declare -a pd_dev
# Array to hold the prefixes for the corresponding interfaces
declare -a ip6_prefixes
# Variable to hold ip6 address
declare ip6_address

# Array to hold the parts of an IPv6 prefix to help to generate prefixes
declare -a ip6_parts

declare -r BOXINFO="/opt/phion/bin/boxinfo"

# current config file
if [[ $interface == dhcp* ]]; then
	declare -r CONFFILE="/var/phion/preserve/boxnet/DHCP/xdhcp_${interface}"
elif [[ $interface == ath* ]]; then
	declare -r CONFFILE="/dev/shm/boxnet/WIFIC/${interface}_Current_DHCP"
fi

# get config entry for 'Use Assigned IP'
function phion_config_lsrc {
	if [[ "$($BOXINFO config ${CONFFILE} / lsrc)" = "n" ]]; then
		return 1
	fi

	# default is "y", if setting is missing in config
	return 0
}

function phion_config_dfltrt {
	if [[ $interface == dhcp* ]]; then
		# default is "y", if setting is missing in config
		if [[ "$($BOXINFO config ${CONFFILE} / dfltrt)" = "n" ]]; then
			return 1
		else
			return 0
		fi
	elif [[ $interface == ath* ]]; then
		# default is "n" (!), if setting is missing in config
		if [[ "$($BOXINFO config ${CONFFILE} / dfltrt)" = "y" ]]; then
			return 0
		else
			return 1
		fi
	fi

	return 0
}

function phion_config_clone {
	if [[ "$($BOXINFO config ${CONFFILE} / clone)" = "n" ]]; then
		return 1
	fi

	# default is "y", if setting is missing in config
	return 0
}

function UpdateDynDNS {
	local IFACE=${1}
	local MYIP=${2}
	local PINFO EPID
	PINFO=$(ps -e |grep "UpdateDynDNS.${IFACE}")
		set -- $PINFO
		EPID=""
		while [ _${1} != _ ]; do
			EPID="${EPID} ${1}"
			shift 4
		done
	[ _"${EPID}" != _ ] && kill -TERM ${EPID} &>/dev/null
	[ ! -L ${RUNDIR}/UpdateDynDNS.${IFACE} ] && {
		ln -sf /epb/UpdateDynDNS ${RUNDIR}/UpdateDynDNS.${IFACE}
	}
	${RUNDIR}/UpdateDynDNS.${IFACE} ${IFACE} ${MYIP} &>/dev/null &

}

function phion_config_ospf {
	if [[ "$scriptname" == *"scriptv6"* ]]; then
		# not supported for ipv6
		echo ""
		return 1
	fi

	if [[ "$($BOXINFO config ${CONFFILE} / ospf)" = "y" ]]; then
		echo "y"
	else
		echo "n"
	fi

	return 0
}

function phion_config_realm {
	local realmid=""

	if [[ "$scriptname" == *"scriptv6"* ]]; then
		# not supported for ipv6
		echo ""
		return 1
	fi
			
	if [[ $interface == dhcp* ]]; then
		realmid=$($BOXINFO config ${CONFFILE} / drealm)
	elif [[ $interface == ath* ]]; then
		realmid=$($BOXINFO config ${CONFFILE} / realm)
	fi

	if [[ -n ${realmid} ]]; then
		echo ${realmid}
	else
		echo "3"
	fi

	return 0
}

function phion_config_rtable {
	if [[ "$scriptname" == *"scriptv6"* ]]; then
		# not supported for ipv6
		echo ""
		return 1
	fi

	if [[ $interface == dhcp* ]]; then
		# boxnet DHCP client
		# default for "polrt" is "y", if setting is missing
		if [[ "$($BOXINFO config ${CONFFILE} / polrt)" = "n" ]]; then
			echo ""
		else
			if [[ ${interface} == "dhcp" ]]; then
				# first dhcp interface is special. table is called with 1 suffix
				echo "dhcp1"
			else
				echo ${interface}
			fi
		fi
	elif [[ $interface == ath* ]]; then
		# wifi client
		# default for "polrt" is "n" (!), if setting is missing
		if [[ "$($BOXINFO config ${CONFFILE} / polok)" = "y" ]]; then
			echo "wific"
		else
			echo ""
		fi
	fi
}

function phion_config_getindex {
	if [[ ${interface} == "dhcp" ]]; then
		echo "dhcp1"
	else
		echo ${interface}
	fi
}

function phion_config_deviceindex {
	local index
	
	if [[ "$scriptname" == *"scriptv6"* ]]; then
		index=$($BOXINFO config /var/phion/preserve/boxnet/DHCPv6/idxMap${interface}.conf / index)
		echo "v6net$index"
	else 
		index=$($BOXINFO config ${CONFFILE} / dhcpidx)
		echo "net$index"
	fi
	return 0
}

RUNDIR="/var/phion/run/boxnet/DHCP"
UpdateHosts() {
	if [ -z ${new_domain_name} ]; then
		return 0
	fi

	(
		trap '' INT TERM HUP

		if [ -f /etc/phion/dynconf/boxnet.conf.rollout ]; then
			source /etc/phion/dynconf/boxnet.conf.rollout
		else
			return 1
		fi

		MIP=""
		HOSTNAME=""
		# try to get the MIP from activation config
		if [ -f /opt/phion/preserve/boxnet.conf ]; then
			MIP=$(/opt/phion/bin/boxinfo config /opt/phion/preserve/boxnet.conf boxnet ip)
			HOSTNAME=$(/opt/phion/bin/boxinfo config /opt/phion/preserve/boxnet.conf / hostname)
		fi

		if [ -z ${MIP} ]; then
			MIP=${box_boxnet_IP_1}
		fi

		if [ -z ${HOSTNAME} ]; then
			HOSTNAME=${box_HOSTNAME}
		fi

		local MIP_PATTERN=${MIP}
		MIP_PATTERN="${MIP_PATTERN//./\.}"

		sed -i "s/${MIP_PATTERN}.*$/${MIP} ${HOSTNAME}.${new_domain_name} ${HOSTNAME}/" /etc/hosts
	)
}

cuda_resolv_conf() {
    case "${reason}" in
		EXPIRE|FAIL|RELEASE|STOP)
			/epb/writeResolvConf F # triggers reconstruction of DNS forwarding parametrization		
			[ -f /opt/phion/config/active/dynPDNS${interface}.conf ] && rm -f /opt/phion/config/active/dynPDNS${interface}.conf 
			if [ ! -f /opt/phion/preserve/boxnet.conf ]; then
				cp -ra ${RUNDIR}/hosts.nodhcp /etc/hosts
				rm ${RUNDIR}/hosts.nodhcp
			fi
			return
			;;
		*) ;;
	esac

	DYNDNSDIR="/var/phion/run/boxnet/DNS"
	source /var/phion/preserve/boxnet/DHCP/xdhcp_$interface
	[[ ! -d ${DYNDNSDIR} ]] && mkdir -p ${DYNDNSDIR}

	if [[ ${PDNS:-no} = yes ]]; then
		TMPRESOLVCONF=${DYNDNSDIR}/resolv.conf.${interface}
		{ 
			if [[ ${PDOMAIN:-no} = yes ]]; then
				echo "domain ${new_domain_name}"
			fi
			for nameserver in ${new_domain_name_servers} ; do
				echo "nameserver ${nameserver} #pref=${PREF:-0}"
			done
		} > ${TMPRESOLVCONF}

		/etc/phion/bin/writeResolvConf N ${interface} ${new_domain_name_servers}
		# Update /etc/hosts
		if [[ ${PDOMAIN:-no} = yes ]]; then
			cp -ra /etc/hosts ${RUNDIR}/hosts.nodhcp
			UpdateHosts
		fi
	fi
}

logmessage() {
    msg="${1}"
    /etc/phion/bin/phionlog_api "box_Network_dhcp" "notice" "${scriptname}: ${msg}"
}

fix_context() {
    if [ -x /sbin/restorecon ]; then
        /sbin/restorecon ${1} >/dev/null 2>&1
    fi
}

save_previous() {
    origfile="${1}"
    savefile="${SAVEDIR}/${origfile##*/}.predhclient.${interface}"

    if [ ! -d ${SAVEDIR} ]; then
        mkdir -p ${SAVEDIR}
    fi

    if [ -e ${origfile} ]; then
        contents="$(< ${origfile})"
        echo "${contents}" > ${savefile}
        rm -f ${origfile}
    else
        echo > ${savefile}
    fi

    fix_context ${savefile}
}

# make_resolv_conf() will be called for DHCPv4 and DHCPv6!!!!!!
make_resolv_conf() {
    [ "${PEERDNS}" = "no" ] && return

    if [ "${reason}" = "RENEW" ] &&
       [ "${new_domain_name}" = "${old_domain_name}" ] &&
       [ "${new_domain_name_servers}" = "${old_domain_name_servers}" ]; then
        return
    fi

# The DHCPv4 part
    if [ -n "${new_domain_name}" ] ||
       [ -n "${new_domain_name_servers}" ] ||
       [ -n "${new_domain_search}" ]; then
		cuda_resolv_conf
		return


        save_previous /etc/resolv.conf
        rscf="$(mktemp /tmp/XXXXXX)"
        echo "; generated by /sbin/dhclient-script" > ${rscf}

        if [ -n "${SEARCH}" ]; then
            echo "search ${SEARCH}" >> $rscf
        else
            if [ -n "${new_domain_search}" ]; then
                echo "search ${new_domain_search//\\032/ }" >> ${rscf}
            elif [ -n "${new_domain_name}" ]; then
                # Note that the DHCP 'Domain Name Option' is really just a domain
                # name, and that this practice of using the domain name option as
                # a search path is both nonstandard and deprecated.
                echo "search ${new_domain_name//\\032/ }" >> ${rscf}
            fi
        fi

        if [ -n "${RES_OPTIONS}" ]; then
            echo "options ${RES_OPTIONS}" >> ${rscf}
        fi

        for nameserver in ${new_domain_name_servers} ; do
            echo "nameserver ${nameserver}" >> ${rscf}
        done

        change_resolv_conf ${rscf}
        rm -f ${rscf}

        fix_context /etc/resolv.conf
# The DHCPv6 part
    elif [ -n "${new_dhcp6_name_servers}" ] ||
         [ -n "${new_dhcp6_domain_search}" ]; then
        source /var/phion/preserve/boxnet/DHCPv6/xdhcp6_$interface
        if [[ ${PDNS6:-no} = yes ]]; then
        	save_previous /etc/resolv.conf
        	rscf="$(mktemp /tmp/XXXXXX)"
        	echo "; generated by /sbin/dhclient-script" > ${rscf}

			if [[ ${PDOMAIN6:-no} = yes ]]; then
        		if [ -n "${SEARCH}" ]; then
            		echo "search ${SEARCH}" >> $rscf
        		else
            		if [ -n "${new_dhcp6_domain_search}" ]; then
	                	echo "search ${new_dhcp6_domain_search//\\032/ }" >> ${rscf}
            		fi
        		fi
        	fi

        	if [ -n "${RES_OPTIONS}" ]; then
            	echo "options ${RES_OPTIONS}" >> ${rscf}
        	fi

        	for nameserver in ${new_dhcp6_name_servers} ; do
            	echo "nameserver ${nameserver}" >> ${rscf}
        	done

        	change_resolv_conf ${rscf}
        	rm -f ${rscf}

        	fix_context /etc/resolv.conf
        fi
    fi
}

exit_with_hooks() {
    exit_status="${1}"

    if [ -x ${ETCDIR}/dhclient-exit-hooks ]; then
        . ${ETCDIR}/dhclient-exit-hooks
    fi

    exit ${exit_status}
}

quad2num() {
    if [ $# -eq 4 ]; then
        let n="${1} << 24 | ${2} << 16 | ${3} << 8 | ${4}"
        echo "${n}"
        return 0
    else
        echo "0"
        return 1
    fi
}

ip2num() {
    IFS="." quad2num ${1}
}

num2ip() {
    let n="${1}"
    let o1="(n >> 24) & 0xff"
    let o2="(n >> 16) & 0xff"
    let o3="(n >> 8) & 0xff"
    let o4="n & 0xff"
    echo "${o1}.${o2}.${o3}.${o4}"
}

get_network_address() {
# get network address for the given IP address and (netmask or prefix)
    ip="${1}"
    nm="${2}"

    if [ -n "${ip}" -a -n "${nm}" ]; then
        if [[ "${nm}" = *.* ]]; then
            ipcalc -s -n ${ip} ${nm} | cut -d '=' -f 2
        else
            ipcalc -s -n ${ip}/${nm} | cut -d '=' -f 2
        fi
    fi
}

get_prefix() {
# get prefix for the given IP address and mask
    ip="${1}"
    nm="${2}"

    if [ -n "${ip}" -a -n "${nm}" ]; then
        ipcalc -s -p ${ip} ${nm} | cut -d '=' -f 2
    fi
}

class_bits() {
    let ip=$(IFS='.' ip2num $1)
    let bits=32
    let mask='255'
    for ((i=0; i <= 3; i++, 'mask<<=8')); do
        let v='ip&mask'
        if [ "$v" -eq 0 ] ; then
             let bits-=8
        else
             break
        fi
    done
    echo $bits
}

is_router_reachable() {
    # handle DHCP servers that give us a router not on our subnet
    router="${1}"
    routersubnet="$(get_network_address ${router} ${new_subnet_mask})"
    mysubnet="$(get_network_address ${new_ip_address} ${new_subnet_mask})"

    if [[ ! "${routersubnet}" = "${mysubnet}" && -n "${router}" && "${router}" != "0.0.0.0" ]]; then
        ip -4 route replace ${router}/32 dev ${interface}
        if [ $? -eq 0 ]; then
            if ping -q -c1 -w2 -I ${interface} ${router}; then
                return 0
			fi
            if arping -q -c1 -w2 -I ${interface} ${router}; then
                return 0
			fi
			logmessage "warning: DHCP router ${router} is unreachable on DHCP subnet ${mysubnet} router subnet ${routersubnet}"
        else
            logmessage "failed to create host router for unreachable router ${router} not on subnet ${mysubnet}"
            return 1
        fi
    fi

    return 0
}

cuda_add_routes() {
    router="${1}"
    metric=""
	local routing_table=""
	local src_ip=""
	local realm=""
	local proto_spec=""

    if [ $# -gt 1 ] && [ ${2} -gt 0 ]; then
        metric="metric ${2}"
    fi
    if [ $# -gt 2 ] && [ -n "${3}" ]; then
		routing_table="table ${3}"
    fi
    if [ $# -gt 3 ] && [ -n "${4}" ]; then
		src_ip="src ${4}"
    fi
    if [ $# -gt 4 ] && [ -n "${5}" ]; then
		realm="realm ${5}"
    fi
    if [ $# -gt 5 ] && [[ "_${6}" == "_y" ]]; then
		proto_spec="proto advtise"
	else
		#proto_spec="proto dynlink"
		:
    fi

    if is_router_reachable ${router} ; then
		# get routes out of config
		local targets=$($BOXINFO config ${CONFFILE} / targets | tr -d "'")
		
		for target in ${targets}; do
			local current_rt=${routing_table}
			if [[ ${target} == "0.0.0.0/0" ]]; then
				# ignore targets default value
				continue
			elif [[ ${target} == "0.0.0.0/32" ]]; then
				# default route
				if [[ -z ${3} || ${3} == "main" ]]; then
					# default route must not get into main table
					current_rt="table default"
				fi
			fi

			# phion to cidr
			local net=${target%/*}
			local mask=$(expr 32 - ${target#*/})
        	ip -4 route replace "${net}/${mask}" via ${router} dev ${interface} ${metric} ${current_rt} ${src_ip} ${realm} ${proto_spec}
        	if [ $? -ne 0 ]; then
        	    logmessage "failed to create route: ${net}/${mask} ${router} dev ${interface} ${metric} ${current_rt} ${src_ip} ${realm} ${proto_spec}"
			fi
		done
    fi

    return 1
}

add_default_gateway() {
    router="${1}"
    metric=""
	local routing_table=""
	local src_ip=""
	local realm=""
	local proto_spec=""

    if [ $# -gt 1 ] && [ ${2} -gt 0 ]; then
        metric="metric ${2}"
    fi
    if [ $# -gt 2 ] && [ -n "${3}" ]; then
		routing_table="table ${3}"
    fi
    if [ $# -gt 3 ] && [ -n "${4}" ]; then
		src_ip="src ${4}"
    fi
    if [ $# -gt 4 ] && [ -n "${5}" ]; then
		realm="realm ${5}"
    fi
    if [ $# -gt 5 ] && [[ "_${6}" == "_y" ]]; then
		proto_spec="proto advtise"
	else
		#proto_spec="proto dynlink"
		:
    fi

    if is_router_reachable ${router} ; then
        ip -4 route replace default via ${router} dev ${interface} ${metric} ${routing_table} ${src_ip} ${realm} ${proto_spec}
        if [ $? -ne 0 ]; then
            logmessage "failed to create default route: ${router} dev ${interface} ${metric} ${routing_table} ${src_ip} ${realm} ${proto_spec}"
            return 1
        else
            return 0
        fi
    fi

    return 1
}

flush_dev() {
# Instead of bringing the interface down (#574568)
# explicitly clear the ARP cache and flush all addresses & routes.
    ip -4 addr flush dev ${1} >/dev/null 2>&1
    ip -4 route flush dev ${1} >/dev/null 2>&1
    ip -4 neigh flush dev ${1} >/dev/null 2>&1
}

dhconfig() {
	local routing_table=$(phion_config_rtable)
	local ospf=$(phion_config_ospf ${interface})
	local realm_id=$(phion_config_realm ${interface})
	local realm_spec=""
	local proto_spec=""
	local table_pref=""
		
    if [ -n "${old_ip_address}" ] && [ -n "${alias_ip_address}" ] &&
       [ ! "${alias_ip_address}" = "${old_ip_address}" ]; then
        # possible new alias, remove old alias first
        ip -4 addr del ${old_ip_address} dev ${interface}:0
    fi

    if [ -n "${old_ip_address}" ] &&
       [ ! "${old_ip_address}" = "${new_ip_address}" ]; then
        # IP address changed. Delete all routes, and clear the ARP cache.
        flush_dev ${interface}
    fi

	# cuda set assigned DHCP src/policy routing - only necessary if IP changes/initial startup
	if [ -n "${routing_table}" ] && 
			([ ! "${old_ip_address}" = "${new_ip_address}" ] || 
			[ "${reason}" = "REBOOT" ] ||
			[ "${reason}" = "BOUND" ]); then

		if [[ $interface == ath* ]]; then
			table_pref="$($BOXINFO config ${CONFFILE} / tblprio)"
		else
			table_pref="$($BOXINFO config ${CONFFILE} / dhcpprio)"
		fi

		[ -n "${table_pref}" ] && table_pref="pref ${table_pref}"

		# delete old entries
		[ -n "${old_ip_address}" ] && ip -4 rule del from ${old_ip_address} table ${routing_table}
		ip -4 rule del from 0.0.0.0 table ${routing_table} 2>/dev/null

		if phion_config_lsrc; then
			# add table with preference and new source ip address
			ip -4 rule add from ${new_ip_address} table ${routing_table} ${table_pref}
		fi

		if [[ $interface == ath* ]]; then
			# wifi client
			local src_nets=$($BOXINFO config ${CONFFILE} / srcnets | tr -d "'")
			for srcnet in ${src_nets}; do
				# phion to cidr
				local net=${srcnet%/*}
				local mask=$(expr 32 - ${srcnet#*/})
				# entry may already exist, so ignore output
				ip -4 rule add from "${net}/${mask}" table ${routing_table} ${table_pref} 2>/dev/null
			done
		fi
	fi

    if [ "${reason}" = "BOUND" ] || [ "${reason}" = "REBOOT" ] ||
       [ ! "${old_ip_address}" = "${new_ip_address}" ] ||
       [ ! "${old_subnet_mask}" = "${new_subnet_mask}" ] ||
       [ ! "${old_network_number}" = "${new_network_number}" ] ||
       [ ! "${old_broadcast_address}" = "${new_broadcast_address}" ] ||
       [ ! "${old_routers}" = "${new_routers}" ] ||
       [ ! "${old_interface_mtu}" = "${new_interface_mtu}" ]; then
        ip -4 addr add ${new_ip_address}/${new_prefix} broadcast ${new_broadcast_address} dev ${interface}
        ip link set dev ${interface} up

		if [[ "_${ospf}" == "_y" ]]; then
			proto_spec="proto advtise"
		else
			#proto_spec="proto dynlink"
			:
		fi

		# cuda, adding /32 to gateway in main table and DHCP subnet route in dhcp table
		# violating RFC3442 which says:
		# "If the DHCP server returns both a Classless Static Routes option and
		# a Router option, the DHCP client MUST ignore the Router option."
		# however, since we introduce static routes in dedicated routing tables, we may not have a route
		# to the gateway, preventing our routes to be inserted
		realm_spec=""
		if [ -n "${realm_id}" ]; then
			realm_spec="realm ${realm_id}"
		fi
		for n_router in ${new_routers}; do
			# add direct /32 route to gateway in main table
			ip -4 route add ${n_router}/32 src ${new_ip_address} dev ${interface} table main ${realm_spec}
		done
        [ -n "${routing_table}" ] && ip -4 route add ${new_network_number}/${new_prefix} src ${new_ip_address} dev ${interface} table ${routing_table} ${realm_spec} ${proto_spec}

		# add ip with peer as gateway. see openxdhcp GW monitoring for reason
		# do NOT remove just because you dont understand
		if [[ ${#new_routers[@]} -ge 1 ]]; then
			ip -4 a add ${new_ip_address} peer ${new_routers[0]} dev ${interface}
		else
			# if no router are set, use server IP, as in openxdhcp
			ip -4 a add ${new_ip_address} peer ${new_dhcp_server_identifier} dev ${interface}
		fi

        # The 576 MTU is only used for X.25 and dialup connections
        # where the admin wants low latency.  Such a low MTU can cause
        # problems with UDP traffic, among other things.  As such,
        # disallow MTUs from 576 and below by default, so that broken
        # MTUs are ignored, but higher stuff is allowed (1492, 1500, etc).
        if [ -n "${new_interface_mtu}" ] && [ ${new_interface_mtu} -gt 576 ]; then
            ip link set ${interface} mtu ${new_interface_mtu}
        fi

        if [ -x ${ETCDIR}/dhclient-${interface}-up-hooks ]; then
            . ${ETCDIR}/dhclient-${interface}-up-hooks
        elif [ -x ${ETCDIR}/dhclient-up-hooks ]; then
            . ${ETCDIR}/dhclient-up-hooks
        fi

        # static routes
        if [ -n "${new_classless_static_routes}" ] ||
           [ -n "${new_static_routes}" ]; then
            if [ -n "${new_classless_static_routes}" ]; then
                IFS=', |' static_routes=(${new_classless_static_routes})
            else
                IFS=', |' static_routes=(${new_static_routes})
            fi
            route_targets=()

            for((i=0; i<${#static_routes[@]}; i+=2)); do
                target=${static_routes[$i]}
                if [ -n "${new_classless_static_routes}" ]; then
                    if [ ${target} = "0" ]; then
                        # If the DHCP server returns both a Classless Static Routes option and
                        # a Router option, the DHCP client MUST ignore the Router option. (RFC3442)
                        new_routers=""
                        prefix="0"
                    else
                        prefix=$(echo ${target} | cut -d "." -f 1)
                        target=$(echo ${target} | cut -d "." -f 2-)
                        IFS="." target_arr=(${target})
                        unset IFS
                        ((pads=4-${#target_arr[@]}))
                        for j in $(seq $pads); do
                            target=${target}".0"
                        done

                        # Client MUST zero any bits in the subnet number where the corresponding bit in the mask is zero.
                        # In other words, the subnet number installed in the routing table is the logical AND of
                        # the subnet number and subnet mask given in the Classless Static Routes option. (RFC3442)
                        target="$(get_network_address ${target} ${prefix})"
                    fi
                else
                    prefix=$(class_bits ${target})
                fi
                gateway=${static_routes[$i+1]}

                #metric=''
				#metric=$($BOXINFO config /var/phion/preserve/boxnet/DHCP/xdhcp_${interface} / pref 2>/dev/null)
				metric=$($BOXINFO config ${CONFFILE} / pref)
                for t in ${route_targets[@]}; do
                    if [ ${t} = ${target} ]; then
                        if [ -z "${metric}" ]; then
                            metric=1
                        else
                            ((metric=metric+1))
                        fi
                    fi
                done

                if [ -n "${metric}" ]; then
                    metric="metric ${metric}"
                fi

				rt_spec=""
				if [ -n "${routing_table}" ]; then
					rt_spec="table ${routing_table}"
				fi

				src_spec=""
				if [ -n "${new_ip_address}" ]; then
					src_spec="src ${new_ip_address}"
				fi

				realm_spec=""
				if [ -n "${realm_id}" ]; then
					realm_spec="realm ${realm_id}"
				fi

				proto_spec=""
				if [[ "_${ospf}" == "_y" ]]; then
					proto_spec="proto advtise"
				else
					#proto_spec="proto dynlink"
					:
				fi 

                if is_router_reachable ${gateway}; then
                    ip -4 route replace ${target}/${prefix} via ${gateway} dev ${interface} ${metric} ${src_spec} ${rt_spec} ${realm_spec} ${proto_spec}
                    if [ $? -ne 0 ]; then
                        logmessage "failed to create route: ${target}/${prefix} via ${gateway} dev ${interface} ${metric} ${src_spec} ${rt_spec} ${realm_spec} ${proto_spec}"
                    else
                        route_targets=(${route_targets[@]} ${target})
                    fi
					# when adding default route, add it to default table as well
					if [[ -n "${prefix}" && "${prefix}" == "0" ]]; then
                    	ip -4 route replace ${target}/${prefix} via ${gateway} dev ${interface} ${metric} ${src_spec} table default ${realm_spec} ${proto_spec}
                    	if [ $? -ne 0 ]; then
                    	    logmessage "failed to create route: ${target}/${prefix} via ${gateway} dev ${interface} ${metric} ${src_spec} table default ${realm_spec} ${proto_spec}"
                    	fi
					elif [[ -n "${prefix}" && -n "${rt_spec}" ]]; then
						# we have own routing table. if clone routes is activated, put them in main as well
						if phion_config_clone; then
							ip -4 route replace ${target}/${prefix} via ${gateway} dev ${interface} ${metric} ${src_spec} ${realm_spec} ${proto_spec}
						fi
					fi
                fi
            done
        fi

        # gateways
        if [[ ( "${DEFROUTE}" != "no") &&
              (( -z "${GATEWAYDEV}" ) ||
               ( "${GATEWAYDEV}" = "${interface}" )) ]]; then
            if [[ ( -z "$GATEWAY" ) ||
                  (( -n "$DHCLIENT_IGNORE_GATEWAY" ) &&
                   ( "$DHCLIENT_IGNORE_GATEWAY" = [Yy]* )) ]]; then
                metric="${METRIC:-}"
                default_routers=()

				config_metric=$($BOXINFO config ${CONFFILE} / pref)

                for router in ${new_routers} ; do
                    added_router=-

                    for r in ${default_routers[@]} ; do
                        if [ "${r}" = "${router}" ]; then
                            added_router=1
                        fi
                    done

                    if [ -z "${router}" ] ||
                       [ "${added_router}" = "1" ] ||
                       [ $(IFS=. ip2num ${router}) -le 0 ] ||
                       [[ ( "${router}" = "${new_broadcast_address}" ) &&
                          ( "${new_subnet_mask}" != "255.255.255.255" ) ]]; then
                        continue
                    fi

                    default_routers=(${default_routers[@]} ${router})
					if phion_config_dfltrt; then
						if [[ -n ${routing_table} ]]; then		# do not add default route to main table
							add_default_gateway ${router} ${config_metric} "${routing_table}" "${new_ip_address}" "${realm_id}" "${ospf}" # add to dhcp routing table
						fi
						phion_config_clone
						if [[ $? -eq 0  || -z ${routing_table} ]]; then
							# when cloning routes or no dedicated dhcp table, put route to main table
							add_default_gateway ${router} ${config_metric} "default" "${new_ip_address}" "${realm_id}" "${ospf}"	# add to default routing table
						fi
					else
						cuda_add_routes ${router} ${config_metric} "${routing_table}" "${new_ip_address}" "${realm_id}"	"${ospf}" # add to dhcp routing table
						if phion_config_clone; then
							# add to main table, when clone routes is not disabled
							cuda_add_routes ${router} ${config_metric} "main" "${new_ip_address}" "${realm_id}"	"${ospf}" 
						fi
					fi
                    let config_metric=config_metric+1		# multiple routers, increase metric otherwise duplicate routes
                done
            elif [ -n "${GATEWAY}" ]; then
                routersubnet=$(get_network_address ${GATEWAY} ${new_subnet_mask})
                mysubnet=$(get_network_address ${new_ip_address} ${new_subnet_mask})

                if [ "${routersubnet}" = "${mysubnet}" ]; then
                    ip -4 route replace default via ${GATEWAY} dev ${interface}
                fi
            fi
        fi
		
		[[ -f /var/phion/preserve/boxnet/DHCP/dyndns.$(phion_config_getindex) ]] && UpdateDynDNS $(phion_config_getindex) ${new_ip_address}
    fi

    if [ ! "${new_ip_address}" = "${alias_ip_address}" ] &&
       [ -n "${alias_ip_address}" ]; then
        ip -4 addr flush dev ${interface}:0 >/dev/null 2>&1
        ip -4 addr add ${alias_ip_address}/${alias_prefix} dev ${interface}:0
        ip -4 route replace ${alias_ip_address}/32 dev ${interface}:0
    fi

    make_resolv_conf

    if [ -n "${new_host_name}" ] && need_hostname; then
        hostname ${new_host_name} || echo "See -nc option in dhclient(8) man page."
    fi

    if [ -n "${DHCP_TIME_OFFSET_SETS_TIMEZONE}" ] &&
       [[ "${DHCP_TIME_OFFSET_SETS_TIMEZONE}" = [yY1]* ]]; then
        if [ -n "${new_time_offset}" ]; then
            # DHCP option "time-offset" is requested by default and should be
            # handled.  The geographical zone abbreviation cannot be determined
            # from the GMT offset, but the $ZONEINFO/Etc/GMT$offset file can be
            # used - note: this disables DST.
            ((z=new_time_offset/3600))
            ((hoursWest=$(printf '%+d' $z)))

            if (( $hoursWest < 0 )); then
                # tzdata treats negative 'hours west' as positive 'gmtoff'!
                ((hoursWest*=-1))
            fi

            tzfile=/usr/share/zoneinfo/Etc/GMT$(printf '%+d' ${hoursWest})
            if [ -e ${tzfile} ]; then
                save_previous /etc/localtime
                cp -fp ${tzfile} /etc/localtime
                touch /etc/localtime
                fix_context /etc/localtime
            fi
        fi
    fi

    # execute any additional client side configuration scripts we have
    if [ -d ${ETCDIR}/dhclient.d ]; then
        for f in ${ETCDIR}/dhclient.d/*.sh ; do
            if [ -x ${f} ]; then
                subsystem="${f%.sh}"
                subsystem="${subsystem##*/}"
                . ${f}
                "${subsystem}_config"
            fi
        done
    fi
    updateDynConfFile
}

function readDynConfFile {
    local line
	local value
	local idx=0
	{
		while read -r line; do
			  [[ _"${line}" = _ ]] && continue
			  set -- ${line//=/ }
			  if [ _"${1}" == "_IP" ]; then
			  	 ip6_address=${2}
			  fi
			  if [ _"${1}" == "_PD[]" ]; then
			  	 shift
				 idx=0
				 until [ $# -eq 0 ]; do
				 	   ip6_prefixes[idx]=${1}
					   ((idx += 1))
					   shift
				 done
			  fi
			  if [ _"${1}" == "_PDDEV[]" ]; then
			  	 shift
				 idx=0
			  	 until [ $# -eq 0 ]; do
			  	 	   pd_dev[idx]=${1}
					   ((idx += 1))
					   shift
			  	 done
			  fi
		done
	} < ${FILE}
}

# function to split up IPv6 parts into the array 'ip6_parts' and expand to /64
function splitIP6_pref64() {
	local idx=0
	#The parts come via $1 $2 ... the ':' is the seperator via setting IFS
	for arg in "$@"; do 														
		if [ -n "${arg}" ]; then												#Detect a '::'
			ip6_parts[idx]=${arg} 
		else
			ip6_parts[idx]="0"													# if '::' expand to 0
		fi
		((idx +=1 ))
		if [ ${idx} -eq 4 ]; then												# if /64 prefix is reached stop
			break
		fi
	done

	while [ ${idx} -lt 4 ]; do													# if /64 prefix is not reached fill up with '0'
		ip6_parts[idx]="0"
		((idx +=1 ))
	done
}

# function to create /64 prefixes according to the number of interfaces 
# $1 net $2 prefix $3 nr of interfaces
function createIP6_pref64() {
	splitIP6_pref64 ${1}														# split net up into array
	local idx=0
	local nr_pref=${3}			
	local nr_net=0																# also 0 is a valid net
	local max_nr_pref=$(echo "a=64-$2; b=(2^a)-1; b" | bc) 						# calc max nr of prefixes 
	((max_nr_pref += 1)) 														# take 0 as valid net into account
	if [ ${max_nr_pref} -gt 65535 ]; then										# max nr of prefixes will be set to 65535
		max_nr_pref=65535
	fi
	if [ ${nr_pref} -gt ${max_nr_pref} ]; then									# check if it is possible and correct it
		logmessage "Warning: Can only assign ${max_nr_pref}"
		nr_pref=$max_nr_pref
	fi
	# create prefixes
	until [ ${nr_pref} -eq 0 ]; do
		ip6_prefixes[idx]="${ip6_parts[0]}:${ip6_parts[1]}:${ip6_parts[2]}:"	# store first 3 parts
		local dec_net=$(echo "${ip6_parts[3]}" | awk '{print toupper($0)}')		# convert the net part to upper case for calc with bc
		dec_net=$(echo "ibase=16; $dec_net" | bc)								# convert to decimal number
		if [ "${nr_net}" -lt 65535 ]; then										#  we only handle 65535 prefixes 
			local net=0
			((net = dec_net | nr_net))											# create prefix
			local hex_net=$(echo "obase=16; $net" | bc)							# convert prefix to hex
			hex_net=$(echo "${hex_net}" | awk '{print tolower($0)}')			# convert prefix to lower case because bc give back upper case
			ip6_prefixes[idx]+="${hex_net}::/64"								# complete the prefix
		else
			logmessage "ERROR: Cannot handle prefixes above 65535"
		fi
		((idx += 1))		
		((nr_net += 1))
		((nr_pref -= 1))
	done
}

function checkPrefix() {
    local prefix=${new_ip6_prefix#*/}											# get prefix size
	local net=${new_ip6_prefix%/*}												# get net
	local nr_if=${#pd_dev[@]}													# get nr of configured interfaces (stored in array pd_dev)
	if [ "${prefix}" -gt "64" ]; then
	    logmessage "ERROR: Prefix is to small for delegation -> need at least a /64 prefix"
		exit_with_hooks 1
	fi
	
	# Note IFS (Internal Field separator) will be changed to ':' to split up $net
	# in the function splitIP6_pref64()
	IFS=: createIP6_pref64 ${net} ${prefix} ${nr_if}							# create prefixes -> stored in array ip6_prefixes
	unset IFS
}

function updateDynConfFile() {
	if [ -f /etc/phion/functions ]; then
		source  /etc/phion/functions
	else
		logmessage "ERROR: Unable to load '/etc/phion/functions'"
	fi	

	{
		echo "DEV=${interface}"
		if [ -n "${new_ip6_address}" ]; then
		    echo "IP=${new_ip6_address}/${new_ip6_prefixlen}"
		else
			if [ -n "${new_ip_address}" ]; then
				echo "IPADDR=${new_ip_address}"
			else
				echo "IP=${ip6_address}"
			fi
		fi
		echo "PD[]=${ip6_prefixes[@]}"
		echo "PDDEV[]=${pd_dev[@]}"
	} > ${tmpFile}

	if ! MoveOrDelOnDiff ${tmpFile} ${FILE} &>/dev/null; then
		if [[ "x${interface_idx}" = "xnet1" ]]; then
			/bin/cp -af ${FILE} /opt/phion/config/active/dynDHCPnet.conf
		fi
		# reload hostfw ruleset as list of dhcp IPs changed
		/opb/acpfrule i /opt/phion/config/active/boxfw.lfwrule7 > /dev/null 2>&1
	fi
}

function activate_dhcpe()
{
	local OUT=$(/opt/phion/bin/phionctrl module show dhcpe 2>/dev/null)
	set -- ${OUT}
	server=${2}
	service=${3}
	if [ -n "${server}" ] &&
	   [ -n "${service}" ]; then
	   /opt/phion/modules/server/dhcpe/bin/activate "${server}_${service}" &>/dev/null
	fi	
}

function activate_radvd_dhcpe()
{
	local OUT=$(/opt/phion/bin/phionctrl module show firewall 2>/dev/null)
	set -- ${OUT}
	server=${2}
	service=${3}
	if [ -n "${server}" ] &&
	   [ -n "${service}" ]; then
	   radvdconfpath=/phion0/preserve/radvd/${server}_${service}/root/
	   radvdconffile=radvd.conf
	   cp "${radvdconfpath}${radvdconffile}" "${radvdconfpath}${radvdconffile}.$$.tmp" &>/dev/null  # save old conf for recognizing diff to reload conf or not
	   /opt/phion/modules/server/firewall/bin/activate_radvd "${server}_${service}" &>/dev/null
	   if ! diff --brief "${radvdconfpath}${radvdconffile}" "${radvdconfpath}${radvdconffile}.$$.tmp" &>/dev/null; then
	   	  kill -SIGHUP "$(cat /var/run/radvd/radvd.pid)"			# force radvd config reload!
		  activate_dhcpe	  										# force dhcpe config reload, could be that a dhcp client link for prefix was configured
	   fi
	   rm -f "${radvdconfpath}${radvdconffile}.$$.tmp" &>/dev/null
	fi
}

function addIPv6PD_onIf()
{
	local nr_pref=${#ip6_prefixes[@]}						# nr of available prefixes
	local nr_if=${#pd_dev[@]}								# nr of available interfaces
	local nr_add=${nr_if}									# nr of ip addresses to add
	local idx=0												# index for array access
	local ip6_addr											# IPv6 address to introduce

	# Optimal is when nr prefixes and interfaces are equal - but we have to check
	if [ ${nr_pref} -lt ${nr_if} ]; then
	    nr_add=${nr_pref}
	fi
	until [ ${nr_add} -eq 0 ]; do
	    ip6_addr="${ip6_prefixes[idx]%/*}1/${ip6_prefixes[idx]#*/}"		# add the first ip on the interface
		ip -6 addr add ${ip6_addr} dev ${pd_dev[idx]} scope global		# add IP on corresponding interface
		((nr_add -= 1))
		((idx += 1))
	done
}

function deleteIPv6PD_onIf()
{
    local nr_pref=${#ip6_prefixes[@]}						# nr of available prefixes
    local nr_if=${#pd_dev[@]}								# nr of available interfaces
    local nr_add=${nr_if}									# nr of ip addresses to add
    local idx=0												# index for array access
    local ip6_addr											# IPv6 address to introduce

    # Optimal is when nr prefixes and interfaces are equal - but we have to check
    if [ ${nr_pref} -lt ${nr_if} ]; then
        nr_add=${nr_pref}
    fi
    until [ ${nr_add} -eq 0 ]; do
        ip6_addr="${ip6_prefixes[idx]%/*}1/${ip6_prefixes[idx]#*/}"		# add the first ip on the interface
        ip -6 add del ${ip6_addr} dev ${pd_dev[idx]}
        ip -6 route del ${ip6_prefixes[idx]} dev ${pd_dev[idx]}
        ((nr_add -= 1))
        ((idx += 1))
    done
}


# Section 18.1.8. (Receipt of Reply Messages) of RFC 3315 says:
# The client SHOULD perform duplicate address detection on each of
# the addresses in any IAs it receives in the Reply message before
# using that address for traffic.
add_ipv6_addr_with_DAD() {
            ip -6 addr add ${new_ip6_address}/${new_ip6_prefixlen} \
                dev ${interface} scope global

            # repeatedly test whether newly added address passed
            # duplicate address detection (DAD)
            for i in $(seq 5); do
                sleep 1 # give the DAD some time

                # tentative flag = DAD is still not complete or failed
                duplicate=$(ip -6 addr show dev ${interface} tentative \
                              | grep ${new_ip6_address}/${new_ip6_prefixlen})

                # if there's no tentative flag, address passed DAD
                if [ -z "${duplicate}" ]; then
                    break
                fi
            done

            # if there's still tentative flag = address didn't pass DAD = 
            # = it's duplicate = remove it
            if [ -n "${duplicate}" ]; then
                ip -6 addr del ${new_ip6_address}/${new_ip6_prefixlen} dev ${interface}
                exit_with_hooks 3
            fi
			readDynConfFile
			updateDynConfFile
}

dh6config() {
    case "${reason}" in
        BOUND6)
			#Prefix delegation
			if [ -n "${new_ip6_prefix}" ]; then
			    readDynConfFile
				checkPrefix
				updateDynConfFile
				activate_radvd_dhcpe
				addIPv6PD_onIf
				exit_with_hooks 0
			fi
			
            if [ -z "${new_ip6_address}" ] ||
               [ -z "${new_ip6_prefixlen}" ]; then
                exit_with_hooks 2
            fi

			# Normal address allocation
            add_ipv6_addr_with_DAD

            make_resolv_conf
            ;;

        RENEW6|REBIND6)
			# Prefix Delegation
			if [ -n "${new_ip6_prefix}" ]; then	
				readDynConfFile
				checkPrefix
				updateDynConfFile
				activate_radvd_dhcpe
				addIPv6PD_onIf
				exit_with_hooks 0
			fi

			# Stateless
			if [ -z "${new_ip6_address}" ] &&
			   [ -z "${new_ip6_prefixlen}" ] &&
			   [ -n "${new_dhcp6_name_servers}" ] ||
			   [ -n "${new_dhcp6_domain_search}" ]; then
			   
			   	 if [ ! "${new_dhcp6_name_servers}" = "${old_dhcp6_name_servers}" ] ||
               	 	[ ! "${new_dhcp6_domain_search}" = "${old_dhcp6_domain_search}" ]; then
                	make_resolv_conf
            	 fi

				 exit_with_hooks 0
			fi
			
            if [ -z "${new_ip6_address}" ] ||
               [ -z "${new_ip6_prefixlen}" ]; then
                exit_with_hooks 2
            fi

			# Normal address allocation
            if [  ! "${new_ip6_address}" = "${old_ip6_address}" ]; then
                add_ipv6_addr_with_DAD
            fi

            if [ ! "${new_dhcp6_name_servers}" = "${old_dhcp6_name_servers}" ] ||
               [ ! "${new_dhcp6_domain_search}" = "${old_dhcp6_domain_search}" ]; then
                make_resolv_conf
            fi
            ;;

        DEPREF6)
            if [ -z "${new_ip6_prefixlen}" ]; then
                exit_with_hooks 2
            fi

            ip -6 addr change ${new_ip6_address}/${new_ip6_prefixlen} \
                dev ${interface} scope global preferred_lft 0
			readDynConfFile
			updateDynConfFile
            ;;
    esac

    # execute any additional client side configuration scripts we have
    if [ -d ${ETCDIR}/dhclient.d ]; then
        for f in ${ETCDIR}/dhclient.d/*.sh ; do
            if [ -x ${f} ]; then
                subsystem="${f%.sh}"
                subsystem="${subsystem##*/}"
                . ${f}
                "${subsystem}_config"
            fi
        done
    fi
}


#
# ### MAIN
#

if [ -x ${ETCDIR}/dhclient-enter-hooks ]; then
    exit_status=0

    # dhclient-enter-hooks can abort dhclient-script by setting
    # the exit_status variable to a non-zero value
    . ${ETCDIR}/dhclient-enter-hooks
    if [ ${exit_status} -ne 0 ]; then
        exit ${exit_status}
    fi
fi

if [ ! -r /etc/sysconfig/network-scripts/network-functions ]; then
    echo "Missing /etc/sysconfig/network-scripts/network-functions, exiting." >&2
    exit 1
fi

if [ ! -r /etc/rc.d/init.d/functions ]; then
    echo "Missing /etc/rc.d/init.d/functions, exiting." >&2
    exit 1
fi

. /etc/sysconfig/network-scripts/network-functions
. /etc/rc.d/init.d/functions

if [ -f /etc/sysconfig/network ]; then
    . /etc/sysconfig/network
fi

if [ -f /etc/sysconfig/networking/network ]; then
    . /etc/sysconfig/networking/network
fi

cd /etc/sysconfig/network-scripts
CONFIG="ifcfg-${interface}"
interface_idx=$(phion_config_deviceindex ${interface})
FILE="/opt/phion/config/active/dynDHCP${interface_idx}.conf"
tmpFile="/opt/phion/config/active/dynDHCP${interface_idx}.conf.$$.tmp"
need_config ${CONFIG}
source_config >/dev/null 2>&1

new_prefix="$(get_prefix ${new_ip_address} ${new_subnet_mask})"
old_prefix="$(get_prefix ${old_ip_address} ${old_subnet_mask})"
alias_prefix="$(get_prefix ${alias_ip_address} ${alias_subnet_mask})"

case "${reason}" in
    MEDIUM)
        # Linux doesn't handle mediums (media)
        exit_with_hooks 0
        ;;

    PREINIT)
        if [ -n "${alias_ip_address}" ]; then
            # Bring down alias interface, its routes will disappear too.
            ip link set ${interface}:0 down
        fi

        if [ "${keep_old_ip}" = "yes" ]; then
            ip link set ${interface} up
        else
            ip -4 addr flush dev ${interface} >/dev/null 2>&1
            ip -4 route flush dev ${interface} >/dev/null 2>&1
            ip link set ${interface} up
        fi

        if [ -n "${DHCLIENT_DELAY}" ] && [ ${DHCLIENT_DELAY} -gt 0 ]; then
            sleep ${DHCLIENT_DELAY}
        fi

        exit_with_hooks 0
        ;;

    PREINIT6)
        # ensure interface is up
        ip link set ${interface} up

        # remove any stale addresses from aborted clients
        ip -6 addr flush dev ${interface} scope global permanent

        exit_with_hooks 0
        ;;

    ARPCHECK|ARPSEND)
        if [ -z "${new_ip_address}" ] || [ -z "${interface}" ] ||
           arping -q -f -c 2 -w 3 -D -I ${interface} ${new_ip_address}; then
            exit_with_hooks 0
        else
            exit_with_hooks 1
        fi
        ;;

    BOUND|RENEW|REBIND|REBOOT)
        dhconfig
        exit_with_hooks 0
        ;;

    BOUND6|RENEW6|REBIND6|DEPREF6)
        dh6config
        exit_with_hooks 0
        ;;

    EXPIRE6|RELEASE6|STOP6)		
        local prefix
        local net
        local nr_if
        
        # when v6 prefix expired, remove route/IP
        if [ -n "${old_ip6_prefix}" ] && [ -z "${old_ip6_address}" ]; then
            # get prefix and netmask from released ranged
            prefix=${old_ip6_prefix#*/}
            net=${old_ip6_prefix%/*}
            
            # get number of interfaces from config file
            readDynConfFile
            nr_if=${#pd_dev[@]}
            
            if [ "${prefix}" -gt "64" ]; then
                exit_with_hooks 1
            fi
            
            # calculate actual ranges and delete them
            # Note IFS (Internal Field separator) will be changed to ':' to split up $net
            # in the function splitIP6_pref64()
            IFS=: createIP6_pref64 ${net} ${prefix} ${nr_if}
            unset IFS
            deleteIPv6PD_onIf
        fi 

        if [ -z "${old_ip6_address}" ] || [ -z "${old_ip6_prefixlen}" ]; then
            exit_with_hooks 2
        fi

        ip -6 addr del ${old_ip6_address}/${old_ip6_prefixlen} \
            dev ${interface}

        # execute any additional client side configuration scripts we have
        if [ -d ${ETCDIR}/dhclient.d ]; then
            for f in ${ETCDIR}/dhclient.d/*.sh ; do
                if [ -x ${f} ]; then
                    subsystem="${f%.sh}"
                    subsystem="${subsystem##*/}"
                    . ${f}
                    "${subsystem}_restore"
                fi
            done
        fi

        if [ -x ${ETCDIR}/dhclient-${interface}-down-hooks ]; then
            . ${ETCDIR}/dhclient-${interface}-down-hooks
        elif [ -x ${ETCDIR}/dhclient-down-hooks ]; then
            . ${ETCDIR}/dhclient-down-hooks
        fi

        exit_with_hooks 0
        ;;

    EXPIRE|FAIL|RELEASE|STOP)
        # only restore config files if there are no other dhclient processes
        # running (#306381)
        any_other_clients="$(ps -eo pid,ppid,comm | grep dhclient | grep -v ${PPID})"
        if [ -n "${any_other_clients}" ]; then
            if [ -f ${SAVEDIR}/resolv.conf.predhclient.${interface} ]; then
                change_resolv_conf ${SAVEDIR}/resolv.conf.predhclient.${interface}
                rm -f ${SAVEDIR}/resolv.conf.predhclient.${interface}
            fi

            if [ -n "${DHCP_TIME_OFFSET_SETS_TIMEZONE}" ] &&
               [[ "${DHCP_TIME_OFFSET_SETS_TIMEZONE}" = [yY1]* ]]; then
                if [ -e ${SAVEDIR}/localtime.predhclient.${interface} ]; then
                    rm -f /etc/localtime
                    contents="$(< ${SAVEDIR}/localtime.predhclient.${interface})"
                    echo "${contents}" > /etc/localtime
                    rm -f ${SAVEDIR}/localtime.predhclient.${interface}
                    touch /etc/localtime
                    fix_context /etc/localtime
                fi
            fi
        fi

        # execute any additional client side configuration scripts we have
        if [ -d ${ETCDIR}/dhclient.d ]; then
            for f in ${ETCDIR}/dhclient.d/*.sh ; do
                if [ -x ${f} ]; then
                    subsystem="${f%.sh}"
                    subsystem="${subsystem##*/}"
                    . ${f}
                    "${subsystem}_restore"
                fi
            done
        fi

        if [ -x ${ETCDIR}/dhclient-${interface}-down-hooks ]; then
            . ${ETCDIR}/dhclient-${interface}-down-hooks
        elif [ -x ${ETCDIR}/dhclient-down-hooks ]; then
            . ${ETCDIR}/dhclient-down-hooks
        fi

        if [ -n "${alias_ip_address}" ]; then
            # Turn off alias interface
            ip link set ${interface}:0 down
        fi

        if [ -n "${old_ip_address}" ]; then
            # Delete addresses/routes/arp cache.
            flush_dev ${interface}
			# cuda delete rule table entry
			ip -4 rule del from ${old_ip_address}
        fi

        if [ -n "${alias_ip_address}" ]; then
            ip -4 addr add ${alias_ip_address}/${alias_prefix} dev ${interface}:0
            ip -4 route replace ${alias_ip_address}/32 ${interface}:0
        fi

        exit_with_hooks 0
        ;;

    TIMEOUT)
        if [ -n "${new_routers}" ]; then
            if [ -n "${alias_ip_address}" ]; then
                ip -4 addr flush dev ${interface}:0 >/dev/null 2>&1
            fi

            ip -4 addr add ${new_ip_address}/${new_prefix} broadcast ${new_broadcast_address} dev ${interface}
            set ${new_routers}

            if ping -q -c 1 -w 10 -I ${interface} ${1}; then
                dhconfig
                exit_with_hooks 0
            fi

            flush_dev ${interface}
            exit_with_hooks 1
        else
            exit_with_hooks 1
        fi
        ;;

    *)
        logmessage "unhandled state: ${reason}"
        exit_with_hooks 1
        ;;
esac

exit_with_hooks 0
