#!/bin/sh # # network-functions-ipv6 # # Taken from: network-functions-ipv6 # (P) & (C) 1997-2002 by Peter Bieringer # # Version: 2002-11-12 # # Extended address detection is enabled, if 'ipv6calc' is installed # Available here: http://www.bieringer.de/linux/IPv6/ipv6calc/ # # ##### Logging function # $1: : message string # $2: [stdout|stderr].[err|warn[ing]|inf[o]|notice] : log level with optional channel, default is "stdout.notice" # [syslog.[facility.].err|warn[ing]|inf[o]|notice : syslog channel, default is "syslog.user.notice" # $3: : name of function which calls this log function, can be empty using "" # return code: 0=ok 1=argument error 3=major problem ipv6_log() { local message="$1" local level="$2" local name="$3" if [ -z "$message" ]; then echo $"ERROR: [ipv6_log] Missing 'message' (arg 1)" >/dev/stderr return 1 fi if [ -z "$level" ]; then local level="stdout.notice" fi # Map loglevel now local fn=1 local fnawk="print \$$fn" local t="`echo $level | awk -F. "{ $fnawk }"`" # Check channel, if given case $t in 'stdout'|'stderr'|'syslog') local channel="$t" local fn=$[ $fn + 1 ] ;; *) local channel="stdout" ;; esac # Check syslog facilty, if given if [ "$channel" = "syslog" ]; then local fnawk="print \$$fn" local t="`echo $level | awk -F. "{ $fnawk }"`" case $t in 'local0'|'local1'|'local2'|'local3'|'local4'|'local5'|'local6'|'local7'|'daemon') local facility="$t" local fn=$[ $fn + 1 ] ;; *) local facility="user" ;; esac fi local fnawk="print \$$fn" local t="`echo $level | awk -F. "{ $fnawk }"`" # Map priority [ "$t" = "inf" ] && local t="info" [ "$t" = "deb" ] && local t="debug" [ "$t" = "warning" ] && local t="warn" [ "$t" = "error" ] && local t="err" [ "$t" = "critical" ] && local t="crit" # Check priority, if given case $t in 'info'|'debug'|'notice'|'warn'|'err'|'crit') local priority="$t" local fn=$[ $fn + 1 ] ;; *) local priority="notice" ;; esac local fnawk="print \$$fn" local t="`echo $level | awk -F. "{ $fnawk }"`" if [ -n "$t" ]; then echo $"ERROR: [ipv6_log] Loglevel isn't valid '$level' (arg 2)" >/dev/stderr return 1 fi # Generate function text if [ -z "$name" ]; then local txt_name="" else local txt_name="[$name]" fi # Log message case $channel in 'stdout'|'stderr') # Generate level text case $priority in 'debug') local txt_level=$"DEBUG " ;; 'err') local txt_level=$"ERROR " ;; 'warn') local txt_level=$"WARN " ;; 'crit') local txt_level=$"CRITICAL " ;; 'info') local txt_level=$"INFO " ;; 'notice') local txt_level=$"NOTICE " ;; esac [ -n "$txt_name" ] && local txt_name="$txt_name " if [ "$channel" = "stderr" ]; then echo "$txt_level: ${txt_name}${message}" >/dev/stderr elif [ "$channel" = "stdout" ]; then echo "$txt_level: ${txt_name}${message}" fi ;; 'syslog') # note: logger resides in /usr/bin, but not used by default if ! [ -x logger ]; then echo $"ERROR: [ipv6_log] Syslog is chosen, but binary 'logger' doesn't exist or isn't executable" >/dev/stderr return 3 fi if [ -z "$txt_name" ]; then logger -p $facility.$priority $message else logger -p $facility.$priority -t "$txt_name" "$message" fi ;; *) echo $"ERROR: [ipv6_log] Cannot log to channel '$channel'" >/dev/stderr return 3 ;; esac return 0 } ###### Beginning of main code here, always executed on "source|. network-functions-ipv6" ##### Test for "ipv6calc" (used for better existing address detection) EXISTS_ipv6calc=no if [ -x /bin/ipv6calc ]; then if /bin/ipv6calc --if_inet62addr 3ffeffff0100f1010000000000000001 40 | LC_ALL=C grep -q -v '3ffe:ffff:100:f101::1/64'; then false elif /bin/ipv6calc --addr2if_inet6 3ffe:ffff:100::1/64 | LC_ALL=C grep -q -v '3ffeffff010000000000000000000001 00 40'; then false else EXISTS_ipv6calc=yes fi else false fi ###### End of main code here ##### Test for IPv6 capabilites # $1: (optional) testflag: currently supported: "testonly" (do not load a module) # return code: 0=ok 2=IPv6 test fails ipv6_test() { local fn="ipv6_test" local testflag=$1 if ! [ -f /proc/net/if_inet6 ]; then if [ "$testflag" = "testonly" ]; then return 2 else modprobe ipv6 if ! [ -f /proc/net/if_inet6 ]; then ipv6_log $"Kernel is not compiled with IPv6 support" crit $fn return 2 fi fi fi if ! [ -d /proc/sys/net/ipv6/conf/ ]; then return 2 fi if ! [ -x /sbin/ip ]; then ipv6_log $"Utility 'ip' (package: iproute) doesn't exist or isn't executable - stop" crit $fn return 2 fi if ! [ -x /sbin/sysctl ]; then ipv6_log $"Utility 'sysctl' (package: procps) doesn't exist or isn't executable - stop" crit $fn return 2 fi return 0 } ##### Get version of this function library # stdout: getversion_ipv6_functions() { local version_ipv6_functions="`cat /etc/sysconfig/network-scripts/network-functions-ipv6 | LC_ALL=C grep "^# Version:" | awk '{ print $3 }' | sed 's/-//g' | sed 's/[A-Za-z]*$//g'`" echo $version_ipv6_functions } ##### Wrapper for used binaries ## ifconfig # $*: # return code: result of execution ipv6_exec_ifconfig() { local options=$* LC_ALL=C /sbin/ifconfig $options return $? } ## route # $*: # return code: result of execution ipv6_exec_route() { local options=$* LC_ALL=C /sbin/route $options return $? } ## ip # $*: # return code: result of execution ipv6_exec_ip() { local options=$* LC_ALL=C /sbin/ip $options return $? } ## sysctl # $*: # return code: result of execution ipv6_exec_sysctl() { local options=$* LC_ALL=C /sbin/sysctl -e $options return $? } ##### Control IPv6 forwarding # Control IPv6 forwarding # $1: yes|no|on|off : control value # $2: [] : (optional), if not given, global IPv6 forwarding is set [OBSOLETE] # return code: 0=ok 1=argument error 2=IPv6 test fails ipv6_control_forwarding() { local fn="ipv6_control_forwarding" local fw_control=$1 local fw_device=$2 # maybe empty if [ -z "$fw_control" ]; then ipv6_log $"Missing parameter 'forwarding control' (arg 1)" err $fn return 1 fi if ! [ "$fw_control" = "yes" -o "$fw_control" = "no" -o "$fw_control" = "on" -o "$fw_control" = "off" ]; then ipv6_log $"Forwarding control parameter isn't valid '$fw_control' (arg 1)" err $fn return 1 fi ipv6_test || return 2 if [ "$fw_control" = "yes" -o "$fw_control" = "on" ]; then local status=1 else local status=0 fi # Global control? (if no device is given) if [ -z "$fw_device" ]; then ipv6_exec_sysctl -w net.ipv6.conf.all.forwarding=$status >/dev/null 2>&1 fi # Per device control (not implemented in kernel) if [ -n "$fw_device" ]; then ipv6_log $"IPv6 forwarding per device cannot be controlled via sysctl - use netfilter6 instead" warn $fn fi return 0 } ##### Static IPv6 route configuration # Set static IPv6 route # $1: : to route # $2: : over which $1 should be routed (if "::", gw will be skipped) # $3: [] : (optional) # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem adding route ipv6_add_route() { local fn="ipv6_add_route" local networkipv6=$1 local gatewayipv6=$2 local device=$3 # maybe empty if [ -z "$networkipv6" ]; then ipv6_log $"Missing parameter 'IPv6-network' (arg 1)" err $fn return 1 fi if [ -z "$gatewayipv6" ]; then ipv6_log $"Missing parameter 'IPv6-gateway' (arg 2)" err $fn return 1 fi ipv6_test || return 2 ipv6_test_ipv6_addr_valid $networkipv6 || return 2 ipv6_test_ipv6_addr_valid $gatewayipv6 || return 2 if [ -z "$device" ]; then local returntxt="`ipv6_exec_ip -6 route add $networkipv6 via $gatewayipv6 metric 1 2>&1`" else if [ "$gatewayipv6" = "::" ]; then local returntxt="`ipv6_exec_ip -6 route add $networkipv6 dev $device metric 1 2>&1`" else local returntxt="`ipv6_exec_ip -6 route add $networkipv6 via $gatewayipv6 dev $device metric 1 2>&1`" fi fi if [ -n "$returntxt" ]; then if echo $returntxt | LC_ALL=C grep -q "File exists"; then # Netlink: "File exists" true elif echo $returntxt | LC_ALL=C grep -q "No route to host"; then # Netlink: "No route to host" ipv6_log $"'No route to host' adding route '$networkipv6' via gateway '$gatewayipv6' through device '$device'" warn $fn return 3 else ipv6_log $"Unknown error" warn $fn return 3 fi fi return 0 } # Delete a static IPv6 route # $1: : to route # $2: : over which $1 should be routed (if "::", gw will be skipped) # $3: [] : (optional) # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem adding route ipv6_del_route() { local fn="ipv6_del_route" local networkipv6=$1 local gatewayipv6=$2 local device=$3 # maybe empty if [ -z "$networkipv6" ]; then ipv6_log $"Missing parameter 'IPv6-network' (arg 1)" err $fn return 1 fi if [ -z "$gatewayipv6" ]; then ipv6_log $"Missing parameter 'IPv6-gateway' (arg 2)" err $fn return 1 fi ipv6_test testonly || return 2 # Test, whether given IPv6 address is valid ipv6_test_ipv6_addr_valid $networkipv6 || return 1 ipv6_test_ipv6_addr_valid $gatewayipv6 || return 1 if [ -z "$device" ]; then ipv6_exec_ip -6 route del $networkipv6 via $gatewayipv6 local result=$? else if [ "$gatewayipv6" = "::" ]; then ipv6_exec_ip -6 route del $networkipv6 dev $device local result=$? else ipv6_exec_ip -6 route del $networkipv6 via $gatewayipv6 dev $device local result=$? fi fi if [ $result -eq 2 ]; then # Netlink: "No such process" true elif [ $result -ne 0 ]; then return 3 fi return 0 } # Delete all static IPv6 routes through a given interface # $1: # $2: [] : to match (optional) # return code: 0=ok 1=argument error 2=IPv6 test fails ipv6_cleanup_routes() { local fn="ipv6_cleanup_routes" local device=$1 local gatewaymatch=$2 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi ipv6_test testonly || return 2 # Get all IPv6 routes through given interface and remove them ipv6_exec_route -A inet6 -n | LC_ALL=C grep "$device\W*$" | while read ipv6net nexthop flags metric ref use iface args; do if [ "$iface" = "$device" ]; then if [ -n "$gatewaymatch" ]; then # Test if given gateway matches if [ "$gatewaymatch" != "$nexthop" ]; then continue fi fi # Only non addrconf (automatic installed) routes should be removed if echo $flags | LC_ALL=C grep -v -q "A"; then ipv6_exec_route -A inet6 del $ipv6net gw $nexthop dev $iface fi fi done return 0 } ##### automatic tunneling configuration ## Configure automatic tunneling up # return code: 0=ok 2=IPv6 test fails 3=major problem ipv6_enable_autotunnel() { local fn="ipv6_enable_autotunnel" ipv6_test || return 2 # enable IPv6-over-IPv4 tunnels if ipv6_test_device_status sit0; then true else # bring up basic tunnel device ipv6_exec_ifconfig sit0 up if ! ipv6_test_device_status sit0; then ipv6_log $"Tunnel device 'sit0' enabling didn't work" err $fn return 3 fi # Set sysctls proper (regardless "default") ipv6_exec_sysctl -w net.ipv6.conf.sit0.forwarding=1 >/dev/null 2>&1 ipv6_exec_sysctl -w net.ipv6.conf.sit0.accept_ra=0 >/dev/null 2>&1 ipv6_exec_sysctl -w net.ipv6.conf.sit0.accept_redirects=0 >/dev/null 2>&1 fi return 0 } ## Configure automatic tunneling down # return code: 0=ok 2=IPv6 test fails 3=major problem ipv6_disable_autotunnel() { local fn="ipv6_disable_autotunnel" ipv6_test testonly || return 2 if ipv6_test_device_status sit0; then # disable IPv6-over-IPv4 tunnels (if a tunnel is no longer up) if ipv6_exec_route -A inet6 -n 2>/dev/null | LC_ALL=C grep "sit0\W*$" | awk '{ print $2 }' | LC_ALL=C grep -v -q "^::$"; then # still existing routes, skip shutdown of sit0 true elif ipv6_exec_ip -6 -o addr show dev sit0 | awk '{ print $4 }' | LC_ALL=C grep -v -q '^::'; then # still existing IPv6 addresses, skip shutdown of sit0 true else # take down basic tunnel device ipv6_exec_sysctl -w net.ipv6.conf.sit0.forwarding=0 >/dev/null 2>&1 ipv6_exec_sysctl -w net.ipv6.conf.sit0.accept_ra=0 >/dev/null 2>&1 ipv6_exec_sysctl -w net.ipv6.conf.sit0.accept_redirects=0 >/dev/null 2>&1 ipv6_exec_ifconfig sit0 down if ipv6_test_device_status sit0; then ipv6_log $"Tunnel device 'sit0' is still up" err $fn return 3 fi fi fi return 0 } ##### Test, whether an IPv6 address exists on an interface # $1: : to testing # $2: : to test (without prefix length) # $3: : of address $2 # return values: 0=ok (exists) 1=argument error 3=major problem 10=not exists ipv6_test_addr_exists_on_device() { local fn="ipv6_test_addr_exists_on_device" local testdevice=$1 local testaddr=$2 local testprefix=$3 if [ -z "$testdevice" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$testaddr" ]; then ipv6_log $"Missing parameter 'IPv6 address to test' (arg 2)" err $fn return 1 fi if [ -z "$testprefix" ]; then ipv6_log $"Missing parameter 'IPv6 address prefix length' (arg 3)" err $fn return 1 fi ipv6_test testonly || return 2 if [ "$EXISTS_ipv6calc" = "yes" ]; then # Using ipv6calc and compare against /proc/net/if_inet6 local convertresult="`/bin/ipv6calc --addr2if_inet6 $testaddr/$testprefix`" # Split in address, scope and prefix length local test_addr="`echo $convertresult | awk '{ print $1 }'`" local test_scope="`echo $convertresult | awk '{ print $2 }'`" local test_prefixlength="`echo $convertresult | awk '{ print $3 }'`" if [ -z "$test_prefixlength" ]; then local testresult="`LC_ALL=C grep "$test_addr .. .. $test_scope .." /proc/net/if_inet6 | LC_ALL=C grep $testdevice$`" else local testresult="`LC_ALL=C grep "$test_addr .. $test_prefixlength $test_scope .." /proc/net/if_inet6 | LC_ALL=C grep $testdevice$`" fi if [ -n "$testresult" ]; then # exists return 0 else # not exists return 10 fi else # low budget version, only works if given address is in equal form like "ip" displays local testresult="`ipv6_exec_ip -o -6 addr show dev $testdevice | awk '{ print $4 }' | LC_ALL=C grep -i "^$testaddr/$testprefix$"`" if [ -n "$testresult" ]; then # exists return 0 else # not exists return 10 fi fi # Normally this lines not reached return 3 } ##### Interface configuration ## Add an IPv6 address for given interface # $1: # $2: # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_add_addr_on_device() { local fn="ipv6_add_addr_on_device" local device=$1 local address=$2 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$address" ]; then ipv6_log $"Missing parameter 'IPv6-address' (arg 2)" err $fn return 1 fi ipv6_test || return 2 ipv6_test_ipv6_addr_valid $address || return 1 ipv6_test_device_status $device local result=$? if [ "$result" = "0" ]; then true elif [ "$result" != "11" ]; then ipv6_log $"Device '$device' doesn't exist" err $fn return 3 else ipv6_exec_ifconfig $device up if ! ipv6_test_device_status $device; then ipv6_log $"Device '$device' enabling didn't work" err $fn return 3 fi fi # Extract address parts local prefixlength_implicit="`echo $address | awk -F/ '{ print $2 }'`" local address_implicit="`echo $address | awk -F/ '{ print $1 }'`" # Check prefix length and using '64' as default if [ -z "$prefixlength_implicit" ]; then local prefixlength_implicit="64" local address="$address_implicit/$prefixlength_implicit" fi # Only add if address does not already exist ipv6_test_addr_exists_on_device $device $address_implicit $prefixlength_implicit local result=$? if [ $result -ne 0 -a $result -ne 10 ]; then return 3 fi if [ $result -eq 0 ]; then true else ipv6_exec_ifconfig $device inet6 add $address || return 3 fi return 0 } ## Remove all IPv6 routes and addresses on given interface (cleanup to prevent kernel crashes) # $1: # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_cleanup_device() { local fn="ipv6_cleanup_device" local device=$1 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi ipv6_test testonly || return 2 # Remove all IPv6 routes through this device (but not "lo") if [ "$device" != "lo" ]; then ipv6_exec_ip -6 route flush dev $device >/dev/null 2>&1 fi # Remove all IPv6 addresses on this interface ipv6_exec_ip -6 addr flush dev $device >/dev/null 2>&1 return 0 } ## Remove an IPv6 address on given interface # $1: # $2: # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_del_addr_on_device() { local fn="ipv6_del_addr_on_device" local device=$1 local address=$2 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$address" ]; then ipv6_log $"Missing parameter 'IPv6 address' (arg 2)" err $fn return 1 fi ipv6_test testonly || return 2 ipv6_test_ipv6_addr_valid $address || return 1 # Extract address parts local prefixlength_implicit="`echo $address | awk -F/ '{ print $2 }'`" local address_implicit="`echo $address | awk -F/ '{ print $1 }'`" # Check prefix length and using '64' as default if [ -z "$prefixlength_implicit" ]; then local prefixlength_implicit="64" local address="$address_implicit/$prefixlength_implicit" fi # Only remove, if address exists and is not link-local (prevents from kernel crashing) ipv6_test_addr_exists_on_device $device $address_implicit $prefixlength_implicit local result=$? if [ $result -ne 0 -a $result -ne 10 ]; then return 3 fi if [ $result -eq 0 ]; then ipv6_exec_ifconfig $device inet6 del $address || return 3 else true fi return 0 } ##### Some address test functions ## Test a given IPv6 address for validity # $1: # $2: [quiet] : (optional) don't display error message # return code: 0=ok 1=argument error 10=not valid ipv6_test_ipv6_addr_valid() { local fn="ipv6_test_ipv6_addr_valid" local testipv6addr_valid=$1 local modequiet=$2 if [ -z "$testipv6addr_valid" ]; then return 1 fi if [ -n "$modequiet" ]; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"Parameter '$modequiet' for 'quiet' mode is not valid (arg 2)" err $fn return 1 fi fi # Extract parts local prefixlength_implicit="`echo $testipv6addr_valid | awk -F/ '{ print $2 }'`" local address_implicit="`echo $testipv6addr_valid | awk -F/ '{ print $1 }'`" if [ "$EXISTS_ipv6calc" = "yes" ]; then if ! /bin/ipv6calc --addr2uncompaddr $testipv6addr_valid >/dev/null 2>&1; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"Given IPv6 address '$testipv6addr_valid' is not valid" err $fn fi return 10 fi else # Test for a valid format if ! echo "$address_implicit" | LC_ALL=C egrep -q '^[[:xdigit:]]|[:\.]*$'; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"Given IPv6 address '$testipv6addr_valid' is not valid" err $fn fi return 10 fi fi # Test for prefix length if [ -z "$prefixlength_implicit" ]; then if echo "$testipv6addr_valid" | LC_ALL=C grep "/$"; then # Trailing "/", but no value if [ "$modequiet" != "quiet" ]; then ipv6_log $"Missing prefix length for given address '$testipv6addr_valid'" err $fn fi return 10 else return 0 fi elif [ $prefixlength_implicit -lt 0 -o $prefixlength_implicit -gt 128 ]; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"On given address '$testipv6addr_valid' the prefix length is out of range (valid: 0-128)" err $fn fi return 10 fi return 0 } ## Test a given IPv4 address for validity # $1: # $2: [quiet] : (optional) don't display error message # return code: 0=ok 1=argument error 10=not valid ipv6_test_ipv4_addr_valid() { local fn="ipv6_test_ipv4_addr_valid" local testipv4addr_valid=$1 local modequiet=$2 if [ -z "$testipv4addr_valid" ]; then return 1 fi if [ -n "$modequiet" ]; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"Parameter '$modequiet' for 'quiet' mode is not valid (arg 2)" err $fn return 1 fi fi # Test for a valid format if echo "$testipv4addr_valid" | LC_ALL=C egrep -q -v '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"Given IPv4 address '$testipv4addr_valid' has no proper format" err $fn fi return 10 fi # Test for valid IPv4 address parts local number1="`echo $testipv4addr_valid | awk -F. '{ print $1 }'`" local number2="`echo $testipv4addr_valid | awk -F. '{ print $2 }'`" local number3="`echo $testipv4addr_valid | awk -F. '{ print $3 }'`" local number4="`echo $testipv4addr_valid | awk -F. '{ print $4 }'`" local c=1 for number in "$number1" "$number2" "$number3" "$number4"; do if [ $number -lt 0 -o $number -gt 255 ]; then if [ "$modequiet" != "quiet" ]; then ipv6_log $"Part $c of given IPv4 address '$testipv4addr_valid' is out of range" err $fn fi return 10 fi local c=$[ $c + 1 ] done return 0 } ## Test a given IPv4 address for not a private but unicast one # $1: # return code: 0=ok 1=argument error 10=private or not unicast ipv6_test_ipv4_addr_global_usable() { local fn="ipv6_test_ipv4_addr_global_usable" local testipv4addr_globalusable=$1 if [ -z "$testipv4addr_globalusable" ]; then return 1 fi # Test for a globally usable IPv4 address now # test 0.0.0.0/8 /bin/ipcalc --network $testipv4addr_globalusable 255.0.0.0 | LC_ALL=C grep -q "NETWORK=0\.0\.0\.0" && return 10 # test 10.0.0.0/8 (RFC 1918 / private) /bin/ipcalc --network $testipv4addr_globalusable 255.0.0.0 | LC_ALL=C grep -q "NETWORK=10\.0\.0\.0" && return 10 # test 127.0.0.0/8 (loopback) /bin/ipcalc --network $testipv4addr_globalusable 255.0.0.0 | LC_ALL=C grep -q "NETWORK=127\.0\.0\.0" && return 10 # test 169.254.0.0/16 (APIPA / DHCP link local) /bin/ipcalc --network $testipv4addr_globalusable 255.255.0.0 | LC_ALL=C grep -q "NETWORK=169\.254\.0\.0" && return 10 # test 172.16.0.0/12 (RFC 1918 / private) /bin/ipcalc --network $testipv4addr_globalusable 255.240.0.0 | LC_ALL=C grep -q "NETWORK=172\.16\.0\.0" && return 10 # test 192.168.0.0/16 (RFC 1918 / private) /bin/ipcalc --network $testipv4addr_globalusable 255.255.0.0 | LC_ALL=C grep -q "NETWORK=192\.168\.0\.0" && return 10 # test 224.0.0.0/3 (multicast and reserved, broadcast) /bin/ipcalc --network $testipv4addr_globalusable 224.0.0.0 | LC_ALL=C grep -q "NETWORK=224\.0\.0\.0" && return 10 return 0 } ## Test a given device for status # $1: # return code: 0=ok 1=argument error 10=not exists 11=down ipv6_test_device_status() { local fn="ipv6_test_device_status" local device=$1 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi # Test if device exists if ! ipv6_exec_ifconfig $device >/dev/null 2>&1; then # not exists return 10 fi # Test if device is up if ipv6_exec_ifconfig $device 2>/dev/null | LC_ALL=C grep -q "UP "; then # up return 0 else # down return 11 fi } ## Create 6to4 prefix # $1: # stdout: <6to4address> # return code: 0=ok 1=argument error ipv6_create_6to4_prefix() { local fn="ipv6_create_6to4_prefix" local ipv4addr=$1 if [ -z "$ipv4addr" ]; then ipv6_log $"Missing parameter 'IPv4 address' (arg 1)" stderr.err $fn fi local major1="`echo $ipv4addr | awk -F. '{ print $1 }'`" local minor1="`echo $ipv4addr | awk -F. '{ print $2 }'`" local major2="`echo $ipv4addr | awk -F. '{ print $3 }'`" local minor2="`echo $ipv4addr | awk -F. '{ print $4 }'`" if [ -z "$major1" -o -z "$minor1" -o -z "$major2" -o -z "$minor2" ]; then return 1 fi if [ $major1 -eq 0 ]; then local block1="`printf "%x" $minor1`" else local block1="`printf "%x%02x" $major1 $minor1`" fi if [ $major2 -eq 0 ]; then local block2="`printf "%x" $minor2`" else local block2="`printf "%x%02x" $major2 $minor2`" fi local prefix6to4="2002:$block1:$block2" echo "$prefix6to4" return 0 } ## Check and create 6to4 tunnel relay address # $1: # stdout: # return code: 0=ok 1=argument error ipv6_create_6to4_relay_address() { local fn="ipv6_create_6to4_relay_address" local addr=$1 if [ -z "$addr" ]; then ipv6_log $"Missing parameter 'address' (arg 1)" stderr.err $fn return 1 fi # Check if ipv6_test_ipv4_addr_valid $addr quiet; then # ok, a IPv4 one if ipv6_test_ipv4_addr_global_usable $addr; then # IPv4 globally usable local ipv6to4_relay="::$addr" else ipv6_log $"Given address '$addr' is not a global IPv4 one (arg 1)" stderr.err $fn return 1 fi else ipv6_log $"Given address '$addr' is not a valid IPv4 one (arg 1)" stderr.err $fn return 1 fi echo "$ipv6to4_relay" return 0 } ##### 6to4 tunneling setup ## Configure 6to4 tunneling up # $1: : only "tun6to4" is supported # $2: : global address of local interface # $3: [] : for 6to4 prefix (optional, default is "::1") # $4: [] : MTU of tunnel device (optional, default is automatic) # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_add_6to4_tunnel() { local fn="ipv6_add_6to4_tunnel" local device=$1 local localipv4=$2 local localipv6to4suffix=$3 local mtu=$4 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$localipv4" ]; then ipv6_log $"Missing parameter 'local IPv4 address' (arg 2)" err $fn return 1 fi # Check device if [ "$device" != "tun6to4" ]; then ipv6_log $"Given device '$device' is not supported (arg 1)" err $fn return 1 fi ipv6_test || return 2 # Generate 6to4 address local prefix6to4="`ipv6_create_6to4_prefix $localipv4`" if [ $? -ne 0 -o -z "$prefix6to4" ]; then return 3 fi if [ -z "$localipv6to4suffix" ]; then local address6to4="${prefix6to4}::1/16" else local address6to4="${prefix6to4}::${localipv6to4suffix}/16" fi ipv6_add_tunnel_device tun6to4 0.0.0.0 $address6to4 $localipv4 if [ $? -ne 0 ]; then local retval=3 else local retval=0 fi # Add unspecific unreachable route for local 6to4 address space ipv6_exec_ip route add unreach ${prefix6to4}::/48 # Set MTU, if given if [ -n "$mtu" ]; then ipv6_set_mtu $device $mtu fi return $retval } ## Configure all 6to4 tunneling down # $1: : only "tun6to4" is supported # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_cleanup_6to4_tunnels() { local fn="ipv6_cleanup_6to4_tunnels" local device=$1 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi # Check device if [ "$device" != "tun6to4" ]; then ipv6_log $"Given device '$device' is not supported (arg 1)" err $fn return 1 fi ipv6_test testonly || return 2 ipv6_del_tunnel_device tun6to4 # Remove all unspecific unreachable routes for local 6to4 address space ipv6_exec_ip -6 route | LC_ALL=C grep "^unreachable 2002:" | LC_ALL=C grep "/48 dev lo" | while read token net rest; do ipv6_exec_ip route del unreach $net done return 0 } ## Configure 6to4 tunneling down # $1: : only "tun6to4" is supported # $2: : global address of local interface # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_del_6to4_tunnel() { local fn="ipv6_del_6to4_tunnel" local device=$1 local localipv4=$2 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$localipv4" ]; then ipv6_log $"Missing parameter 'local IPv4 address' (arg 2)" err $fn return 1 fi # Check device if [ "$device" != "tun6to4" ]; then ipv6_log $"Given device '$device' is not supported (arg 1)" err $fn return 1 fi ipv6_test || return 2 ipv6_del_tunnel_device tun6to4 local retval=$? # Remove unspecific unreachable route for local 6to4 address space ipv6_exec_ip route del unreach ${prefix6to4}::/48 return $retval } ## Configure a static tunnel device up # $1: # $2: : of foreign tunnel # $3: [] : local one of a P-t-P tunnel (optional) # $4: [] : local one of tunnel (optional) # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_add_tunnel_device() { local fn="ipv6_add_tunnel_device" local device=$1 local addressipv4tunnel=$2 local addressipv6local=$3 local addressipv4tunnellocal=$4 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$addressipv4tunnel" ]; then ipv6_log $"Missing parameter 'IPv4-tunnel address' (arg 2)" err $fn return 1 fi if [ -z "$addressipv4tunnellocal" ]; then local addressipv4tunnellocal="any" fi ipv6_test || return 2 if ! ipv6_test_device_status $device; then local ttldefault="`ipv6_exec_sysctl net.ipv4.ip_default_ttl | awk '{ print $3 }'`" if [ -z "$ttldefault" ]; then local ttldefault=64 fi # Test whether remote IPv4 address was already applied to another tunnel (does not catch IPv4 addresses with leading 0's) ipv6_exec_ip tunnel show 2>/dev/null | LC_ALL=C grep -w "ipv6/ip" | LC_ALL=C grep "$addressipv4tunnel" | while read dev type tag remote tag local tag ttl rest; do local devnew="`echo $dev | sed 's/:$//g'`" if [ "$remote" = "$addressipv4tunnel" ]; then ipv6_log $"Given remote address '$addressipv4tunnel' on tunnel device '$device' is already configured on device '$devnew'" err $fn return 3 fi done if [ $? -ne 0 ]; then return 3 fi ipv6_exec_ip tunnel add $device mode sit ttl $ttldefault remote $addressipv4tunnel local $addressipv4tunnellocal # Test, whether "ip tunnel show" works without error ipv6_exec_ip tunnel show $device >/dev/null 2>&1 if [ $? -ne 0 ]; then ipv6_log $"Tunnel device '$device' creation didn't work" err $fn return 3 fi # Test, whether "ip tunnel show" reports valid content if ! ipv6_exec_ip tunnel show $device 2>/dev/null | LC_ALL=C grep -q -w "remote"; then ipv6_log $"Tunnel device '$device' creation didn't work" err $fn return 3 fi ipv6_exec_ifconfig $device up if ! ipv6_test_device_status $device; then ipv6_log $"Tunnel device '$device' bringing up didn't work" err $fn return 3 fi # Set sysctls proper (regardless "default") ipv6_exec_sysctl -w net.ipv6.conf.$device.forwarding=1 >/dev/null 2>&1 ipv6_exec_sysctl -w net.ipv6.conf.$device.accept_ra=0 >/dev/null 2>&1 ipv6_exec_sysctl -w net.ipv6.conf.$device.accept_redirects=0 >/dev/null 2>&1 if [ -n "$addressipv6local" ]; then # Setup P-t-P address ipv6_add_addr_on_device $device $addressipv6local if [ $? -ne 0 ]; then return 3 fi fi else false fi return 0 } ## Configure a static tunnel device down # $1: # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_del_tunnel_device() { local fn="ipv6_del_tunnel_device" local device=$1 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi ipv6_test testonly || return 2 if ipv6_test_device_status $device; then ipv6_cleanup_device $device else if [ "$device" != "sit0" ]; then false fi fi if [ "$device" != "sit0" ]; then if ipv6_exec_ip tunnel show $device 2>/dev/null | LC_ALL=C grep -q -w "ipv6/ip"; then ipv6_exec_ip tunnel del $device if ipv6_test_device_status $device; then return 3 fi else false fi fi return 0 } ## Cleanup all dedicated tunnel devices ipv6_cleanup_tunnel_devices() { local fn="ipv6_cleanup_tunnel_devices" ipv6_test testonly || return 2 # Find still existing tunnel devices and shutdown and delete them ipv6_exec_ip tunnel show | LC_ALL=C grep -w "ipv6/ip" | awk -F: '{ print $1 }' | while read device; do ipv6_del_tunnel_device $device done return 0 } ## Get address of a dedicated tunnel # $1: # $2: local|remote : local or remote address # stdout: if available # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_get_ipv4addr_of_tunnel() { local fn="ipv6_get_local_ipv4_of_tunnel" local device=$1 local selection=$2 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" stderr.err $fn return 1 fi if [ -z "$selection" ]; then ipv6_log $"Missing parameter 'selection' (arg 2)" stderr.err $fn return 1 fi if [ "$selection" != "local" -a "$selection" != "remote" ]; then ipv6_log $"Unsupported selection '$selection' specified (arg 2)" stderr.err $fn return 1 fi ipv6_test testonly || return 2 ipv6_test_device_status $device if [ $? != 0 -a $? != 11 ]; then # Device doesn't exist return 3 fi # Device exists, retrieve address if [ "$selection" = "local" ]; then local tunnel_local_ipv4addr="`ipv6_exec_ip tunnel show $device | awk '{ print $6 }'`" elif [ "$selection" = "remote" ]; then local tunnel_local_ipv4addr="`ipv6_exec_ip tunnel show $device | awk '{ print $4 }'`" fi if [ $? != 0 ]; then return 3 fi if [ "$tunnel_local_ipv4addr" = "any" ]; then local tunnel_local_ipv4addr="0.0.0.0" fi echo "$tunnel_local_ipv4addr" return 0 } ## Get IPv4 address of a device # $1: # stdout: if available # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem (more than one IPv4 address applied) ipv6_get_ipv4addr_of_device() { local fn="ipv6_get_ipv4addr_of_device" local device=$1 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" stderr.err $fn return 1 fi ipv6_test_device_status $device if [ $? != 0 -a $? != 11 ]; then # Device doesn't exist return 3 fi # Device exists, retrieve the first address only local ipv4addr="`ipv6_exec_ip -o -4 addr show dev $device | awk '{ print $4 }' | awk -F/ '{ print $1; exit }'`" if [ $? != 0 ]; then return 3 fi if [ "$ipv4addr" = "any" ]; then local ipv4addr="0.0.0.0" fi echo "$ipv4addr" return 0 } ## Set IPv6 MTU for a device # $1: # $2: # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_set_mtu() { local fn="ipv6_set_mtu" local device=$1 local ipv6_mtu=$2 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi if [ -z "$ipv6_mtu" ]; then ipv6_log $"Missing parameter 'IPv6 MTU' (arg 2)" err $fn return 1 fi # Check range if [ $ipv6_mtu -lt 1280 -o $ipv6_mtu -gt 65535 ]; then ipv6_log $"Given IPv6 MTU '$ipv6_mtu' is out of range" err $fn return 1 fi ipv6_test testonly || return 2 # Check whether key exists ipv6_exec_sysctl net.ipv6.conf.$device.mtu >/dev/null 2>&1 if [ $? -ne 0 ]; then return 3 fi # Set value ipv6_exec_sysctl -w net.ipv6.conf.$device.mtu=$ipv6_mtu >/dev/null 2>&1 return 0 } ## Set a default route # $1: : gateway, can also contain scope suffix (device name), cause a warning if not matching with $2 (but will have precedence) # $2: : gateway device (optional in case of $1 is a global address or $1 contains scope suffix) # $3: : (optional) device to check scope and gateway device against (setup is skipped, if not matching) # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_set_default_route() { local fn="ipv6_set_default_route" local address=$1 local device=$2 local device_check=$3 ipv6_test testonly || return 2 # Map the unspecified address to nothing if [ "$address" = "::" ]; then local address="" fi if [ -n "$address" ]; then local addressgw=`echo $address | awk -F% '{ print $1 }'` local device_scope=`echo $address | awk -F% '{ print $2 }'` if [ -z "$addressgw" ]; then ipv6_log $"Given IPv6 default gateway '$address' is not in proper format" err $fn return 3 fi # Scope device has precedence if [ -n "$device_scope" -a -n "$device" -a "$device_scope" != "$device" ]; then ipv6_log $"Given IPv6 default gateway '$address' has scope '$device_scope' defined, given default gateway device '$device' will be not used" inf $fn local device="" fi # Link local addresses require a device if echo $addressgw | LC_ALL=C grep -qi "^fe80:"; then if [ -z "$device_scope" ]; then if [ -z "$device" ]; then ipv6_log $"Given IPv6 default gateway '$address' is link-local, but no scope or gateway device is specified" err $fn return 3 fi fi fi # Check whether the route belongs to the specific given interface if [ -n "$device_check" ]; then # Check whether scope device matches given check device if [ -n "$device_scope" -a "$device_check" != "$device_scope" ]; then # scope device != specific given -> skip return 0 elif [ -n "$device" -a "$device_check" != "$device" ]; then # gateway device != specific given -> skip return 0 fi fi # Set device now, if not given if [ -z "$device" ]; then local device="$device_scope" fi if [ -z "$device" ]; then # Note: this can cause a warning and a not installed route, if given address is not reachable on the link #ipv6_add_route ::/0 $addressgw ipv6_add_route 2000::/3 $addressgw else #ipv6_add_route ::/0 $addressgw $device ipv6_add_route 2000::/3 $addressgw $device fi elif [ -n "$device" ]; then # Check whether the route belongs to the specific given interface if [ -n "$device_check" -a "$device_check" != "$device" ]; then # gateway device != specific given -> skip return 0 fi ipv6_test_route_requires_next_hop $device local result=$? if [ $result = 0 ]; then ipv6_log $"Given IPv6 default device '$device' requires an explicit nexthop" err $fn return 3 elif [ $result != 10 ]; then ipv6_log $"Given IPv6 default device '$device' doesn't exist or isn't up" err $fn return 3 fi #ipv6_add_route ::/0 :: $device ipv6_add_route 2000::/3 :: $device else ipv6_log $"No parameters given to setup a default route" err $fn return 3 fi return 0 } ## Resolve need of explicit next hop for an interface # $1: # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem 10=needs no explicit hop ipv6_test_route_requires_next_hop() { local fn="ipv6_test_route_requires_next_hop" local device=$1 if [ -z "$device" ]; then ipv6_log $"Missing parameter 'device' (arg 1)" err $fn return 1 fi ipv6_test testonly || return 2 ipv6_test_device_status $device if [ $? != 0 ]; then return 3 fi if [ "$device" = "sit0" ]; then return 10 fi if ipv6_exec_ip -o link show $device 2>/dev/null | LC_ALL=C grep -q "POINTOPOINT"; then return 10 fi return 0 } ## Trigger radvd # $1: up|down : device reason for triggering (coming up or going down) # $2: [startstop|restart|reload|SIGHUP] : triger mechanism (default is "SIGHUP") # "startstop" : reason=up -> start, reason=down -> stop # $3: [] : alternative pid file [optional] # return code: 0=ok 1=argument error 2=IPv6 test fails 3=major problem ipv6_trigger_radvd() { local fn="ipv6_trigger_radvd" local reason=$1 local mechanism=$2 local pidfile=$3 if [ -z "$reason" ]; then ipv6_log $"No reason given for sending trigger to radvd" err $fn return 1 fi if [ "$reason" != "up" -a "$reason" != "down" ]; then ipv6_log $"Unsupported reason '$reason' for sending trigger to radvd" err $fn return 1 fi if [ -z "$mechanism" ]; then # Take default local mechanism="SIGHUP" fi if [ -z "$pidfile" ]; then local pidfile="/var/run/radvd/radvd.pid" fi # Print message and select action case $mechanism in 'startstop') case $reason in up) local action="start" ;; down) local action="stop" ;; esac ;; 'reload'|'restart'|'SIGHUP') local action="$mechanism" ;; *) ipv6_log $"Unsupported mechanism '$mechanism' for sending trigger to radvd" err $fn return 3 ;; esac # PID file needed? if [ "$action" = "SIGHUP" ]; then if ! [ -f "$pidfile" ]; then if [ "$reason" = "down" ]; then # be quiet because triggering may have been disabled true else ipv6_log $"Given pidfile '$pidfile' doesn't exist, cannot send trigger to radvd" err $fn fi return 3 fi # Get PID local pid="`cat $pidfile`" if [ -z "$pid" ]; then # pidfile empty - strange ipv6_log $"Pidfile '$pidfile' is empty, cannot send trigger to radvd" err $fn return 3 fi fi # Do action case $action in 'SIGHUP') kill -HUP $pid ;; 'reload'|'restart'|'stop'|'start') if ! /sbin/chkconfig --list radvd >/dev/null 2>&1; then if [ "$reason" = "down" ]; then # be quiet because triggering may have been disabled true else ipv6_log $"radvd not (properly) installed, triggering failed" err $fn fi return 3 else /sbin/service radvd $action >/dev/null 2>&1 fi ;; *) # Normally not reached, "action" is set above to proper value ;; esac return 0 } >934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
// --- BEGIN COPYRIGHT BLOCK ---
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation;
// version 2.1 of the License.
// 
// This library 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
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA 
// 
// Copyright (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---

#ifdef __cplusplus
extern "C"
{
#endif
#include <stdio.h>
//#include <wchar.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "httpd/httpd.h"
#include "prmem.h"
#include "prsystem.h"
#include "plstr.h"
#include "prio.h"
#include "prprf.h"
#include "plhash.h"
#include "pk11func.h"
#include "cert.h"
#include "certt.h"
#include "secerr.h"
#include "tus/tus_db.h"
#include "secder.h"
#include "nss.h"
#include "nssb64.h"

#ifdef __cplusplus
}
#endif

#include "main/Memory.h"
#include "main/ConfigStore.h"
#include "main/RA_Context.h"
#include "channel/Secure_Channel.h"
#include "engine/RA.h"
#include "main/Util.h"
#include "cms/HttpConnection.h"
#include "main/RA_pblock.h"
#include "main/LogFile.h"
#include "main/RollingLogFile.h"
#include "selftests/SelfTest.h"

typedef struct
{
    enum
    {
        PW_NONE = 0,
        PW_FROMFILE = 1,
        PW_PLAINTEXT = 2,
        PW_EXTERNAL = 3
    } source;
    char *data;
} secuPWData;


static ConfigStore *m_cfg = NULL;
static LogFile* m_debug_log = (LogFile *)NULL; 
static LogFile* m_error_log = (LogFile *)NULL; 
static LogFile* m_audit_log = (LogFile *)NULL; 
static LogFile* m_selftest_log = (LogFile *)NULL;

static int tokendbInitialized = 0;
static int tpsConfigured = 0;

RA_Context *RA::m_ctx = NULL;
bool RA::m_pod_enable=false;
int RA::m_pod_curr = 0;
PRLock *RA::m_pod_lock = NULL;
int RA::m_auth_curr;
PRLock *RA::m_verify_lock = NULL;
PRLock *RA::m_auth_lock = NULL;
PRLock *RA::m_debug_log_lock = NULL;
PRLock *RA::m_error_log_lock = NULL;
PRLock *RA::m_selftest_log_lock = NULL;
PRLock *RA::m_config_lock = NULL;
PRMonitor *RA::m_audit_log_monitor = NULL;
bool RA::m_audit_enabled = false;
bool RA::m_audit_signed = false;
SECKEYPrivateKey *RA::m_audit_signing_key = NULL;
NSSUTF8 *RA::m_last_audit_signature = NULL;
SECOidTag RA::m_audit_signAlgTag;
SecurityLevel RA::m_global_security_level;
char *RA::m_signedAuditSelectedEvents = NULL;
char *RA::m_signedAuditSelectableEvents = NULL;
char *RA::m_signedAuditNonSelectableEvents = NULL;

char *RA::m_audit_log_buffer = NULL;
PRThread *RA::m_flush_thread = (PRThread *) NULL;
size_t RA::m_bytes_unflushed =0;
size_t RA::m_buffer_size = 512;
int RA::m_flush_interval = 5;

int RA::m_audit_log_level = (int) LL_PER_SERVER;
int RA::m_debug_log_level = (int) LL_PER_SERVER;
int RA::m_error_log_level = (int) LL_PER_SERVER;
int RA::m_selftest_log_level = (int) LL_PER_SERVER;
int RA::m_caConns_len = 0;
int RA::m_tksConns_len = 0;
int RA::m_drmConns_len = 0;
int RA::m_auth_len = 0;

#define MAX_BODY_LEN 4096

#define MAX_CA_CONNECTIONS 20
#define MAX_TKS_CONNECTIONS 20
#define MAX_DRM_CONNECTIONS 20
#define MAX_AUTH_LIST_MEMBERS 20
HttpConnection* RA::m_caConnection[MAX_CA_CONNECTIONS];
HttpConnection* RA::m_tksConnection[MAX_TKS_CONNECTIONS];
AuthenticationEntry* RA::m_auth_list[MAX_AUTH_LIST_MEMBERS];
HttpConnection* RA::m_drmConnection[MAX_DRM_CONNECTIONS];
int RA::m_num_publishers = 0;
PublisherEntry *RA::publisher_list = NULL;

/* TKS response parameters */
const char *RA::TKS_RESPONSE_STATUS = "status";
const char *RA::TKS_RESPONSE_SessionKey = "sessionKey";
const char *RA::TKS_RESPONSE_EncSessionKey = "encSessionKey";
const char *RA::TKS_RESPONSE_KEK_DesKey = "kek_wrapped_desKey";
const char *RA::TKS_RESPONSE_DRM_Trans_DesKey = "drm_trans_wrapped_desKey";
const char *RA::TKS_RESPONSE_HostCryptogram = "hostCryptogram";

const char *RA::CFG_DEBUG_ENABLE = "logging.debug.enable"; 
const char *RA::CFG_DEBUG_FILENAME = "logging.debug.filename"; 
const char *RA::CFG_DEBUG_LEVEL = "logging.debug.level";
const char *RA::CFG_AUDIT_ENABLE = "logging.audit.enable"; 
const char *RA::CFG_AUDIT_FILENAME = "logging.audit.filename"; 
const char *RA::CFG_SIGNED_AUDIT_FILENAME = "logging.audit.signedAuditFilename"; 
const char *RA::CFG_AUDIT_LEVEL = "logging.audit.level";
const char *RA::CFG_AUDIT_SIGNED = "logging.audit.logSigning";
const char *RA::CFG_AUDIT_SIGNING_CERT_NICK = "logging.audit.signedAuditCertNickname";
const char *RA::CFG_ERROR_ENABLE = "logging.error.enable"; 
const char *RA::CFG_ERROR_FILENAME = "logging.error.filename"; 
const char *RA::CFG_ERROR_LEVEL = "logging.error.level";
const char *RA::CFG_SELFTEST_ENABLE = "selftests.container.logger.enable";
const char *RA::CFG_SELFTEST_FILENAME = "selftests.container.logger.fileName";
const char *RA::CFG_SELFTEST_LEVEL = "selftests.container.logger.level";
const char *RA::CFG_CHANNEL_SEC_LEVEL = "channel.securityLevel"; 
const char *RA::CFG_CHANNEL_ENCRYPTION = "channel.encryption";
const char *RA::CFG_APPLET_CARDMGR_INSTANCE_AID = "applet.aid.cardmgr_instance"; 
const char *RA::CFG_APPLET_NETKEY_INSTANCE_AID = "applet.aid.netkey_instance"; 
const char *RA::CFG_APPLET_NETKEY_FILE_AID = "applet.aid.netkey_file"; 
const char *RA::CFG_APPLET_NETKEY_OLD_INSTANCE_AID = "applet.aid.netkey_old_instance"; 
const char *RA::CFG_APPLET_NETKEY_OLD_FILE_AID = "applet.aid.netkey_old_file"; 
const char *RA::CFG_APPLET_SO_PIN = "applet.so_pin"; 
const char *RA::CFG_APPLET_DELETE_NETKEY_OLD = "applet.delete_old"; 
const char *RA::CFG_AUDIT_SELECTED_EVENTS="logging.audit.selected.events";
const char *RA::CFG_AUDIT_NONSELECTABLE_EVENTS="logging.audit.nonselectable.events";
const char *RA::CFG_AUDIT_SELECTABLE_EVENTS="logging.audit.selectable.events";
const char *RA::CFG_AUDIT_BUFFER_SIZE = "logging.audit.buffer.size";
const char *RA::CFG_AUDIT_FLUSH_INTERVAL = "logging.audit.flush.interval";
const char *RA::CFG_AUDIT_FILE_TYPE = "logging.audit.file.type";
const char *RA::CFG_DEBUG_FILE_TYPE = "logging.debug.file.type";
const char *RA::CFG_ERROR_FILE_TYPE = "logging.error.file.type";
const char *RA::CFG_SELFTEST_FILE_TYPE = "selftests.container.logger.file.type";
const char *RA::CFG_AUDIT_PREFIX = "logging.audit";
const char *RA::CFG_ERROR_PREFIX = "logging.error";
const char *RA::CFG_DEBUG_PREFIX = "logging.debug";
const char *RA::CFG_SELFTEST_PREFIX = "selftests.container.logger";

const char *RA::CFG_AUTHS_ENABLE="auth.enable";

/* default values */
const char *RA::CFG_DEF_CARDMGR_INSTANCE_AID = "A0000000030000"; 
const char *RA::CFG_DEF_NETKEY_INSTANCE_AID = "627601FF000000"; 
const char *RA::CFG_DEF_NETKEY_FILE_AID = "627601FF0000"; 
const char *RA::CFG_DEF_NETKEY_OLD_INSTANCE_AID = "A00000000101"; 
const char *RA::CFG_DEF_NETKEY_OLD_FILE_AID = "A000000001"; 
const char *RA::CFG_DEF_APPLET_SO_PIN = "000000000000"; 

typedef IPublisher* (*makepublisher)();
typedef Authentication* (*makeauthentication)();

extern void BuildHostPortLists(char *host, char *port, char **hostList, 
  char **portList, int len);

#ifdef XP_WIN32
#define TPS_PUBLIC __declspec(dllexport)
#else /* !XP_WIN32 */
#define TPS_PUBLIC
#endif /* !XP_WIN32 */

/**
 * Constructs a Registration Authority object.
 */
RA::RA ()
{ 
}

/**
 * Destructs a Registration Authority object.
 */
RA::~RA ()
{
    do_free(m_signedAuditSelectedEvents);
    do_free(m_signedAuditSelectableEvents);
    do_free(m_signedAuditNonSelectableEvents);

    if (m_cfg != NULL) {
        delete m_cfg;
        m_cfg = NULL;
    }
}

TPS_PUBLIC ConfigStore *RA::GetConfigStore()
{
	return m_cfg;
}

PRLock *RA::GetVerifyLock()
{
  return m_verify_lock;
}

PRLock *RA::GetConfigLock()
{
  return m_config_lock;
}

void RA::do_free(char *p)
{
    if (p != NULL) {
        PR_Free(p);
        p = NULL;
    }
}

int RA::InitializeSignedAudit()
{
    // cfu
    RA::Debug("RA:: InitializeSignedAudit", "begins pid: %d",getpid());
    tpsConfigured = m_cfg->GetConfigAsBool("tps.configured", false);
    // During installation config, don't do this
    if (IsTpsConfigured() && (m_audit_signed == true) && (m_audit_signing_key == NULL)) {
        RA::Debug("RA:: InitializeSignedAudit", "signed audit is on... initializing signing key...");
        // get audit signing cert
        const char *audit_signing_cert_nick = m_cfg->GetConfigAsString(CFG_AUDIT_SIGNING_CERT_NICK, "auditSigningCert cert-pki-tps");
        char certNick[256];
        PR_snprintf((char *)certNick, 256, audit_signing_cert_nick);
        RA::Debug("RA:: InitializeSignedAudit", "got audit signing cert nickname: %s", certNick);

        CERTCertDBHandle *cert_handle = 0;
        cert_handle = CERT_GetDefaultCertDB();
        if (cert_handle == 0) {
            RA::Debug("RA:: InitializeSignedAudit", "did not get cert_handle");
            goto loser;
        } else {
            RA::Debug("RA:: InitializeSignedAudit", "got cert_handle");
        }
        CERTCertificate *cert = NULL; 
        cert = CERT_FindCertByNickname( cert_handle, (char *) certNick );
        if (cert != NULL) { // already configed
            RA::Debug("RA:: InitializeSignedAudit", "got audit signing cert");
            // get private key from cert
            m_audit_signing_key =
            PK11_FindKeyByAnyCert(cert, /*wincx*/ NULL);
            if (m_audit_signing_key == NULL) {
                RA::Debug("RA:: InitializeSignedAudit", "audit signing key not initialized...");
                goto loser;
            } else {
                RA::Debug("RA:: InitializeSignedAudit", "got audit signing key");
            }
            switch(m_audit_signing_key->keyType) {
                case rsaKey:
                  m_audit_signAlgTag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION;
                  break;
                case dsaKey:
                  m_audit_signAlgTag = SEC_OID_ANSIX9_DSA_SIGNATURE_WITH_SHA1_DIGEST;
                  break;
                default:
                  RA::Debug("RA:: InitializeSignedAudit", "unknown key type for audit signing cert");
                  goto loser;
                  break;
            } //switch
            RA::Debug("RA:: InitializeSignedAudit", "audit signing initialized");
//            m_cfg->Add("tps.signedAudit.initialized", "true");
        } else {
            RA::Debug("RA:: InitializeSignedAudit", "no audit signing cert found... still configuring...");
        }

        RA::getLastSignature();
        if (cert != NULL) {
            CERT_DestroyCertificate(cert);
            cert = NULL;
        }
    } // if (m_audit_signed == true)

    // Initialize audit flush thread
    if (IsTpsConfigured() && (m_flush_thread == NULL)) {
        m_flush_thread = PR_CreateThread( PR_USER_THREAD, RunFlushThread, (void *) NULL,
                                 PR_PRIORITY_NORMAL,      /* Priority */
                                 PR_GLOBAL_THREAD,   /* Scope */
                                 PR_JOINABLE_THREAD, /* State */
                                 0   /* Stack Size */);
    }

    return 0;
loser:
    RA::Debug("RA:: InitializeSignedAudit", "audit function startup failed");
    return -1;
//do something
}

void RA::RunFlushThread(void *arg) {
    RA::Debug("RA::FlushThread", "Starting audit flush thread");
    while (m_flush_interval >0) {
        PR_Sleep(PR_SecondsToInterval(m_flush_interval));
        if (m_flush_interval ==0)
            break;
        if (m_bytes_unflushed > 0)
            FlushAuditLogBuffer();
    }
}

/*
 * read off the last sig record of the audit file for computing MAC
 */
void RA::getLastSignature() {
    char line[1024];
    char *sig = NULL;

    RA::Debug("RA:: getLastSignature", "starts");
    if ((m_audit_log != NULL) && (m_audit_log_monitor != NULL)) {
        PR_EnterMonitor(m_audit_log_monitor);
        int removed_return;
        while (1) {
          int n = m_audit_log->ReadLine(line, 1024, &removed_return);
          if (n > 0) {
            sig = strstr(line, "AUDIT_LOG_SIGNING");
            if (sig != NULL) {
                // sig entry found
                m_last_audit_signature = PL_strdup(line);
            }
          } else if (n == 0 && removed_return == 1) {
            continue; /* skip empty line */
          } else {
            break;
          }
        } 
        RA::Debug("RA:: getLastSignature", "ends");
        PR_ExitMonitor(m_audit_log_monitor);
    }

    if (m_last_audit_signature != NULL) {
        RA::Debug("RA:: getLastSignature", "got last sig from file: %s",
            m_last_audit_signature);
    }
}

TPS_PUBLIC LogFile* RA::GetLogFile(const char *log_type)
{
    if (strcmp(log_type, "RollingLogFile") == 0) {
        return new RollingLogFile();
    } else {
        return new LogFile();  // default
    }
}

/**
 * Initializes RA with the given configuration file.
 */
TPS_PUBLIC int RA::Initialize(char *cfg_path, RA_Context *ctx)
{
	int rc = -1;
        int i = 0;
        int status = 0;

    //  Authentication *auth;
	//	int secLevel = 0; // for getting config param
	bool global_enc = false;
	SecurityLevel security_level = SECURE_MSG_MAC_ENC;

	m_verify_lock = PR_NewLock();
	m_debug_log_lock = PR_NewLock();
	m_error_log_lock = PR_NewLock();
	m_selftest_log_lock = PR_NewLock();
	m_config_lock = PR_NewLock();
	m_cfg = ConfigStore::CreateFromConfigFile(cfg_path);
    if( m_cfg == NULL ) {
        rc = -2;
        goto loser;
    }

        m_ctx = ctx;

	if (m_cfg->GetConfigAsBool(CFG_DEBUG_ENABLE, 0)) {
                m_debug_log = GetLogFile(m_cfg->GetConfigAsString(CFG_DEBUG_FILE_TYPE, "LogFile"));
                status = m_debug_log->startup(ctx, CFG_DEBUG_PREFIX, 
                             m_cfg->GetConfigAsString(CFG_DEBUG_FILENAME, "/tmp/debug.log"),
                             false);
                if (status != PR_SUCCESS) 
                    goto loser;

                status = m_debug_log->open();
                if (status != PR_SUCCESS) 
                    goto loser;
	}

        m_error_log_level = m_cfg->GetConfigAsInt(CFG_ERROR_LEVEL, (int) LL_PER_SERVER);
        m_debug_log_level = m_cfg->GetConfigAsInt(CFG_DEBUG_LEVEL, (int) LL_PER_SERVER);
        m_selftest_log_level = m_cfg->GetConfigAsInt(CFG_SELFTEST_LEVEL, (int) LL_PER_SERVER);

	if (m_cfg->GetConfigAsBool(CFG_ERROR_ENABLE, 0)) {
                m_error_log = GetLogFile(m_cfg->GetConfigAsString(CFG_ERROR_FILE_TYPE, "LogFile"));
                status = m_error_log->startup(ctx, CFG_ERROR_PREFIX,
                             m_cfg->GetConfigAsString(CFG_ERROR_FILENAME, "/tmp/error.log"),
                             false);
                if (status != PR_SUCCESS)
                    goto loser;

                status = m_error_log->open();
                if (status != PR_SUCCESS)
                    goto loser;

	}

	if (m_cfg->GetConfigAsBool(CFG_SELFTEST_ENABLE, 0)) {
                m_selftest_log = GetLogFile(m_cfg->GetConfigAsString(CFG_SELFTEST_FILE_TYPE, "LogFile"));
                status = m_selftest_log->startup(ctx, CFG_SELFTEST_PREFIX,
                             m_cfg->GetConfigAsString(CFG_SELFTEST_FILENAME, "/tmp/selftest.log"),
                             false);
                if (status != PR_SUCCESS)
                    goto loser;

                status = m_selftest_log->open();
                if (status != PR_SUCCESS)
                    goto loser;

	}


	RA::Debug("RA:: Initialize", "CS TPS starting...");

    rc = InitializeTokendb(cfg_path);
    if( rc != LDAP_SUCCESS ) {
      RA::Debug("RA:: Initialize", "Token DB initialization failed, server continues");
        ctx->LogError( "RA::Initialize",
                       __LINE__,
                       "The TPS plugin could NOT load the "
                       "Tokendb library!  See specific details in the "
                       "TPS plugin log files." );
        // Since the server hasn't started yet, there is
        // no need to perform a call to RA::Shutdown()!
        //goto loser;
    } else
      RA::Debug("RA:: Initialize", "Token DB initialization succeeded");

    //testTokendb();

    m_pod_enable = m_cfg->GetConfigAsBool("failover.pod.enable", false);
    m_pod_curr = 0;
    m_auth_curr = 0;
    m_pod_lock = PR_NewLock();
    m_auth_lock = PR_NewLock();


    // make encryption not default for operations globally
    // individual security levels can override
    //    secLevel = RA::GetConfigAsInt(RA::CFG_CHANNEL_SEC_LEVEL,
    //				  SECURE_MSG_MAC);

    global_enc = m_cfg->GetConfigAsBool(RA::CFG_CHANNEL_ENCRYPTION, true);
    if (global_enc == true)
	  security_level = SECURE_MSG_MAC_ENC;
	else
	  security_level = SECURE_MSG_MAC;

    RA::SetGlobalSecurityLevel(security_level);

    // Initialize the CA connection pool to be empty
    for (i=0; i<MAX_CA_CONNECTIONS; i++) {
        m_caConnection[i] = NULL;
    }

    // Initialize the TKS connection pool to be empty
    for (i=0; i<MAX_TKS_CONNECTIONS; i++) {
        m_tksConnection[i] = NULL;
    }

    // Initialize the DRM connection pool to be empty
    for (i=0; i<MAX_DRM_CONNECTIONS; i++) {
        m_drmConnection[i] = NULL;
    }

    // Initialize the authentication list to be empty
    for (i=0; i<MAX_AUTH_LIST_MEMBERS; i++) {
        m_auth_list[i] = NULL;
    }

    // even rc != 0, we still go ahead starting up the server.
    rc = InitializeAuthentication();

    //Initialize Publisher Library
    InitializePublishers();

    rc = 1;
loser:
	
    // Log the status of this TPS plugin into the web server's log:
    if( rc != 1 ) {
        ctx->LogError( "RA::Initialize",
                       __LINE__,
                       "The TPS plugin could NOT be "
                       "loaded (rc = %d)!  See specific details in the "
                       "TPS plugin log files.", rc );
    } else {
        ctx->LogInfo( "RA::Initialize",
                      __LINE__,
                      "The TPS plugin was "
                      "successfully loaded!" );
    }
    return rc;
}

int RA::InitializeInChild(RA_Context *ctx, int nSignedAuditInitCount) {

    int rc = -1;
    SECStatus rv;
    int status = 0;
    char configname[256];

    RA::Debug( LL_PER_SERVER, "RA::InitializeInChild", "begins: %d pid: %d ppid: %d",
                nSignedAuditInitCount,getpid(),getppid());
    if (!NSS_IsInitialized()) {

        RA::Debug( LL_PER_SERVER, "RA::InitializeInChild", "Initializing NSS");

        PR_snprintf((char *)configname, 256, "%s/alias", 
            m_cfg->GetConfigAsString("service.instanceDir", NULL));
        rv = NSS_Initialize (configname, "", "", SECMOD_DB, NSS_INIT_READONLY);
        if (rv != SECSuccess) {
            RA::Error( LL_PER_SERVER, "RA::InitializeInChild",
                "NSS not initialized successfully");
            ctx->InitializationError( "RA::InitializeHttpConnections",
                                       __LINE__ );
            goto loser;
        }
    } else {
        RA::Debug( LL_PER_SERVER, "RA::InitializeInChild", "NSS already initialized");
    }
    //initialize CA Connections
    status = InitializeHttpConnections("ca", &m_caConns_len,
         m_caConnection, ctx);
    if (status != 0) {
        RA::Debug( LL_PER_SERVER, "RA::InitializeInChild", 
            "Failed to initialize CA Connection, rc=%i", 
            (int)status);
        goto loser;
    } 
    // initialize TKS connections
    status = InitializeHttpConnections("tks", &m_tksConns_len,
        m_tksConnection, ctx);
    if (status != 0) {
        RA::Debug( LL_PER_SERVER, "RA::InitializeInChild", 
            "Failed to initialize TKS Connection, rc=%i", 
            (int)status);
        goto loser;
    } 
    // initialize DRM connections
    status = InitializeHttpConnections("drm", &m_drmConns_len,
        m_drmConnection, ctx);
    if (status != 0) {
        RA::Debug( LL_PER_SERVER, "RA::InitializeInChild", 
            "Failed to initialize DRM Connection, rc=%i", 
            (int)status);
        goto loser;
    } 

    // open audit log
    m_audit_log_monitor = PR_NewMonitor();
    m_audit_log_level = m_cfg->GetConfigAsInt(CFG_AUDIT_LEVEL, (int) LL_PER_SERVER);

    // get events for audit signing
    m_signedAuditSelectedEvents = PL_strdup(m_cfg->GetConfigAsString(
                                                CFG_AUDIT_SELECTED_EVENTS, ""));
    m_signedAuditSelectableEvents = PL_strdup(m_cfg->GetConfigAsString(
                                                CFG_AUDIT_SELECTABLE_EVENTS, ""));
    m_signedAuditNonSelectableEvents= PL_strdup(m_cfg->GetConfigAsString(
                                                CFG_AUDIT_NONSELECTABLE_EVENTS, ""));
    m_audit_enabled = m_cfg->GetConfigAsBool(CFG_AUDIT_ENABLE, false);
    m_buffer_size = m_cfg->GetConfigAsInt(CFG_AUDIT_BUFFER_SIZE, 512);
    m_flush_interval = m_cfg->GetConfigAsInt(CFG_AUDIT_FLUSH_INTERVAL, 5);

    if (m_audit_enabled  && (nSignedAuditInitCount > 1 )) {
        // is audit logSigning on?
        m_audit_signed = m_cfg->GetConfigAsBool(CFG_AUDIT_SIGNED, false);
        RA::Debug("RA:: InitializeInChild", "Audit signing is %s",
                   m_audit_signed? "true":"false");

        m_audit_log = GetLogFile(m_cfg->GetConfigAsString(CFG_AUDIT_FILE_TYPE, "LogFile"));
        status = m_audit_log->startup(ctx, CFG_AUDIT_PREFIX,
                                      m_cfg->GetConfigAsString((m_audit_signed)? 
                                      CFG_SIGNED_AUDIT_FILENAME:CFG_AUDIT_FILENAME,
                                      "/tmp/audit.log"),
                                      m_audit_signed);
        if (status != PR_SUCCESS) 
            goto loser;

        status = m_audit_log->open();
             
        if (status != PR_SUCCESS)
            goto loser;

        m_audit_log_buffer = (char *) PR_Malloc(m_buffer_size);
        if (m_audit_log_buffer == NULL) {
            RA::Debug("RA:: Initialize", "Unable to allocate memory for audit log buffer ..");
            goto loser;
        }
        PR_snprintf((char *) m_audit_log_buffer, m_buffer_size, "");
        m_bytes_unflushed = 0;
    }

    RA::Debug("RA::InitializeInChild", "nSignedAuditInitCount=%i",
             nSignedAuditInitCount); 
    if (NSS_IsInitialized() && (nSignedAuditInitCount >1)) {
        status = InitializeSignedAudit();
        if (status == 0) {
            RA::Audit(EV_AUDIT_LOG_STARTUP, AUDIT_MSG_FORMAT, "System", "Success",
              "audit function startup");
        }
 
        // As per CC requirements, we want to flush the audit log immediately
        // to ensure that the audit log is not full
        FlushAuditLogBuffer();

        rc = SelfTest::runStartUpSelfTests(); // run general self tests
        if (rc != 0) goto loser;
    }

    if (m_debug_log != NULL) {
        m_debug_log->child_init();
    }
     
    if (m_error_log != NULL) {
        m_error_log->child_init();
    }

    if (m_selftest_log != NULL) {
        m_selftest_log->child_init();
    }

    if (m_audit_log != NULL) {
        m_audit_log->child_init();
    }

    rc =1;
loser: 
    // Log the status of this TPS plugin into the web server's log:
    if( rc != 1 ) {
        ctx->LogError( "RA::InitializeInChild",
                       __LINE__,
                       "The TPS plugin could NOT be "
                       "initialized (rc = %d)!  See specific details in the "
                       "TPS plugin log files.", rc );
    } else {
        ctx->LogInfo( "RA::InitializeInChild",
                      __LINE__,
                      "The TPS plugin was "
                      "successfully initialized!" );
    }

    return rc;
}

int RA::testTokendb() {
    // try to see if we can talk to the database
    int st = 0;
    LDAPMessage  *ldapResult = NULL;
    const char * filter = "(cn=0000000000080000*)";

    if ((st = find_tus_db_entries(filter, 0, &ldapResult)) != LDAP_SUCCESS) {
        RA::Debug("RA::testing", "response from token DB failed");
    } else {
        RA::Debug("RA::testing", "response from token DB succeeded");
    }
    if (ldapResult != NULL) {
        ldap_msgfree(ldapResult);
    }

    return st;
}

/*
 * returns true if item is a value in the comma separated list
 * used by audit logging functions and profile selection functions
 */
TPS_PUBLIC bool RA::match_comma_list(const char* item, char *list)
{
    char *pList = PL_strdup(list);
    char *sresult = NULL;
    char *lasts = NULL;

    sresult = PL_strtok_r(pList, ",", &lasts);
    while (sresult != NULL) {
        if (PL_strcmp(sresult, item) == 0) {
            if (pList != NULL) {
                PR_Free(pList);
                pList = NULL;
            }
            return true;
        }
        sresult = PL_strtok_r(NULL, ",", &lasts);
    }
    if (pList != NULL) {
        PR_Free(pList);
        pList = NULL;
    }
    return false;
}

/*
 * return comma separated list with all instances of item removed
 * must be freed by caller
 */
TPS_PUBLIC char* RA::remove_from_comma_list(const char*item, char *list)
{
    int len = PL_strlen(list);
    char *pList=PL_strdup(list);
    char *ret = (char *) PR_Malloc(len);
    char  *sresult = NULL;
    char *lasts = NULL;
    

    PR_snprintf(ret, len, "");
    sresult = PL_strtok_r(pList, ",", &lasts);
    while (sresult != NULL) {
        if (PL_strcmp(sresult, item) != 0) {
            PR_snprintf(ret, len, "%s%s%s", ret, (PL_strlen(ret)>0)? "," : "", sresult);
        }
        sresult = PL_strtok_r(NULL, ",",&lasts);
    }
    if (pList != NULL) {
        PR_Free(pList);
        pList = NULL;
    }
    return ret;
}


/*
 * returns true if an audit event is valid, false if not
 */
bool RA::IsValidEvent(const char *auditEvent)
{
    return match_comma_list(auditEvent, m_signedAuditNonSelectableEvents) ||
           match_comma_list(auditEvent, m_signedAuditSelectableEvents);
}

/*
 * returns true if an audit event is selected, false if not
 */
bool RA::IsAuditEventSelected(const char* auditEvent)
{
  return match_comma_list(auditEvent, m_signedAuditNonSelectableEvents) || 
         match_comma_list(auditEvent, m_signedAuditSelectedEvents);
}

int RA::IsTokendbInitialized()
{
  return tokendbInitialized;
}

int RA::IsTpsConfigured()
{
  return tpsConfigured;
}

TPS_PUBLIC int RA::Child_Shutdown()
{
    RA::Debug("RA::Child_Shutdown", "starts");
    // clean up connections
    if (m_caConnection != NULL) {
        for (int i=0; i<m_caConns_len; i++) {
            if( m_caConnection[i] != NULL ) {
                delete m_caConnection[i];
                m_caConnection[i] = NULL;
            }
        }
    }

    if (m_tksConnection != NULL) {
        for (int i=0; i<m_tksConns_len; i++) {
            if( m_tksConnection[i] != NULL ) {
                delete m_tksConnection[i];
                m_tksConnection[i] = NULL;
            }
        }
    }
    if (m_drmConnection != NULL) {
        for (int i=0; i<m_drmConns_len; i++) {
            if( m_drmConnection[i] != NULL ) {
                delete m_drmConnection[i];
                m_drmConnection[i] = NULL;
            }
        }
    }

    /* log audit log shutdown */
    PR_EnterMonitor(m_audit_log_monitor);
    if( (m_audit_log != NULL)  && (m_audit_log->isOpen())) {
        if (m_audit_log_buffer != NULL) {
            m_flush_interval = 0;  // terminate flush thread 
            PR_Interrupt(m_flush_thread);
            if (m_flush_thread != NULL) {
                PR_JoinThread(m_flush_thread);
            }
        }
        if ((m_audit_signed) && (m_audit_signing_key != NULL)) {
            RA::Audit(EV_AUDIT_LOG_SHUTDOWN, AUDIT_MSG_FORMAT, "System", "Success",
                "audit function shutdown");
        }
    
        if (m_bytes_unflushed > 0) {
                FlushAuditLogBuffer();
        }
    }

    if (m_audit_log != NULL) {
        m_audit_log->shutdown();
        delete m_audit_log;
        m_audit_log = NULL;
    }

    if (m_audit_log_buffer) {
        PR_Free(m_audit_log_buffer);
        m_audit_log_buffer = NULL;
    }
   
    PR_ExitMonitor(m_audit_log_monitor);

    if( m_audit_log_monitor != NULL ) {
        PR_DestroyMonitor( m_audit_log_monitor );
        m_audit_log_monitor = NULL;
    }

    return 1;
}


/**
 * Shutdown RA.
 */
TPS_PUBLIC int RA::Shutdown()
{
    RA::Debug("RA::Shutdown", "starts");

    tus_db_end();
    tus_db_cleanup();

    if( m_pod_lock != NULL ) {
        PR_DestroyLock( m_pod_lock );
        m_pod_lock = NULL;
    }

    if( m_auth_lock != NULL ) {
        PR_DestroyLock( m_auth_lock );
        m_auth_lock = NULL;
    }

    /* close debug file if opened */
    if ( m_debug_log != NULL ) {
        m_debug_log->shutdown();
        delete m_debug_log;
        m_debug_log = NULL;
    }

    /* close error file if opened */
    if( m_error_log != NULL ) {
        m_error_log->shutdown();
        delete m_error_log;
        m_error_log = NULL;
    }

    /* close self test file if opened */
    if( m_selftest_log != NULL ) {
        m_selftest_log->shutdown();
        delete m_selftest_log;
        m_selftest_log = NULL;
    }

    if( m_verify_lock != NULL ) {
        PR_DestroyLock( m_verify_lock );
        m_verify_lock = NULL;
    }

    if( m_debug_log_lock != NULL ) {
        PR_DestroyLock( m_debug_log_lock );
        m_debug_log_lock = NULL;
    }

    if( m_error_log_lock != NULL ) {
        PR_DestroyLock( m_error_log_lock );
        m_error_log_lock = NULL;
    }

    if( m_selftest_log_lock != NULL ) {
        PR_DestroyLock( m_selftest_log_lock );
        m_selftest_log_lock = NULL;
    }

    if( m_config_lock != NULL ) {
        PR_DestroyLock( m_config_lock );
        m_config_lock = NULL;
    }

    if (m_auth_list != NULL) {
        for (int i=0; i<m_auth_len; i++) {
            if( m_auth_list[i] != NULL ) {
                delete m_auth_list[i];
                m_auth_list[i] = NULL;
            }
        }
    }

    /* destroy configuration hashtable */
    if( m_cfg != NULL ) {
        delete m_cfg;
        m_cfg = NULL;
    }

    CleanupPublishers();

    return 1;
}

HttpConnection *RA::GetTKSConn(const char *id) {
    HttpConnection *tksconn = NULL;
    for (int i=0; i<m_tksConns_len; i++) {
        if (strcmp(m_tksConnection[i]->GetId(), id) == 0) {
            tksconn = m_tksConnection[i];   
            break;
        }
    }
    return tksconn; 
}

HttpConnection *RA::GetDRMConn(const char *id) {
    HttpConnection *drmconn = NULL;
    for (int i=0; i<m_drmConns_len; i++) {
        if (strcmp(m_drmConnection[i]->GetId(), id) == 0) {
            drmconn = m_drmConnection[i];   
            break;
        }
    }
    return drmconn; 
}

void RA::ReturnTKSConn(HttpConnection *conn) {
    // do nothing for now
}

void RA::ReturnDRMConn(HttpConnection *conn) {
    // do nothing for now
}

HttpConnection *RA::GetCAConn(const char *id) {
    HttpConnection *caconn = NULL;
    if (id == NULL)
      return NULL;
    for (int i=0; i<m_caConns_len; i++) {
        if (strcmp(m_caConnection[i]->GetId(), id) == 0) {
            caconn = m_caConnection[i];
            break;
        }
    }
    return caconn;
}

AuthenticationEntry *RA::GetAuth(const char *id) {
    AuthenticationEntry *authEntry = NULL;
    for (int i=0; i<m_auth_len; i++) {
        authEntry = m_auth_list[i];
        if (strcmp(authEntry->GetId(), id) == 0)
            return authEntry;
    }
    return NULL;
}

void RA::ReturnCAConn(HttpConnection *conn) {
    // do nothing for now
}

TPS_PUBLIC PRLock *RA::GetAuthLock() {
    return m_auth_lock;
}

int RA::GetPodIndex() {
    PR_Lock(m_pod_lock);
    int index = m_pod_curr;
    PR_Unlock(m_pod_lock);
    return index;
}

void RA::SetPodIndex(int index) {
    PR_Lock(m_pod_lock);
    m_pod_curr = index;
    PR_Unlock(m_pod_lock);
}

void RA::SetCurrentIndex(HttpConnection *&conn, int index) {
    PRLock *lock = conn->GetLock();
    PR_Lock(lock);
    conn->SetCurrentIndex(index);
    PR_Unlock(lock);
}

int RA::GetCurrentIndex(HttpConnection *conn) {
    PRLock *lock = conn->GetLock();
    PR_Lock(lock);
    int index = conn->GetCurrentIndex();
    PR_Unlock(lock);
    return index;
}

TPS_PUBLIC int RA::GetAuthCurrentIndex() {
    PR_Lock(m_auth_lock);
    int index = m_auth_curr;
    PR_Unlock(m_auth_lock);
    return index;
}

void RA::SetAuthCurrentIndex(int index) {
    PR_Lock(m_auth_lock);
    m_auth_curr = index;
    PR_Unlock(m_auth_lock);
}

TPS_PUBLIC void RA::IncrementAuthCurrentIndex(int len) {
    PR_Lock(m_auth_lock);
    if ((++m_auth_curr) >= len)
        m_auth_curr = 0;
    PR_Unlock(m_auth_lock);
}

void RA::SetGlobalSecurityLevel(SecurityLevel sl) {
    m_global_security_level = sl;
    RA::Debug(" RA::SetGlobalSecurityLevel", "global security level set to %d", (int) sl);

}

SecurityLevel RA::GetGlobalSecurityLevel() {
    return m_global_security_level;
}


/*
 * recovers user encryption key that was previously archived.
 * It expects DRM to search its archival db by cert.
 *
 * input:
 * @param cuid (cuid of the recovering key's token)
 * @param userid (uid of the recovering key owner
 * @param desKey_s (came from TKS - session key wrapped with DRM transport
 * @param cert (base64 encoded cert of the recovering key)
 * @param connId (drm connectoin id)
 *
 * output:
 * @param publickey_s public key provided by DRM
 * @param wrappedPrivateKey_s encrypted private key provided by DRM
 * @param ivParam_s returned intialization vector
 */
void RA::RecoverKey(RA_Session *session, const char* cuid,
                    const char *userid, char* desKey_s,
                    char *b64cert, char **publicKey_s,
                    char **wrappedPrivateKey_s, const char *connId,  char **ivParam_s)
{
    int status;
    PSHttpResponse *response = NULL;
    HttpConnection *drmConn = NULL;
    char body[MAX_BODY_LEN];
    char configname[256];
    char * cert_s;
    int drm_curr = 0;
    long s;
    char * content = NULL;
    char ** hostport= NULL;
    const char* servletID = NULL;
    char *wrappedDESKey_s= NULL;
    Buffer *decodeKey = NULL;
    ConnectionInfo *connInfo = NULL;
    RA_pblock *ra_pb = NULL;
    int currRetries = 0;
    char *p = NULL;

    RA::Debug(" RA:: RecoverKey", "in RecoverKey");
    if (cuid == NULL) {
      RA::Debug(" RA:: RecoverKey", "in RecoverKey, cuid NULL");
      goto loser;
    }
    if (userid == NULL) {
      RA::Debug(" RA:: RecoverKey", "in RecoverKey, userid NULL");
      goto loser;
    }
    if (b64cert == NULL) {
      RA::Debug(" RA:: RecoverKey", "in RecoverKey, b64cert NULL");
      goto loser;
    }
    if (desKey_s == NULL) {
      RA::Debug(" RA:: RecoverKey", "in RecoverKey, desKey_s NULL");
      goto loser;
    }
    if (connId == NULL) {
      RA::Debug(" RA:: RecoverKey", "in RecoverKey, connId NULL");
      goto loser;
    }
    RA::Debug(" RA:: RecoverKey", "in RecoverKey, desKey_s=%s, connId=%s",desKey_s,  connId);

    cert_s = Util::URLEncode(b64cert);
    drmConn = RA::GetDRMConn(connId);
    if (drmConn == NULL) {
        RA::Debug(" RA:: RecoverKey", "in RecoverKey, failed getting drmconn");
	goto loser;
    }
    RA::Debug(" RA:: RecoverKey", "in RecoverKey, got drmconn");
    connInfo = drmConn->GetFailoverList();
    RA::Debug(" RA:: RecoverKey", "in RecoverKey, got drm failover");
    decodeKey = Util::URLDecode(desKey_s);
    RA::Debug(" RA:: RecoverKey", "in RecoverKey,url decoded des");
    wrappedDESKey_s = Util::SpecialURLEncode(*decodeKey);

    RA::Debug(" RA:: RecoverKey", "in RecoverKey, wrappedDESKey_s=%s", wrappedDESKey_s);

    PR_snprintf((char *)body, MAX_BODY_LEN, 
		"CUID=%s&userid=%s&drm_trans_desKey=%s&cert=%s",cuid, userid, wrappedDESKey_s, cert_s);
    RA::Debug(" RA:: RecoverKey", "in RecoverKey, body=%s", body);
        PR_snprintf((char *)configname, 256, "conn.%s.servlet.TokenKeyRecovery", connId);
        servletID = GetConfigStore()->GetConfigAsString(configname);
    RA::Debug(" RA:: RecoverKey", "in RecoverKey, configname=%s", configname);

    drm_curr = RA::GetCurrentIndex(drmConn);
    response = drmConn->getResponse(drm_curr, servletID, body);
    hostport = connInfo->GetHostPortList();
    if (response == NULL) {
        RA::Debug(LL_PER_PDU, "The recoverKey response from DRM ", 
          "at %s is NULL.", hostport[drm_curr]);
 
      //goto loser;
    } else {
        RA::Debug(LL_PER_PDU, "The recoverKey response from DRM ", 
          "at %s is not NULL.", hostport[drm_curr]);
    }

    while (response == NULL) {
        RA::Failover(drmConn, connInfo->GetHostPortListLen());
    
        drm_curr = RA::GetCurrentIndex(drmConn);
        RA::Debug(LL_PER_PDU, "RA is reconnecting to DRM ", 
          "at %s for recoverKey.", hostport[drm_curr]);
    
        if (++currRetries >= drmConn->GetNumOfRetries()) {
            RA::Debug("Used up all the retries in recoverKey. Response is NULL","");
            RA::Error("RA::RecoverKey","Failed connecting to DRM after %d retries", currRetries);

            goto loser;
        }
        response = drmConn->getResponse(drm_curr, servletID, body);
    }

    RA::Debug(" RA:: RecoverKey", "in RecoverKey - got response");
    // XXXskip handling fallback host for prototype

    content = response->getContent();
    p = strstr(content, "status=");
    content = p; //skip the HTTP header

    s = response->getStatus();

    if ((content != NULL) && (s == 200)) {
      RA::Debug("RA::RecoverKey", "response from DRM status ok");

      Buffer* status_b;
      char* status_s;

      ra_pb = ( RA_pblock * ) session->create_pblock(content);
      if (ra_pb == NULL)
	goto loser;

      status_b = ra_pb->find_val("status");
      if (status_b == NULL) {
	status = 4;
	goto loser;
      }
      else {
	status_s = status_b->string();
	status = atoi(status_s);
        if (status_s != NULL) {
            PR_Free(status_s);
        }
      }


      char * tmp = NULL;
      tmp = ra_pb->find_val_s("public_key");
      if ((tmp == NULL) || (strcmp(tmp,"")==0)) {
	RA::Error(LL_PER_PDU, "RecoverKey"," got no public key");
	goto loser;
      } else {
	RA::Debug(LL_PER_PDU, "RecoverKey", "got public key =%s", tmp);
	*publicKey_s  = PL_strdup(tmp);
      }

      tmp = NULL;
      tmp = ra_pb->find_val_s("wrapped_priv_key");
      if ((tmp == NULL) || (strcmp(tmp,"")==0)) {
	RA::Error(LL_PER_PDU, "RecoverKey"," got no wrapped private key");
	//XXX	      goto loser;
      } else {
	RA::Debug(LL_PER_PDU, "RecoverKey", "got wrappedprivate key =%s", tmp);
	*wrappedPrivateKey_s  = PL_strdup(tmp);
      }

      tmp = ra_pb->find_val_s("iv_param");
      if ((tmp == NULL) || (strcmp(tmp,"")==0)) {
          RA::Error(LL_PER_PDU, "RecoverKey",
              "did not get iv_param for recovered  key in DRM response");
      } else {
          RA::Debug(LL_PER_PDU, "ServerSideKeyGen", "got iv_param for recovered key =%s", tmp);
          *ivParam_s  = PL_strdup(tmp);
      }

    } else {// if content is NULL or status not 200
      if (content != NULL)
	RA::Debug("RA::RecoverKey", "response from DRM error status %ld", s);
      else
	RA::Debug("RA::RecoverKey", "response from DRM no content");
    }
 loser:
    if (desKey_s != NULL)
      PR_Free(desKey_s);

    if (decodeKey != NULL)
      PR_Free(decodeKey);

    if (wrappedDESKey_s != NULL)
      PR_Free(wrappedDESKey_s);

    if (drmConn != NULL)
      RA::ReturnDRMConn(drmConn);

    if (response != NULL) {
      if (content != NULL)
	response->freeContent();
      delete response;
    }

    if (ra_pb != NULL) {
      delete ra_pb;
    }

}



/*
 * input:
 * @param desKey_s provided for drm to wrap user private
 * @param publicKey_s returned for key injection back to token
 *
 * Output:
 * @param publicKey_s public key provided by DRM
 * @param wrappedPrivateKey_s encrypted private key provided by DRM
 */
void RA::ServerSideKeyGen(RA_Session *session, const char* cuid,
                          const char *userid, char* desKey_s,
	                      char **publicKey_s,
                          char **wrappedPrivateKey_s,
                          char **ivParam_s, const char *connId,
                          bool archive, int keysize)
{

	const char *FN="RA::ServerSideKeyGen";
    int status;
    PSHttpResponse *response = NULL;
    HttpConnection *drmConn = NULL;
    char body[MAX_BODY_LEN];
    char configname[256];

    long s;
    char * content = NULL;
    char ** hostport = NULL;
    const char* servletID = NULL;
    char *wrappedDESKey_s = NULL;
    Buffer *decodeKey = NULL;
    ConnectionInfo *connInfo = NULL;
    RA_pblock *ra_pb = NULL;
    int drm_curr = 0;
    int currRetries = 0;
    char *p = NULL;

    if ((cuid == NULL) || (strcmp(cuid,"")==0)) {
      RA::Debug( LL_PER_CONNECTION, FN,
			"error: passed invalid cuid");
      goto loser;
    }
    if ((userid == NULL) || (strcmp(userid,"")==0)) {
      RA::Debug(LL_PER_CONNECTION, FN,
			"error: passed invalid userid");
      goto loser;
    }
    if ((desKey_s == NULL) || (strcmp(desKey_s,"")==0)) {
      RA::Debug(LL_PER_CONNECTION, FN, 
			 "error: passed invalid desKey_s");
      goto loser;
    }
    if ((connId == NULL) ||(strcmp(connId,"")==0)) {
      RA::Debug(LL_PER_CONNECTION, FN,
			 "error: passed invalid connId");
      goto loser;
    }
    RA::Debug(LL_PER_CONNECTION, FN,
			 "desKey_s=%s, connId=%s",desKey_s,  connId);
    drmConn = RA::GetDRMConn(connId);

    if (drmConn == NULL) {
        RA::Debug(LL_PER_CONNECTION, FN,
			"drmconn is null");
		goto loser;
    }
    RA::Debug(LL_PER_CONNECTION, FN,
			"found DRM connection info");
    connInfo = drmConn->GetFailoverList();
    RA::Debug(LL_PER_CONNECTION, FN,
		 "got DRM failover list");

    decodeKey = Util::URLDecode(desKey_s);
    if (decodeKey == NULL) {
      RA::Debug(LL_PER_CONNECTION, FN,
		"url-decoding of des key-transport-key failed");
      goto loser;
    }
    RA::Debug(LL_PER_CONNECTION, FN,
		"successfully url-decoded key-transport-key");
    wrappedDESKey_s = Util::SpecialURLEncode(*decodeKey);

    RA::Debug(LL_PER_CONNECTION, FN,
		"wrappedDESKey_s=%s", wrappedDESKey_s);

    PR_snprintf((char *)body, MAX_BODY_LEN, 
		"archive=%s&CUID=%s&userid=%s&keysize=%d&drm_trans_desKey=%s",archive?"true":"false",cuid, userid, keysize, wrappedDESKey_s);
    RA::Debug(LL_PER_CONNECTION, FN, 
		"sending to DRM: query=%s", body);

    PR_snprintf((char *)configname, 256, "conn.%s.servlet.GenerateKeyPair", connId);
    servletID = GetConfigStore()->GetConfigAsString(configname);
    RA::Debug(LL_PER_CONNECTION, FN,
		 "finding DRM servlet info, configname=%s", configname);

    drm_curr = RA::GetCurrentIndex(drmConn);
    response = drmConn->getResponse(drm_curr, servletID, body);
    hostport = connInfo->GetHostPortList();
    if (response == NULL) {
        RA::Error(LL_PER_CONNECTION, FN, 
			"failed to get response from DRM at %s", 
			hostport[drm_curr]);
        RA::Debug(LL_PER_CONNECTION, FN, 
			"failed to get response from DRM at %s", 
			hostport[drm_curr]);
    } else { 
        RA::Debug(LL_PER_CONNECTION, FN,
			"response from DRM (%s) is not NULL.",
			 hostport[drm_curr]);
    }

    while (response == NULL) {
        RA::Failover(drmConn, connInfo->GetHostPortListLen());

        drm_curr = RA::GetCurrentIndex(drmConn);
        RA::Debug(LL_PER_CONNECTION, FN,
			"RA is failing over to DRM at %s", hostport[drm_curr]);

        if (++currRetries >= drmConn->GetNumOfRetries()) {
            RA::Debug(LL_PER_CONNECTION, FN,
				"Failed to get response from all DRMs in conn group '%s'"
				" after %d retries", connId, currRetries);
            RA::Error(LL_PER_CONNECTION, FN,
				"Failed to get response from all DRMs in conn group '%s'"
				" after %d retries", connId, currRetries);


            goto loser;
        }
        response = drmConn->getResponse(drm_curr, servletID, body);
    }

    RA::Debug(" RA:: ServerSideKeyGen", "in ServerSideKeyGen - got response");
    // XXX skip handling fallback host for prototype

    content = response->getContent();
    p = strstr(content, "status=");
    content = p; //skip the HTTP header
    s = response->getStatus();

    if ((content != NULL) && (s == 200)) {
	  RA::Debug("RA::ServerSideKeyGen", "response from DRM status ok");

	  Buffer* status_b;
	  char* status_s;

	  ra_pb = ( RA_pblock * ) session->create_pblock(content);
	  if (ra_pb == NULL)
	    goto loser;

	  status_b = ra_pb->find_val("status");
	  if (status_b == NULL) {
	    status = 4;
	    goto loser;
	  } else {
	    status_s = status_b->string();
	    status = atoi(status_s);
            if (status_s != NULL) {
                PR_Free(status_s);
            }
	  }

	  char * tmp = NULL;
	  tmp = ra_pb->find_val_s("public_key");
	  if (tmp == NULL) {
	    RA::Error(LL_PER_CONNECTION, FN,
			"Did not get public key in DRM response");
	  } else {
	    RA::Debug(LL_PER_PDU, "ServerSideKeyGen", "got public key =%s", tmp);
	    *publicKey_s  = PL_strdup(tmp);
	  }

	  tmp = NULL;
	  tmp = ra_pb->find_val_s("wrapped_priv_key");
	  if ((tmp == NULL) || (strcmp(tmp,"")==0)) {
	    RA::Error(LL_PER_CONNECTION, FN,
				"did not get wrapped private key in DRM response");
	  } else {
	    RA::Debug(LL_PER_CONNECTION, FN,
			"got wrappedprivate key =%s", tmp);
	    *wrappedPrivateKey_s  = PL_strdup(tmp);
	  }

	  tmp = ra_pb->find_val_s("iv_param");
	  if ((tmp == NULL) || (strcmp(tmp,"")==0)) {
	    RA::Error(LL_PER_CONNECTION, FN,
				"did not get iv_param for private key in DRM response");
	  } else {
	    RA::Debug(LL_PER_PDU, "ServerSideKeyGen", "got iv_param for private key =%s", tmp);
	    *ivParam_s  = PL_strdup(tmp);
	  }

    } else {// if content is NULL or status not 200
	  if (content != NULL)
	    RA::Debug("RA::ServerSideKeyGen", "response from DRM error status %ld", s);
	  else
	    RA::Debug("RA::ServerSideKeyGen", "response from DRM no content");
    }

 loser:
    if (desKey_s != NULL)
      PR_Free(desKey_s);

    if (decodeKey != NULL) {
      delete decodeKey;
    }

    if (wrappedDESKey_s != NULL)
      PR_Free(wrappedDESKey_s);

    if (drmConn != NULL)
      RA::ReturnDRMConn(drmConn);

    if (response != NULL) {
      if (content != NULL)
	response->freeContent();
      delete response;
    }

    if (ra_pb != NULL) {
      delete ra_pb;
    }

}


#define DES2_WORKAROUND
#define MAX_BODY_LEN 4096

PK11SymKey *RA::ComputeSessionKey(RA_Session *session,
                                  Buffer &CUID,
                                  Buffer &keyInfo,
                                  Buffer &card_challenge,
                                  Buffer &host_challenge,
                                  Buffer **host_cryptogram,
                                  Buffer &card_cryptogram,
                                  PK11SymKey **encSymKey,
                                  char** drm_desKey_s,
                                  char** kek_desKey_s,
                                  char** keycheck_s,
                                  const char *connId)
{
    PK11SymKey *symKey = NULL;
    PK11SymKey *symKey24 = NULL;
    PK11SymKey *encSymKey24 = NULL;
    PK11SymKey *transportKey = NULL;
    PK11SymKey *encSymKey16 = NULL;
    char body[MAX_BODY_LEN];
    char configname[256];
    char * cardc = NULL;
    char * hostc = NULL;
    char * cardCrypto = NULL;
    char * cuid = NULL;
    char * keyinfo =  NULL;
    PSHttpResponse *response = NULL;
    HttpConnection *tksConn = NULL;
    RA_pblock *ra_pb = NULL;
    SECItem *SecParam = PK11_ParamFromIV(CKM_DES3_ECB, NULL);
    char* transportKeyName = NULL;

    RA::Debug(LL_PER_PDU, "Start ComputeSessionKey", "");
    tksConn = RA::GetTKSConn(connId);
    if (tksConn == NULL) {
        RA::Error(LL_PER_PDU, "RA::ComputeSessionKey", "Failed to get TKSConnection %s", connId);
        return NULL;
    } else {
        int currRetries = 0;
        ConnectionInfo *connInfo = tksConn->GetFailoverList();

	PR_snprintf((char *) configname, 256, "conn.%s.keySet", connId);
	const char *keySet = RA::GetConfigStore()->GetConfigAsString(configname, "defKeySet");
	// is serversideKeygen on?
	PR_snprintf((char *) configname, 256, "conn.%s.serverKeygen", connId);
	bool serverKeygen = RA::GetConfigStore()->GetConfigAsBool(configname, false);
	if (serverKeygen)
	  RA::Debug(LL_PER_PDU, "RA::ComputeSessionKey", "serverKeygen for %s is on", connId);
	else
	  RA::Debug(LL_PER_PDU, "RA::ComputeSessionKey", "serverKeygen for %s is off", connId);

        cardc = Util::SpecialURLEncode(card_challenge);
        hostc = Util::SpecialURLEncode(host_challenge);
        cardCrypto = Util::SpecialURLEncode(card_cryptogram);
        cuid = Util::SpecialURLEncode(CUID);
        keyinfo = Util::SpecialURLEncode(keyInfo);

        if ((cardc == NULL) || (hostc == NULL) || (cardCrypto == NULL) ||
          (cuid == NULL) || (keyinfo == NULL))
	    goto loser;

        PR_snprintf((char *)body, MAX_BODY_LEN, 
          "serversideKeygen=%s&CUID=%s&card_challenge=%s&host_challenge=%s&KeyInfo=%s&card_cryptogram=%s&keySet=%s", serverKeygen? "true":"false", cuid, 
          cardc, hostc, keyinfo, cardCrypto, keySet);

        PR_snprintf((char *)configname, 256, "conn.%s.servlet.computeSessionKey", connId);
        const char *servletID = GetConfigStore()->GetConfigAsString(configname);
        int tks_curr = RA::GetCurrentIndex(tksConn);
        response = tksConn->getResponse(tks_curr, servletID, body);
        char **hostport = connInfo->GetHostPortList();
        if (response == NULL)
            RA::Debug(LL_PER_PDU, "The computeSessionKey response from TKS ", 
              "at %s is NULL.", hostport[tks_curr]);
        else 
            RA::Debug(LL_PER_PDU, "The computeSessionKey response from TKS ", 
              "at %s is not NULL.", hostport[tks_curr]);

        while (response == NULL) {
            RA::Failover(tksConn, connInfo->GetHostPortListLen());

            tks_curr = RA::GetCurrentIndex(tksConn);
            RA::Debug(LL_PER_PDU, "RA is reconnecting to TKS ", 
              "at %s for computeSessionKey.", hostport[tks_curr]);

            if (++currRetries >= tksConn->GetNumOfRetries()) {
                RA::Debug("Used up all the retries in ComputeSessionKey. Response is NULL","");
                RA::Error("RA::ComputeSessionKey","Failed connecting to TKS after %d retries", currRetries);

                goto loser;
            }
            response = tksConn->getResponse(tks_curr, servletID, body); 
        }

        RA::Debug(LL_PER_PDU, "ComputeSessionKey Response is not ","NULL");
        char * content = response->getContent();

	PK11SlotInfo *slot = PK11_GetInternalKeySlot();

        if (content != NULL) {
	  Buffer *status_b;

	  char *status_s, *sessionKey_s, *encSessionKey_s, *hostCryptogram_s;
	  int status;

      /* strip the http header */
      /* raidzilla 57722: strip the HTTP header and just pass
         name value pairs into the pblock parsing code.
       */
      RA::Debug("RA::Engine", "Pre-processing content '%s", content);
      char *cx = content;
      while (cx[0] != '\0' && (!(cx[0] == '\r' && cx[1] == '\n' && 
                 cx[2] == '\r' && cx[3] == '\n')))
      {
          cx++;
      }
      if (cx[0] != '\0') {
          cx+=4;
      }
      RA::Debug("RA::Engine", "Post-processing content '%s", cx);
	  ra_pb = ( RA_pblock * ) session->create_pblock(cx);
	  if (ra_pb == NULL) {
	    RA::Debug(LL_PER_PDU, "RA:ComputeSessionKey", "fail no ra_pb");
	    goto loser;
	  }

	status_b = ra_pb->find_val(TKS_RESPONSE_STATUS);
	if (status_b == NULL) {
	  status = 4;
	    RA::Error(LL_PER_SERVER, "RA:ComputeSessionKey", "Bad TKS Connection. Please make sure TKS is accessible by TPS.");