1#!/bin/sh
2#
3# $FreeBSD$
4#
5
6# PROVIDE: random
7# REQUIRE: initrandom FILESYSTEMS
8# BEFORE: netif
9# KEYWORD: nojail shutdown
10
11. /etc/rc.subr
12
13name="random"
14start_cmd="random_start"
15stop_cmd="random_stop"
16
17extra_commands="saveseed"
18saveseed_cmd="${name}_stop"
19
20feed_dev_random()
21{
22	if [ -f "${1}" -a -r "${1}" -a -s "${1}" ]; then
23		cat "${1}" | dd of=/dev/random bs=8k 2>/dev/null
24	fi
25}
26
27random_start()
28{
29	# Reseed /dev/random with previously stored entropy.
30	case ${entropy_dir} in
31	[Nn][Oo])
32		;;
33	*)
34		entropy_dir=${entropy_dir:-/var/db/entropy}
35		if [ -d "${entropy_dir}" ]; then
36			if [ -w /dev/random ]; then
37				for seedfile in ${entropy_dir}/*; do
38					feed_dev_random "${seedfile}"
39				done
40			fi
41		fi
42		;;
43	esac
44
45	case ${entropy_file} in
46	[Nn][Oo] | '')
47		;;
48	*)
49		if [ -w /dev/random ]; then
50			feed_dev_random "${entropy_file}"
51			feed_dev_random /var/db/entropy-file
52		fi
53		;;
54	esac
55}
56
57random_stop()
58{
59	# Write some entropy so when the machine reboots /dev/random
60	# can be reseeded
61	#
62	case ${entropy_file} in
63	[Nn][Oo] | '')
64		;;
65	*)
66		echo -n 'Writing entropy file:'
67		rm -f ${entropy_file} 2> /dev/null
68		oumask=`umask`
69		umask 077
70		if touch ${entropy_file} 2> /dev/null; then
71			entropy_file_confirmed="${entropy_file}"
72		else
73			# Try this as a reasonable alternative for read-only
74			# roots, diskless workstations, etc.
75			rm -f /var/db/entropy-file 2> /dev/null
76			if touch /var/db/entropy-file 2> /dev/null; then
77				entropy_file_confirmed=/var/db/entropy-file
78			fi
79		fi
80		case ${entropy_file_confirmed} in
81		'')
82			warn 'write failed (read-only fs?)'
83			;;
84		*)
85			dd if=/dev/random of=${entropy_file_confirmed} \
86			   bs=4096 count=1 2> /dev/null
87			echo '.'
88			;;
89		esac
90		umask ${oumask}
91		;;
92	esac
93}
94
95load_rc_config $name
96run_rc_command "$1"
97