1# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2# $FreeBSD$
3#
4# Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
5# All rights reserved.
6#
7# This code is derived from software contributed to The NetBSD Foundation
8# by Luke Mewburn.
9#
10# Redistribution and use in source and binary forms, with or without
11# modification, are permitted provided that the following conditions
12# are met:
13# 1. Redistributions of source code must retain the above copyright
14#    notice, this list of conditions and the following disclaimer.
15# 2. Redistributions in binary form must reproduce the above copyright
16#    notice, this list of conditions and the following disclaimer in the
17#    documentation and/or other materials provided with the distribution.
18#
19# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29# POSSIBILITY OF SUCH DAMAGE.
30#
31# rc.subr
32#	functions used by various rc scripts
33#
34
35: ${RC_PID:=$$}; export RC_PID
36
37#
38#	Operating System dependent/independent variables
39#
40
41if [ -z "${_rc_subr_loaded}" ]; then
42
43_rc_subr_loaded="YES"
44
45SYSCTL="/sbin/sysctl"
46SYSCTL_N="${SYSCTL} -n"
47SYSCTL_W="${SYSCTL}"
48ID="/usr/bin/id"
49IDCMD="if [ -x $ID ]; then $ID -un; fi"
50PS="/bin/ps -ww"
51JID=`$PS -p $$ -o jid=`
52
53#
54#	functions
55#	---------
56
57# set_rcvar_obsolete oldvar [newvar] [msg]
58#	Define obsolete variable.
59#	Global variable $rcvars_obsolete is used.
60#
61set_rcvar_obsolete()
62{
63	local _var
64	_var=$1
65	debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
66
67	rcvars_obsolete="${rcvars_obsolete# } $1"
68	eval ${1}_newvar=\"$2\"
69	shift 2
70	eval ${_var}_obsolete_msg=\"$*\"
71}
72
73#
74# force_depend script [rcvar]
75#	Force a service to start. Intended for use by services
76#	to resolve dependency issues.
77#	$1 - filename of script, in /etc/rc.d, to run
78#	$2 - name of the script's rcvar (minus the _enable)
79#
80force_depend()
81{
82	local _depend _dep_rcvar
83
84	_depend="$1"
85	_dep_rcvar="${2:-$1}_enable"
86
87	[ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
88	    checkyesno $_dep_rcvar && return 0
89
90	/etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
91
92	info "${name} depends on ${_depend}, which will be forced to start."
93	if ! /etc/rc.d/${_depend} forcestart; then
94		warn "Unable to force ${_depend}. It may already be running."
95		return 1
96	fi
97}
98
99#
100# checkyesno var
101#	Test $1 variable, and warn if not set to YES or NO.
102#	Return 0 if it's "yes" (et al), nonzero otherwise.
103#
104checkyesno()
105{
106	eval _value=\$${1}
107	debug "checkyesno: $1 is set to $_value."
108	case $_value in
109
110		#	"yes", "true", "on", or "1"
111	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
112		return 0
113		;;
114
115		#	"no", "false", "off", or "0"
116	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
117		return 1
118		;;
119	*)
120		warn "\$${1} is not set properly - see rc.conf(5)."
121		return 1
122		;;
123	esac
124}
125
126#
127# reverse_list list
128#	print the list in reverse order
129#
130reverse_list()
131{
132	_revlist=
133	for _revfile; do
134		_revlist="$_revfile $_revlist"
135	done
136	echo $_revlist
137}
138
139# stop_boot always
140#	If booting directly to multiuser or $always is enabled,
141#	send SIGTERM to the parent (/etc/rc) to abort the boot.
142#	Otherwise just exit.
143#
144stop_boot()
145{
146	local always
147
148	case $1 in
149		#	"yes", "true", "on", or "1"
150        [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
151		always=true
152		;;
153	*)
154		always=false
155		;;
156	esac
157	if [ "$autoboot" = yes -o "$always" = true ]; then
158		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
159		kill -TERM ${RC_PID}
160	fi
161	exit 1
162}
163
164#
165# mount_critical_filesystems type
166#	Go through the list of critical filesystems as provided in
167#	the rc.conf(5) variable $critical_filesystems_${type}, checking
168#	each one to see if it is mounted, and if it is not, mounting it.
169#
170mount_critical_filesystems()
171{
172	eval _fslist=\$critical_filesystems_${1}
173	for _fs in $_fslist; do
174		mount | (
175			_ismounted=false
176			while read what _on on _type type; do
177				if [ $on = $_fs ]; then
178					_ismounted=true
179				fi
180			done
181			if $_ismounted; then
182				:
183			else
184				mount $_fs >/dev/null 2>&1
185			fi
186		)
187	done
188}
189
190#
191# check_pidfile pidfile procname [interpreter]
192#	Parses the first line of pidfile for a PID, and ensures
193#	that the process is running and matches procname.
194#	Prints the matching PID upon success, nothing otherwise.
195#	interpreter is optional; see _find_processes() for details.
196#
197check_pidfile()
198{
199	_pidfile=$1
200	_procname=$2
201	_interpreter=$3
202	if [ -z "$_pidfile" -o -z "$_procname" ]; then
203		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
204	fi
205	if [ ! -f $_pidfile ]; then
206		debug "pid file ($_pidfile): not readable."
207		return
208	fi
209	read _pid _junk < $_pidfile
210	if [ -z "$_pid" ]; then
211		debug "pid file ($_pidfile): no pid in file."
212		return
213	fi
214	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
215}
216
217#
218# check_process procname [interpreter]
219#	Ensures that a process (or processes) named procname is running.
220#	Prints a list of matching PIDs.
221#	interpreter is optional; see _find_processes() for details.
222#
223check_process()
224{
225	_procname=$1
226	_interpreter=$2
227	if [ -z "$_procname" ]; then
228		err 3 'USAGE: check_process procname [interpreter]'
229	fi
230	_find_processes $_procname ${_interpreter:-.} '-ax'
231}
232
233#
234# _find_processes procname interpreter psargs
235#	Search for procname in the output of ps generated by psargs.
236#	Prints the PIDs of any matching processes, space separated.
237#
238#	If interpreter == ".", check the following variations of procname
239#	against the first word of each command:
240#		procname
241#		`basename procname`
242#		`basename procname` + ":"
243#		"(" + `basename procname` + ")"
244#		"[" + `basename procname` + "]"
245#
246#	If interpreter != ".", read the first line of procname, remove the
247#	leading #!, normalise whitespace, append procname, and attempt to
248#	match that against each command, either as is, or with extra words
249#	at the end.  As an alternative, to deal with interpreted daemons
250#	using perl, the basename of the interpreter plus a colon is also
251#	tried as the prefix to procname.
252#
253_find_processes()
254{
255	if [ $# -ne 3 ]; then
256		err 3 'USAGE: _find_processes procname interpreter psargs'
257	fi
258	_procname=$1
259	_interpreter=$2
260	_psargs=$3
261
262	_pref=
263	if [ $_interpreter != "." ]; then	# an interpreted script
264		_script="${_chroot}${_chroot:+/}$_procname"
265		if [ -r "$_script" ]; then
266			read _interp < $_script	# read interpreter name
267			case "$_interp" in
268			\#!*)
269				_interp=${_interp#\#!}	# strip #!
270				set -- $_interp
271				case $1 in
272				*/bin/env)
273					shift	# drop env to get real name
274					;;
275				esac
276				if [ $_interpreter != $1 ]; then
277					warn "\$command_interpreter $_interpreter != $1"
278				fi
279				;;
280			*)
281				warn "no shebang line in $_script"
282				set -- $_interpreter
283				;;
284			esac
285		else
286			warn "cannot read shebang line from $_script"
287			set -- $_interpreter
288		fi
289		_interp="$* $_procname"		# cleanup spaces, add _procname
290		_interpbn=${1##*/}
291		_fp_args='_argv'
292		_fp_match='case "$_argv" in
293		    ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
294	else					# a normal daemon
295		_procnamebn=${_procname##*/}
296		_fp_args='_arg0 _argv'
297		_fp_match='case "$_arg0" in
298		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
299	fi
300
301	_proccheck="\
302		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
303		while read _npid _jid '"$_fp_args"'; do
304			'"$_fp_match"'
305				if [ "$JID" -eq "$_jid" ];
306				then echo -n "$_pref$_npid";
307				_pref=" ";
308				fi
309				;;
310			esac
311		done'
312
313#	debug "in _find_processes: proccheck is ($_proccheck)."
314	eval $_proccheck
315}
316
317#
318# wait_for_pids pid [pid ...]
319#	spins until none of the pids exist
320#
321wait_for_pids()
322{
323	local _list _prefix _nlist _j
324
325	_list="$@"
326	if [ -z "$_list" ]; then
327		return
328	fi
329	_prefix=
330	while true; do
331		_nlist="";
332		for _j in $_list; do
333			if kill -0 $_j 2>/dev/null; then
334				_nlist="${_nlist}${_nlist:+ }$_j"
335				[ -n "$_prefix" ] && sleep 1
336			fi
337		done
338		if [ -z "$_nlist" ]; then
339			break
340		fi
341		_list=$_nlist
342		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
343		_prefix=", "
344		pwait $_list 2>/dev/null
345	done
346	if [ -n "$_prefix" ]; then
347		echo "."
348	fi
349}
350
351#
352# get_pidfile_from_conf string file
353#
354#	Takes a string to search for in the specified file.
355#	Ignores lines with traditional comment characters.
356#
357# Example:
358#
359# if get_pidfile_from_conf string file; then
360#	pidfile="$_pidfile_from_conf"
361# else
362#	pidfile='appropriate default'
363# fi
364#
365get_pidfile_from_conf()
366{
367	if [ -z "$1" -o -z "$2" ]; then
368		err 3 "USAGE: get_pidfile_from_conf string file ($name)"
369	fi
370
371	local string file line
372
373	string="$1" ; file="$2"
374
375	if [ ! -s "$file" ]; then
376		err 3 "get_pidfile_from_conf: $file does not exist ($name)"
377	fi
378
379	while read line; do
380		case "$line" in
381		*[#\;]*${string}*)	continue ;;
382		*${string}*)		break ;;
383		esac
384	done < $file
385
386	if [ -n "$line" ]; then
387		line=${line#*/}
388		_pidfile_from_conf="/${line%%[\"\;]*}"
389	else
390		return 1
391	fi
392}
393
394#
395# check_startmsgs
396#	If rc_quiet is set (usually as a result of using faststart at
397#	boot time) check if rc_startmsgs is enabled.
398#
399check_startmsgs()
400{
401	if [ -n "$rc_quiet" ]; then
402		checkyesno rc_startmsgs
403	else
404		return 0
405	fi
406}
407
408#
409# run_rc_command argument
410#	Search for argument in the list of supported commands, which is:
411#		"start stop restart rcvar status poll ${extra_commands}"
412#	If there's a match, run ${argument}_cmd or the default method
413#	(see below).
414#
415#	If argument has a given prefix, then change the operation as follows:
416#		Prefix	Operation
417#		------	---------
418#		fast	Skip the pid check, and set rc_fast=yes, rc_quiet=yes
419#		force	Set ${rcvar} to YES, and set rc_force=yes
420#		one	Set ${rcvar} to YES
421#		quiet	Don't output some diagnostics, and set rc_quiet=yes
422#
423#	The following globals are used:
424#
425#	Name		Needed	Purpose
426#	----		------	-------
427#	name		y	Name of script.
428#
429#	command		n	Full path to command.
430#				Not needed if ${rc_arg}_cmd is set for
431#				each keyword.
432#
433#	command_args	n	Optional args/shell directives for command.
434#
435#	command_interpreter n	If not empty, command is interpreted, so
436#				call check_{pidfile,process}() appropriately.
437#
438#	desc		n	Description of script.
439#
440#	extra_commands	n	List of extra commands supported.
441#
442#	pidfile		n	If set, use check_pidfile $pidfile $command,
443#				otherwise use check_process $command.
444#				In either case, only check if $command is set.
445#
446#	procname	n	Process name to check for instead of $command.
447#
448#	rcvar		n	This is checked with checkyesno to determine
449#				if the action should be run.
450#
451#	${name}_program	n	Full path to command.
452#				Meant to be used in /etc/rc.conf to override
453#				${command}.
454#
455#	${name}_chroot	n	Directory to chroot to before running ${command}
456#				Requires /usr to be mounted.
457#
458#	${name}_chdir	n	Directory to cd to before running ${command}
459#				(if not using ${name}_chroot).
460#
461#	${name}_flags	n	Arguments to call ${command} with.
462#				NOTE:	$flags from the parent environment
463#					can be used to override this.
464#
465#	${name}_fib	n	Routing table number to run ${command} with.
466#
467#	${name}_nice	n	Nice level to run ${command} at.
468#
469#	${name}_user	n	User to run ${command} as, using su(1) if not
470#				using ${name}_chroot.
471#				Requires /usr to be mounted.
472#
473#	${name}_group	n	Group to run chrooted ${command} as.
474#				Requires /usr to be mounted.
475#
476#	${name}_groups	n	Comma separated list of supplementary groups
477#				to run the chrooted ${command} with.
478#				Requires /usr to be mounted.
479#
480#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
481#				Otherwise, use default command (see below)
482#
483#	${rc_arg}_precmd n	If set, run just before performing the
484#				${rc_arg}_cmd method in the default
485#				operation (i.e, after checking for required
486#				bits and process (non)existence).
487#				If this completes with a non-zero exit code,
488#				don't run ${rc_arg}_cmd.
489#
490#	${rc_arg}_postcmd n	If set, run just after performing the
491#				${rc_arg}_cmd method, if that method
492#				returned a zero exit code.
493#
494#	required_dirs	n	If set, check for the existence of the given
495#				directories before running a (re)start command.
496#
497#	required_files	n	If set, check for the readability of the given
498#				files before running a (re)start command.
499#
500#	required_modules n	If set, ensure the given kernel modules are
501#				loaded before running a (re)start command.
502#				The check and possible loads are actually
503#				done after start_precmd so that the modules
504#				aren't loaded in vain, should the precmd
505#				return a non-zero status to indicate a error.
506#				If a word in the list looks like "foo:bar",
507#				"foo" is the KLD file name and "bar" is the
508#				module name.  If a word looks like "foo~bar",
509#				"foo" is the KLD file name and "bar" is a
510#				egrep(1) pattern matching the module name.
511#				Otherwise the module name is assumed to be
512#				the same as the KLD file name, which is most
513#				common.  See load_kld().
514#
515#	required_vars	n	If set, perform checkyesno on each of the
516#				listed variables before running the default
517#				(re)start command.
518#
519#	Default behaviour for a given argument, if no override method is
520#	provided:
521#
522#	Argument	Default behaviour
523#	--------	-----------------
524#	start		if !running && checkyesno ${rcvar}
525#				${command}
526#
527#	stop		if ${pidfile}
528#				rc_pid=$(check_pidfile $pidfile $command)
529#			else
530#				rc_pid=$(check_process $command)
531#			kill $sig_stop $rc_pid
532#			wait_for_pids $rc_pid
533#			($sig_stop defaults to TERM.)
534#
535#	reload		Similar to stop, except use $sig_reload instead,
536#			and doesn't wait_for_pids.
537#			$sig_reload defaults to HUP.
538#			Note that `reload' isn't provided by default,
539#			it should be enabled via $extra_commands.
540#
541#	restart		Run `stop' then `start'.
542#
543#	status		Show if ${command} is running, etc.
544#
545#	poll		Wait for ${command} to exit.
546#
547#	rcvar		Display what rc.conf variable is used (if any).
548#
549#	enabled		Return true if the service is enabled.
550#
551#	Variables available to methods, and after run_rc_command() has
552#	completed:
553#
554#	Variable	Purpose
555#	--------	-------
556#	rc_arg		Argument to command, after fast/force/one processing
557#			performed
558#
559#	rc_flags	Flags to start the default command with.
560#			Defaults to ${name}_flags, unless overridden
561#			by $flags from the environment.
562#			This variable may be changed by the precmd method.
563#
564#	rc_pid		PID of command (if appropriate)
565#
566#	rc_fast		Not empty if "fast" was provided (q.v.)
567#
568#	rc_force	Not empty if "force" was provided (q.v.)
569#
570#	rc_quiet	Not empty if "quiet" was provided
571#
572#
573run_rc_command()
574{
575	_return=0
576	rc_arg=$1
577	if [ -z "$name" ]; then
578		err 3 'run_rc_command: $name is not set.'
579	fi
580
581	# Don't repeat the first argument when passing additional command-
582	# line arguments to the command subroutines.
583	#
584	shift 1
585	rc_extra_args="$*"
586
587	_rc_prefix=
588	case "$rc_arg" in
589	fast*)				# "fast" prefix; don't check pid
590		rc_arg=${rc_arg#fast}
591		rc_fast=yes
592		rc_quiet=yes
593		;;
594	force*)				# "force" prefix; always run
595		rc_force=yes
596		_rc_prefix=force
597		rc_arg=${rc_arg#${_rc_prefix}}
598		if [ -n "${rcvar}" ]; then
599			eval ${rcvar}=YES
600		fi
601		;;
602	one*)				# "one" prefix; set ${rcvar}=yes
603		_rc_prefix=one
604		rc_arg=${rc_arg#${_rc_prefix}}
605		if [ -n "${rcvar}" ]; then
606			eval ${rcvar}=YES
607		fi
608		;;
609	quiet*)				# "quiet" prefix; omit some messages
610		_rc_prefix=quiet
611		rc_arg=${rc_arg#${_rc_prefix}}
612		rc_quiet=yes
613		;;
614	esac
615
616	eval _override_command=\$${name}_program
617	command=${_override_command:-$command}
618
619	_keywords="start stop restart rcvar enabled $extra_commands"
620	rc_pid=
621	_pidcmd=
622	_procname=${procname:-${command}}
623
624					# setup pid check command
625	if [ -n "$_procname" ]; then
626		if [ -n "$pidfile" ]; then
627			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
628		else
629			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
630		fi
631		if [ -n "$_pidcmd" ]; then
632			_keywords="${_keywords} status poll"
633		fi
634	fi
635
636	if [ -z "$rc_arg" ]; then
637		rc_usage $_keywords
638	fi
639
640	if [ "$rc_arg" = "enabled" ] ; then
641		checkyesno ${rcvar}
642		return $?
643	fi
644
645	if [ -n "$flags" ]; then	# allow override from environment
646		rc_flags=$flags
647	else
648		eval rc_flags=\$${name}_flags
649	fi
650	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
651	    _nice=\$${name}_nice	_user=\$${name}_user \
652	    _group=\$${name}_group	_groups=\$${name}_groups \
653	    _fib=\$${name}_fib
654
655	if [ -n "$_user" ]; then	# unset $_user if running as that user
656		if [ "$_user" = "$(eval $IDCMD)" ]; then
657			unset _user
658		fi
659	fi
660
661	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
662
663	for _elem in $_keywords; do
664		if [ "$_elem" != "$rc_arg" ]; then
665			continue
666		fi
667					# if ${rcvar} is set, $1 is not "rcvar"
668					# and ${rc_pid} is not set, then run
669					#	checkyesno ${rcvar}
670					# and return if that failed
671					#
672		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
673		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
674			if ! checkyesno ${rcvar}; then
675				if [ -n "${rc_quiet}" ]; then
676					return 0
677				fi
678				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
679				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
680				echo "instead of '${rc_arg}'."
681				return 0
682			fi
683		fi
684
685					# if there's a custom ${XXX_cmd},
686					# run that instead of the default
687					#
688		eval _cmd=\$${rc_arg}_cmd \
689		     _precmd=\$${rc_arg}_precmd \
690		     _postcmd=\$${rc_arg}_postcmd
691
692		if [ -n "$_cmd" ]; then
693			_run_rc_precmd || return 1
694			_run_rc_doit "$_cmd $rc_extra_args" || return 1
695			_run_rc_postcmd
696			return $_return
697		fi
698
699		case "$rc_arg" in	# default operations...
700
701		status)
702			_run_rc_precmd || return 1
703			if [ -n "$rc_pid" ]; then
704				echo "${name} is running as pid $rc_pid."
705			else
706				echo "${name} is not running."
707				return 1
708			fi
709			_run_rc_postcmd
710			;;
711
712		start)
713			if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
714				if [ -z "$rc_quiet" ]; then
715					echo 1>&2 "${name} already running? " \
716					    "(pid=$rc_pid)."
717				fi
718				return 1
719			fi
720
721			if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
722				warn "run_rc_command: cannot run $command"
723				return 1
724			fi
725
726			if ! _run_rc_precmd; then
727				warn "failed precmd routine for ${name}"
728				return 1
729			fi
730
731					# setup the full command to run
732					#
733			check_startmsgs && echo "Starting ${name}."
734			if [ -n "$_chroot" ]; then
735				_doit="\
736${_nice:+nice -n $_nice }\
737${_fib:+setfib -F $_fib }\
738chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
739$_chroot $command $rc_flags $command_args"
740			else
741				_doit="\
742${_chdir:+cd $_chdir && }\
743${_fib:+setfib -F $_fib }\
744$command $rc_flags $command_args"
745				if [ -n "$_user" ]; then
746				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
747				fi
748				if [ -n "$_nice" ]; then
749					if [ -z "$_user" ]; then
750						_doit="sh -c \"$_doit\""
751					fi
752					_doit="nice -n $_nice $_doit"
753				fi
754			fi
755
756					# run the full command
757					#
758			if ! _run_rc_doit "$_doit"; then
759				warn "failed to start ${name}"
760				return 1
761			fi
762
763					# finally, run postcmd
764					#
765			_run_rc_postcmd
766			;;
767
768		stop)
769			if [ -z "$rc_pid" ]; then
770				[ -n "$rc_fast" ] && return 0
771				_run_rc_notrunning
772				return 1
773			fi
774
775			_run_rc_precmd || return 1
776
777					# send the signal to stop
778					#
779			echo "Stopping ${name}."
780			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
781			_run_rc_doit "$_doit" || return 1
782
783					# wait for the command to exit,
784					# and run postcmd.
785			wait_for_pids $rc_pid
786
787			_run_rc_postcmd
788			;;
789
790		reload)
791			if [ -z "$rc_pid" ]; then
792				_run_rc_notrunning
793				return 1
794			fi
795
796			_run_rc_precmd || return 1
797
798			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
799			_run_rc_doit "$_doit" || return 1
800
801			_run_rc_postcmd
802			;;
803
804		restart)
805					# prevent restart being called more
806					# than once by any given script
807					#
808			if ${_rc_restart_done:-false}; then
809				return 0
810			fi
811			_rc_restart_done=true
812
813			_run_rc_precmd || return 1
814
815			# run those in a subshell to keep global variables
816			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
817			( run_rc_command ${_rc_prefix}start $rc_extra_args )
818			_return=$?
819			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
820
821			_run_rc_postcmd
822			;;
823
824		poll)
825			_run_rc_precmd || return 1
826			if [ -n "$rc_pid" ]; then
827				wait_for_pids $rc_pid
828			fi
829			_run_rc_postcmd
830			;;
831
832		rcvar)
833			echo -n "# $name"
834			if [ -n "$desc" ]; then
835				echo " : $desc"
836			else
837				echo ""
838			fi
839			echo "#"
840			# Get unique vars in $rcvar
841			for _v in $rcvar; do
842				case $v in
843				$_v\ *|\ *$_v|*\ $_v\ *) ;;
844				*)	v="${v# } $_v" ;;
845				esac
846			done
847
848			# Display variables.
849			for _v in $v; do
850				if [ -z "$_v" ]; then
851					continue
852				fi
853
854				eval _desc=\$${_v}_desc
855				eval _defval=\$${_v}_defval
856				_h="-"
857
858				eval echo \"$_v=\\\"\$$_v\\\"\"
859				# decode multiple lines of _desc
860				while [ -n "$_desc" ]; do
861					case $_desc in
862					*^^*)
863						echo "# $_h ${_desc%%^^*}"
864						_desc=${_desc#*^^}
865						_h=" "
866						;;
867					*)
868						echo "# $_h ${_desc}"
869						break
870						;;
871					esac
872				done
873				echo "#   (default: \"$_defval\")"
874			done
875			echo ""
876			;;
877
878		*)
879			rc_usage $_keywords
880			;;
881
882		esac
883		return $_return
884	done
885
886	echo 1>&2 "$0: unknown directive '$rc_arg'."
887	rc_usage $_keywords
888	# not reached
889}
890
891#
892# Helper functions for run_rc_command: common code.
893# They use such global variables besides the exported rc_* ones:
894#
895#	name	       R/W
896#	------------------
897#	_precmd		R
898#	_postcmd	R
899#	_return		W
900#
901_run_rc_precmd()
902{
903	check_required_before "$rc_arg" || return 1
904
905	if [ -n "$_precmd" ]; then
906		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
907		eval "$_precmd $rc_extra_args"
908		_return=$?
909
910		# If precmd failed and force isn't set, request exit.
911		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
912			return 1
913		fi
914	fi
915
916	check_required_after "$rc_arg" || return 1
917
918	return 0
919}
920
921_run_rc_postcmd()
922{
923	if [ -n "$_postcmd" ]; then
924		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
925		eval "$_postcmd $rc_extra_args"
926		_return=$?
927	fi
928	return 0
929}
930
931_run_rc_doit()
932{
933	debug "run_rc_command: doit: $*"
934	eval "$@"
935	_return=$?
936
937	# If command failed and force isn't set, request exit.
938	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
939		return 1
940	fi
941
942	return 0
943}
944
945_run_rc_notrunning()
946{
947	local _pidmsg
948
949	if [ -n "$pidfile" ]; then
950		_pidmsg=" (check $pidfile)."
951	else
952		_pidmsg=
953	fi
954	echo 1>&2 "${name} not running?${_pidmsg}"
955}
956
957_run_rc_killcmd()
958{
959	local _cmd
960
961	_cmd="kill -$1 $rc_pid"
962	if [ -n "$_user" ]; then
963		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
964	fi
965	echo "$_cmd"
966}
967
968#
969# run_rc_script file arg
970#	Start the script `file' with `arg', and correctly handle the
971#	return value from the script.
972#	If `file' ends with `.sh', it's sourced into the current environment
973#	when $rc_fast_and_loose is set, otherwise it is run as a child process.
974#	If `file' appears to be a backup or scratch file, ignore it.
975#	Otherwise if it is executable run as a child process.
976#
977run_rc_script()
978{
979	_file=$1
980	_arg=$2
981	if [ -z "$_file" -o -z "$_arg" ]; then
982		err 3 'USAGE: run_rc_script file arg'
983	fi
984
985	unset	name command command_args command_interpreter \
986		extra_commands pidfile procname \
987		rcvar rcvars_obsolete required_dirs required_files \
988		required_vars
989	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
990
991	case "$_file" in
992	/etc/rc.d/*.sh)			# no longer allowed in the base
993		warn "Ignoring old-style startup script $_file"
994		;;
995	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
996		warn "Ignoring scratch file $_file"
997		;;
998	*)				# run in subshell
999		if [ -x $_file ]; then
1000			if [ -n "$rc_fast_and_loose" ]; then
1001				set $_arg; . $_file
1002			else
1003				( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1004				  trap "echo Script $_file interrupted >&2 ; exit 1" 2
1005				  trap "echo Script $_file running >&2" 29
1006				  set $_arg; . $_file )
1007			fi
1008		fi
1009		;;
1010	esac
1011}
1012
1013#
1014# load_rc_config name
1015#	Source in the configuration file for a given name.
1016#
1017load_rc_config()
1018{
1019	local _name _rcvar_val _var _defval _v _msg _new
1020	_name=$1
1021	if [ -z "$_name" ]; then
1022		err 3 'USAGE: load_rc_config name'
1023	fi
1024
1025	if ${_rc_conf_loaded:-false}; then
1026		:
1027	else
1028		if [ -r /etc/defaults/rc.conf ]; then
1029			debug "Sourcing /etc/defaults/rc.conf"
1030			. /etc/defaults/rc.conf
1031			source_rc_confs
1032		elif [ -r /etc/rc.conf ]; then
1033			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1034			. /etc/rc.conf
1035		fi
1036		_rc_conf_loaded=true
1037	fi
1038	if [ -f /etc/rc.conf.d/"$_name" ]; then
1039		debug "Sourcing /etc/rc.conf.d/${_name}"
1040		. /etc/rc.conf.d/"$_name"
1041	fi
1042
1043	# Set defaults if defined.
1044	for _var in $rcvar; do
1045		eval _defval=\$${_var}_defval
1046		if [ -n "$_defval" ]; then
1047			eval : \${$_var:=\$${_var}_defval}
1048		fi
1049	done
1050
1051	# check obsolete rc.conf variables
1052	for _var in $rcvars_obsolete; do
1053		eval _v=\$$_var
1054		eval _msg=\$${_var}_obsolete_msg
1055		eval _new=\$${_var}_newvar
1056		case $_v in
1057		"")
1058			;;
1059		*)
1060			if [ -z "$_new" ]; then
1061				_msg="Ignored."
1062			else
1063				eval $_new=\"\$$_var\"
1064				if [ -z "$_msg" ]; then
1065					_msg="Use \$$_new instead."
1066				fi
1067			fi
1068			warn "\$$_var is obsolete.  $_msg"
1069			;;
1070		esac
1071	done
1072}
1073
1074#
1075# load_rc_config_var name var
1076#	Read the rc.conf(5) var for name and set in the
1077#	current shell, using load_rc_config in a subshell to prevent
1078#	unwanted side effects from other variable assignments.
1079#
1080load_rc_config_var()
1081{
1082	if [ $# -ne 2 ]; then
1083		err 3 'USAGE: load_rc_config_var name var'
1084	fi
1085	eval $(eval '(
1086		load_rc_config '$1' >/dev/null;
1087                if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1088			echo '$2'=\'\''${'$2'}\'\'';
1089		fi
1090	)' )
1091}
1092
1093#
1094# rc_usage commands
1095#	Print a usage string for $0, with `commands' being a list of
1096#	valid commands.
1097#
1098rc_usage()
1099{
1100	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1101
1102	_sep=
1103	for _elem; do
1104		echo -n 1>&2 "$_sep$_elem"
1105		_sep="|"
1106	done
1107	echo 1>&2 ")"
1108	exit 1
1109}
1110
1111#
1112# err exitval message
1113#	Display message to stderr and log to the syslog, and exit with exitval.
1114#
1115err()
1116{
1117	exitval=$1
1118	shift
1119
1120	if [ -x /usr/bin/logger ]; then
1121		logger "$0: ERROR: $*"
1122	fi
1123	echo 1>&2 "$0: ERROR: $*"
1124	exit $exitval
1125}
1126
1127#
1128# warn message
1129#	Display message to stderr and log to the syslog.
1130#
1131warn()
1132{
1133	if [ -x /usr/bin/logger ]; then
1134		logger "$0: WARNING: $*"
1135	fi
1136	echo 1>&2 "$0: WARNING: $*"
1137}
1138
1139#
1140# info message
1141#	Display informational message to stdout and log to syslog.
1142#
1143info()
1144{
1145	case ${rc_info} in
1146	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1147		if [ -x /usr/bin/logger ]; then
1148			logger "$0: INFO: $*"
1149		fi
1150		echo "$0: INFO: $*"
1151		;;
1152	esac
1153}
1154
1155#
1156# debug message
1157#	If debugging is enabled in rc.conf output message to stderr.
1158#	BEWARE that you don't call any subroutine that itself calls this
1159#	function.
1160#
1161debug()
1162{
1163	case ${rc_debug} in
1164	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1165		if [ -x /usr/bin/logger ]; then
1166			logger "$0: DEBUG: $*"
1167		fi
1168		echo 1>&2 "$0: DEBUG: $*"
1169		;;
1170	esac
1171}
1172
1173#
1174# backup_file action file cur backup
1175#	Make a backup copy of `file' into `cur', and save the previous
1176#	version of `cur' as `backup' or use rcs for archiving.
1177#
1178#	This routine checks the value of the backup_uses_rcs variable,
1179#	which can be either YES or NO.
1180#
1181#	The `action' keyword can be one of the following:
1182#
1183#	add		`file' is now being backed up (and is possibly
1184#			being reentered into the backups system).  `cur'
1185#			is created and RCS files, if necessary, are
1186#			created as well.
1187#
1188#	update		`file' has changed and needs to be backed up.
1189#			If `cur' exists, it is copied to to `back' or
1190#			checked into RCS (if the repository file is old),
1191#			and then `file' is copied to `cur'.  Another RCS
1192#			check in done here if RCS is being used.
1193#
1194#	remove		`file' is no longer being tracked by the backups
1195#			system.  If RCS is not being used, `cur' is moved
1196#			to `back', otherwise an empty file is checked in,
1197#			and then `cur' is removed.
1198#
1199#
1200backup_file()
1201{
1202	_action=$1
1203	_file=$2
1204	_cur=$3
1205	_back=$4
1206
1207	if checkyesno backup_uses_rcs; then
1208		_msg0="backup archive"
1209		_msg1="update"
1210
1211		# ensure that history file is not locked
1212		if [ -f $_cur,v ]; then
1213			rcs -q -u -U -M $_cur
1214		fi
1215
1216		# ensure after switching to rcs that the
1217		# current backup is not lost
1218		if [ -f $_cur ]; then
1219			# no archive, or current newer than archive
1220			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1221				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1222				rcs -q -kb -U $_cur
1223				co -q -f -u $_cur
1224			fi
1225		fi
1226
1227		case $_action in
1228		add|update)
1229			cp -p $_file $_cur
1230			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1231			rcs -q -kb -U $_cur
1232			co -q -f -u $_cur
1233			chown root:wheel $_cur $_cur,v
1234			;;
1235		remove)
1236			cp /dev/null $_cur
1237			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1238			rcs -q -kb -U $_cur
1239			chown root:wheel $_cur $_cur,v
1240			rm $_cur
1241			;;
1242		esac
1243	else
1244		case $_action in
1245		add|update)
1246			if [ -f $_cur ]; then
1247				cp -p $_cur $_back
1248			fi
1249			cp -p $_file $_cur
1250			chown root:wheel $_cur
1251			;;
1252		remove)
1253			mv -f $_cur $_back
1254			;;
1255		esac
1256	fi
1257}
1258
1259# make_symlink src link
1260#	Make a symbolic link 'link' to src from basedir. If the
1261#	directory in which link is to be created does not exist
1262#	a warning will be displayed and an error will be returned.
1263#	Returns 0 on success, 1 otherwise.
1264#
1265make_symlink()
1266{
1267	local src link linkdir _me
1268	src="$1"
1269	link="$2"
1270	linkdir="`dirname $link`"
1271	_me="make_symlink()"
1272
1273	if [ -z "$src" -o -z "$link" ]; then
1274		warn "$_me: requires two arguments."
1275		return 1
1276	fi
1277	if [ ! -d "$linkdir" ]; then
1278		warn "$_me: the directory $linkdir does not exist."
1279		return 1
1280	fi
1281	if ! ln -sf $src $link; then
1282		warn "$_me: unable to make a symbolic link from $link to $src"
1283		return 1
1284	fi
1285	return 0
1286}
1287
1288# devfs_rulesets_from_file file
1289#	Reads a set of devfs commands from file, and creates
1290#	the specified rulesets with their rules. Returns non-zero
1291#	if there was an error.
1292#
1293devfs_rulesets_from_file()
1294{
1295	local file _err _me _opts
1296	file="$1"
1297	_me="devfs_rulesets_from_file"
1298	_err=0
1299
1300	if [ -z "$file" ]; then
1301		warn "$_me: you must specify a file"
1302		return 1
1303	fi
1304	if [ ! -e "$file" ]; then
1305		debug "$_me: no such file ($file)"
1306		return 0
1307	fi
1308
1309	# Disable globbing so that the rule patterns are not expanded
1310	# by accident with matching filesystem entries.
1311	_opts=$-; set -f
1312
1313	debug "reading rulesets from file ($file)"
1314	{ while read line
1315	do
1316		case $line in
1317		\#*)
1318			continue
1319			;;
1320		\[*\]*)
1321			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1322			if [ -z "$rulenum" ]; then
1323				warn "$_me: cannot extract rule number ($line)"
1324				_err=1
1325				break
1326			fi
1327			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1328			if [ -z "$rulename" ]; then
1329				warn "$_me: cannot extract rule name ($line)"
1330				_err=1
1331				break;
1332			fi
1333			eval $rulename=\$rulenum
1334			debug "found ruleset: $rulename=$rulenum"
1335			if ! /sbin/devfs rule -s $rulenum delset; then
1336				_err=1
1337				break
1338			fi
1339			;;
1340		*)
1341			rulecmd="${line%%"\#*"}"
1342			# evaluate the command incase it includes
1343			# other rules
1344			if [ -n "$rulecmd" ]; then
1345				debug "adding rule ($rulecmd)"
1346				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1347				then
1348					_err=1
1349					break
1350				fi
1351			fi
1352			;;
1353		esac
1354		if [ $_err -ne 0 ]; then
1355			debug "error in $_me"
1356			break
1357		fi
1358	done } < $file
1359	case $_opts in *f*) ;; *) set +f ;; esac
1360	return $_err
1361}
1362
1363# devfs_init_rulesets
1364#	Initializes rulesets from configuration files. Returns
1365#	non-zero if there was an error.
1366#
1367devfs_init_rulesets()
1368{
1369	local file _me
1370	_me="devfs_init_rulesets"
1371
1372	# Go through this only once
1373	if [ -n "$devfs_rulesets_init" ]; then
1374		debug "$_me: devfs rulesets already initialized"
1375		return
1376	fi
1377	for file in $devfs_rulesets; do
1378		if ! devfs_rulesets_from_file $file; then
1379			warn "$_me: could not read rules from $file"
1380			return 1
1381		fi
1382	done
1383	devfs_rulesets_init=1
1384	debug "$_me: devfs rulesets initialized"
1385	return 0
1386}
1387
1388# devfs_set_ruleset ruleset [dir]
1389#	Sets the default ruleset of dir to ruleset. The ruleset argument
1390#	must be a ruleset name as specified in devfs.rules(5) file.
1391#	Returns non-zero if it could not set it successfully.
1392#
1393devfs_set_ruleset()
1394{
1395	local devdir rs _me
1396	[ -n "$1" ] && eval rs=\$$1 || rs=
1397	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1398	_me="devfs_set_ruleset"
1399
1400	if [ -z "$rs" ]; then
1401		warn "$_me: you must specify a ruleset number"
1402		return 1
1403	fi
1404	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1405	if ! /sbin/devfs $devdir ruleset $rs; then
1406		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1407		return 1
1408	fi
1409	return 0
1410}
1411
1412# devfs_apply_ruleset ruleset [dir]
1413#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1414#	The ruleset argument must be a ruleset name as specified
1415#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1416#	if it could not apply the ruleset.
1417#
1418devfs_apply_ruleset()
1419{
1420	local devdir rs _me
1421	[ -n "$1" ] && eval rs=\$$1 || rs=
1422	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1423	_me="devfs_apply_ruleset"
1424
1425	if [ -z "$rs" ]; then
1426		warn "$_me: you must specify a ruleset"
1427		return 1
1428	fi
1429	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1430	if ! /sbin/devfs $devdir rule -s $rs applyset; then
1431		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1432		return 1
1433	fi
1434	return 0
1435}
1436
1437# devfs_domount dir [ruleset]
1438#	Mount devfs on dir. If ruleset is specified it is set
1439#	on the mount-point. It must also be a ruleset name as specified
1440#	in a devfs.rules(5) file. Returns 0 on success.
1441#
1442devfs_domount()
1443{
1444	local devdir rs _me
1445	devdir="$1"
1446	[ -n "$2" ] && rs=$2 || rs=
1447	_me="devfs_domount()"
1448
1449	if [ -z "$devdir" ]; then
1450		warn "$_me: you must specify a mount-point"
1451		return 1
1452	fi
1453	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1454	if ! mount -t devfs dev "$devdir"; then
1455		warn "$_me: Unable to mount devfs on $devdir"
1456		return 1
1457	fi
1458	if [ -n "$rs" ]; then
1459		devfs_init_rulesets
1460		devfs_set_ruleset $rs $devdir
1461		devfs -m $devdir rule applyset
1462	fi
1463	return 0
1464}
1465
1466# Provide a function for normalizing the mounting of memory
1467# filesystems.  This should allow the rest of the code here to remain
1468# as close as possible between 5-current and 4-stable.
1469#   $1 = size
1470#   $2 = mount point
1471#   $3 = (optional) extra mdmfs flags
1472mount_md()
1473{
1474	if [ -n "$3" ]; then
1475		flags="$3"
1476	fi
1477	/sbin/mdmfs $flags -s $1 md $2
1478}
1479
1480# Code common to scripts that need to load a kernel module
1481# if it isn't in the kernel yet. Syntax:
1482#   load_kld [-e regex] [-m module] file
1483# where -e or -m chooses the way to check if the module
1484# is already loaded:
1485#   regex is egrep'd in the output from `kldstat -v',
1486#   module is passed to `kldstat -m'.
1487# The default way is as though `-m file' were specified.
1488load_kld()
1489{
1490	local _loaded _mod _opt _re
1491
1492	while getopts "e:m:" _opt; do
1493		case "$_opt" in
1494		e) _re="$OPTARG" ;;
1495		m) _mod="$OPTARG" ;;
1496		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1497		esac
1498	done
1499	shift $(($OPTIND - 1))
1500	if [ $# -ne 1 ]; then
1501		err 3 'USAGE: load_kld [-e regex] [-m module] file'
1502	fi
1503	_mod=${_mod:-$1}
1504	_loaded=false
1505	if [ -n "$_re" ]; then
1506		if kldstat -v | egrep -q -e "$_re"; then
1507			_loaded=true
1508		fi
1509	else
1510		if kldstat -q -m "$_mod"; then
1511			_loaded=true
1512		fi
1513	fi
1514	if ! $_loaded; then
1515		if ! kldload "$1"; then
1516			warn "Unable to load kernel module $1"
1517			return 1
1518		else
1519			info "$1 kernel module loaded."
1520		fi
1521	else
1522		debug "load_kld: $1 kernel module already loaded."
1523	fi
1524	return 0
1525}
1526
1527# ltr str src dst
1528#	Change every $src in $str to $dst.
1529#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1530#	awk(1).
1531ltr()
1532{
1533	local _str _src _dst _out _com
1534	_str=$1
1535	_src=$2
1536	_dst=$3
1537	_out=""
1538
1539	IFS=${_src}
1540	for _com in ${_str}; do
1541		if [ -z "${_out}" ]; then
1542			_out="${_com}"
1543		else
1544			_out="${_out}${_dst}${_com}"
1545		fi
1546	done
1547	echo "${_out}"
1548}
1549
1550# Creates a list of providers for GELI encryption.
1551geli_make_list()
1552{
1553	local devices devices2
1554	local provider mountpoint type options rest
1555
1556	# Create list of GELI providers from fstab.
1557	while read provider mountpoint type options rest ; do
1558		case ":${options}" in
1559		:*noauto*)
1560			noauto=yes
1561			;;
1562		*)
1563			noauto=no
1564			;;
1565		esac
1566
1567		case ":${provider}" in
1568		:#*)
1569			continue
1570			;;
1571		*.eli)
1572			# Skip swap devices.
1573			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1574				continue
1575			fi
1576			devices="${devices} ${provider}"
1577			;;
1578		esac
1579	done < /etc/fstab
1580
1581	# Append providers from geli_devices.
1582	devices="${devices} ${geli_devices}"
1583
1584	for provider in ${devices}; do
1585		provider=${provider%.eli}
1586		provider=${provider#/dev/}
1587		devices2="${devices2} ${provider}"
1588	done
1589
1590	echo ${devices2}
1591}
1592
1593# Find scripts in local_startup directories that use the old syntax
1594#
1595find_local_scripts_old() {
1596	zlist=''
1597	slist=''
1598	for dir in ${local_startup}; do
1599		if [ -d "${dir}" ]; then
1600			for file in ${dir}/[0-9]*.sh; do
1601				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1602				    continue
1603				zlist="$zlist $file"
1604			done
1605			for file in ${dir}/[!0-9]*.sh; do
1606				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1607				    continue
1608				slist="$slist $file"
1609			done
1610		fi
1611	done
1612}
1613
1614find_local_scripts_new() {
1615	local_rc=''
1616	for dir in ${local_startup}; do
1617		if [ -d "${dir}" ]; then
1618			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1619				case "$file" in
1620				*.sample) ;;
1621				*)	if [ -x "$file" ]; then
1622						local_rc="${local_rc} ${file}"
1623					fi
1624					;;
1625				esac
1626			done
1627		fi
1628	done
1629}
1630
1631# check_required_{before|after} command
1632#	Check for things required by the command before and after its precmd,
1633#	respectively.  The two separate functions are needed because some
1634#	conditions should prevent precmd from being run while other things
1635#	depend on precmd having already been run.
1636#
1637check_required_before()
1638{
1639	local _f
1640
1641	case "$1" in
1642	start)
1643		for _f in $required_vars; do
1644			if ! checkyesno $_f; then
1645				warn "\$${_f} is not enabled."
1646				if [ -z "$rc_force" ]; then
1647					return 1
1648				fi
1649			fi
1650		done
1651
1652		for _f in $required_dirs; do
1653			if [ ! -d "${_f}/." ]; then
1654				warn "${_f} is not a directory."
1655				if [ -z "$rc_force" ]; then
1656					return 1
1657				fi
1658			fi
1659		done
1660
1661		for _f in $required_files; do
1662			if [ ! -r "${_f}" ]; then
1663				warn "${_f} is not readable."
1664				if [ -z "$rc_force" ]; then
1665					return 1
1666				fi
1667			fi
1668		done
1669		;;
1670	esac
1671
1672	return 0
1673}
1674
1675check_required_after()
1676{
1677	local _f _args
1678
1679	case "$1" in
1680	start)
1681		for _f in $required_modules; do
1682			case "${_f}" in
1683				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
1684				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
1685				*)	_args="${_f}" ;;
1686			esac
1687			if ! load_kld ${_args}; then
1688				if [ -z "$rc_force" ]; then
1689					return 1
1690				fi
1691			fi
1692		done
1693		;;
1694	esac
1695
1696	return 0
1697}
1698
1699# check_kern_features mib
1700#	Return existence of kern.features.* sysctl MIB as true or
1701#	false.  The result will be cached in $_rc_cache_kern_features_
1702#	namespace.  "0" means the kern.features.X exists.
1703
1704check_kern_features()
1705{
1706	local _v
1707
1708	[ -n "$1" ] || return 1;
1709	eval _v=\$_rc_cache_kern_features_$1
1710	[ -n "$_v" ] && return "$_v";
1711
1712	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1713		eval _rc_cache_kern_features_$1=0
1714		return 0
1715	else
1716		eval _rc_cache_kern_features_$1=1
1717		return 1
1718	fi
1719}
1720
1721# check_namevarlist var
1722#	Return "0" if ${name}_var is reserved in rc.subr.
1723
1724_rc_namevarlist="program chroot chdir flags fib nice user group groups"
1725check_namevarlist()
1726{
1727	local _v
1728
1729	for _v in $_rc_namevarlist; do
1730	case $1 in
1731	$_v)	return 0 ;;
1732	esac
1733	done
1734
1735	return 1
1736}
1737
1738# _echoonce var msg mode
1739#	mode=0: Echo $msg if ${$var} is empty.
1740#	        After doing echo, a string is set to ${$var}.
1741#
1742#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
1743#
1744_echoonce()
1745{
1746	local _var _msg _mode
1747	eval _var=\$$1
1748	_msg=$2
1749	_mode=$3
1750
1751	case $_mode in
1752	1)	[ -n "$_var" ] && echo "$_msg" ;;
1753	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1754	esac
1755}
1756
1757fi # [ -z "${_rc_subr_loaded}" ]
1758
1759_rc_subr_loaded=:
1760