xref: /freebsd/libexec/rc/rc.subr (revision e2257b31)
1# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2#
3# Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
4# All rights reserved.
5#
6# This code is derived from software contributed to The NetBSD Foundation
7# by Luke Mewburn.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12# 1. Redistributions of source code must retain the above copyright
13#    notice, this list of conditions and the following disclaimer.
14# 2. Redistributions in binary form must reproduce the above copyright
15#    notice, this list of conditions and the following disclaimer in the
16#    documentation and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
22# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29#
30# rc.subr
31#	functions used by various rc scripts
32#
33
34: ${RC_PID:=$$}; export RC_PID
35
36#
37#	Operating System dependent/independent variables
38#
39
40if [ -n "${_rc_subr_loaded}" ]; then
41	return
42fi
43
44_rc_subr_loaded="YES"
45
46SYSCTL="/sbin/sysctl"
47SYSCTL_N="${SYSCTL} -n"
48SYSCTL_W="${SYSCTL}"
49PROTECT="/usr/bin/protect"
50ID="/usr/bin/id"
51IDCMD="if [ -x $ID ]; then $ID -un; fi"
52PS="/bin/ps -ww"
53JID=0
54CPUSET="/bin/cpuset"
55
56# rc_service provides the path to the service script that we are executing.
57# This is not being set here in an execution context, necessarily, so it's
58# really just a reasonable guess, and it will get overwritten later if
59# we are executing from some other means than direct execution by service(8)
60# or manual invocation of the service script.  The prime example of this is
61# during system startup, all rc scripts will be invoked via /etc/rc, so
62# run_rc_script will overwrite rc_service with the file being sourced.
63rc_service="$0"
64
65#
66#	functions
67#	---------
68
69# is_verified file
70#	if VERIEXEC is active check that $file is verified
71#
72VERIEXEC="/sbin/veriexec"
73if test -x $VERIEXEC && $VERIEXEC -i active > /dev/null 2>&1; then
74	is_verified() { $VERIEXEC -x $1; }
75else
76	is_verified() { return 0; }
77fi
78
79# indicate that we have vdot
80_VDOT_SH=:
81
82# current state of O_VERIFY
83o_verify()
84{
85	case $(echo $(set -o)) in
86	*verify" "off*) echo off;;
87	*verify" "on*) echo on;;
88	esac
89}
90
91##
92# o_verify_set want [save]
93#
94# record current state of verify in $save
95# and set it to $want if different
96#
97o_verify_set() {
98	local x=$(o_verify)
99
100	[ -z "$x" ] && return 0
101	[ -z "$2" ] || eval $2=$x
102	[ "$x" = "$1" ] && return 0
103	case "$1" in
104	on)
105		set -o verify
106		;;
107	off)
108		set +o verify
109		;;
110	esac
111}
112
113# for unverified files
114dotted=
115dot()
116{
117	local f verify
118
119	o_verify_set off verify
120	for f in "$@"; do
121		if [ -f $f -a -s $f ]; then
122			dotted="$dotted $f"
123			. $f
124		fi
125	done
126	o_verify_set $verify
127}
128
129# try for verified, fallback to safe
130sdot()
131{
132	local f
133
134	for f in "$@"; do
135		[ -f $f -a -s $f ] || continue
136		vdot $f || safe_dot $f
137	done
138}
139
140# convenience function - skip if not verified
141vdot()
142{
143	local f rc=0 verify
144
145	o_verify_set on verify
146	for f in "$@"; do
147		[ -f $f -a -s $f ] || continue
148		if is_verified $f 2> /dev/null; then
149			dotted="$dotted $f"
150			. $f
151		else
152			rc=80	# EAUTH
153		fi
154	done
155	o_verify_set $verify
156	return $rc
157}
158
159# Exists [test] file ...
160# report the first "file" that passes "test" (default -s).
161Exists()
162{
163	local f _t=-s
164
165	while :; do
166		: 1=$1
167		case "$1" in
168		-?)
169			_t=$1
170			shift
171			;;
172		*)
173			break
174			;;
175		esac
176	done
177
178	for f in "$@"; do
179		[ $_t $f ] || continue
180		echo $f
181		return 0
182	done
183	return 1
184}
185
186# do we have $1 (could be a function)
187have()
188{
189       type "$1" > /dev/null 2>&1
190}
191
192# provide consistent means of logging progress
193rc_log()
194{
195	date "+@ %s [%Y-%m-%d %H:%M:%S %Z] $*"
196}
197
198# only rc_log if tracing enabled
199# and $level >= $RC_LEVEL
200rc_trace()
201{
202	local level=$1; shift
203	local cf=/etc/rc.conf.d/rc_trace
204
205	if [ -z "$RC_LEVEL" ]; then
206		[ -f $cf ] || return
207		if [ -s $cf ]; then
208			# don't try to set RC_LEVEL without sed
209			if [ -n "$SED" ]; then
210				RC_LEVEL=$($SED -n '/^RC_LEVEL=/ { s/.*=//p;q; }' $cf)
211				RC_LEVEL=${RC_LEVEL:-0}
212			fi
213		else
214			RC_LEVEL=0
215		fi
216	fi
217	[ ${RC_LEVEL:-0} -ge ${level:-0} ] || return
218	rc_log "$@"
219}
220
221# list_vars pattern
222#	List variables matching glob pattern.
223#
224list_vars()
225{
226	# Localize 'set' option below.
227	local -
228	local IFS=$'\n' line varname
229
230	# Disable path expansion in unquoted 'for' parameters below.
231	set -o noglob
232
233	for line in $(set); do
234		varname="${line%%=*}"
235
236		case "$varname" in
237		"$line"|*[!a-zA-Z0-9_]*)
238			continue
239			;;
240		$1)
241			echo $varname
242			;;
243		esac
244	done
245}
246
247# set_rcvar [var] [defval] [desc]
248#
249#	Echo or define a rc.conf(5) variable name.  Global variable
250#	$rcvars is used.
251#
252#	If no argument is specified, echo "${name}_enable".
253#
254#	If only a var is specified, echo "${var}_enable".
255#
256#	If var and defval are specified, the ${var} is defined as
257#	rc.conf(5) variable and the default value is ${defvar}.  An
258#	optional argument $desc can also be specified to add a
259#	description for that.
260#
261set_rcvar()
262{
263	local _var
264
265	case $# in
266	0)	echo ${name}_enable ;;
267	1)	echo ${1}_enable ;;
268	*)
269		debug "set_rcvar: \$$1=$2 is added" \
270		    " as a rc.conf(5) variable."
271		_var=$1
272		rcvars="${rcvars# } $_var"
273		eval ${_var}_defval=\"$2\"
274		shift 2
275		eval ${_var}_desc=\"$*\"
276	;;
277	esac
278}
279
280# set_rcvar_obsolete oldvar [newvar] [msg]
281#	Define obsolete variable.
282#	Global variable $rcvars_obsolete is used.
283#
284set_rcvar_obsolete()
285{
286	local _var
287	_var=$1
288	debug "set_rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
289
290	rcvars_obsolete="${rcvars_obsolete# } $1"
291	eval ${1}_newvar=\"$2\"
292	shift 2
293	eval ${_var}_obsolete_msg=\"$*\"
294}
295
296#
297# force_depend script [rcvar]
298#	Force a service to start. Intended for use by services
299#	to resolve dependency issues.
300#	$1 - filename of script, in /etc/rc.d, to run
301#	$2 - name of the script's rcvar (minus the _enable)
302#
303force_depend()
304{
305	local _depend _dep_rcvar
306
307	_depend="$1"
308	_dep_rcvar="${2:-$1}_enable"
309
310	[ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
311	    checkyesno $_dep_rcvar && return 0
312
313	/etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
314
315	info "${name} depends on ${_depend}, which will be forced to start."
316	if ! /etc/rc.d/${_depend} forcestart; then
317		warn "Unable to force ${_depend}. It may already be running."
318		return 1
319	fi
320}
321
322#
323# checkyesno var
324#	Test $1 variable, and warn if not set to YES or NO.
325#	Return 0 if it's "yes" (et al), nonzero otherwise.
326#
327checkyesno()
328{
329	eval _value=\$${1}
330	debug "checkyesno: $1 is set to $_value."
331	case $_value in
332
333		#	"yes", "true", "on", or "1"
334	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
335		return 0
336		;;
337
338		#	"no", "false", "off", or "0"
339	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
340		return 1
341		;;
342	*)
343		warn "\$${1} is not set properly - see rc.conf(5)."
344		return 1
345		;;
346	esac
347}
348
349#
350# reverse_list list
351#	print the list in reverse order
352#
353reverse_list()
354{
355	_revlist=
356	for _revfile; do
357		_revlist="$_revfile $_revlist"
358	done
359	echo $_revlist
360}
361
362# stop_boot always
363#	If booting directly to multiuser or $always is enabled,
364#	send SIGTERM to the parent (/etc/rc) to abort the boot.
365#	Otherwise just exit.
366#
367stop_boot()
368{
369	local always
370
371	case $1 in
372		#	"yes", "true", "on", or "1"
373	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
374		always=true
375		;;
376	*)
377		always=false
378		;;
379	esac
380	if [ "$autoboot" = yes -o "$always" = true ]; then
381		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
382		kill -TERM ${RC_PID}
383	fi
384	exit 1
385}
386
387#
388# mount_critical_filesystems type
389#	Go through the list of critical filesystems as provided in
390#	the rc.conf(5) variable $critical_filesystems_${type}, checking
391#	each one to see if it is mounted, and if it is not, mounting it.
392#
393mount_critical_filesystems()
394{
395	eval _fslist=\$critical_filesystems_${1}
396	for _fs in $_fslist; do
397		mount | (
398			_ismounted=false
399			while read what _on on _type type; do
400				if [ $on = $_fs ]; then
401					_ismounted=true
402				fi
403			done
404			if $_ismounted; then
405				:
406			else
407				mount $_fs >/dev/null 2>&1
408			fi
409		)
410	done
411}
412
413#
414# check_pidfile pidfile procname [interpreter]
415#	Parses the first line of pidfile for a PID, and ensures
416#	that the process is running and matches procname.
417#	Prints the matching PID upon success, nothing otherwise.
418#	interpreter is optional; see _find_processes() for details.
419#
420check_pidfile()
421{
422	_pidfile=$1
423	_procname=$2
424	_interpreter=$3
425	if [ -z "$_pidfile" -o -z "$_procname" ]; then
426		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
427	fi
428	if [ ! -f $_pidfile ]; then
429		debug "pid file ($_pidfile): not readable."
430		return
431	fi
432	read _pid _junk < $_pidfile
433	if [ -z "$_pid" ]; then
434		debug "pid file ($_pidfile): no pid in file."
435		return
436	fi
437	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
438}
439
440#
441# check_process procname [interpreter]
442#	Ensures that a process (or processes) named procname is running.
443#	Prints a list of matching PIDs.
444#	interpreter is optional; see _find_processes() for details.
445#
446check_process()
447{
448	_procname=$1
449	_interpreter=$2
450	if [ -z "$_procname" ]; then
451		err 3 'USAGE: check_process procname [interpreter]'
452	fi
453	_find_processes $_procname ${_interpreter:-.} '-ax'
454}
455
456#
457# _find_processes procname interpreter psargs
458#	Search for procname in the output of ps generated by psargs.
459#	Prints the PIDs of any matching processes, space separated.
460#
461#	If interpreter == ".", check the following variations of procname
462#	against the first word of each command:
463#		procname
464#		`basename procname`
465#		`basename procname` + ":"
466#		"(" + `basename procname` + ")"
467#		"[" + `basename procname` + "]"
468#
469#	If interpreter != ".", read the first line of procname, remove the
470#	leading #!, normalise whitespace, append procname, and attempt to
471#	match that against each command, either as is, or with extra words
472#	at the end.  As an alternative, to deal with interpreted daemons
473#	using perl, the basename of the interpreter plus a colon is also
474#	tried as the prefix to procname.
475#
476_find_processes()
477{
478	if [ $# -ne 3 ]; then
479		err 3 'USAGE: _find_processes procname interpreter psargs'
480	fi
481	_procname=$1
482	_interpreter=$2
483	_psargs=$3
484
485	_pref=
486	if [ $_interpreter != "." ]; then	# an interpreted script
487		_script="${_chroot}${_chroot:+/}$_procname"
488		if [ -r "$_script" ]; then
489			read _interp < $_script	# read interpreter name
490			case "$_interp" in
491			\#!*)
492				_interp=${_interp#\#!}	# strip #!
493				set -- $_interp
494				case $1 in
495				*/bin/env)
496					shift	# drop env to get real name
497					;;
498				esac
499				if [ $_interpreter != $1 ]; then
500					warn "\$command_interpreter $_interpreter != $1"
501				fi
502				;;
503			*)
504				warn "no shebang line in $_script"
505				set -- $_interpreter
506				;;
507			esac
508		else
509			warn "cannot read shebang line from $_script"
510			set -- $_interpreter
511		fi
512		_interp="$* $_procname"		# cleanup spaces, add _procname
513		_interpbn=${1##*/}
514		_fp_args='_argv'
515		_fp_match='case "$_argv" in
516		    ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
517	else					# a normal daemon
518		_procnamebn=${_procname##*/}
519		_fp_args='_arg0 _argv'
520		_fp_match='case "$_arg0" in
521		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
522	fi
523
524	_proccheck="\
525		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
526		while read _npid _jid '"$_fp_args"'; do
527			'"$_fp_match"'
528				if [ "$JID" -eq "$_jid" ];
529				then echo -n "$_pref$_npid";
530				_pref=" ";
531				fi
532				;;
533			esac
534		done'
535
536#	debug "in _find_processes: proccheck is ($_proccheck)."
537	eval $_proccheck
538}
539
540# sort_lite [-b] [-n] [-k POS] [-t SEP]
541#	A lite version of sort(1) (supporting a few options) that can be used
542#	before the real sort(1) is available (e.g., in scripts that run prior
543#	to mountcritremote). Requires only shell built-in functionality.
544#
545sort_lite()
546{
547	local funcname=sort_lite
548	local sort_sep="$IFS" sort_ignore_leading_space=
549	local sort_field=0 sort_strict_fields= sort_numeric=
550	local nitems=0 skip_leading=0 trim=
551
552	local OPTIND flag
553	while getopts bnk:t: flag; do
554		case "$flag" in
555		b) sort_ignore_leading_space=1 ;;
556		n) sort_numeric=1 sort_ignore_leading_space=1 ;;
557		k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
558			# NB: Unlike sort(1) only one POS allowed
559		t) sort_sep="$OPTARG"
560		   if [ ${#sort_sep} -gt 1 ]; then
561		   	echo "$funcname: multi-character tab \`$sort_sep'" >&2
562		   	return 1
563		   fi
564		   sort_strict_fields=1
565		   ;;
566		\?) return 1 ;;
567		esac
568	done
569	shift $(( $OPTIND - 1 ))
570
571	# Create transformation pattern to trim leading text if desired
572	case "$sort_field" in
573	""|[!0-9]*|*[!0-9.]*)
574		echo "$funcname: invalid sort field \`$sort_field'" >&2
575		return 1
576		;;
577	*.*)
578		skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
579		while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
580			trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
581		done
582	esac
583
584	# Copy input to series of local numbered variables
585	# NB: IFS of NULL preserves leading whitespace
586	local LINE
587	while IFS= read -r LINE || [ "$LINE" ]; do
588		nitems=$(( $nitems + 1 ))
589		local src_$nitems="$LINE"
590	done
591
592	#
593	# Sort numbered locals using insertion sort
594	#
595	local curitem curitem_orig curitem_mod curitem_haskey
596	local dest dest_orig dest_mod dest_haskey
597	local d gt n
598	local i=1
599	while [ $i -le $nitems ]; do
600		curitem_haskey=1 # Assume sort field (-k POS) exists
601		eval curitem=\"\$src_$i\"
602		curitem_mod="$curitem" # for modified comparison
603		curitem_orig="$curitem" # for original comparison
604
605		# Trim leading whitespace if desired
606		if [ "$sort_ignore_leading_space" ]; then
607			while case "$curitem_orig" in
608				[$IFS]*) : ;; *) false; esac
609			do
610				curitem_orig="${curitem_orig#?}"
611			done
612			curitem_mod="$curitem_orig"
613		fi
614
615		# Shift modified comparison value if sort field (-k POS) is > 1
616		n=$sort_field
617		while [ $n -gt 1 ]; do
618			case "$curitem_mod" in
619			*[$sort_sep]*)
620				# Cut text up-to (and incl.) first separator
621				curitem_mod="${curitem_mod#*[$sort_sep]}"
622
623				# Skip NULLs unless strict field splitting
624				[ "$sort_strict_fields" ] ||
625					[ "${curitem_mod%%[$sort_sep]*}" ] ||
626					[ $n -eq 2 ] ||
627					continue
628				;;
629			*)
630				# Asked for a field that doesn't exist
631				curitem_haskey= break
632			esac
633			n=$(( $n - 1 ))
634		done
635
636		# Trim trailing words if sort field >= 1
637		[ $sort_field -ge 1 -a "$sort_numeric" ] &&
638			curitem_mod="${curitem_mod%%[$sort_sep]*}"
639
640		# Apply optional trim (-k POS.TRIM) to cut leading characters
641		curitem_mod="${curitem_mod#$trim}"
642
643		# Determine the type of modified comparison to use initially
644		# NB: Prefer numerical if requested but fallback to standard
645		case "$curitem_mod" in
646		""|[!0-9]*) # NULL or begins with non-number
647			gt=">"
648			[ "$sort_numeric" ] && curitem_mod=0
649			;;
650		*)
651			if [ "$sort_numeric" ]; then
652				gt="-gt"
653				curitem_mod="${curitem_mod%%[!0-9]*}"
654					# NB: trailing non-digits removed
655					# otherwise numeric comparison fails
656			else
657				gt=">"
658			fi
659		esac
660
661		# If first time through, short-circuit below position-search
662		if [ $i -le 1 ]; then
663			d=0
664		else
665			d=1
666		fi
667
668		#
669		# Find appropriate element position
670		#
671		while [ $d -gt 0 ]
672		do
673			dest_haskey=$curitem_haskey
674			eval dest=\"\$dest_$d\"
675			dest_mod="$dest" # for modified comparison
676			dest_orig="$dest" # for original comparison
677
678			# Trim leading whitespace if desired
679			if [ "$sort_ignore_leading_space" ]; then
680				while case "$dest_orig" in
681					[$IFS]*) : ;; *) false; esac
682				do
683					dest_orig="${dest_orig#?}"
684				done
685				dest_mod="$dest_orig"
686			fi
687
688			# Shift modified value if sort field (-k POS) is > 1
689			n=$sort_field
690			while [ $n -gt 1 ]; do
691				case "$dest_mod" in
692				*[$sort_sep]*)
693					# Cut text up-to (and incl.) 1st sep
694					dest_mod="${dest_mod#*[$sort_sep]}"
695
696					# Skip NULLs unless strict fields
697					[ "$sort_strict_fields" ] ||
698					    [ "${dest_mod%%[$sort_sep]*}" ] ||
699					    [ $n -eq 2 ] ||
700					    continue
701					;;
702				*)
703					# Asked for a field that doesn't exist
704					dest_haskey= break
705				esac
706				n=$(( $n - 1 ))
707			done
708
709			# Trim trailing words if sort field >= 1
710			[ $sort_field -ge 1 -a "$sort_numeric" ] &&
711				dest_mod="${dest_mod%%[$sort_sep]*}"
712
713			# Apply optional trim (-k POS.TRIM), cut leading chars
714			dest_mod="${dest_mod#$trim}"
715
716			# Determine type of modified comparison to use
717			# NB: Prefer numerical if requested, fallback to std
718			case "$dest_mod" in
719			""|[!0-9]*) # NULL or begins with non-number
720				gt=">"
721				[ "$sort_numeric" ] && dest_mod=0
722				;;
723			*)
724				if [ "$sort_numeric" ]; then
725					gt="-gt"
726					dest_mod="${dest_mod%%[!0-9]*}"
727						# NB: kill trailing non-digits
728						# for numeric comparison safety
729				else
730					gt=">"
731				fi
732			esac
733
734			# Break if we've found the proper element position
735			if [ "$curitem_haskey" -a "$dest_haskey" ]; then
736				if [ "$dest_mod" = "$curitem_mod" ]; then
737					[ "$dest_orig" ">" "$curitem_orig" ] &&
738						break
739				elif [ "$dest_mod" $gt "$curitem_mod" ] \
740					2> /dev/null
741				then
742					break
743				fi
744			else
745				[ "$dest_orig" ">" "$curitem_orig" ] && break
746			fi
747
748			# Break if we've hit the end
749			[ $d -ge $i ] && break
750
751			d=$(( $d + 1 ))
752		done
753
754		# Shift remaining positions forward, making room for new item
755		n=$i
756		while [ $n -ge $d ]; do
757			# Shift destination item forward one placement
758			eval dest_$(( $n + 1 ))=\"\$dest_$n\"
759			n=$(( $n - 1 ))
760		done
761
762		# Place the element
763		if [ $i -eq 1 ]; then
764			local dest_1="$curitem"
765		else
766			local dest_$d="$curitem"
767		fi
768
769		i=$(( $i + 1 ))
770	done
771
772	# Print sorted results
773	d=1
774	while [ $d -le $nitems ]; do
775		eval echo \"\$dest_$d\"
776		d=$(( $d + 1 ))
777	done
778}
779
780#
781# wait_for_pids pid [pid ...]
782#	spins until none of the pids exist
783#
784wait_for_pids()
785{
786	local _list _prefix _nlist _j
787
788	_list="$@"
789	if [ -z "$_list" ]; then
790		return
791	fi
792	_prefix=
793	while true; do
794		_nlist="";
795		for _j in $_list; do
796			if kill -0 $_j 2>/dev/null; then
797				_nlist="${_nlist}${_nlist:+ }$_j"
798				[ -n "$_prefix" ] && sleep 1
799			fi
800		done
801		if [ -z "$_nlist" ]; then
802			break
803		fi
804		_list=$_nlist
805		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
806		_prefix=", "
807		pwait $_list 2>/dev/null
808	done
809	if [ -n "$_prefix" ]; then
810		echo "."
811	fi
812}
813
814#
815# get_pidfile_from_conf string file
816#
817#	Takes a string to search for in the specified file.
818#	Ignores lines with traditional comment characters.
819#
820# Example:
821#
822# if get_pidfile_from_conf string file; then
823#	pidfile="$_pidfile_from_conf"
824# else
825#	pidfile='appropriate default'
826# fi
827#
828get_pidfile_from_conf()
829{
830	if [ -z "$1" -o -z "$2" ]; then
831		err 3 "USAGE: get_pidfile_from_conf string file ($name)"
832	fi
833
834	local string file line
835
836	string="$1" ; file="$2"
837
838	if [ ! -s "$file" ]; then
839		err 3 "get_pidfile_from_conf: $file does not exist ($name)"
840	fi
841
842	while read line; do
843		case "$line" in
844		*[#\;]*${string}*)	continue ;;
845		*${string}*)		break ;;
846		esac
847	done < $file
848
849	if [ -n "$line" ]; then
850		line=${line#*/}
851		_pidfile_from_conf="/${line%%[\"\;]*}"
852	else
853		return 1
854	fi
855}
856
857#
858# check_startmsgs
859#	If rc_quiet is set (usually as a result of using faststart at
860#	boot time) check if rc_startmsgs is enabled.
861#
862check_startmsgs()
863{
864	if [ -n "$rc_quiet" ]; then
865		checkyesno rc_startmsgs
866	else
867		return 0
868	fi
869}
870
871#
872# startmsg
873#	Preferred method to use when displaying start messages in lieu of echo.
874#
875startmsg()
876{
877	check_startmsgs && echo "$@"
878}
879
880#
881# run_rc_command argument
882#	Search for argument in the list of supported commands, which is:
883#		"start stop restart rcvar status poll ${extra_commands}"
884#	If there's a match, run ${argument}_cmd or the default method
885#	(see below).
886#
887#	If argument has a given prefix, then change the operation as follows:
888#		Prefix	Operation
889#		------	---------
890#		fast	Skip the pid check, and set rc_fast=yes, rc_quiet=yes
891#		force	Set ${rcvar} to YES, and set rc_force=yes
892#		one	Set ${rcvar} to YES
893#		quiet	Don't output some diagnostics, and set rc_quiet=yes
894#
895#	The following globals are used:
896#
897#	Name		Needed	Purpose
898#	----		------	-------
899#	name		y	Name of script.
900#
901#	command		n	Full path to command.
902#				Not needed if ${rc_arg}_cmd is set for
903#				each keyword.
904#
905#	command_args	n	Optional args/shell directives for command.
906#
907#	command_interpreter n	If not empty, command is interpreted, so
908#				call check_{pidfile,process}() appropriately.
909#
910#	desc		n	Description of script.
911#
912#	extra_commands	n	List of extra commands supported.
913#
914#	pidfile		n	If set, use check_pidfile $pidfile $command,
915#				otherwise use check_process $command.
916#				In either case, only check if $command is set.
917#
918#	procname	n	Process name to check for instead of $command.
919#
920#	rcvar		n	This is checked with checkyesno to determine
921#				if the action should be run.
922#
923#	${name}_program	n	Full path to command.
924#				Meant to be used in /etc/rc.conf to override
925#				${command}.
926#
927#	${name}_chroot	n	Directory to chroot to before running ${command}
928#				Requires /usr to be mounted.
929#
930#	${name}_chdir	n	Directory to cd to before running ${command}
931#				(if not using ${name}_chroot).
932#
933#	${name}_cpuset	n	A list of CPUs to run ${command} on.
934#				Requires /usr to be mounted.
935#
936#	${name}_flags	n	Arguments to call ${command} with.
937#				NOTE:	$flags from the parent environment
938#					can be used to override this.
939#
940#	${name}_env	n	Environment variables to run ${command} with.
941#
942#	${name}_env_file n	File to source variables to run ${command} with.
943#
944#	${name}_fib	n	Routing table number to run ${command} with.
945#
946#	${name}_nice	n	Nice level to run ${command} at.
947#
948#	${name}_oomprotect n	Don't kill ${command} when swap space is exhausted.
949#
950#	${name}_umask	n	The file creation mask to run ${command} with.
951#
952#	${name}_user	n	User to run ${command} as, using su(1) if not
953#				using ${name}_chroot.
954#				Requires /usr to be mounted.
955#
956#	${name}_group	n	Group to run chrooted ${command} as.
957#				Requires /usr to be mounted.
958#
959#	${name}_groups	n	Comma separated list of supplementary groups
960#				to run the chrooted ${command} with.
961#				Requires /usr to be mounted.
962#
963#	${name}_prepend	n	Command added before ${command}.
964#
965#	${name}_setup	n	Command executed before ${command}.
966#
967#	${name}_login_class n	Login class to use, else "daemon".
968#
969#	${name}_limits	n	limits(1) to apply to ${command}.
970#
971#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
972#				Otherwise, use default command (see below)
973#
974#	${rc_arg}_precmd n	If set, run just before performing the
975#				${rc_arg}_cmd method in the default
976#				operation (i.e, after checking for required
977#				bits and process (non)existence).
978#				If this completes with a non-zero exit code,
979#				don't run ${rc_arg}_cmd.
980#
981#	${rc_arg}_postcmd n	If set, run just after performing the
982#				${rc_arg}_cmd method, if that method
983#				returned a zero exit code.
984#
985#	required_dirs	n	If set, check for the existence of the given
986#				directories before running a (re)start command.
987#
988#	required_files	n	If set, check for the readability of the given
989#				files before running a (re)start command.
990#
991#	required_modules n	If set, ensure the given kernel modules are
992#				loaded before running a (re)start command.
993#				The check and possible loads are actually
994#				done after start_precmd so that the modules
995#				aren't loaded in vain, should the precmd
996#				return a non-zero status to indicate a error.
997#				If a word in the list looks like "foo:bar",
998#				"foo" is the KLD file name and "bar" is the
999#				module name.  If a word looks like "foo~bar",
1000#				"foo" is the KLD file name and "bar" is a
1001#				egrep(1) pattern matching the module name.
1002#				Otherwise the module name is assumed to be
1003#				the same as the KLD file name, which is most
1004#				common.  See load_kld().
1005#
1006#	required_vars	n	If set, perform checkyesno on each of the
1007#				listed variables before running the default
1008#				(re)start command.
1009#
1010#	Default behaviour for a given argument, if no override method is
1011#	provided:
1012#
1013#	Argument	Default behaviour
1014#	--------	-----------------
1015#	start		if !running && checkyesno ${rcvar}
1016#				${command}
1017#
1018#	stop		if ${pidfile}
1019#				rc_pid=$(check_pidfile $pidfile $command)
1020#			else
1021#				rc_pid=$(check_process $command)
1022#			kill $sig_stop $rc_pid
1023#			wait_for_pids $rc_pid
1024#			($sig_stop defaults to TERM.)
1025#
1026#	reload		Similar to stop, except use $sig_reload instead,
1027#			and don't wait_for_pids.
1028#			$sig_reload defaults to HUP.
1029#			Note that `reload' isn't provided by default,
1030#			it should be enabled via $extra_commands.
1031#
1032#	restart		Run `stop' then `start'.
1033#
1034#	status		Show if ${command} is running, etc.
1035#
1036#	poll		Wait for ${command} to exit.
1037#
1038#	rcvar		Display what rc.conf variable is used (if any).
1039#
1040#	enabled		Return true if the service is enabled.
1041#
1042#	describe	Show the service's description
1043#
1044#	extracommands	Show the service's extra commands
1045#
1046#	Variables available to methods, and after run_rc_command() has
1047#	completed:
1048#
1049#	Variable	Purpose
1050#	--------	-------
1051#	rc_arg		Argument to command, after fast/force/one processing
1052#			performed
1053#
1054#	rc_flags	Flags to start the default command with.
1055#			Defaults to ${name}_flags, unless overridden
1056#			by $flags from the environment.
1057#			This variable may be changed by the precmd method.
1058#
1059#	rc_service	Path to the service being executed, in case the service
1060#			needs to re-invoke itself.
1061#
1062#	rc_pid		PID of command (if appropriate)
1063#
1064#	rc_fast		Not empty if "fast" was provided (q.v.)
1065#
1066#	rc_force	Not empty if "force" was provided (q.v.)
1067#
1068#	rc_quiet	Not empty if "quiet" was provided
1069#
1070#
1071run_rc_command()
1072{
1073	_return=0
1074	rc_arg=$1
1075	if [ -z "$name" ]; then
1076		err 3 'run_rc_command: $name is not set.'
1077	fi
1078
1079	DebugOn rc:$name rc:$name:$rc_arg $name:$rc_arg
1080
1081	# Don't repeat the first argument when passing additional command-
1082	# line arguments to the command subroutines.
1083	#
1084	shift 1
1085	rc_extra_args="$*"
1086
1087	_rc_prefix=
1088	case "$rc_arg" in
1089	fast*)				# "fast" prefix; don't check pid
1090		rc_arg=${rc_arg#fast}
1091		rc_fast=yes
1092		rc_quiet=yes
1093		;;
1094	force*)				# "force" prefix; always run
1095		rc_force=yes
1096		_rc_prefix=force
1097		rc_arg=${rc_arg#${_rc_prefix}}
1098		if [ -n "${rcvar}" ]; then
1099			eval ${rcvar}=YES
1100		fi
1101		;;
1102	one*)				# "one" prefix; set ${rcvar}=yes
1103		_rc_prefix=one
1104		rc_arg=${rc_arg#${_rc_prefix}}
1105		if [ -n "${rcvar}" ]; then
1106			eval ${rcvar}=YES
1107		fi
1108		;;
1109	quiet*)				# "quiet" prefix; omit some messages
1110		_rc_prefix=quiet
1111		rc_arg=${rc_arg#${_rc_prefix}}
1112		rc_quiet=yes
1113		;;
1114	esac
1115
1116	eval _override_command=\$${name}_program
1117	command=${_override_command:-$command}
1118
1119	_keywords="start stop restart rcvar enable disable delete enabled describe extracommands $extra_commands"
1120	rc_pid=
1121	_pidcmd=
1122	_procname=${procname:-${command}}
1123
1124	eval _cpuset=\$${name}_cpuset
1125
1126	# Loose validation of the configured cpuset; just make sure it starts
1127	# with a number.  There have also been cases in the past where a hyphen
1128	# in a service name has caused eval errors, which trickle down into
1129	# various variables; don't let a situation like that break a bunch of
1130	# services just because of cpuset(1).
1131	case "$_cpuset" in
1132	[0-9]*)	;;
1133	*)	_cpuset="" ;;
1134	esac
1135
1136	_cpusetcmd=
1137	if [ -n "$_cpuset" ]; then
1138		_cpusetcmd="$CPUSET -l $_cpuset"
1139	fi
1140
1141					# setup pid check command
1142	if [ -n "$_procname" ]; then
1143		if [ -n "$pidfile" ]; then
1144			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
1145		else
1146			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
1147		fi
1148		_keywords="${_keywords} status poll"
1149	else
1150		if [ ! -z "${status_cmd}" ]
1151		then
1152			_keywords="${_keywords} status"
1153		fi
1154	fi
1155
1156	if [ -z "$rc_arg" ]; then
1157		rc_usage $_keywords
1158	fi
1159
1160	if [ "$rc_arg" = "enabled" ] ; then
1161		checkyesno ${rcvar}
1162		return $?
1163	fi
1164
1165	if [ -n "$flags" ]; then	# allow override from environment
1166		rc_flags=$flags
1167	else
1168		eval rc_flags=\$${name}_flags
1169	fi
1170	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
1171	    _nice=\$${name}_nice	_user=\$${name}_user \
1172	    _group=\$${name}_group	_groups=\$${name}_groups \
1173	    _fib=\$${name}_fib		_env=\$${name}_env \
1174	    _prepend=\$${name}_prepend	_login_class=\${${name}_login_class:-daemon} \
1175	    _limits=\$${name}_limits	_oomprotect=\$${name}_oomprotect \
1176	    _setup=\$${name}_setup	_env_file=\$${name}_env_file \
1177	    _umask=\$${name}_umask
1178
1179	if [ -n "$_env_file" ] && [ -r "${_env_file}" ]; then	# load env from file
1180		set -a
1181		. $_env_file
1182		set +a
1183	fi
1184
1185	if [ -n "$_user" ]; then	# unset $_user if running as that user
1186		if [ "$_user" = "$(eval $IDCMD)" ]; then
1187			unset _user
1188		fi
1189	fi
1190
1191	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
1192
1193	for _elem in $_keywords; do
1194		if [ "$_elem" != "$rc_arg" ]; then
1195			continue
1196		fi
1197					# if ${rcvar} is set, $1 is not "rcvar", "describe",
1198					# "enable", "delete" or "status", and ${rc_pid} is
1199					# not set, run:
1200					#	checkyesno ${rcvar}
1201					# and return if that failed
1202					#
1203		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
1204		    -a "$rc_arg" != "delete" -a "$rc_arg" != "enable" \
1205		    -a "$rc_arg" != "describe" -a "$rc_arg" != "status" ] ||
1206		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
1207			if ! checkyesno ${rcvar}; then
1208				if [ -n "${rc_quiet}" ]; then
1209					return 0
1210				fi
1211				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
1212				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
1213				echo "instead of '${rc_arg}'."
1214				return 0
1215			fi
1216		fi
1217
1218		if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1219			if [ -z "$rc_quiet" ]; then
1220				echo 1>&2 "${name} already running? " \
1221				    "(pid=$rc_pid)."
1222			fi
1223			return 1
1224		fi
1225
1226					# if there's a custom ${XXX_cmd},
1227					# run that instead of the default
1228					#
1229		eval _cmd=\$${rc_arg}_cmd \
1230		     _precmd=\$${rc_arg}_precmd \
1231		     _postcmd=\$${rc_arg}_postcmd
1232
1233		if [ -n "$_cmd" ]; then
1234			rc_trace 1 "$_cmd"
1235			if [ -n "$_env" ]; then
1236				eval "export -- $_env"
1237			fi
1238			_run_rc_precmd || return 1
1239			_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || return 1
1240			_run_rc_postcmd
1241			return $_return
1242		fi
1243
1244		case "$rc_arg" in	# default operations...
1245
1246		describe)
1247			if [ -n "$desc" ]; then
1248				echo "$desc"
1249			fi
1250			;;
1251
1252		extracommands)
1253			echo "$extra_commands"
1254			;;
1255
1256		enable)
1257			_out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=YES") &&
1258				echo "$name enabled in ${_out%%:*}"
1259			;;
1260
1261		disable)
1262			_out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=NO") &&
1263				echo "$name disabled in ${_out%%:*}"
1264			;;
1265
1266		delete)
1267			_files=
1268			for _file in $(sysrc -lEs "$name"); do
1269				_out=$(sysrc -Fif $_file "$rcvar") && _files="$_files $_file"
1270			done
1271			/usr/sbin/sysrc -x "$rcvar" && echo "$rcvar deleted in ${_files# }"
1272				# delete file in rc.conf.d if desired and empty.
1273			checkyesno service_delete_empty || _files=
1274			for _file in $_files; do
1275				[ "$_file" = "${_file#*/rc.conf.d/}" ] && continue
1276				[ $(/usr/bin/stat -f%z $_file) -gt 0 ] && continue
1277				/bin/rm "$_file" && echo "Empty file $_file removed"
1278			done
1279			;;
1280
1281		status)
1282			_run_rc_precmd || return 1
1283			if [ -n "$rc_pid" ]; then
1284				echo "${name} is running as pid $rc_pid."
1285			else
1286				echo "${name} is not running."
1287				return 1
1288			fi
1289			_run_rc_postcmd
1290			;;
1291
1292		start)
1293			if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1294				warn "run_rc_command: cannot run $command"
1295				return 1
1296			fi
1297
1298			if ! _run_rc_precmd; then
1299				warn "failed precmd routine for ${name}"
1300				return 1
1301			fi
1302
1303					# setup the full command to run
1304					#
1305			startmsg "Starting ${name}."
1306			if [ -n "$_chroot" ]; then
1307				_cd=
1308				_doit="\
1309${_nice:+nice -n $_nice }\
1310$_cpusetcmd \
1311${_fib:+setfib -F $_fib }\
1312${_env:+env $_env }\
1313chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1314$_chroot $command $rc_flags $command_args"
1315			else
1316				_cd="${_chdir:+cd $_chdir && }"
1317				_doit="\
1318${_fib:+setfib -F $_fib }\
1319${_env:+env $_env }\
1320$_cpusetcmd $command $rc_flags $command_args"
1321				if [ -n "$_user" ]; then
1322				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1323				fi
1324				if [ -n "$_nice" ]; then
1325					if [ -z "$_user" ]; then
1326						_doit="sh -c \"$_doit\""
1327					fi
1328					_doit="nice -n $_nice $_doit"
1329				fi
1330				if [ -n "$_prepend" ]; then
1331					_doit="$_prepend $_doit"
1332				fi
1333			fi
1334
1335			if [ -n "$_setup" ]; then
1336				if ! _run_rc_doit "$_setup"; then
1337					warn "failed to setup ${name}"
1338				fi
1339			fi
1340
1341					# Prepend default limits
1342			_doit="$_cd limits -C $_login_class $_limits $_doit"
1343
1344					# run the full command
1345					#
1346			if ! _run_rc_doit "$_doit"; then
1347				warn "failed to start ${name}"
1348				return 1
1349			fi
1350
1351					# finally, run postcmd
1352					#
1353			_run_rc_postcmd
1354			;;
1355
1356		stop)
1357			if [ -z "$rc_pid" ]; then
1358				[ -n "$rc_fast" ] && return 0
1359				_run_rc_notrunning
1360				return 1
1361			fi
1362
1363			_run_rc_precmd || return 1
1364
1365					# send the signal to stop
1366					#
1367			echo "Stopping ${name}."
1368			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1369			_run_rc_doit "$_doit" || return 1
1370
1371					# wait for the command to exit,
1372					# and run postcmd.
1373			wait_for_pids $rc_pid
1374
1375			_run_rc_postcmd
1376			;;
1377
1378		reload)
1379			if [ -z "$rc_pid" ]; then
1380				_run_rc_notrunning
1381				return 1
1382			fi
1383
1384			_run_rc_precmd || return 1
1385
1386			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1387			_run_rc_doit "$_doit" || return 1
1388
1389			_run_rc_postcmd
1390			;;
1391
1392		restart)
1393					# prevent restart being called more
1394					# than once by any given script
1395					#
1396			if ${_rc_restart_done:-false}; then
1397				return 0
1398			fi
1399			_rc_restart_done=true
1400
1401			_run_rc_precmd || return 1
1402
1403			# run those in a subshell to keep global variables
1404			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1405			( run_rc_command ${_rc_prefix}start $rc_extra_args )
1406			_return=$?
1407			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1408
1409			_run_rc_postcmd
1410			;;
1411
1412		poll)
1413			_run_rc_precmd || return 1
1414			if [ -n "$rc_pid" ]; then
1415				wait_for_pids $rc_pid
1416			fi
1417			_run_rc_postcmd
1418			;;
1419
1420		rcvar)
1421			echo -n "# $name"
1422			if [ -n "$desc" ]; then
1423				echo " : $desc"
1424			else
1425				echo ""
1426			fi
1427			echo "#"
1428			# Get unique vars in $rcvar $rcvars
1429			for _v in $rcvar $rcvars; do
1430				case $v in
1431				$_v\ *|\ *$_v|*\ $_v\ *) ;;
1432				*)	v="${v# } $_v" ;;
1433				esac
1434			done
1435
1436			# Display variables.
1437			for _v in $v; do
1438				if [ -z "$_v" ]; then
1439					continue
1440				fi
1441
1442				eval _desc=\$${_v}_desc
1443				eval _defval=\$${_v}_defval
1444				_h="-"
1445
1446				eval echo \"$_v=\\\"\$$_v\\\"\"
1447				# decode multiple lines of _desc
1448				while [ -n "$_desc" ]; do
1449					case $_desc in
1450					*^^*)
1451						echo "# $_h ${_desc%%^^*}"
1452						_desc=${_desc#*^^}
1453						_h=" "
1454						;;
1455					*)
1456						echo "# $_h ${_desc}"
1457						break
1458						;;
1459					esac
1460				done
1461				echo "#   (default: \"$_defval\")"
1462			done
1463			echo ""
1464			;;
1465
1466		*)
1467			rc_usage $_keywords
1468			;;
1469
1470		esac
1471
1472		# Apply protect(1) to the PID if ${name}_oomprotect is set.
1473		case "$rc_arg" in
1474		start)
1475			# We cannot use protect(1) inside jails.
1476			if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1477			    [ "$(sysctl -n security.jail.jailed)" -eq 0 ]; then
1478				[ -z "${rc_pid}" ] && eval $_pidcmd
1479				case $_oomprotect in
1480				[Aa][Ll][Ll])
1481					${PROTECT} -d -i -p ${rc_pid}
1482					;;
1483				[Yy][Ee][Ss])
1484					${PROTECT} -p ${rc_pid}
1485					;;
1486				esac
1487			fi
1488		;;
1489		esac
1490
1491		return $_return
1492	done
1493
1494	echo 1>&2 "$0: unknown directive '$rc_arg'."
1495	rc_usage $_keywords
1496	# not reached
1497}
1498
1499#
1500# Helper functions for run_rc_command: common code.
1501# They use such global variables besides the exported rc_* ones:
1502#
1503#	name	       R/W
1504#	------------------
1505#	_precmd		R
1506#	_postcmd	R
1507#	_return		W
1508#
1509_run_rc_precmd()
1510{
1511	check_required_before "$rc_arg" || return 1
1512
1513	if [ -n "$_precmd" ]; then
1514		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1515		eval "$_precmd $rc_extra_args"
1516		_return=$?
1517
1518		# If precmd failed and force isn't set, request exit.
1519		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1520			return 1
1521		fi
1522	fi
1523
1524	check_required_after "$rc_arg" || return 1
1525
1526	return 0
1527}
1528
1529_run_rc_postcmd()
1530{
1531	if [ -n "$_postcmd" ]; then
1532		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1533		eval "$_postcmd $rc_extra_args"
1534		_return=$?
1535	fi
1536	return 0
1537}
1538
1539_run_rc_doit()
1540{
1541	local _m
1542
1543	debug "run_rc_command: doit: $*"
1544	_m=$(umask)
1545	${_umask:+umask ${_umask}}
1546	eval "$@"
1547	_return=$?
1548	umask ${_m}
1549
1550	# If command failed and force isn't set, request exit.
1551	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1552		return 1
1553	fi
1554
1555	return 0
1556}
1557
1558_run_rc_notrunning()
1559{
1560	local _pidmsg
1561
1562	if [ -n "$pidfile" ]; then
1563		_pidmsg=" (check $pidfile)."
1564	else
1565		_pidmsg=
1566	fi
1567	echo 1>&2 "${name} not running?${_pidmsg}"
1568}
1569
1570_run_rc_killcmd()
1571{
1572	local _cmd
1573
1574	_cmd="kill -$1 $rc_pid"
1575	if [ -n "$_user" ]; then
1576		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1577	fi
1578	echo "$_cmd"
1579}
1580
1581#
1582# run_rc_script file arg
1583#	Start the script `file' with `arg', and correctly handle the
1584#	return value from the script.
1585#	If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1586#	an old-style startup file.
1587#	If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1588#	into the current environment if $rc_fast_and_loose is set; otherwise
1589#	it is run as a child process.
1590#	If `file' appears to be a backup or scratch file, ignore it.
1591#	Otherwise if it is executable run as a child process.
1592#
1593run_rc_script()
1594{
1595	_file=$1
1596	_arg=$2
1597	if [ -z "$_file" -o -z "$_arg" ]; then
1598		err 3 'USAGE: run_rc_script file arg'
1599	fi
1600
1601	unset	name command command_args command_interpreter \
1602		extra_commands pidfile procname \
1603		rcvar rcvars rcvars_obsolete required_dirs required_files \
1604		required_vars
1605	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1606
1607	rc_trace 0 "$_file $_arg"
1608	# don't use it if we don't trust it
1609	is_verified $_file || return
1610
1611	rc_service="$_file"
1612	case "$_file" in
1613	/etc/rc.d/*.sh)			# no longer allowed in the base
1614		warn "Ignoring old-style startup script $_file"
1615		;;
1616	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
1617		warn "Ignoring scratch file $_file"
1618		;;
1619	*)				# run in subshell
1620		if [ -x $_file ]; then
1621			DebugOn $_file $_file:$_arg rc:${_file##*/} rc:${_file##*/}:$_arg ${_file##*/} ${_file##*/}:$_arg
1622
1623			if [ -n "$rc_boottrace" ]; then
1624				boottrace_fn "$_file" "$_arg"
1625			elif [ -n "$rc_fast_and_loose" ]; then
1626				set $_arg; . $_file
1627			else
1628				( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1629				  trap "echo Script $_file interrupted >&2 ; exit 1" 2
1630				  trap "echo Script $_file running >&2" 29
1631				  set $_arg; . $_file )
1632			fi
1633			DebugOff $_file $_file:$_arg rc:${_file##*/} rc:${_file##*/}:$_arg ${_file##*/} ${_file##*/}:$_arg
1634		fi
1635		;;
1636	esac
1637}
1638
1639#
1640# run_rc_scripts [options] file [...]
1641#
1642# Call `run_rc_script' for each "file" unless already listed in
1643# $_rc_elem_done.
1644#
1645# Options:
1646#
1647#	--arg "arg"
1648#		Pass "arg" to `run_rc_script' default is $_boot.
1649#
1650#	--break "marker"
1651#		If any "file" matches "marker" stop processing.
1652#
1653_rc_elem_done=
1654run_rc_scripts()
1655{
1656	local _arg=${_boot}
1657	local _rc_elem
1658	local _rc_breaks=
1659
1660	while :; do
1661		case "$1" in
1662		--arg)
1663                        _arg="$2"
1664                        shift 2
1665                        ;;
1666		--break)
1667                        _rc_breaks="$_rc_breaks $2"
1668                        shift 2
1669                        ;;
1670		*)
1671                        break
1672                        ;;
1673		esac
1674	done
1675	for _rc_elem in "$@"; do
1676		: _rc_elem=$_rc_elem
1677		case " $_rc_elem_done " in
1678		*" $_rc_elem "*)
1679                        continue
1680                        ;;
1681		esac
1682		run_rc_script ${_rc_elem} ${_arg}
1683		_rc_elem_done="$_rc_elem_done $_rc_elem"
1684		case " $_rc_breaks " in
1685		*" ${_rc_elem##*/} "*)
1686                        break
1687                        ;;
1688		esac
1689	done
1690}
1691
1692boottrace_fn()
1693{
1694	local _file _arg
1695	_file=$1
1696	_arg=$2
1697
1698	if [ -n "$rc_fast_and_loose" ]; then
1699		boottrace_sysctl "$_file start"
1700		set $_arg; . $_file
1701		boottrace_sysctl "$_file done"
1702	else
1703		$boottrace_cmd "$_file" "$_arg"
1704	fi
1705}
1706
1707boottrace_sysctl()
1708{
1709	${SYSCTL} kern.boottrace.boottrace="$1"
1710}
1711
1712#
1713# load_rc_config [service]
1714#	Source in the configuration file(s) for a given service.
1715#	If no service is specified, only the global configuration
1716#	file(s) will be loaded.
1717#
1718load_rc_config()
1719{
1720	local _name _rcvar_val _var _defval _v _msg _new _d _dot
1721	_name=$1
1722	_dot=${load_rc_config_reader:-dot}
1723
1724	case "$_dot" in
1725	dot|[sv]dot)
1726		;;
1727	*)	warn "Ignoring invalid load_rc_config_reader"
1728		_dot=dot
1729		;;
1730	esac
1731	case "$1" in
1732	-s|--safe)
1733                _dot=sdot
1734                _name=$2
1735                shift
1736                ;;
1737	-v|--verify)
1738                _dot=vdot
1739                _name=$2
1740                shift
1741                ;;
1742	esac
1743
1744	DebugOn rc:$_name $_name
1745
1746	if ${_rc_conf_loaded:-false}; then
1747		:
1748	else
1749		if [ -r /etc/defaults/rc.conf ]; then
1750			debug "Sourcing /etc/defaults/rc.conf"
1751			$_dot /etc/defaults/rc.conf
1752			source_rc_confs
1753		elif [ -r /etc/rc.conf ]; then
1754			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1755			$_dot /etc/rc.conf
1756		fi
1757		_rc_conf_loaded=true
1758	fi
1759
1760	# If a service name was specified, attempt to load
1761	# service-specific configuration
1762	if [ -n "$_name" ] ; then
1763		for _d in /etc ${local_startup}; do
1764			_d=${_d%/rc.d}
1765			if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1766				debug "Sourcing ${_d}/rc.conf.d/$_name"
1767				$_dot ${_d}/rc.conf.d/"$_name"
1768			elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
1769				local _rc
1770				for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
1771					if [ -f "$_rc" ] ; then
1772						debug "Sourcing $_rc"
1773						$_dot "$_rc"
1774					fi
1775				done
1776			fi
1777		done
1778	fi
1779
1780	# Set defaults if defined.
1781	for _var in $rcvar $rcvars; do
1782		eval _defval=\$${_var}_defval
1783		if [ -n "$_defval" ]; then
1784			eval : \${$_var:=\$${_var}_defval}
1785		fi
1786	done
1787
1788	# check obsolete rc.conf variables
1789	for _var in $rcvars_obsolete; do
1790		eval _v=\$$_var
1791		eval _msg=\$${_var}_obsolete_msg
1792		eval _new=\$${_var}_newvar
1793		case $_v in
1794		"")
1795			;;
1796		*)
1797			if [ -z "$_new" ]; then
1798				_msg="Ignored."
1799			else
1800				eval $_new=\"\$$_var\"
1801				if [ -z "$_msg" ]; then
1802					_msg="Use \$$_new instead."
1803				fi
1804			fi
1805			warn "\$$_var is obsolete.  $_msg"
1806			;;
1807		esac
1808	done
1809}
1810
1811#
1812# load_rc_config_var name var
1813#	Read the rc.conf(5) var for name and set in the
1814#	current shell, using load_rc_config in a subshell to prevent
1815#	unwanted side effects from other variable assignments.
1816#
1817load_rc_config_var()
1818{
1819	if [ $# -ne 2 ]; then
1820		err 3 'USAGE: load_rc_config_var name var'
1821	fi
1822	eval $(eval '(
1823		load_rc_config '$1' >/dev/null;
1824		if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1825			echo '$2'=\'\''${'$2'}\'\'';
1826		fi
1827	)' )
1828}
1829
1830#
1831# rc_usage commands
1832#	Print a usage string for $0, with `commands' being a list of
1833#	valid commands.
1834#
1835rc_usage()
1836{
1837	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1838
1839	_sep=
1840	for _elem; do
1841		echo -n 1>&2 "$_sep$_elem"
1842		_sep="|"
1843	done
1844	echo 1>&2 ")"
1845	exit 1
1846}
1847
1848#
1849# err exitval message
1850#	Display message to stderr and log to the syslog, and exit with exitval.
1851#
1852err()
1853{
1854	exitval=$1
1855	shift
1856
1857	if [ -x /usr/bin/logger ]; then
1858		logger "$0: ERROR: $*"
1859	fi
1860	echo 1>&2 "$0: ERROR: $*"
1861	exit $exitval
1862}
1863
1864#
1865# warn message
1866#	Display message to stderr and log to the syslog.
1867#
1868warn()
1869{
1870	if [ -x /usr/bin/logger ]; then
1871		logger "$0: WARNING: $*"
1872	fi
1873	echo 1>&2 "$0: WARNING: $*"
1874}
1875
1876#
1877# info message
1878#	Display informational message to stdout and log to syslog.
1879#
1880info()
1881{
1882	case ${rc_info} in
1883	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1884		if [ -x /usr/bin/logger ]; then
1885			logger "$0: INFO: $*"
1886		fi
1887		echo "$0: INFO: $*"
1888		;;
1889	esac
1890}
1891
1892#
1893# debug message
1894#	If debugging is enabled in rc.conf output message to stderr.
1895#	BEWARE that you don't call any subroutine that itself calls this
1896#	function.
1897#
1898debug()
1899{
1900	case ${rc_debug} in
1901	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1902		if [ -x /usr/bin/logger ]; then
1903			logger "$0: DEBUG: $*"
1904		fi
1905		echo 1>&2 "$0: DEBUG: $*"
1906		;;
1907	esac
1908}
1909
1910#
1911# backup_file action file cur backup
1912#	Make a backup copy of `file' into `cur', and save the previous
1913#	version of `cur' as `backup'.
1914#
1915#	The `action' keyword can be one of the following:
1916#
1917#	add		`file' is now being backed up (and is possibly
1918#			being reentered into the backups system).  `cur'
1919#			is created.
1920#
1921#	update		`file' has changed and needs to be backed up.
1922#			If `cur' exists, it is copied to `back'
1923#			and then `file' is copied to `cur'.
1924#
1925#	remove		`file' is no longer being tracked by the backups
1926#			system.  `cur' is moved `back'.
1927#
1928#
1929backup_file()
1930{
1931	_action=$1
1932	_file=$2
1933	_cur=$3
1934	_back=$4
1935
1936	case $_action in
1937	add|update)
1938		if [ -f $_cur ]; then
1939			cp -p $_cur $_back
1940		fi
1941		cp -p $_file $_cur
1942		chown root:wheel $_cur
1943		;;
1944	remove)
1945		mv -f $_cur $_back
1946		;;
1947	esac
1948}
1949
1950# make_symlink src link
1951#	Make a symbolic link 'link' to src from basedir. If the
1952#	directory in which link is to be created does not exist
1953#	a warning will be displayed and an error will be returned.
1954#	Returns 0 on success, 1 otherwise.
1955#
1956make_symlink()
1957{
1958	local src link linkdir _me
1959	src="$1"
1960	link="$2"
1961	linkdir="`dirname $link`"
1962	_me="make_symlink()"
1963
1964	if [ -z "$src" -o -z "$link" ]; then
1965		warn "$_me: requires two arguments."
1966		return 1
1967	fi
1968	if [ ! -d "$linkdir" ]; then
1969		warn "$_me: the directory $linkdir does not exist."
1970		return 1
1971	fi
1972	if ! ln -sf $src $link; then
1973		warn "$_me: unable to make a symbolic link from $link to $src"
1974		return 1
1975	fi
1976	return 0
1977}
1978
1979# devfs_rulesets_from_file file
1980#	Reads a set of devfs commands from file, and creates
1981#	the specified rulesets with their rules. Returns non-zero
1982#	if there was an error.
1983#
1984devfs_rulesets_from_file()
1985{
1986	local file _err _me _opts
1987	file="$1"
1988	_me="devfs_rulesets_from_file"
1989	_err=0
1990
1991	if [ -z "$file" ]; then
1992		warn "$_me: you must specify a file"
1993		return 1
1994	fi
1995	if [ ! -e "$file" ]; then
1996		debug "$_me: no such file ($file)"
1997		return 0
1998	fi
1999
2000	# Disable globbing so that the rule patterns are not expanded
2001	# by accident with matching filesystem entries.
2002	_opts=$-; set -f
2003
2004	debug "reading rulesets from file ($file)"
2005	{ while read line
2006	do
2007		case $line in
2008		\#*)
2009			continue
2010			;;
2011		\[*\]*)
2012			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
2013			if [ -z "$rulenum" ]; then
2014				warn "$_me: cannot extract rule number ($line)"
2015				_err=1
2016				break
2017			fi
2018			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
2019			if [ -z "$rulename" ]; then
2020				warn "$_me: cannot extract rule name ($line)"
2021				_err=1
2022				break;
2023			fi
2024			eval $rulename=\$rulenum
2025			debug "found ruleset: $rulename=$rulenum"
2026			if ! /sbin/devfs rule -s $rulenum delset; then
2027				_err=1
2028				break
2029			fi
2030			;;
2031		*)
2032			rulecmd="${line%%"\#*"}"
2033			# evaluate the command incase it includes
2034			# other rules
2035			if [ -n "$rulecmd" ]; then
2036				debug "adding rule ($rulecmd)"
2037				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
2038				then
2039					_err=1
2040					break
2041				fi
2042			fi
2043			;;
2044		esac
2045		if [ $_err -ne 0 ]; then
2046			debug "error in $_me"
2047			break
2048		fi
2049	done } < $file
2050	case $_opts in *f*) ;; *) set +f ;; esac
2051	return $_err
2052}
2053
2054# devfs_init_rulesets
2055#	Initializes rulesets from configuration files. Returns
2056#	non-zero if there was an error.
2057#
2058devfs_init_rulesets()
2059{
2060	local file _me
2061	_me="devfs_init_rulesets"
2062
2063	# Go through this only once
2064	if [ -n "$devfs_rulesets_init" ]; then
2065		debug "$_me: devfs rulesets already initialized"
2066		return
2067	fi
2068	for file in $devfs_rulesets; do
2069		if ! devfs_rulesets_from_file $file; then
2070			warn "$_me: could not read rules from $file"
2071			return 1
2072		fi
2073	done
2074	devfs_rulesets_init=1
2075	debug "$_me: devfs rulesets initialized"
2076	return 0
2077}
2078
2079# devfs_set_ruleset ruleset [dir]
2080#	Sets the default ruleset of dir to ruleset. The ruleset argument
2081#	must be a ruleset name as specified in devfs.rules(5) file.
2082#	Returns non-zero if it could not set it successfully.
2083#
2084devfs_set_ruleset()
2085{
2086	local devdir rs _me
2087	[ -n "$1" ] && eval rs=\$$1 || rs=
2088	[ -n "$2" ] && devdir="-m "$2"" || devdir=
2089	_me="devfs_set_ruleset"
2090
2091	if [ -z "$rs" ]; then
2092		warn "$_me: you must specify a ruleset number"
2093		return 1
2094	fi
2095	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
2096	if ! /sbin/devfs $devdir ruleset $rs; then
2097		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
2098		return 1
2099	fi
2100	return 0
2101}
2102
2103# devfs_apply_ruleset ruleset [dir]
2104#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
2105#	The ruleset argument must be a ruleset name as specified
2106#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
2107#	if it could not apply the ruleset.
2108#
2109devfs_apply_ruleset()
2110{
2111	local devdir rs _me
2112	[ -n "$1" ] && eval rs=\$$1 || rs=
2113	[ -n "$2" ] && devdir="-m "$2"" || devdir=
2114	_me="devfs_apply_ruleset"
2115
2116	if [ -z "$rs" ]; then
2117		warn "$_me: you must specify a ruleset"
2118		return 1
2119	fi
2120	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
2121	if ! /sbin/devfs $devdir rule -s $rs applyset; then
2122		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
2123		return 1
2124	fi
2125	return 0
2126}
2127
2128# devfs_domount dir [ruleset]
2129#	Mount devfs on dir. If ruleset is specified it is set
2130#	on the mount-point. It must also be a ruleset name as specified
2131#	in a devfs.rules(5) file. Returns 0 on success.
2132#
2133devfs_domount()
2134{
2135	local devdir rs _me
2136	devdir="$1"
2137	[ -n "$2" ] && rs=$2 || rs=
2138	_me="devfs_domount()"
2139
2140	if [ -z "$devdir" ]; then
2141		warn "$_me: you must specify a mount-point"
2142		return 1
2143	fi
2144	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
2145	if ! mount -t devfs dev "$devdir"; then
2146		warn "$_me: Unable to mount devfs on $devdir"
2147		return 1
2148	fi
2149	if [ -n "$rs" ]; then
2150		devfs_init_rulesets
2151		devfs_set_ruleset $rs $devdir
2152		devfs -m $devdir rule applyset
2153	fi
2154	return 0
2155}
2156
2157# Provide a function for normalizing the mounting of memory
2158# filesystems.  This should allow the rest of the code here to remain
2159# as close as possible between 5-current and 4-stable.
2160#   $1 = size
2161#   $2 = mount point
2162#   $3 = (optional) extra mdmfs flags
2163mount_md()
2164{
2165	if [ -n "$3" ]; then
2166		flags="$3"
2167	fi
2168	/sbin/mdmfs $flags -s $1 ${mfs_type} $2
2169}
2170
2171# Code common to scripts that need to load a kernel module
2172# if it isn't in the kernel yet. Syntax:
2173#   load_kld [-e regex] [-m module] file
2174# where -e or -m chooses the way to check if the module
2175# is already loaded:
2176#   regex is egrep'd in the output from `kldstat -v',
2177#   module is passed to `kldstat -m'.
2178# The default way is as though `-m file' were specified.
2179load_kld()
2180{
2181	local _loaded _mod _opt _re
2182
2183	while getopts "e:m:" _opt; do
2184		case "$_opt" in
2185		e) _re="$OPTARG" ;;
2186		m) _mod="$OPTARG" ;;
2187		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
2188		esac
2189	done
2190	shift $(($OPTIND - 1))
2191	if [ $# -ne 1 ]; then
2192		err 3 'USAGE: load_kld [-e regex] [-m module] file'
2193	fi
2194	_mod=${_mod:-$1}
2195	_loaded=false
2196	if [ -n "$_re" ]; then
2197		if kldstat -v | egrep -q -e "$_re"; then
2198			_loaded=true
2199		fi
2200	else
2201		if kldstat -q -m "$_mod"; then
2202			_loaded=true
2203		fi
2204	fi
2205	if ! $_loaded; then
2206		if ! kldload "$1"; then
2207			warn "Unable to load kernel module $1"
2208			return 1
2209		else
2210			info "$1 kernel module loaded."
2211			if [ -f "/etc/sysctl.kld.d/$1.conf" ]; then
2212				sysctl -f "/etc/sysctl.kld.d/$1.conf"
2213			fi
2214		fi
2215	else
2216		debug "load_kld: $1 kernel module already loaded."
2217	fi
2218	return 0
2219}
2220
2221# ltr str src dst [var]
2222#	Change every $src in $str to $dst.
2223#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
2224#	awk(1). If var is non-NULL, set it to the result.
2225ltr()
2226{
2227	local _str _src _dst _out _com _var
2228	_str="$1"
2229	_src="$2"
2230	_dst="$3"
2231	_var="$4"
2232	_out=""
2233
2234	local IFS="${_src}"
2235	for _com in ${_str}; do
2236		if [ -z "${_out}" ]; then
2237			_out="${_com}"
2238		else
2239			_out="${_out}${_dst}${_com}"
2240		fi
2241	done
2242	if [ -n "${_var}" ]; then
2243		setvar "${_var}" "${_out}"
2244	else
2245		echo "${_out}"
2246	fi
2247}
2248
2249# Creates a list of providers for GELI encryption.
2250geli_make_list()
2251{
2252	local devices devices2
2253	local provider mountpoint type options rest
2254
2255	# Create list of GELI providers from fstab.
2256	while read provider mountpoint type options rest ; do
2257		case ":${options}" in
2258		:*noauto*)
2259			noauto=yes
2260			;;
2261		*)
2262			noauto=no
2263			;;
2264		esac
2265
2266		case ":${provider}" in
2267		:#*)
2268			continue
2269			;;
2270		*.eli)
2271			# Skip swap devices.
2272			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
2273				continue
2274			fi
2275			devices="${devices} ${provider}"
2276			;;
2277		esac
2278	done < /etc/fstab
2279
2280	# Append providers from geli_devices.
2281	devices="${devices} ${geli_devices}"
2282
2283	for provider in ${devices}; do
2284		provider=${provider%.eli}
2285		provider=${provider#/dev/}
2286		devices2="${devices2} ${provider}"
2287	done
2288
2289	echo ${devices2}
2290}
2291
2292# Originally, root mount hold had to be released before mounting
2293# the root filesystem.  This delayed the boot, so it was changed
2294# to only wait if the root device isn't readily available.  This
2295# can result in rc scripts executing before all the devices - such
2296# as graid(8), or USB disks - can be accessed.  This function can
2297# be used to explicitly wait for root mount holds to be released.
2298root_hold_wait()
2299{
2300	local wait waited holders
2301
2302	waited=0
2303	while true; do
2304		holders="$(sysctl -n vfs.root_mount_hold)"
2305		if [ -z "${holders}" ]; then
2306			break;
2307		fi
2308		if [ ${waited} -eq 0 ]; then
2309			echo -n "Waiting ${root_hold_delay}s" \
2310			"for the root mount holders: ${holders}"
2311		else
2312			echo -n .
2313		fi
2314		if [ ${waited} -ge ${root_hold_delay} ]; then
2315			echo
2316			break
2317		fi
2318		sleep 1
2319		waited=$(($waited + 1))
2320	done
2321}
2322
2323# Find scripts in local_startup directories that use the old syntax
2324#
2325find_local_scripts_old() {
2326	zlist=''
2327	slist=''
2328	for dir in ${local_startup}; do
2329		if [ -d "${dir}" ]; then
2330			for file in ${dir}/[0-9]*.sh; do
2331				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2332				    continue
2333				zlist="$zlist $file"
2334			done
2335			for file in ${dir}/[!0-9]*.sh; do
2336				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2337				    continue
2338				slist="$slist $file"
2339			done
2340		fi
2341	done
2342}
2343
2344find_local_scripts_new() {
2345	local_rc=''
2346	for dir in ${local_startup}; do
2347		if [ -d "${dir}" ]; then
2348			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
2349				case "$file" in
2350				*.sample|*.pkgsave) ;;
2351				*)	if [ -x "$file" ]; then
2352						local_rc="${local_rc} ${file}"
2353					fi
2354					;;
2355				esac
2356			done
2357		fi
2358	done
2359}
2360
2361find_system_scripts() {
2362	system_rc=''
2363	for file in /etc/rc.d/*; do
2364		case "${file##*/}" in
2365		*.pkgsave) ;;
2366		*)	if [ -x "$file" ]; then
2367				system_rc="${system_rc} ${file}"
2368			fi
2369			;;
2370		esac
2371	done
2372}
2373
2374# check_required_{before|after} command
2375#	Check for things required by the command before and after its precmd,
2376#	respectively.  The two separate functions are needed because some
2377#	conditions should prevent precmd from being run while other things
2378#	depend on precmd having already been run.
2379#
2380check_required_before()
2381{
2382	local _f
2383
2384	case "$1" in
2385	start)
2386		for _f in $required_vars; do
2387			if ! checkyesno $_f; then
2388				warn "\$${_f} is not enabled."
2389				if [ -z "$rc_force" ]; then
2390					return 1
2391				fi
2392			fi
2393		done
2394
2395		for _f in $required_dirs; do
2396			if [ ! -d "${_f}/." ]; then
2397				warn "${_f} is not a directory."
2398				if [ -z "$rc_force" ]; then
2399					return 1
2400				fi
2401			fi
2402		done
2403
2404		for _f in $required_files; do
2405			if [ ! -r "${_f}" ]; then
2406				warn "${_f} is not readable."
2407				if [ -z "$rc_force" ]; then
2408					return 1
2409				fi
2410			fi
2411		done
2412		;;
2413	esac
2414
2415	return 0
2416}
2417
2418check_required_after()
2419{
2420	local _f _args
2421
2422	case "$1" in
2423	start)
2424		for _f in $required_modules; do
2425			case "${_f}" in
2426				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
2427				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
2428				*)	_args="${_f}" ;;
2429			esac
2430			if ! load_kld ${_args}; then
2431				if [ -z "$rc_force" ]; then
2432					return 1
2433				fi
2434			fi
2435		done
2436		;;
2437	esac
2438
2439	return 0
2440}
2441
2442# check_jail mib
2443#	Return true if security.jail.$mib exists and set to 1.
2444
2445check_jail()
2446{
2447	local _mib _v
2448
2449	_mib=$1
2450	if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2451		case $_v in
2452		1)	return 0;;
2453		esac
2454	fi
2455	return 1
2456}
2457
2458# check_kern_features mib
2459#	Return existence of kern.features.* sysctl MIB as true or
2460#	false.  The result will be cached in $_rc_cache_kern_features_
2461#	namespace.  "0" means the kern.features.X exists.
2462
2463check_kern_features()
2464{
2465	local _v
2466
2467	[ -n "$1" ] || return 1;
2468	eval _v=\$_rc_cache_kern_features_$1
2469	[ -n "$_v" ] && return "$_v";
2470
2471	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2472		eval _rc_cache_kern_features_$1=0
2473		return 0
2474	else
2475		eval _rc_cache_kern_features_$1=1
2476		return 1
2477	fi
2478}
2479
2480# check_namevarlist var
2481#	Return "0" if ${name}_var is reserved in rc.subr.
2482
2483_rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend setup"
2484check_namevarlist()
2485{
2486	local _v
2487
2488	for _v in $_rc_namevarlist; do
2489	case $1 in
2490	$_v)	return 0 ;;
2491	esac
2492	done
2493
2494	return 1
2495}
2496
2497# _echoonce var msg mode
2498#	mode=0: Echo $msg if ${$var} is empty.
2499#	        After doing echo, a string is set to ${$var}.
2500#
2501#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
2502#
2503_echoonce()
2504{
2505	local _var _msg _mode
2506	eval _var=\$$1
2507	_msg=$2
2508	_mode=$3
2509
2510	case $_mode in
2511	1)	[ -n "$_var" ] && echo "$_msg" ;;
2512	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2513	esac
2514}
2515
2516# If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2517# still override this, but /etc/defaults/rc.conf can't unconditionally set this
2518# since it would undo what we've done here.
2519if kenv -q rc.debug > /dev/null ; then
2520	rc_debug=YES
2521fi
2522
2523boottrace_cmd=`command -v boottrace`
2524if [ -n "$boottrace_cmd" ] && [ "`${SYSCTL_N} -q kern.boottrace.enabled`" = "1" ]; then
2525	rc_boottrace=YES
2526fi
2527
2528SED=${SED:-$(Exists -x /usr/bin/sed /rescue/sed)}
2529
2530# Allow for local additions and overrides.
2531# Use vdot to ensure the file has not been tampered with.
2532vdot /etc/local.rc.subr
2533
2534# Avoid noise - when we do not have /usr mounted,
2535# and we cannot use safe_dot without sed.
2536if ! have basename; then
2537	basename()
2538	{
2539		local b=${1%$2}
2540		echo ${b##*/}
2541	}
2542	tty()
2543	{
2544		return 0
2545	}
2546	# we cannot use safe_dot without sed
2547	[ -z "$SED" ] && _SAFE_EVAL_SH=:
2548fi
2549# safe_eval.sh provides safe_dot - for untrusted files
2550$_SAFE_EVAL_SH vdot /libexec/safe_eval.sh
2551$_DEBUG_SH vdot /libexec/debug.sh
2552
2553# Ensure we can still operate if debug.sh and
2554# safe_eval.sh are not found.
2555if have DebugOn; then
2556	# allow DEBUG_SH to be set from loader prompt
2557	DEBUG_SH=${DEBUG_SH:-$(kenv -q DEBUG_SH)}
2558else
2559	DebugOn() { return 0; }
2560	DebugOff() { return 0; }
2561fi
2562if ! have save_dot; then
2563	safe_dot() { dot "$@"; }
2564fi
2565