1#!/bin/sh
2#
3# This file, originally written by Garrett A. Wollman, is in the public
4# domain.
5#
6# $FreeBSD$
7#
8
9# PROVIDE: disks
10# KEYWORD: nojail
11
12. /etc/rc.subr
13
14name="gbde"
15desc="GEOM Based Disk Encryption"
16start_precmd="find_gbde_devices start"
17stop_precmd="find_gbde_devices stop"
18start_cmd="gbde_start"
19stop_cmd="gbde_stop"
20
21find_gbde_devices()
22{
23	case "${gbde_devices-auto}" in
24	[Aa][Uu][Tt][Oo])
25		gbde_devices=""
26		;;
27	*)
28		return 0
29		;;
30	esac
31
32	case "$1" in
33	start)
34		fstab="/etc/fstab"
35		;;
36	stop)
37		fstab=$(mktemp /tmp/mtab.XXXXXX)
38		mount -p >${fstab}
39		;;
40	esac
41
42	#
43	# We can't use "mount -p | while ..." because when a shell loop
44	# is the target of a pipe it executes in a subshell, and so can't
45	# modify variables in the script.
46	#
47	while read device mountpt type options dump pass; do
48		case "$device" in
49		*.bde)
50			# Ignore swap devices
51			case "$type" in
52			swap)
53				continue
54				;;
55			esac
56
57			case "$options" in
58			*noauto*)
59				if checkyesno gbde_autoattach_all; then
60					gbde_devices="${gbde_devices} ${device}"
61				fi
62				;;
63			*)
64				gbde_devices="${gbde_devices} ${device}"
65				;;
66			esac
67			;;
68		esac
69	done <${fstab}
70
71	case "$1" in
72	stop)
73		rm -f ${fstab}
74		;;
75	esac
76
77	return 0
78}
79
80gbde_start()
81{
82	for device in $gbde_devices; do
83		parent=${device%.bde}
84		parent=${parent#/dev/}
85		parent_=`ltr ${parent} '/' '_'`
86		eval "lock=\${gbde_lock_${parent_}-\"${gbde_lockdir}/${parent_}.lock\"}"
87		if [ -e "/dev/${parent}" -a ! -e "/dev/${parent}.bde" ]; then
88			echo "Configuring Disk Encryption for ${parent}."
89
90			count=1
91			while [ ${count} -le ${gbde_attach_attempts} ]; do
92				if [ -e "${lock}" ]; then
93					gbde attach ${parent} -l ${lock}
94				else
95					gbde attach ${parent}
96				fi
97				if [ -e "/dev/${parent}.bde" ]; then
98					break
99				fi
100				echo "Attach failed; attempt ${count} of ${gbde_attach_attempts}."
101				count=$((${count} + 1))
102			done
103		fi
104	done
105}
106
107gbde_stop()
108{
109	for device in $gbde_devices; do
110		parent=${device%.bde}
111		parent=${parent#/dev/}
112		if [ -e "/dev/${parent}.bde" ]; then
113			umount "/dev/${parent}.bde" 2>/dev/null
114			gbde detach "${parent}"
115		fi
116	done
117}
118
119load_rc_config $name
120run_rc_command "$1"
121