rc.subr revision 231667
1# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2# $FreeBSD: head/etc/rc.subr 231667 2012-02-14 10:51:24Z dougb $
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}: ${_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}_nice	n	Nice level to run ${command} at.
466#
467#	${name}_user	n	User to run ${command} as, using su(1) if not
468#				using ${name}_chroot.
469#				Requires /usr to be mounted.
470#
471#	${name}_group	n	Group to run chrooted ${command} as.
472#				Requires /usr to be mounted.
473#
474#	${name}_groups	n	Comma separated list of supplementary groups
475#				to run the chrooted ${command} with.
476#				Requires /usr to be mounted.
477#
478#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
479#				Otherwise, use default command (see below)
480#
481#	${rc_arg}_precmd n	If set, run just before performing the
482#				${rc_arg}_cmd method in the default
483#				operation (i.e, after checking for required
484#				bits and process (non)existence).
485#				If this completes with a non-zero exit code,
486#				don't run ${rc_arg}_cmd.
487#
488#	${rc_arg}_postcmd n	If set, run just after performing the
489#				${rc_arg}_cmd method, if that method
490#				returned a zero exit code.
491#
492#	required_dirs	n	If set, check for the existence of the given
493#				directories before running a (re)start command.
494#
495#	required_files	n	If set, check for the readability of the given
496#				files before running a (re)start command.
497#
498#	required_modules n	If set, ensure the given kernel modules are
499#				loaded before running a (re)start command.
500#				The check and possible loads are actually
501#				done after start_precmd so that the modules
502#				aren't loaded in vain, should the precmd
503#				return a non-zero status to indicate a error.
504#				If a word in the list looks like "foo:bar",
505#				"foo" is the KLD file name and "bar" is the
506#				module name.  If a word looks like "foo~bar",
507#				"foo" is the KLD file name and "bar" is a
508#				egrep(1) pattern matching the module name.
509#				Otherwise the module name is assumed to be
510#				the same as the KLD file name, which is most
511#				common.  See load_kld().
512#
513#	required_vars	n	If set, perform checkyesno on each of the
514#				listed variables before running the default
515#				(re)start command.
516#
517#	Default behaviour for a given argument, if no override method is
518#	provided:
519#
520#	Argument	Default behaviour
521#	--------	-----------------
522#	start		if !running && checkyesno ${rcvar}
523#				${command}
524#
525#	stop		if ${pidfile}
526#				rc_pid=$(check_pidfile $pidfile $command)
527#			else
528#				rc_pid=$(check_process $command)
529#			kill $sig_stop $rc_pid
530#			wait_for_pids $rc_pid
531#			($sig_stop defaults to TERM.)
532#
533#	reload		Similar to stop, except use $sig_reload instead,
534#			and doesn't wait_for_pids.
535#			$sig_reload defaults to HUP.
536#			Note that `reload' isn't provided by default,
537#			it should be enabled via $extra_commands.
538#
539#	restart		Run `stop' then `start'.
540#
541#	status		Show if ${command} is running, etc.
542#
543#	poll		Wait for ${command} to exit.
544#
545#	rcvar		Display what rc.conf variable is used (if any).
546#
547#	Variables available to methods, and after run_rc_command() has
548#	completed:
549#
550#	Variable	Purpose
551#	--------	-------
552#	rc_arg		Argument to command, after fast/force/one processing
553#			performed
554#
555#	rc_flags	Flags to start the default command with.
556#			Defaults to ${name}_flags, unless overridden
557#			by $flags from the environment.
558#			This variable may be changed by the precmd method.
559#
560#	rc_pid		PID of command (if appropriate)
561#
562#	rc_fast		Not empty if "fast" was provided (q.v.)
563#
564#	rc_force	Not empty if "force" was provided (q.v.)
565#
566#	rc_quiet	Not empty if "quiet" was provided
567#
568#
569run_rc_command()
570{
571	_return=0
572	rc_arg=$1
573	if [ -z "$name" ]; then
574		err 3 'run_rc_command: $name is not set.'
575	fi
576
577	# Don't repeat the first argument when passing additional command-
578	# line arguments to the command subroutines.
579	#
580	shift 1
581	rc_extra_args="$*"
582
583	_rc_prefix=
584	case "$rc_arg" in
585	fast*)				# "fast" prefix; don't check pid
586		rc_arg=${rc_arg#fast}
587		rc_fast=yes
588		rc_quiet=yes
589		;;
590	force*)				# "force" prefix; always run
591		rc_force=yes
592		_rc_prefix=force
593		rc_arg=${rc_arg#${_rc_prefix}}
594		if [ -n "${rcvar}" ]; then
595			eval ${rcvar}=YES
596		fi
597		;;
598	one*)				# "one" prefix; set ${rcvar}=yes
599		_rc_prefix=one
600		rc_arg=${rc_arg#${_rc_prefix}}
601		if [ -n "${rcvar}" ]; then
602			eval ${rcvar}=YES
603		fi
604		;;
605	quiet*)				# "quiet" prefix; omit some messages
606		_rc_prefix=quiet
607		rc_arg=${rc_arg#${_rc_prefix}}
608		rc_quiet=yes
609		;;
610	esac
611
612	eval _override_command=\$${name}_program
613	command=${_override_command:-$command}
614
615	_keywords="start stop restart rcvar $extra_commands"
616	rc_pid=
617	_pidcmd=
618	_procname=${procname:-${command}}
619
620					# setup pid check command
621	if [ -n "$_procname" ]; then
622		if [ -n "$pidfile" ]; then
623			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
624		else
625			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
626		fi
627		if [ -n "$_pidcmd" ]; then
628			_keywords="${_keywords} status poll"
629		fi
630	fi
631
632	if [ -z "$rc_arg" ]; then
633		rc_usage $_keywords
634	fi
635
636	if [ -n "$flags" ]; then	# allow override from environment
637		rc_flags=$flags
638	else
639		eval rc_flags=\$${name}_flags
640	fi
641	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
642	    _nice=\$${name}_nice	_user=\$${name}_user \
643	    _group=\$${name}_group	_groups=\$${name}_groups
644
645	if [ -n "$_user" ]; then	# unset $_user if running as that user
646		if [ "$_user" = "$(eval $IDCMD)" ]; then
647			unset _user
648		fi
649	fi
650
651	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
652
653	for _elem in $_keywords; do
654		if [ "$_elem" != "$rc_arg" ]; then
655			continue
656		fi
657					# if ${rcvar} is set, $1 is not "rcvar"
658					# and ${rc_pid} is not set, then run
659					#	checkyesno ${rcvar}
660					# and return if that failed
661					#
662		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
663		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
664			if ! checkyesno ${rcvar}; then
665				if [ -n "${rc_quiet}" ]; then
666					return 0
667				fi
668				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
669				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
670				echo "instead of '${rc_arg}'."
671				return 0
672			fi
673		fi
674
675					# if there's a custom ${XXX_cmd},
676					# run that instead of the default
677					#
678		eval _cmd=\$${rc_arg}_cmd \
679		     _precmd=\$${rc_arg}_precmd \
680		     _postcmd=\$${rc_arg}_postcmd
681
682		if [ -n "$_cmd" ]; then
683			_run_rc_precmd || return 1
684			_run_rc_doit "$_cmd $rc_extra_args" || return 1
685			_run_rc_postcmd
686			return $_return
687		fi
688
689		case "$rc_arg" in	# default operations...
690
691		status)
692			_run_rc_precmd || return 1
693			if [ -n "$rc_pid" ]; then
694				echo "${name} is running as pid $rc_pid."
695			else
696				echo "${name} is not running."
697				return 1
698			fi
699			_run_rc_postcmd
700			;;
701
702		start)
703			if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
704				echo 1>&2 "${name} already running? (pid=$rc_pid)."
705				return 1
706			fi
707
708			if [ ! -x ${_chroot}${_chroot:+"/"}${command} ]; then
709				warn "run_rc_command: cannot run $command"
710				return 1
711			fi
712
713			if ! _run_rc_precmd; then
714				warn "failed precmd routine for ${name}"
715				return 1
716			fi
717
718					# setup the full command to run
719					#
720			check_startmsgs && echo "Starting ${name}."
721			if [ -n "$_chroot" ]; then
722				_doit="\
723${_nice:+nice -n $_nice }\
724chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
725$_chroot $command $rc_flags $command_args"
726			else
727				_doit="\
728${_chdir:+cd $_chdir && }\
729$command $rc_flags $command_args"
730				if [ -n "$_user" ]; then
731				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
732				fi
733				if [ -n "$_nice" ]; then
734					if [ -z "$_user" ]; then
735						_doit="sh -c \"$_doit\""
736					fi
737					_doit="nice -n $_nice $_doit"
738				fi
739			fi
740
741					# run the full command
742					#
743			if ! _run_rc_doit "$_doit"; then
744				warn "failed to start ${name}"
745				return 1
746			fi
747
748					# finally, run postcmd
749					#
750			_run_rc_postcmd
751			;;
752
753		stop)
754			if [ -z "$rc_pid" ]; then
755				[ -n "$rc_fast" ] && return 0
756				_run_rc_notrunning
757				return 1
758			fi
759
760			_run_rc_precmd || return 1
761
762					# send the signal to stop
763					#
764			echo "Stopping ${name}."
765			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
766			_run_rc_doit "$_doit" || return 1
767
768					# wait for the command to exit,
769					# and run postcmd.
770			wait_for_pids $rc_pid
771
772			_run_rc_postcmd
773			;;
774
775		reload)
776			if [ -z "$rc_pid" ]; then
777				_run_rc_notrunning
778				return 1
779			fi
780
781			_run_rc_precmd || return 1
782
783			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
784			_run_rc_doit "$_doit" || return 1
785
786			_run_rc_postcmd
787			;;
788
789		restart)
790					# prevent restart being called more
791					# than once by any given script
792					#
793			if ${_rc_restart_done:-false}; then
794				return 0
795			fi
796			_rc_restart_done=true
797
798			_run_rc_precmd || return 1
799
800			# run those in a subshell to keep global variables
801			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
802			( run_rc_command ${_rc_prefix}start $rc_extra_args )
803			_return=$?
804			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
805
806			_run_rc_postcmd
807			;;
808
809		poll)
810			_run_rc_precmd || return 1
811			if [ -n "$rc_pid" ]; then
812				wait_for_pids $rc_pid
813			fi
814			_run_rc_postcmd
815			;;
816
817		rcvar)
818			echo -n "# $name"
819			if [ -n "$desc" ]; then
820				echo " : $desc"
821			else
822				echo ""
823			fi
824			echo "#"
825			# Get unique vars in $rcvar
826			for _v in $rcvar; do
827				case $v in
828				$_v\ *|\ *$_v|*\ $_v\ *) ;;
829				*)	v="${v# } $_v" ;;
830				esac
831			done
832
833			# Display variables.
834			for _v in $v; do
835				if [ -z "$_v" ]; then
836					continue
837				fi
838
839				eval _desc=\$${_v}_desc
840				eval _defval=\$${_v}_defval
841				_h="-"
842
843				eval echo \"$_v=\\\"\$$_v\\\"\"
844				# decode multiple lines of _desc
845				while [ -n "$_desc" ]; do
846					case $_desc in
847					*^^*)
848						echo "# $_h ${_desc%%^^*}"
849						_desc=${_desc#*^^}
850						_h=" "
851						;;
852					*)
853						echo "# $_h ${_desc}"
854						break
855						;;
856					esac
857				done
858				echo "#   (default: \"$_defval\")"
859			done
860			echo ""
861			;;
862
863		*)
864			rc_usage $_keywords
865			;;
866
867		esac
868		return $_return
869	done
870
871	echo 1>&2 "$0: unknown directive '$rc_arg'."
872	rc_usage $_keywords
873	# not reached
874}
875
876#
877# Helper functions for run_rc_command: common code.
878# They use such global variables besides the exported rc_* ones:
879#
880#	name	       R/W
881#	------------------
882#	_precmd		R
883#	_postcmd	R
884#	_return		W
885#
886_run_rc_precmd()
887{
888	check_required_before "$rc_arg" || return 1
889
890	if [ -n "$_precmd" ]; then
891		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
892		eval "$_precmd $rc_extra_args"
893		_return=$?
894
895		# If precmd failed and force isn't set, request exit.
896		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
897			return 1
898		fi
899	fi
900
901	check_required_after "$rc_arg" || return 1
902
903	return 0
904}
905
906_run_rc_postcmd()
907{
908	if [ -n "$_postcmd" ]; then
909		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
910		eval "$_postcmd $rc_extra_args"
911		_return=$?
912	fi
913	return 0
914}
915
916_run_rc_doit()
917{
918	debug "run_rc_command: doit: $*"
919	eval "$@"
920	_return=$?
921
922	# If command failed and force isn't set, request exit.
923	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
924		return 1
925	fi
926
927	return 0
928}
929
930_run_rc_notrunning()
931{
932	local _pidmsg
933
934	if [ -n "$pidfile" ]; then
935		_pidmsg=" (check $pidfile)."
936	else
937		_pidmsg=
938	fi
939	echo 1>&2 "${name} not running?${_pidmsg}"
940}
941
942_run_rc_killcmd()
943{
944	local _cmd
945
946	_cmd="kill -$1 $rc_pid"
947	if [ -n "$_user" ]; then
948		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
949	fi
950	echo "$_cmd"
951}
952
953#
954# run_rc_script file arg
955#	Start the script `file' with `arg', and correctly handle the
956#	return value from the script.
957#	If `file' ends with `.sh', it's sourced into the current environment
958#	when $rc_fast_and_loose is set, otherwise it is run as a child process.
959#	If `file' appears to be a backup or scratch file, ignore it.
960#	Otherwise if it is executable run as a child process.
961#
962run_rc_script()
963{
964	_file=$1
965	_arg=$2
966	if [ -z "$_file" -o -z "$_arg" ]; then
967		err 3 'USAGE: run_rc_script file arg'
968	fi
969
970	unset	name command command_args command_interpreter \
971		extra_commands pidfile procname \
972		rcvar rcvars_obsolete required_dirs required_files \
973		required_vars
974	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
975
976	case "$_file" in
977	/etc/rc.d/*.sh)			# no longer allowed in the base
978		warn "Ignoring old-style startup script $_file"
979		;;
980	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
981		warn "Ignoring scratch file $_file"
982		;;
983	*)				# run in subshell
984		if [ -x $_file ]; then
985			if [ -n "$rc_fast_and_loose" ]; then
986				set $_arg; . $_file
987			else
988				( trap "echo Script $_file interrupted; kill -QUIT $$" 3
989				  trap "echo Script $_file interrupted; exit 1" 2
990				  trap "echo Script $_file running" 29
991				  set $_arg; . $_file )
992			fi
993		fi
994		;;
995	esac
996}
997
998#
999# load_rc_config name
1000#	Source in the configuration file for a given name.
1001#
1002load_rc_config()
1003{
1004	local _name _rcvar_val _var _defval _v _msg _new
1005	_name=$1
1006	if [ -z "$_name" ]; then
1007		err 3 'USAGE: load_rc_config name'
1008	fi
1009
1010	if ${_rc_conf_loaded:-false}; then
1011		:
1012	else
1013		if [ -r /etc/defaults/rc.conf ]; then
1014			debug "Sourcing /etc/defaults/rc.conf"
1015			. /etc/defaults/rc.conf
1016			source_rc_confs
1017		elif [ -r /etc/rc.conf ]; then
1018			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1019			. /etc/rc.conf
1020		fi
1021		_rc_conf_loaded=true
1022	fi
1023	if [ -f /etc/rc.conf.d/"$_name" ]; then
1024		debug "Sourcing /etc/rc.conf.d/${_name}"
1025		. /etc/rc.conf.d/"$_name"
1026	fi
1027
1028	# Set defaults if defined.
1029	for _var in $rcvar; do
1030		eval _defval=\$${_var}_defval
1031		if [ -n "$_defval" ]; then
1032			eval : \${$_var:=\$${_var}_defval}
1033		fi
1034	done
1035
1036	# check obsolete rc.conf variables
1037	for _var in $rcvars_obsolete; do
1038		eval _v=\$$_var
1039		eval _msg=\$${_var}_obsolete_msg
1040		eval _new=\$${_var}_newvar
1041		case $_v in
1042		"")
1043			;;
1044		*)
1045			if [ -z "$_new" ]; then
1046				_msg="Ignored."
1047			else
1048				eval $_new=\"\$$_var\"
1049				if [ -z "$_msg" ]; then
1050					_msg="Use \$$_new instead."
1051				fi
1052			fi
1053			warn "\$$_var is obsolete.  $_msg"
1054			;;
1055		esac
1056	done
1057}
1058
1059#
1060# load_rc_config_var name var
1061#	Read the rc.conf(5) var for name and set in the
1062#	current shell, using load_rc_config in a subshell to prevent
1063#	unwanted side effects from other variable assignments.
1064#
1065load_rc_config_var()
1066{
1067	if [ $# -ne 2 ]; then
1068		err 3 'USAGE: load_rc_config_var name var'
1069	fi
1070	eval $(eval '(
1071		load_rc_config '$1' >/dev/null;
1072                if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1073			echo '$2'=\'\''${'$2'}\'\'';
1074		fi
1075	)' )
1076}
1077
1078#
1079# rc_usage commands
1080#	Print a usage string for $0, with `commands' being a list of
1081#	valid commands.
1082#
1083rc_usage()
1084{
1085	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1086
1087	_sep=
1088	for _elem; do
1089		echo -n 1>&2 "$_sep$_elem"
1090		_sep="|"
1091	done
1092	echo 1>&2 ")"
1093	exit 1
1094}
1095
1096#
1097# err exitval message
1098#	Display message to stderr and log to the syslog, and exit with exitval.
1099#
1100err()
1101{
1102	exitval=$1
1103	shift
1104
1105	if [ -x /usr/bin/logger ]; then
1106		logger "$0: ERROR: $*"
1107	fi
1108	echo 1>&2 "$0: ERROR: $*"
1109	exit $exitval
1110}
1111
1112#
1113# warn message
1114#	Display message to stderr and log to the syslog.
1115#
1116warn()
1117{
1118	if [ -x /usr/bin/logger ]; then
1119		logger "$0: WARNING: $*"
1120	fi
1121	echo 1>&2 "$0: WARNING: $*"
1122}
1123
1124#
1125# info message
1126#	Display informational message to stdout and log to syslog.
1127#
1128info()
1129{
1130	case ${rc_info} in
1131	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1132		if [ -x /usr/bin/logger ]; then
1133			logger "$0: INFO: $*"
1134		fi
1135		echo "$0: INFO: $*"
1136		;;
1137	esac
1138}
1139
1140#
1141# debug message
1142#	If debugging is enabled in rc.conf output message to stderr.
1143#	BEWARE that you don't call any subroutine that itself calls this
1144#	function.
1145#
1146debug()
1147{
1148	case ${rc_debug} in
1149	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1150		if [ -x /usr/bin/logger ]; then
1151			logger "$0: DEBUG: $*"
1152		fi
1153		echo 1>&2 "$0: DEBUG: $*"
1154		;;
1155	esac
1156}
1157
1158#
1159# backup_file action file cur backup
1160#	Make a backup copy of `file' into `cur', and save the previous
1161#	version of `cur' as `backup' or use rcs for archiving.
1162#
1163#	This routine checks the value of the backup_uses_rcs variable,
1164#	which can be either YES or NO.
1165#
1166#	The `action' keyword can be one of the following:
1167#
1168#	add		`file' is now being backed up (and is possibly
1169#			being reentered into the backups system).  `cur'
1170#			is created and RCS files, if necessary, are
1171#			created as well.
1172#
1173#	update		`file' has changed and needs to be backed up.
1174#			If `cur' exists, it is copied to to `back' or
1175#			checked into RCS (if the repository file is old),
1176#			and then `file' is copied to `cur'.  Another RCS
1177#			check in done here if RCS is being used.
1178#
1179#	remove		`file' is no longer being tracked by the backups
1180#			system.  If RCS is not being used, `cur' is moved
1181#			to `back', otherwise an empty file is checked in,
1182#			and then `cur' is removed.
1183#
1184#
1185backup_file()
1186{
1187	_action=$1
1188	_file=$2
1189	_cur=$3
1190	_back=$4
1191
1192	if checkyesno backup_uses_rcs; then
1193		_msg0="backup archive"
1194		_msg1="update"
1195
1196		# ensure that history file is not locked
1197		if [ -f $_cur,v ]; then
1198			rcs -q -u -U -M $_cur
1199		fi
1200
1201		# ensure after switching to rcs that the
1202		# current backup is not lost
1203		if [ -f $_cur ]; then
1204			# no archive, or current newer than archive
1205			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1206				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1207				rcs -q -kb -U $_cur
1208				co -q -f -u $_cur
1209			fi
1210		fi
1211
1212		case $_action in
1213		add|update)
1214			cp -p $_file $_cur
1215			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1216			rcs -q -kb -U $_cur
1217			co -q -f -u $_cur
1218			chown root:wheel $_cur $_cur,v
1219			;;
1220		remove)
1221			cp /dev/null $_cur
1222			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1223			rcs -q -kb -U $_cur
1224			chown root:wheel $_cur $_cur,v
1225			rm $_cur
1226			;;
1227		esac
1228	else
1229		case $_action in
1230		add|update)
1231			if [ -f $_cur ]; then
1232				cp -p $_cur $_back
1233			fi
1234			cp -p $_file $_cur
1235			chown root:wheel $_cur
1236			;;
1237		remove)
1238			mv -f $_cur $_back
1239			;;
1240		esac
1241	fi
1242}
1243
1244# make_symlink src link
1245#	Make a symbolic link 'link' to src from basedir. If the
1246#	directory in which link is to be created does not exist
1247#	a warning will be displayed and an error will be returned.
1248#	Returns 0 on success, 1 otherwise.
1249#
1250make_symlink()
1251{
1252	local src link linkdir _me
1253	src="$1"
1254	link="$2"
1255	linkdir="`dirname $link`"
1256	_me="make_symlink()"
1257
1258	if [ -z "$src" -o -z "$link" ]; then
1259		warn "$_me: requires two arguments."
1260		return 1
1261	fi
1262	if [ ! -d "$linkdir" ]; then
1263		warn "$_me: the directory $linkdir does not exist."
1264		return 1
1265	fi
1266	if ! ln -sf $src $link; then
1267		warn "$_me: unable to make a symbolic link from $link to $src"
1268		return 1
1269	fi
1270	return 0
1271}
1272
1273# devfs_rulesets_from_file file
1274#	Reads a set of devfs commands from file, and creates
1275#	the specified rulesets with their rules. Returns non-zero
1276#	if there was an error.
1277#
1278devfs_rulesets_from_file()
1279{
1280	local file _err _me
1281	file="$1"
1282	_me="devfs_rulesets_from_file"
1283	_err=0
1284
1285	if [ -z "$file" ]; then
1286		warn "$_me: you must specify a file"
1287		return 1
1288	fi
1289	if [ ! -e "$file" ]; then
1290		debug "$_me: no such file ($file)"
1291		return 0
1292	fi
1293	debug "reading rulesets from file ($file)"
1294	{ while read line
1295	do
1296		case $line in
1297		\#*)
1298			continue
1299			;;
1300		\[*\]*)
1301			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1302			if [ -z "$rulenum" ]; then
1303				warn "$_me: cannot extract rule number ($line)"
1304				_err=1
1305				break
1306			fi
1307			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1308			if [ -z "$rulename" ]; then
1309				warn "$_me: cannot extract rule name ($line)"
1310				_err=1
1311				break;
1312			fi
1313			eval $rulename=\$rulenum
1314			debug "found ruleset: $rulename=$rulenum"
1315			if ! /sbin/devfs rule -s $rulenum delset; then
1316				_err=1
1317				break
1318			fi
1319			;;
1320		*)
1321			rulecmd="${line%%"\#*"}"
1322			# evaluate the command incase it includes
1323			# other rules
1324			if [ -n "$rulecmd" ]; then
1325				debug "adding rule ($rulecmd)"
1326				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1327				then
1328					_err=1
1329					break
1330				fi
1331			fi
1332			;;
1333		esac
1334		if [ $_err -ne 0 ]; then
1335			debug "error in $_me"
1336			break
1337		fi
1338	done } < $file
1339	return $_err
1340}
1341
1342# devfs_init_rulesets
1343#	Initializes rulesets from configuration files. Returns
1344#	non-zero if there was an error.
1345#
1346devfs_init_rulesets()
1347{
1348	local file _me
1349	_me="devfs_init_rulesets"
1350
1351	# Go through this only once
1352	if [ -n "$devfs_rulesets_init" ]; then
1353		debug "$_me: devfs rulesets already initialized"
1354		return
1355	fi
1356	for file in $devfs_rulesets; do
1357		if ! devfs_rulesets_from_file $file; then
1358			warn "$_me: could not read rules from $file"
1359			return 1
1360		fi
1361	done
1362	devfs_rulesets_init=1
1363	debug "$_me: devfs rulesets initialized"
1364	return 0
1365}
1366
1367# devfs_set_ruleset ruleset [dir]
1368#	Sets the default ruleset of dir to ruleset. The ruleset argument
1369#	must be a ruleset name as specified in devfs.rules(5) file.
1370#	Returns non-zero if it could not set it successfully.
1371#
1372devfs_set_ruleset()
1373{
1374	local devdir rs _me
1375	[ -n "$1" ] && eval rs=\$$1 || rs=
1376	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1377	_me="devfs_set_ruleset"
1378
1379	if [ -z "$rs" ]; then
1380		warn "$_me: you must specify a ruleset number"
1381		return 1
1382	fi
1383	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1384	if ! /sbin/devfs $devdir ruleset $rs; then
1385		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1386		return 1
1387	fi
1388	return 0
1389}
1390
1391# devfs_apply_ruleset ruleset [dir]
1392#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1393#	The ruleset argument must be a ruleset name as specified
1394#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1395#	if it could not apply the ruleset.
1396#
1397devfs_apply_ruleset()
1398{
1399	local devdir rs _me
1400	[ -n "$1" ] && eval rs=\$$1 || rs=
1401	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1402	_me="devfs_apply_ruleset"
1403
1404	if [ -z "$rs" ]; then
1405		warn "$_me: you must specify a ruleset"
1406		return 1
1407	fi
1408	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1409	if ! /sbin/devfs $devdir rule -s $rs applyset; then
1410		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1411		return 1
1412	fi
1413	return 0
1414}
1415
1416# devfs_domount dir [ruleset]
1417#	Mount devfs on dir. If ruleset is specified it is set
1418#	on the mount-point. It must also be a ruleset name as specified
1419#	in a devfs.rules(5) file. Returns 0 on success.
1420#
1421devfs_domount()
1422{
1423	local devdir rs _me
1424	devdir="$1"
1425	[ -n "$2" ] && rs=$2 || rs=
1426	_me="devfs_domount()"
1427
1428	if [ -z "$devdir" ]; then
1429		warn "$_me: you must specify a mount-point"
1430		return 1
1431	fi
1432	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1433	if ! mount -t devfs dev "$devdir"; then
1434		warn "$_me: Unable to mount devfs on $devdir"
1435		return 1
1436	fi
1437	if [ -n "$rs" ]; then
1438		devfs_init_rulesets
1439		devfs_set_ruleset $rs $devdir
1440		devfs -m $devdir rule applyset
1441	fi
1442	return 0
1443}
1444
1445# devfs_mount_jail dir [ruleset]
1446#	Mounts a devfs file system appropriate for jails
1447#	on the directory dir. If ruleset is specified, the ruleset
1448#	it names will be used instead.  If present, ruleset must
1449#	be the name of a ruleset as defined in a devfs.rules(5) file.
1450#	This function returns non-zero if an error occurs.
1451#
1452devfs_mount_jail()
1453{
1454	local jdev rs _me
1455	jdev="$1"
1456	[ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1457	_me="devfs_mount_jail"
1458
1459	devfs_init_rulesets
1460	if ! devfs_domount "$jdev" $rs; then
1461		warn "$_me: devfs was not mounted on $jdev"
1462		return 1
1463	fi
1464	return 0
1465}
1466
1467# Provide a function for normalizing the mounting of memory
1468# filesystems.  This should allow the rest of the code here to remain
1469# as close as possible between 5-current and 4-stable.
1470#   $1 = size
1471#   $2 = mount point
1472#   $3 = (optional) extra mdmfs flags
1473mount_md()
1474{
1475	if [ -n "$3" ]; then
1476		flags="$3"
1477	fi
1478	/sbin/mdmfs $flags -s $1 md $2
1479}
1480
1481# Code common to scripts that need to load a kernel module
1482# if it isn't in the kernel yet. Syntax:
1483#   load_kld [-e regex] [-m module] file
1484# where -e or -m chooses the way to check if the module
1485# is already loaded:
1486#   regex is egrep'd in the output from `kldstat -v',
1487#   module is passed to `kldstat -m'.
1488# The default way is as though `-m file' were specified.
1489load_kld()
1490{
1491	local _loaded _mod _opt _re
1492
1493	while getopts "e:m:" _opt; do
1494		case "$_opt" in
1495		e) _re="$OPTARG" ;;
1496		m) _mod="$OPTARG" ;;
1497		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1498		esac
1499	done
1500	shift $(($OPTIND - 1))
1501	if [ $# -ne 1 ]; then
1502		err 3 'USAGE: load_kld [-e regex] [-m module] file'
1503	fi
1504	_mod=${_mod:-$1}
1505	_loaded=false
1506	if [ -n "$_re" ]; then
1507		if kldstat -v | egrep -q -e "$_re"; then
1508			_loaded=true
1509		fi
1510	else
1511		if kldstat -q -m "$_mod"; then
1512			_loaded=true
1513		fi
1514	fi
1515	if ! $_loaded; then
1516		if ! kldload "$1"; then
1517			warn "Unable to load kernel module $1"
1518			return 1
1519		else
1520			info "$1 kernel module loaded."
1521		fi
1522	else
1523		debug "load_kld: $1 kernel module already loaded."
1524	fi
1525	return 0
1526}
1527
1528# ltr str src dst
1529#	Change every $src in $str to $dst.
1530#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1531#	awk(1).
1532ltr()
1533{
1534	local _str _src _dst _out _com
1535	_str=$1
1536	_src=$2
1537	_dst=$3
1538	_out=""
1539
1540	IFS=${_src}
1541	for _com in ${_str}; do
1542		if [ -z "${_out}" ]; then
1543			_out="${_com}"
1544		else
1545			_out="${_out}${_dst}${_com}"
1546		fi
1547	done
1548	echo "${_out}"
1549}
1550
1551# Creates a list of providers for GELI encryption.
1552geli_make_list()
1553{
1554	local devices devices2
1555	local provider mountpoint type options rest
1556
1557	# Create list of GELI providers from fstab.
1558	while read provider mountpoint type options rest ; do
1559		case ":${options}" in
1560		:*noauto*)
1561			noauto=yes
1562			;;
1563		*)
1564			noauto=no
1565			;;
1566		esac
1567
1568		case ":${provider}" in
1569		:#*)
1570			continue
1571			;;
1572		*.eli)
1573			# Skip swap devices.
1574			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1575				continue
1576			fi
1577			devices="${devices} ${provider}"
1578			;;
1579		esac
1580	done < /etc/fstab
1581
1582	# Append providers from geli_devices.
1583	devices="${devices} ${geli_devices}"
1584
1585	for provider in ${devices}; do
1586		provider=${provider%.eli}
1587		provider=${provider#/dev/}
1588		devices2="${devices2} ${provider}"
1589	done
1590
1591	echo ${devices2}
1592}
1593
1594# Find scripts in local_startup directories that use the old syntax
1595#
1596find_local_scripts_old () {
1597	zlist=''
1598	slist=''
1599	for dir in ${local_startup}; do
1600		if [ -d "${dir}" ]; then
1601			for file in ${dir}/[0-9]*.sh; do
1602				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1603				    continue
1604				zlist="$zlist $file"
1605			done
1606			for file in ${dir}/[!0-9]*.sh; do
1607				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1608				    continue
1609				slist="$slist $file"
1610			done
1611		fi
1612	done
1613}
1614
1615find_local_scripts_new () {
1616	local_rc=''
1617	for dir in ${local_startup}; do
1618		if [ -d "${dir}" ]; then
1619			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1620				case "$file" in
1621				*.sample) ;;
1622				*)	if [ -x "$file" ]; then
1623						local_rc="${local_rc} ${file}"
1624					fi
1625					;;
1626				esac
1627			done
1628		fi
1629	done
1630}
1631
1632# check_required_{before|after} command
1633#	Check for things required by the command before and after its precmd,
1634#	respectively.  The two separate functions are needed because some
1635#	conditions should prevent precmd from being run while other things
1636#	depend on precmd having already been run.
1637#
1638check_required_before()
1639{
1640	local _f
1641
1642	case "$1" in
1643	start)
1644		for _f in $required_vars; do
1645			if ! checkyesno $_f; then
1646				warn "\$${_f} is not enabled."
1647				if [ -z "$rc_force" ]; then
1648					return 1
1649				fi
1650			fi
1651		done
1652
1653		for _f in $required_dirs; do
1654			if [ ! -d "${_f}/." ]; then
1655				warn "${_f} is not a directory."
1656				if [ -z "$rc_force" ]; then
1657					return 1
1658				fi
1659			fi
1660		done
1661
1662		for _f in $required_files; do
1663			if [ ! -r "${_f}" ]; then
1664				warn "${_f} is not readable."
1665				if [ -z "$rc_force" ]; then
1666					return 1
1667				fi
1668			fi
1669		done
1670		;;
1671	esac
1672
1673	return 0
1674}
1675
1676check_required_after()
1677{
1678	local _f _args
1679
1680	case "$1" in
1681	start)
1682		for _f in $required_modules; do
1683			case "${_f}" in
1684				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
1685				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
1686				*)	_args="${_f}" ;;
1687			esac
1688			if ! load_kld ${_args}; then
1689				if [ -z "$rc_force" ]; then
1690					return 1
1691				fi
1692			fi
1693		done
1694		;;
1695	esac
1696
1697	return 0
1698}
1699
1700# check_kern_features mib
1701#	Return existence of kern.features.* sysctl MIB as true or
1702#	false.  The result will be cached in $_rc_cache_kern_features_
1703#	namespace.  "0" means the kern.features.X exists.
1704
1705check_kern_features()
1706{
1707	local _v
1708
1709	[ -n "$1" ] || return 1;
1710	eval _v=\$_rc_cache_kern_features_$1
1711	[ -n "$_v" ] && return "$_v";
1712
1713	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1714		eval _rc_cache_kern_features_$1=0
1715		return 0
1716	else
1717		eval _rc_cache_kern_features_$1=1
1718		return 1
1719	fi
1720}
1721
1722# _echoonce var msg mode
1723#	mode=0: Echo $msg if ${$var} is empty.
1724#	        After doing echo, a string is set to ${$var}.
1725#
1726#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
1727#
1728_echoonce()
1729{
1730	local _var _msg _mode
1731	eval _var=\$$1
1732	_msg=$2
1733	_mode=$3
1734
1735	case $_mode in
1736	1)	[ -n "$_var" ] && echo "$_msg" ;;
1737	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1738	esac
1739}
1740
1741fi # [ -z "${_rc_subr_loaded}" ]
1742
1743_rc_subr_loaded=:
1744