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