#!/bin/sh
#
# $FreeBSD: src/etc/rc.d/random,v 1.3 2003/04/18 17:55:05 mtm Exp $
#

# PROVIDE: random
# REQUIRE: diskless mountcritlocal initrandom
# BEFORE:  FILESYSTEMS
# KEYWORD: shutdown

. /etc/rc.subr

name="random"
start_cmd="random_start"
stop_cmd="random_stop"

feed_dev_random()
{
	if [ -f "${1}" -a -r "${1}" -a -s "${1}" ]; then
		${SYSCTL_W} kern.seedenable=1 >/dev/null
		# Feed using a small block size so that a pool-based CSPRNG
		# is more likely to distribute the entropy over several
		# pools
		cat "${1}" | dd of=/dev/random bs=512 2>/dev/null
		${SYSCTL_W} kern.seedenable=0 >/dev/null
	fi
}

random_start()
{
	# Reseed /dev/random with previously stored entropy.
	case ${entropy_dir} in
	[Nn][Oo] | '')
		;;
	*)
		entropy_dir=${entropy_dir:-/var/db/entropy}
		if [ -d "${entropy_dir}" ]; then
			if [ -w /dev/random ]; then
				for seedfile in ${entropy_dir}/*; do
					feed_dev_random "${seedfile}"
				done
			fi
		fi
		;;
	esac

	case ${entropy_file} in
	[Nn][Oo] | '')
		;;
	*)
		if [ -w /dev/random ]; then
			feed_dev_random "${entropy_file}"
		fi
		;;
	esac
}

random_stop()
{
	# Write some entropy so when the machine reboots /dev/random
	# can be reseeded
	#
	case ${entropy_file} in
	[Nn][Oo] | '')
		;;
	*)
		echo -n 'Writing entropy file:'
		rm -f ${entropy_file}
		oumask=`umask`
		umask 077
		if touch ${entropy_file}; then
			entropy_file_confirmed="${entropy_file}"
		fi
		case ${entropy_file_confirmed} in
		'')
			err 1 '${entropy_file}:' \
			    ' entropy file write failed.'
			;;
		*)
			dd if=/dev/random of=${entropy_file_confirmed} \
			   bs=${entropy_save_sz} count=1 2> /dev/null
			echo '.'
			;;
		esac
		umask ${oumask}
		;;
	esac
}

load_rc_config $name
run_rc_command "$1"
