1164640Sflz# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
298186Sgordon# $FreeBSD: stable/11/etc/rc.subr 343046 2019-01-15 16:12:47Z kevans $
378344Sobrien#
4157473Sflz# Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
578344Sobrien# All rights reserved.
678344Sobrien#
778344Sobrien# This code is derived from software contributed to The NetBSD Foundation
878344Sobrien# by Luke Mewburn.
978344Sobrien#
1078344Sobrien# Redistribution and use in source and binary forms, with or without
1178344Sobrien# modification, are permitted provided that the following conditions
1278344Sobrien# are met:
1378344Sobrien# 1. Redistributions of source code must retain the above copyright
1478344Sobrien#    notice, this list of conditions and the following disclaimer.
1578344Sobrien# 2. Redistributions in binary form must reproduce the above copyright
1678344Sobrien#    notice, this list of conditions and the following disclaimer in the
1778344Sobrien#    documentation and/or other materials provided with the distribution.
1878344Sobrien#
1978344Sobrien# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2078344Sobrien# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2178344Sobrien# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2278344Sobrien# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2378344Sobrien# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2478344Sobrien# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2578344Sobrien# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2678344Sobrien# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
2778344Sobrien# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2878344Sobrien# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2978344Sobrien# POSSIBILITY OF SUCH DAMAGE.
3078344Sobrien#
3178344Sobrien# rc.subr
3278344Sobrien#	functions used by various rc scripts
3378344Sobrien#
3478344Sobrien
35169668Smtm: ${RC_PID:=$$}; export RC_PID
36157473Sflz
3778344Sobrien#
3898186Sgordon#	Operating System dependent/independent variables
3998186Sgordon#
4098186Sgordon
41332371Skevansif [ -n "${_rc_subr_loaded}" ]; then
42332371Skevans	return
43332371Skevansfi
44131550Scperciva
45131550Scperciva_rc_subr_loaded="YES"
46131550Scperciva
4798186SgordonSYSCTL="/sbin/sysctl"
4898186SgordonSYSCTL_N="${SYSCTL} -n"
49202988SemasteSYSCTL_W="${SYSCTL}"
50295949SaraujoPROTECT="/usr/bin/protect"
51124832SmtmID="/usr/bin/id"
52124832SmtmIDCMD="if [ -x $ID ]; then $ID -un; fi"
53161435SyarPS="/bin/ps -ww"
54332367SkevansJID=0
55343046Skevans# rc_service provides the path to the service script that we are executing.
56343046Skevans# This is not being set here in an execution context, necessarily, so it's
57343046Skevans# really just a reasonable guess, and it will get overwritten later if
58343046Skevans# we are executing from some other means than direct execution by service(8)
59343046Skevans# or manual invocation of the service script.  The prime example of this is
60343046Skevans# during system startup, all rc scripts will be invoked via /etc/rc, so
61343046Skevans# run_rc_script will overwrite rc_service with the file being sourced.
62343046Skevansrc_service="$0"
6398186Sgordon
6498186Sgordon#
6578344Sobrien#	functions
6678344Sobrien#	---------
6778344Sobrien
68264243Sdteske# list_vars pattern
69264243Sdteske#	List vars matching pattern.
70264243Sdteske# 
71264243Sdteskelist_vars()
72264243Sdteske{
73264243Sdteske	set | { while read LINE; do
74264243Sdteske		var="${LINE%%=*}"
75264243Sdteske		case "$var" in
76264243Sdteske		"$LINE"|*[!a-zA-Z0-9_]*) continue ;;
77264243Sdteske		$1) echo $var
78264243Sdteske		esac
79264243Sdteske	done; }
80264243Sdteske}
81264243Sdteske
82272393Shrs# set_rcvar [var] [defval] [desc]
83272393Shrs#
84272393Shrs#	Echo or define a rc.conf(5) variable name.  Global variable
85272393Shrs#	$rcvars is used.
86272393Shrs#
87272393Shrs#	If no argument is specified, echo "${name}_enable".
88272393Shrs#
89272393Shrs#	If only a var is specified, echo "${var}_enable".
90272393Shrs#
91272393Shrs#	If var and defval are specified, the ${var} is defined as
92272393Shrs#	rc.conf(5) variable and the default value is ${defvar}.  An
93272393Shrs#	optional argument $desc can also be specified to add a
94272393Shrs#	description for that.
95272393Shrs#
96272393Shrsset_rcvar()
97272393Shrs{
98272393Shrs	local _var
99272393Shrs
100272393Shrs	case $# in
101272393Shrs	0)	echo ${name}_enable ;;
102272393Shrs	1)	echo ${1}_enable ;;
103272393Shrs	*)
104272393Shrs		debug "set_rcvar: \$$1=$2 is added" \
105272393Shrs		    " as a rc.conf(5) variable."
106272393Shrs		_var=$1
107272393Shrs		rcvars="${rcvars# } $_var"
108272393Shrs		eval ${_var}_defval=\"$2\"
109272393Shrs		shift 2
110272393Shrs		eval ${_var}_desc=\"$*\"
111272393Shrs	;;
112272393Shrs	esac
113272393Shrs}
114272393Shrs
115197144Shrs# set_rcvar_obsolete oldvar [newvar] [msg]
116197144Shrs#	Define obsolete variable.
117197144Shrs#	Global variable $rcvars_obsolete is used.
11898186Sgordon#
119197144Shrsset_rcvar_obsolete()
120197144Shrs{
121197144Shrs	local _var
122197144Shrs	_var=$1
123272393Shrs	debug "set_rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
124197144Shrs
125197144Shrs	rcvars_obsolete="${rcvars_obsolete# } $1"
126197144Shrs	eval ${1}_newvar=\"$2\"
127197144Shrs	shift 2
128197144Shrs	eval ${_var}_obsolete_msg=\"$*\"
129197144Shrs}
130197144Shrs
131197144Shrs#
132231667Sdougb# force_depend script [rcvar]
13398186Sgordon#	Force a service to start. Intended for use by services
134231667Sdougb#	to resolve dependency issues.
13598186Sgordon#	$1 - filename of script, in /etc/rc.d, to run
136231667Sdougb#	$2 - name of the script's rcvar (minus the _enable)
13798186Sgordon#
13898186Sgordonforce_depend()
13998186Sgordon{
140231667Sdougb	local _depend _dep_rcvar
141231667Sdougb
14298186Sgordon	_depend="$1"
143231667Sdougb	_dep_rcvar="${2:-$1}_enable"
14498186Sgordon
145231667Sdougb	[ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
146231667Sdougb	    checkyesno $_dep_rcvar && return 0
147231667Sdougb
148231667Sdougb	/etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
149231667Sdougb
15098186Sgordon	info "${name} depends on ${_depend}, which will be forced to start."
151146490Sschweikh	if ! /etc/rc.d/${_depend} forcestart; then
15298186Sgordon		warn "Unable to force ${_depend}. It may already be running."
15398186Sgordon		return 1
15498186Sgordon	fi
15598186Sgordon}
15698186Sgordon
15798186Sgordon#
15878344Sobrien# checkyesno var
15978344Sobrien#	Test $1 variable, and warn if not set to YES or NO.
16078344Sobrien#	Return 0 if it's "yes" (et al), nonzero otherwise.
16178344Sobrien#
16278344Sobriencheckyesno()
16378344Sobrien{
16478344Sobrien	eval _value=\$${1}
16598186Sgordon	debug "checkyesno: $1 is set to $_value."
16678344Sobrien	case $_value in
16778344Sobrien
16878344Sobrien		#	"yes", "true", "on", or "1"
16978344Sobrien	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
17078344Sobrien		return 0
17178344Sobrien		;;
17278344Sobrien
17378344Sobrien		#	"no", "false", "off", or "0"
17478344Sobrien	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
17578344Sobrien		return 1
17678344Sobrien		;;
17778344Sobrien	*)
178229822Sdougb		warn "\$${1} is not set properly - see rc.conf(5)."
17978344Sobrien		return 1
18078344Sobrien		;;
18178344Sobrien	esac
18278344Sobrien}
18378344Sobrien
184157473Sflz#
18598186Sgordon# reverse_list list
18698186Sgordon#	print the list in reverse order
18778344Sobrien#
18898186Sgordonreverse_list()
18998186Sgordon{
19098186Sgordon	_revlist=
191126286Smtm	for _revfile; do
19298186Sgordon		_revlist="$_revfile $_revlist"
19398186Sgordon	done
19498186Sgordon	echo $_revlist
19598186Sgordon}
19698186Sgordon
197169668Smtm# stop_boot always
198169668Smtm#	If booting directly to multiuser or $always is enabled,
199169668Smtm#	send SIGTERM to the parent (/etc/rc) to abort the boot.
200169668Smtm#	Otherwise just exit.
20178344Sobrien#
202169668Smtmstop_boot()
203169668Smtm{
204169668Smtm	local always
205169668Smtm
206178776Smaxim	case $1 in
207178776Smaxim		#	"yes", "true", "on", or "1"
208178770Smtm        [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
209169668Smtm		always=true
210178770Smtm		;;
211178770Smtm	*)
212169668Smtm		always=false
213178770Smtm		;;
214178775Smaxim	esac
215169668Smtm	if [ "$autoboot" = yes -o "$always" = true ]; then
216169668Smtm		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
217169668Smtm		kill -TERM ${RC_PID}
218169668Smtm	fi
219169668Smtm	exit 1
220169668Smtm}
221169668Smtm
222169668Smtm#
22398186Sgordon# mount_critical_filesystems type
22498186Sgordon#	Go through the list of critical filesystems as provided in
22598186Sgordon#	the rc.conf(5) variable $critical_filesystems_${type}, checking
22698186Sgordon#	each one to see if it is mounted, and if it is not, mounting it.
22798186Sgordon#
22878344Sobrienmount_critical_filesystems()
22978344Sobrien{
23098186Sgordon	eval _fslist=\$critical_filesystems_${1}
23178344Sobrien	for _fs in $_fslist; do
23278344Sobrien		mount | (
233126285Smtm			_ismounted=false
23478344Sobrien			while read what _on on _type type; do
23578344Sobrien				if [ $on = $_fs ]; then
236126285Smtm					_ismounted=true
23778344Sobrien				fi
23878344Sobrien			done
239126285Smtm			if $_ismounted; then
240126285Smtm				:
241126285Smtm			else
24278344Sobrien				mount $_fs >/dev/null 2>&1
24378344Sobrien			fi
24498186Sgordon		)
24578344Sobrien	done
24678344Sobrien}
24778344Sobrien
24878344Sobrien#
24998186Sgordon# check_pidfile pidfile procname [interpreter]
25098186Sgordon#	Parses the first line of pidfile for a PID, and ensures
25178344Sobrien#	that the process is running and matches procname.
25298186Sgordon#	Prints the matching PID upon success, nothing otherwise.
25398186Sgordon#	interpreter is optional; see _find_processes() for details.
25478344Sobrien#
25578344Sobriencheck_pidfile()
25678344Sobrien{
25778344Sobrien	_pidfile=$1
25878344Sobrien	_procname=$2
25998186Sgordon	_interpreter=$3
26078344Sobrien	if [ -z "$_pidfile" -o -z "$_procname" ]; then
26198186Sgordon		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
26278344Sobrien	fi
26378344Sobrien	if [ ! -f $_pidfile ]; then
264131061Smtm		debug "pid file ($_pidfile): not readable."
26578344Sobrien		return
26678344Sobrien	fi
26778344Sobrien	read _pid _junk < $_pidfile
26878344Sobrien	if [ -z "$_pid" ]; then
269139949Skeramida		debug "pid file ($_pidfile): no pid in file."
27078344Sobrien		return
27178344Sobrien	fi
27298186Sgordon	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
27378344Sobrien}
27478344Sobrien
27578344Sobrien#
27698186Sgordon# check_process procname [interpreter]
27778344Sobrien#	Ensures that a process (or processes) named procname is running.
27898186Sgordon#	Prints a list of matching PIDs.
27998186Sgordon#	interpreter is optional; see _find_processes() for details.
28078344Sobrien#
28178344Sobriencheck_process()
28278344Sobrien{
28378344Sobrien	_procname=$1
28498186Sgordon	_interpreter=$2
28578344Sobrien	if [ -z "$_procname" ]; then
28698186Sgordon		err 3 'USAGE: check_process procname [interpreter]'
28778344Sobrien	fi
28898186Sgordon	_find_processes $_procname ${_interpreter:-.} '-ax'
28998186Sgordon}
29098186Sgordon
29198186Sgordon#
29298186Sgordon# _find_processes procname interpreter psargs
29398186Sgordon#	Search for procname in the output of ps generated by psargs.
29498186Sgordon#	Prints the PIDs of any matching processes, space separated.
29598186Sgordon#
29698186Sgordon#	If interpreter == ".", check the following variations of procname
29798186Sgordon#	against the first word of each command:
29898186Sgordon#		procname
29998186Sgordon#		`basename procname`
30098186Sgordon#		`basename procname` + ":"
30198186Sgordon#		"(" + `basename procname` + ")"
302155719Sceri#		"[" + `basename procname` + "]"
30398186Sgordon#
30498186Sgordon#	If interpreter != ".", read the first line of procname, remove the
30598186Sgordon#	leading #!, normalise whitespace, append procname, and attempt to
30698186Sgordon#	match that against each command, either as is, or with extra words
307157841Sflz#	at the end.  As an alternative, to deal with interpreted daemons
308157841Sflz#	using perl, the basename of the interpreter plus a colon is also
309157841Sflz#	tried as the prefix to procname.
31098186Sgordon#
31198186Sgordon_find_processes()
31298186Sgordon{
31398186Sgordon	if [ $# -ne 3 ]; then
31498186Sgordon		err 3 'USAGE: _find_processes procname interpreter psargs'
31598186Sgordon	fi
31698186Sgordon	_procname=$1
31798186Sgordon	_interpreter=$2
31898186Sgordon	_psargs=$3
31998186Sgordon
32078344Sobrien	_pref=
32198186Sgordon	if [ $_interpreter != "." ]; then	# an interpreted script
322242183Screes		_script="${_chroot}${_chroot:+/}$_procname"
323242183Screes		if [ -r "$_script" ]; then
324170282Syar			read _interp < $_script	# read interpreter name
325170282Syar			case "$_interp" in
326170282Syar			\#!*)
327170282Syar				_interp=${_interp#\#!}	# strip #!
328170282Syar				set -- $_interp
329170282Syar				case $1 in
330170282Syar				*/bin/env)
331170282Syar					shift	# drop env to get real name
332170282Syar					;;
333170282Syar				esac
334170282Syar				if [ $_interpreter != $1 ]; then
335170282Syar					warn "\$command_interpreter $_interpreter != $1"
336170282Syar				fi
337170282Syar				;;
338170282Syar			*)
339170282Syar				warn "no shebang line in $_script"
340170282Syar				set -- $_interpreter
341170282Syar				;;
342170282Syar			esac
343170282Syar		else
344170282Syar			warn "cannot read shebang line from $_script"
345170282Syar			set -- $_interpreter
34678344Sobrien		fi
34798186Sgordon		_interp="$* $_procname"		# cleanup spaces, add _procname
348157841Sflz		_interpbn=${1##*/}
34998186Sgordon		_fp_args='_argv'
35098186Sgordon		_fp_match='case "$_argv" in
351245250Ssmh		    ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
35298186Sgordon	else					# a normal daemon
35398186Sgordon		_procnamebn=${_procname##*/}
35498186Sgordon		_fp_args='_arg0 _argv'
35598186Sgordon		_fp_match='case "$_arg0" in
356151426Sjhb		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
35798186Sgordon	fi
35898186Sgordon
359161435Syar	_proccheck="\
360161436Syar		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
361157657Sflz		while read _npid _jid '"$_fp_args"'; do
362161436Syar			'"$_fp_match"'
363157657Sflz				if [ "$JID" -eq "$_jid" ];
364157657Sflz				then echo -n "$_pref$_npid";
365157657Sflz				_pref=" ";
366157657Sflz				fi
36798186Sgordon				;;
36898186Sgordon			esac
36998186Sgordon		done'
37098186Sgordon
371114272Smtm#	debug "in _find_processes: proccheck is ($_proccheck)."
37298186Sgordon	eval $_proccheck
37398186Sgordon}
37498186Sgordon
375264243Sdteske# sort_lite [-b] [-n] [-k POS] [-t SEP]
376264243Sdteske#	A lite version of sort(1) (supporting a few options) that can be used
377264243Sdteske#	before the real sort(1) is available (e.g., in scripts that run prior
378264243Sdteske#	to mountcritremote). Requires only shell built-in functionality.
37998186Sgordon#
380264243Sdteskesort_lite()
381264243Sdteske{
382264243Sdteske	local funcname=sort_lite
383264243Sdteske	local sort_sep="$IFS" sort_ignore_leading_space=
384264243Sdteske	local sort_field=0 sort_strict_fields= sort_numeric=
385264243Sdteske	local nitems=0 skip_leading=0 trim=
386264243Sdteske
387264243Sdteske	local OPTIND flag
388264243Sdteske	while getopts bnk:t: flag; do
389264243Sdteske		case "$flag" in
390264243Sdteske		b) sort_ignore_leading_space=1 ;;
391264243Sdteske		n) sort_numeric=1 sort_ignore_leading_space=1 ;;
392264243Sdteske		k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
393264243Sdteske			# NB: Unlike sort(1) only one POS allowed
394264243Sdteske		t) sort_sep="$OPTARG"
395264243Sdteske		   if [ ${#sort_sep} -gt 1 ]; then
396264243Sdteske		   	echo "$funcname: multi-character tab \`$sort_sep'" >&2
397264243Sdteske		   	return 1
398264243Sdteske		   fi
399264243Sdteske		   sort_strict_fields=1
400264243Sdteske		   ;;
401264243Sdteske		\?) return 1 ;;
402264243Sdteske		esac
403264243Sdteske	done
404264243Sdteske	shift $(( $OPTIND - 1 ))
405264243Sdteske
406264243Sdteske	# Create transformation pattern to trim leading text if desired
407264243Sdteske	case "$sort_field" in
408264243Sdteske	""|[!0-9]*|*[!0-9.]*)
409264243Sdteske		echo "$funcname: invalid sort field \`$sort_field'" >&2
410264243Sdteske		return 1
411264243Sdteske		;;
412264243Sdteske	*.*)
413264243Sdteske		skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
414264243Sdteske		while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
415264243Sdteske			trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
416264243Sdteske		done
417264243Sdteske	esac
418264243Sdteske
419264243Sdteske	# Copy input to series of local numbered variables
420264243Sdteske	# NB: IFS of NULL preserves leading whitespace
421264243Sdteske	local LINE
422264243Sdteske	while IFS= read -r LINE || [ "$LINE" ]; do
423264243Sdteske		nitems=$(( $nitems + 1 ))
424264243Sdteske		local src_$nitems="$LINE"
425264243Sdteske	done
426264243Sdteske
427264243Sdteske	#
428264243Sdteske	# Sort numbered locals using insertion sort
429264243Sdteske	#
430264243Sdteske	local curitem curitem_orig curitem_mod curitem_haskey
431264243Sdteske	local dest dest_orig dest_mod dest_haskey
432264243Sdteske	local d gt n
433264243Sdteske	local i=1 
434264243Sdteske	while [ $i -le $nitems ]; do
435264243Sdteske		curitem_haskey=1 # Assume sort field (-k POS) exists
436264243Sdteske		eval curitem=\"\$src_$i\"
437264243Sdteske		curitem_mod="$curitem" # for modified comparison
438264243Sdteske		curitem_orig="$curitem" # for original comparison
439264243Sdteske
440264243Sdteske		# Trim leading whitespace if desired
441264243Sdteske		if [ "$sort_ignore_leading_space" ]; then
442264243Sdteske			while case "$curitem_orig" in
443264243Sdteske				[$IFS]*) : ;; *) false; esac
444264243Sdteske			do
445264243Sdteske				curitem_orig="${curitem_orig#?}"
446264243Sdteske			done
447264243Sdteske			curitem_mod="$curitem_orig"
448264243Sdteske		fi
449264243Sdteske
450264243Sdteske		# Shift modified comparison value if sort field (-k POS) is > 1
451264243Sdteske		n=$sort_field
452264243Sdteske		while [ $n -gt 1 ]; do
453264243Sdteske			case "$curitem_mod" in
454264243Sdteske			*[$sort_sep]*)
455264243Sdteske				# Cut text up-to (and incl.) first separator
456264243Sdteske				curitem_mod="${curitem_mod#*[$sort_sep]}"
457264243Sdteske
458264243Sdteske				# Skip NULLs unless strict field splitting
459264243Sdteske				[ "$sort_strict_fields" ] ||
460264243Sdteske					[ "${curitem_mod%%[$sort_sep]*}" ] ||
461264243Sdteske					[ $n -eq 2 ] ||
462264243Sdteske					continue
463264243Sdteske				;;
464264243Sdteske			*)
465264243Sdteske				# Asked for a field that doesn't exist
466264243Sdteske				curitem_haskey= break
467264243Sdteske			esac
468264243Sdteske			n=$(( $n - 1 ))
469264243Sdteske		done
470264243Sdteske
471264243Sdteske		# Trim trailing words if sort field >= 1
472264243Sdteske		[ $sort_field -ge 1 -a "$sort_numeric" ] &&
473264243Sdteske			curitem_mod="${curitem_mod%%[$sort_sep]*}"
474264243Sdteske
475264243Sdteske		# Apply optional trim (-k POS.TRIM) to cut leading characters
476264243Sdteske		curitem_mod="${curitem_mod#$trim}"
477264243Sdteske
478264243Sdteske		# Determine the type of modified comparison to use initially
479264243Sdteske		# NB: Prefer numerical if requested but fallback to standard
480264243Sdteske		case "$curitem_mod" in
481264243Sdteske		""|[!0-9]*) # NULL or begins with non-number
482264243Sdteske			gt=">"
483264243Sdteske			[ "$sort_numeric" ] && curitem_mod=0
484264243Sdteske			;;
485264243Sdteske		*)
486264243Sdteske			if [ "$sort_numeric" ]; then
487264243Sdteske				gt="-gt"
488264243Sdteske				curitem_mod="${curitem_mod%%[!0-9]*}"
489264243Sdteske					# NB: trailing non-digits removed
490264243Sdteske					# otherwise numeric comparison fails
491264243Sdteske			else
492264243Sdteske				gt=">"
493264243Sdteske			fi
494264243Sdteske		esac
495264243Sdteske
496264243Sdteske		# If first time through, short-circuit below position-search
497264243Sdteske		if [ $i -le 1 ]; then
498264243Sdteske			d=0
499264243Sdteske		else
500264243Sdteske			d=1
501264243Sdteske		fi
502264243Sdteske
503264243Sdteske		#
504264243Sdteske		# Find appropriate element position
505264243Sdteske		#
506264243Sdteske		while [ $d -gt 0 ]
507264243Sdteske		do
508264243Sdteske			dest_haskey=$curitem_haskey
509264243Sdteske			eval dest=\"\$dest_$d\"
510264243Sdteske			dest_mod="$dest" # for modified comparison
511264243Sdteske			dest_orig="$dest" # for original comparison
512264243Sdteske
513264243Sdteske			# Trim leading whitespace if desired
514264243Sdteske			if [ "$sort_ignore_leading_space" ]; then
515264243Sdteske				while case "$dest_orig" in
516264243Sdteske					[$IFS]*) : ;; *) false; esac
517264243Sdteske				do
518264243Sdteske					dest_orig="${dest_orig#?}"
519264243Sdteske				done
520264243Sdteske				dest_mod="$dest_orig"
521264243Sdteske			fi
522264243Sdteske
523264243Sdteske			# Shift modified value if sort field (-k POS) is > 1
524264243Sdteske			n=$sort_field
525264243Sdteske			while [ $n -gt 1 ]; do
526264243Sdteske				case "$dest_mod" in
527264243Sdteske				*[$sort_sep]*)
528264243Sdteske					# Cut text up-to (and incl.) 1st sep
529264243Sdteske					dest_mod="${dest_mod#*[$sort_sep]}"
530264243Sdteske
531264243Sdteske					# Skip NULLs unless strict fields
532264243Sdteske					[ "$sort_strict_fields" ] ||
533264243Sdteske					    [ "${dest_mod%%[$sort_sep]*}" ] ||
534264243Sdteske					    [ $n -eq 2 ] ||
535264243Sdteske					    continue
536264243Sdteske					;;
537264243Sdteske				*)
538264243Sdteske					# Asked for a field that doesn't exist
539264243Sdteske					dest_haskey= break
540264243Sdteske				esac
541264243Sdteske				n=$(( $n - 1 ))
542264243Sdteske			done
543264243Sdteske
544264243Sdteske			# Trim trailing words if sort field >= 1
545264243Sdteske			[ $sort_field -ge 1 -a "$sort_numeric" ] &&
546264243Sdteske				dest_mod="${dest_mod%%[$sort_sep]*}"
547264243Sdteske
548264243Sdteske			# Apply optional trim (-k POS.TRIM), cut leading chars
549264243Sdteske			dest_mod="${dest_mod#$trim}"
550264243Sdteske
551264243Sdteske			# Determine type of modified comparison to use
552264243Sdteske			# NB: Prefer numerical if requested, fallback to std
553264243Sdteske			case "$dest_mod" in
554264243Sdteske			""|[!0-9]*) # NULL or begins with non-number
555264243Sdteske				gt=">"
556264243Sdteske				[ "$sort_numeric" ] && dest_mod=0
557264243Sdteske				;;
558264243Sdteske			*)
559264243Sdteske				if [ "$sort_numeric" ]; then
560264243Sdteske					gt="-gt"
561264243Sdteske					dest_mod="${dest_mod%%[!0-9]*}"
562264243Sdteske						# NB: kill trailing non-digits
563264243Sdteske						# for numeric comparison safety
564264243Sdteske				else
565264243Sdteske					gt=">"
566264243Sdteske				fi
567264243Sdteske			esac
568264243Sdteske
569264243Sdteske			# Break if we've found the proper element position
570264243Sdteske			if [ "$curitem_haskey" -a "$dest_haskey" ]; then
571264243Sdteske				if [ "$dest_mod" = "$curitem_mod" ]; then
572264243Sdteske					[ "$dest_orig" ">" "$curitem_orig" ] &&
573264243Sdteske						break
574264243Sdteske				elif [ "$dest_mod" $gt "$curitem_mod" ] \
575264243Sdteske					2> /dev/null
576264243Sdteske				then
577264243Sdteske					break
578264243Sdteske				fi
579264243Sdteske			else
580264243Sdteske				[ "$dest_orig" ">" "$curitem_orig" ] && break
581264243Sdteske			fi
582264243Sdteske
583264243Sdteske			# Break if we've hit the end
584264243Sdteske			[ $d -ge $i ] && break
585264243Sdteske
586264243Sdteske			d=$(( $d + 1 ))
587264243Sdteske		done
588264243Sdteske
589264243Sdteske		# Shift remaining positions forward, making room for new item
590264243Sdteske		n=$i
591264243Sdteske		while [ $n -ge $d ]; do
592264243Sdteske			# Shift destination item forward one placement
593264243Sdteske			eval dest_$(( $n + 1 ))=\"\$dest_$n\"
594264243Sdteske			n=$(( $n - 1 ))
595264243Sdteske		done
596264243Sdteske
597264243Sdteske		# Place the element
598264243Sdteske		if [ $i -eq 1 ]; then
599264243Sdteske			local dest_1="$curitem"
600264243Sdteske		else
601264243Sdteske			local dest_$d="$curitem"
602264243Sdteske		fi
603264243Sdteske
604264243Sdteske		i=$(( $i + 1 ))
605264243Sdteske	done
606264243Sdteske
607264243Sdteske	# Print sorted results
608264243Sdteske	d=1
609264243Sdteske	while [ $d -le $nitems ]; do
610264243Sdteske		eval echo \"\$dest_$d\"
611264243Sdteske		d=$(( $d + 1 ))
612264243Sdteske	done
613264243Sdteske}
614264243Sdteske
615264243Sdteske#
61698186Sgordon# wait_for_pids pid [pid ...]
61798186Sgordon#	spins until none of the pids exist
61898186Sgordon#
61998186Sgordonwait_for_pids()
62098186Sgordon{
621206248Sdougb	local _list _prefix _nlist _j
622206248Sdougb
623126286Smtm	_list="$@"
62498186Sgordon	if [ -z "$_list" ]; then
62598186Sgordon		return
62698186Sgordon	fi
62798186Sgordon	_prefix=
62898186Sgordon	while true; do
62998186Sgordon		_nlist="";
63098186Sgordon		for _j in $_list; do
63198186Sgordon			if kill -0 $_j 2>/dev/null; then
63298186Sgordon				_nlist="${_nlist}${_nlist:+ }$_j"
633206248Sdougb				[ -n "$_prefix" ] && sleep 1
63498186Sgordon			fi
63598186Sgordon		done
63698186Sgordon		if [ -z "$_nlist" ]; then
63798186Sgordon			break
63878344Sobrien		fi
63998186Sgordon		_list=$_nlist
64098186Sgordon		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
64198186Sgordon		_prefix=", "
642206248Sdougb		pwait $_list 2>/dev/null
64378344Sobrien	done
64498186Sgordon	if [ -n "$_prefix" ]; then
64598186Sgordon		echo "."
64698186Sgordon	fi
64778344Sobrien}
64878344Sobrien
64978344Sobrien#
650220962Sdougb# get_pidfile_from_conf string file
651220962Sdougb#
652220962Sdougb#	Takes a string to search for in the specified file.
653220962Sdougb#	Ignores lines with traditional comment characters.
654220962Sdougb#
655220962Sdougb# Example:
656220962Sdougb#
657220962Sdougb# if get_pidfile_from_conf string file; then
658220962Sdougb#	pidfile="$_pidfile_from_conf"
659220962Sdougb# else
660220962Sdougb#	pidfile='appropriate default'
661220962Sdougb# fi
662220962Sdougb#
663220962Sdougbget_pidfile_from_conf()
664220962Sdougb{
665220963Sdougb	if [ -z "$1" -o -z "$2" ]; then
666220963Sdougb		err 3 "USAGE: get_pidfile_from_conf string file ($name)"
667220963Sdougb	fi
668220963Sdougb
669220962Sdougb	local string file line
670220962Sdougb
671220962Sdougb	string="$1" ; file="$2"
672220962Sdougb
673220963Sdougb	if [ ! -s "$file" ]; then
674220963Sdougb		err 3 "get_pidfile_from_conf: $file does not exist ($name)"
675220962Sdougb	fi
676220962Sdougb
677220962Sdougb	while read line; do
678220962Sdougb		case "$line" in
679220962Sdougb		*[#\;]*${string}*)	continue ;;
680220962Sdougb		*${string}*)		break ;;
681220962Sdougb		esac
682220962Sdougb	done < $file
683220962Sdougb
684220962Sdougb	if [ -n "$line" ]; then
685220962Sdougb		line=${line#*/}
686220962Sdougb		_pidfile_from_conf="/${line%%[\"\;]*}"
687220962Sdougb	else
688220962Sdougb		return 1
689220962Sdougb	fi
690220962Sdougb}
691220962Sdougb
692220962Sdougb#
693197947Sdougb# check_startmsgs
694197947Sdougb#	If rc_quiet is set (usually as a result of using faststart at
695197947Sdougb#	boot time) check if rc_startmsgs is enabled.
696197947Sdougb#
697197947Sdougbcheck_startmsgs()
698197947Sdougb{
699197947Sdougb	if [ -n "$rc_quiet" ]; then
700197947Sdougb		checkyesno rc_startmsgs
701197947Sdougb	else
702197947Sdougb		return 0
703197947Sdougb	fi
704197947Sdougb}
705197947Sdougb
706197947Sdougb#
70798186Sgordon# run_rc_command argument
70898186Sgordon#	Search for argument in the list of supported commands, which is:
70998186Sgordon#		"start stop restart rcvar status poll ${extra_commands}"
71098186Sgordon#	If there's a match, run ${argument}_cmd or the default method
71198186Sgordon#	(see below).
71278344Sobrien#
71398186Sgordon#	If argument has a given prefix, then change the operation as follows:
71498186Sgordon#		Prefix	Operation
71578344Sobrien#		------	---------
716175676Smtm#		fast	Skip the pid check, and set rc_fast=yes, rc_quiet=yes
71798186Sgordon#		force	Set ${rcvar} to YES, and set rc_force=yes
718126303Smtm#		one	Set ${rcvar} to YES
719175676Smtm#		quiet	Don't output some diagnostics, and set rc_quiet=yes
72078344Sobrien#
72178344Sobrien#	The following globals are used:
72278344Sobrien#
72398186Sgordon#	Name		Needed	Purpose
72498186Sgordon#	----		------	-------
72578344Sobrien#	name		y	Name of script.
72678344Sobrien#
72778344Sobrien#	command		n	Full path to command.
72898186Sgordon#				Not needed if ${rc_arg}_cmd is set for
72978344Sobrien#				each keyword.
73078344Sobrien#
73178344Sobrien#	command_args	n	Optional args/shell directives for command.
73278344Sobrien#
73398186Sgordon#	command_interpreter n	If not empty, command is interpreted, so
73498186Sgordon#				call check_{pidfile,process}() appropriately.
73598186Sgordon#
736197144Shrs#	desc		n	Description of script.
737197144Shrs#
73878344Sobrien#	extra_commands	n	List of extra commands supported.
73978344Sobrien#
74098186Sgordon#	pidfile		n	If set, use check_pidfile $pidfile $command,
74198186Sgordon#				otherwise use check_process $command.
74298186Sgordon#				In either case, only check if $command is set.
74378344Sobrien#
74498186Sgordon#	procname	n	Process name to check for instead of $command.
74598186Sgordon#
74678344Sobrien#	rcvar		n	This is checked with checkyesno to determine
74778344Sobrien#				if the action should be run.
74878344Sobrien#
749157653Sflz#	${name}_program	n	Full path to command.
750157653Sflz#				Meant to be used in /etc/rc.conf to override
751157653Sflz#				${command}.
752157653Sflz#
75378344Sobrien#	${name}_chroot	n	Directory to chroot to before running ${command}
75498186Sgordon#				Requires /usr to be mounted.
75578344Sobrien#
75678344Sobrien#	${name}_chdir	n	Directory to cd to before running ${command}
75778344Sobrien#				(if not using ${name}_chroot).
75878344Sobrien#
75978344Sobrien#	${name}_flags	n	Arguments to call ${command} with.
76078344Sobrien#				NOTE:	$flags from the parent environment
76178344Sobrien#					can be used to override this.
76278344Sobrien#
763272974Shrs#	${name}_env	n	Environment variables to run ${command} with.
764272974Shrs#
765242184Shrs#	${name}_fib	n	Routing table number to run ${command} with.
766242184Shrs#
76778344Sobrien#	${name}_nice	n	Nice level to run ${command} at.
76878344Sobrien#
769295949Saraujo#	${name}_oomprotect n	Don't kill ${command} when swap space is exhausted.
770295949Saraujo#
77178344Sobrien#	${name}_user	n	User to run ${command} as, using su(1) if not
77278344Sobrien#				using ${name}_chroot.
77398186Sgordon#				Requires /usr to be mounted.
77478344Sobrien#
77578344Sobrien#	${name}_group	n	Group to run chrooted ${command} as.
77698186Sgordon#				Requires /usr to be mounted.
77778344Sobrien#
77898186Sgordon#	${name}_groups	n	Comma separated list of supplementary groups
77998186Sgordon#				to run the chrooted ${command} with.
78098186Sgordon#				Requires /usr to be mounted.
78178344Sobrien#
782272974Shrs#	${name}_prepend	n	Command added before ${command}.
783272974Shrs#
784288291Sadrian#	${name}_login_class n	Login class to use, else "daemon".
785288291Sadrian#
78698186Sgordon#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
78778344Sobrien#				Otherwise, use default command (see below)
78878344Sobrien#
78998186Sgordon#	${rc_arg}_precmd n	If set, run just before performing the
79098186Sgordon#				${rc_arg}_cmd method in the default
79198186Sgordon#				operation (i.e, after checking for required
79298186Sgordon#				bits and process (non)existence).
79378344Sobrien#				If this completes with a non-zero exit code,
79498186Sgordon#				don't run ${rc_arg}_cmd.
79578344Sobrien#
79698186Sgordon#	${rc_arg}_postcmd n	If set, run just after performing the
79798186Sgordon#				${rc_arg}_cmd method, if that method
79898186Sgordon#				returned a zero exit code.
79998186Sgordon#
80078344Sobrien#	required_dirs	n	If set, check for the existence of the given
801165565Syar#				directories before running a (re)start command.
80278344Sobrien#
80378344Sobrien#	required_files	n	If set, check for the readability of the given
804165565Syar#				files before running a (re)start command.
80578344Sobrien#
806165565Syar#	required_modules n	If set, ensure the given kernel modules are
807165565Syar#				loaded before running a (re)start command.
808165565Syar#				The check and possible loads are actually
809165565Syar#				done after start_precmd so that the modules
810165565Syar#				aren't loaded in vain, should the precmd
811165565Syar#				return a non-zero status to indicate a error.
812165565Syar#				If a word in the list looks like "foo:bar",
813165565Syar#				"foo" is the KLD file name and "bar" is the
814165565Syar#				module name.  If a word looks like "foo~bar",
815165565Syar#				"foo" is the KLD file name and "bar" is a
816165565Syar#				egrep(1) pattern matching the module name.
817165565Syar#				Otherwise the module name is assumed to be
818165565Syar#				the same as the KLD file name, which is most
819165565Syar#				common.  See load_kld().
820165565Syar#
82178344Sobrien#	required_vars	n	If set, perform checkyesno on each of the
82278344Sobrien#				listed variables before running the default
82378344Sobrien#				(re)start command.
82478344Sobrien#
82598186Sgordon#	Default behaviour for a given argument, if no override method is
82698186Sgordon#	provided:
82778344Sobrien#
82898186Sgordon#	Argument	Default behaviour
82998186Sgordon#	--------	-----------------
83078344Sobrien#	start		if !running && checkyesno ${rcvar}
83178344Sobrien#				${command}
83278344Sobrien#
83378344Sobrien#	stop		if ${pidfile}
83498186Sgordon#				rc_pid=$(check_pidfile $pidfile $command)
83578344Sobrien#			else
83698186Sgordon#				rc_pid=$(check_process $command)
83798186Sgordon#			kill $sig_stop $rc_pid
83898186Sgordon#			wait_for_pids $rc_pid
83998186Sgordon#			($sig_stop defaults to TERM.)
84078344Sobrien#
84198186Sgordon#	reload		Similar to stop, except use $sig_reload instead,
84298186Sgordon#			and doesn't wait_for_pids.
84378344Sobrien#			$sig_reload defaults to HUP.
844151685Syar#			Note that `reload' isn't provided by default,
845151685Syar#			it should be enabled via $extra_commands.
84678344Sobrien#
84778344Sobrien#	restart		Run `stop' then `start'.
84878344Sobrien#
84998186Sgordon#	status		Show if ${command} is running, etc.
85078344Sobrien#
85198186Sgordon#	poll		Wait for ${command} to exit.
85298186Sgordon#
85398186Sgordon#	rcvar		Display what rc.conf variable is used (if any).
85498186Sgordon#
855255809Sdes#	enabled		Return true if the service is enabled.
856255809Sdes#
857298515Slme#	describe	Show the service's description
858298515Slme#
859298515Slme#	extracommands	Show the service's extra commands
860298515Slme#
86198186Sgordon#	Variables available to methods, and after run_rc_command() has
86298186Sgordon#	completed:
86398186Sgordon#
86498186Sgordon#	Variable	Purpose
86598186Sgordon#	--------	-------
866126303Smtm#	rc_arg		Argument to command, after fast/force/one processing
86798186Sgordon#			performed
86898186Sgordon#
86998186Sgordon#	rc_flags	Flags to start the default command with.
87098186Sgordon#			Defaults to ${name}_flags, unless overridden
87198186Sgordon#			by $flags from the environment.
87298186Sgordon#			This variable may be changed by the precmd method.
87398186Sgordon#
874343046Skevans#       rc_service      Path to the service being executed, in case the service
875343046Skevans#                       needs to re-invoke itself.
876343046Skevans#
87798186Sgordon#	rc_pid		PID of command (if appropriate)
87898186Sgordon#
87998186Sgordon#	rc_fast		Not empty if "fast" was provided (q.v.)
88098186Sgordon#
88198186Sgordon#	rc_force	Not empty if "force" was provided (q.v.)
88298186Sgordon#
883175676Smtm#	rc_quiet	Not empty if "quiet" was provided
88498186Sgordon#
885175676Smtm#
88678344Sobrienrun_rc_command()
88778344Sobrien{
888116097Smtm	_return=0
88998186Sgordon	rc_arg=$1
89078344Sobrien	if [ -z "$name" ]; then
89198186Sgordon		err 3 'run_rc_command: $name is not set.'
89278344Sobrien	fi
89378344Sobrien
894132892Smtm	# Don't repeat the first argument when passing additional command-
895132892Smtm	# line arguments to the command subroutines.
896132892Smtm	#
897132892Smtm	shift 1
898132892Smtm	rc_extra_args="$*"
899132892Smtm
900126303Smtm	_rc_prefix=
90198186Sgordon	case "$rc_arg" in
90278344Sobrien	fast*)				# "fast" prefix; don't check pid
90398186Sgordon		rc_arg=${rc_arg#fast}
90498186Sgordon		rc_fast=yes
905175676Smtm		rc_quiet=yes
90678344Sobrien		;;
907198216Sed	force*)				# "force" prefix; always run
90898186Sgordon		rc_force=yes
909126303Smtm		_rc_prefix=force
910126303Smtm		rc_arg=${rc_arg#${_rc_prefix}}
91178344Sobrien		if [ -n "${rcvar}" ]; then
91278344Sobrien			eval ${rcvar}=YES
91378344Sobrien		fi
91478344Sobrien		;;
915126303Smtm	one*)				# "one" prefix; set ${rcvar}=yes
916126303Smtm		_rc_prefix=one
917126303Smtm		rc_arg=${rc_arg#${_rc_prefix}}
918126303Smtm		if [ -n "${rcvar}" ]; then
919126303Smtm			eval ${rcvar}=YES
920126303Smtm		fi
921126303Smtm		;;
922175676Smtm	quiet*)				# "quiet" prefix; omit some messages
923175676Smtm		_rc_prefix=quiet
924175676Smtm		rc_arg=${rc_arg#${_rc_prefix}}
925175676Smtm		rc_quiet=yes
926175676Smtm		;;
92778344Sobrien	esac
92878344Sobrien
929161530Sflz	eval _override_command=\$${name}_program
930198162Sdougb	command=${_override_command:-$command}
931161530Sflz
932298515Slme	_keywords="start stop restart rcvar enabled describe extracommands $extra_commands"
93398186Sgordon	rc_pid=
93478344Sobrien	_pidcmd=
93598186Sgordon	_procname=${procname:-${command}}
93698186Sgordon
937131135Smtm					# setup pid check command
938131135Smtm	if [ -n "$_procname" ]; then
93978344Sobrien		if [ -n "$pidfile" ]; then
94098186Sgordon			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
94198186Sgordon		else
94298186Sgordon			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
94378344Sobrien		fi
944332371Skevans		_keywords="${_keywords} status poll"
94578344Sobrien	fi
94678344Sobrien
94798186Sgordon	if [ -z "$rc_arg" ]; then
948150796Syar		rc_usage $_keywords
94978344Sobrien	fi
95078344Sobrien
951255809Sdes	if [ "$rc_arg" = "enabled" ] ; then
952255809Sdes		checkyesno ${rcvar}
953255809Sdes		return $?
954255809Sdes	fi
955255809Sdes
95678344Sobrien	if [ -n "$flags" ]; then	# allow override from environment
95798186Sgordon		rc_flags=$flags
95878344Sobrien	else
95998186Sgordon		eval rc_flags=\$${name}_flags
96078344Sobrien	fi
96198186Sgordon	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
96298186Sgordon	    _nice=\$${name}_nice	_user=\$${name}_user \
963242184Shrs	    _group=\$${name}_group	_groups=\$${name}_groups \
964272974Shrs	    _fib=\$${name}_fib		_env=\$${name}_env \
965295949Saraujo	    _prepend=\$${name}_prepend	_login_class=\${${name}_login_class:-daemon} \
966332363Skevans	    _oomprotect=\$${name}_oomprotect
96778344Sobrien
96898186Sgordon	if [ -n "$_user" ]; then	# unset $_user if running as that user
969124832Smtm		if [ "$_user" = "$(eval $IDCMD)" ]; then
97098186Sgordon			unset _user
97198186Sgordon		fi
97298186Sgordon	fi
97398186Sgordon
974230374Sdougb	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
975179870Smtm
976179870Smtm	for _elem in $_keywords; do
977179870Smtm		if [ "$_elem" != "$rc_arg" ]; then
978179870Smtm			continue
979179870Smtm		fi
980298515Slme					# if ${rcvar} is set, $1 is not "rcvar" and not "describe"
981206686Sdougb					# and ${rc_pid} is not set, then run
98278344Sobrien					#	checkyesno ${rcvar}
98378344Sobrien					# and return if that failed
98478344Sobrien					#
985298515Slme		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
986298515Slme		    -a "$rc_arg" != "describe" ] ||
987220760Sdougb		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
988179870Smtm			if ! checkyesno ${rcvar}; then
989179870Smtm				if [ -n "${rc_quiet}" ]; then
990179870Smtm					return 0
991179870Smtm				fi
992179870Smtm				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
993179870Smtm				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
994179870Smtm				echo "instead of '${rc_arg}'."
995175676Smtm				return 0
996175676Smtm			fi
99778344Sobrien		fi
99878344Sobrien
999291770Sjilles		if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1000291770Sjilles			if [ -z "$rc_quiet" ]; then
1001291770Sjilles				echo 1>&2 "${name} already running? " \
1002291770Sjilles				    "(pid=$rc_pid)."
1003291770Sjilles			fi
1004291770Sjilles			return 1
1005291770Sjilles		fi
1006291770Sjilles
100778344Sobrien					# if there's a custom ${XXX_cmd},
100878344Sobrien					# run that instead of the default
100978344Sobrien					#
1010165565Syar		eval _cmd=\$${rc_arg}_cmd \
1011165565Syar		     _precmd=\$${rc_arg}_precmd \
1012165565Syar		     _postcmd=\$${rc_arg}_postcmd
1013165565Syar
101478344Sobrien		if [ -n "$_cmd" ]; then
1015165565Syar			_run_rc_precmd || return 1
1016165565Syar			_run_rc_doit "$_cmd $rc_extra_args" || return 1
1017165565Syar			_run_rc_postcmd
1018116097Smtm			return $_return
101978344Sobrien		fi
102078344Sobrien
102198186Sgordon		case "$rc_arg" in	# default operations...
102278344Sobrien
1023298515Slme		describe)
1024298515Slme			if [ -n "$desc" ]; then
1025298515Slme				echo "$desc"
1026298515Slme			fi
1027298515Slme			;;
1028298515Slme	
1029298515Slme		extracommands)
1030298515Slme			echo "$extra_commands"
1031298515Slme			;;
1032298515Slme
103378344Sobrien		status)
1034165565Syar			_run_rc_precmd || return 1
103598186Sgordon			if [ -n "$rc_pid" ]; then
103698186Sgordon				echo "${name} is running as pid $rc_pid."
103778344Sobrien			else
103878344Sobrien				echo "${name} is not running."
103978344Sobrien				return 1
104078344Sobrien			fi
1041165565Syar			_run_rc_postcmd
104278344Sobrien			;;
104378344Sobrien
104478344Sobrien		start)
1045242183Screes			if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1046160667Syar				warn "run_rc_command: cannot run $command"
1047153152Syar				return 1
104878344Sobrien			fi
104978344Sobrien
1050179946Smtm			if ! _run_rc_precmd; then
1051179946Smtm				warn "failed precmd routine for ${name}"
1052179946Smtm				return 1
1053179946Smtm			fi
105478344Sobrien
1055160668Syar					# setup the full command to run
105678344Sobrien					#
1057197947Sdougb			check_startmsgs && echo "Starting ${name}."
105878344Sobrien			if [ -n "$_chroot" ]; then
1059310010Sdteske				_cd=
106078344Sobrien				_doit="\
106178344Sobrien${_nice:+nice -n $_nice }\
1062242184Shrs${_fib:+setfib -F $_fib }\
1063272974Shrs${_env:+env $_env }\
106478344Sobrienchroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
106598186Sgordon$_chroot $command $rc_flags $command_args"
106678344Sobrien			else
1067310010Sdteske				_cd="${_chdir:+cd $_chdir && }"
106878344Sobrien				_doit="\
1069242184Shrs${_fib:+setfib -F $_fib }\
1070272974Shrs${_env:+env $_env }\
107198186Sgordon$command $rc_flags $command_args"
107298186Sgordon				if [ -n "$_user" ]; then
107398186Sgordon				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
107498186Sgordon				fi
1075161396Syar				if [ -n "$_nice" ]; then
1076161396Syar					if [ -z "$_user" ]; then
1077161396Syar						_doit="sh -c \"$_doit\""
1078201036Sdougb					fi
1079161396Syar					_doit="nice -n $_nice $_doit"
1080161396Syar				fi
1081272974Shrs				if [ -n "$_prepend" ]; then
1082272974Shrs					_doit="$_prepend $_doit"
1083272974Shrs				fi
108478344Sobrien			fi
108598186Sgordon
1086288291Sadrian					# Prepend default limits
1087332363Skevans			_doit="$_cd limits -C $_login_class $_doit"
1088288291Sadrian
1089165565Syar					# run the full command
109098186Sgordon					#
1091179946Smtm			if ! _run_rc_doit "$_doit"; then
1092179946Smtm				warn "failed to start ${name}"
1093179946Smtm				return 1
1094179946Smtm			fi
109598186Sgordon
109698186Sgordon					# finally, run postcmd
109798186Sgordon					#
1098165565Syar			_run_rc_postcmd
109978344Sobrien			;;
110078344Sobrien
110178344Sobrien		stop)
110298186Sgordon			if [ -z "$rc_pid" ]; then
1103153152Syar				[ -n "$rc_fast" ] && return 0
1104165565Syar				_run_rc_notrunning
1105153152Syar				return 1
110678344Sobrien			fi
110778344Sobrien
1108165565Syar			_run_rc_precmd || return 1
110998186Sgordon
111098186Sgordon					# send the signal to stop
111198186Sgordon					#
111278344Sobrien			echo "Stopping ${name}."
1113165565Syar			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1114165565Syar			_run_rc_doit "$_doit" || return 1
111598186Sgordon
111698186Sgordon					# wait for the command to exit,
111798186Sgordon					# and run postcmd.
111898186Sgordon			wait_for_pids $rc_pid
1119165565Syar
1120165565Syar			_run_rc_postcmd
112178344Sobrien			;;
112278344Sobrien
112378344Sobrien		reload)
112498186Sgordon			if [ -z "$rc_pid" ]; then
1125165565Syar				_run_rc_notrunning
1126153152Syar				return 1
112778344Sobrien			fi
1128165565Syar
1129165565Syar			_run_rc_precmd || return 1
1130165565Syar
1131165565Syar			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1132165565Syar			_run_rc_doit "$_doit" || return 1
1133165565Syar
1134165565Syar			_run_rc_postcmd
113578344Sobrien			;;
113678344Sobrien
113778344Sobrien		restart)
113878344Sobrien					# prevent restart being called more
113978344Sobrien					# than once by any given script
114078344Sobrien					#
1141126285Smtm			if ${_rc_restart_done:-false}; then
114278344Sobrien				return 0
114378344Sobrien			fi
1144126285Smtm			_rc_restart_done=true
114578344Sobrien
1146165565Syar			_run_rc_precmd || return 1
1147165565Syar
1148165565Syar			# run those in a subshell to keep global variables
1149152519Syar			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1150165565Syar			( run_rc_command ${_rc_prefix}start $rc_extra_args )
1151165565Syar			_return=$?
1152165565Syar			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
115398186Sgordon
1154165565Syar			_run_rc_postcmd
115578344Sobrien			;;
115678344Sobrien
115798186Sgordon		poll)
1158165565Syar			_run_rc_precmd || return 1
115998186Sgordon			if [ -n "$rc_pid" ]; then
116098186Sgordon				wait_for_pids $rc_pid
116198186Sgordon			fi
1162165565Syar			_run_rc_postcmd
116398186Sgordon			;;
116498186Sgordon
116578344Sobrien		rcvar)
1166197144Shrs			echo -n "# $name"
1167197144Shrs			if [ -n "$desc" ]; then
1168197144Shrs				echo " : $desc"
1169197144Shrs			else
1170197144Shrs				echo ""
1171197144Shrs			fi
1172197144Shrs			echo "#"
1173272393Shrs			# Get unique vars in $rcvar $rcvars
1174272393Shrs			for _v in $rcvar $rcvars; do
1175197144Shrs				case $v in
1176197144Shrs				$_v\ *|\ *$_v|*\ $_v\ *) ;;
1177197144Shrs				*)	v="${v# } $_v" ;;
1178197144Shrs				esac
1179197144Shrs			done
1180197144Shrs
1181197144Shrs			# Display variables.
1182197144Shrs			for _v in $v; do
1183197144Shrs				if [ -z "$_v" ]; then
1184197144Shrs					continue
118578344Sobrien				fi
1186197144Shrs
1187197144Shrs				eval _desc=\$${_v}_desc
1188197144Shrs				eval _defval=\$${_v}_defval
1189197144Shrs				_h="-"
1190197144Shrs
1191197144Shrs				eval echo \"$_v=\\\"\$$_v\\\"\"
1192197144Shrs				# decode multiple lines of _desc
1193197144Shrs				while [ -n "$_desc" ]; do
1194197144Shrs					case $_desc in
1195197144Shrs					*^^*)
1196197144Shrs						echo "# $_h ${_desc%%^^*}"
1197197144Shrs						_desc=${_desc#*^^}
1198197144Shrs						_h=" "
1199197144Shrs						;;
1200197144Shrs					*)
1201197144Shrs						echo "# $_h ${_desc}"
1202197144Shrs						break
1203197144Shrs						;;
1204197144Shrs					esac
1205197144Shrs				done
1206197144Shrs				echo "#   (default: \"$_defval\")"
1207197144Shrs			done
1208197144Shrs			echo ""
120978344Sobrien			;;
121078344Sobrien
121178344Sobrien		*)
1212150796Syar			rc_usage $_keywords
121378344Sobrien			;;
121478344Sobrien
121578344Sobrien		esac
1216295949Saraujo
1217295949Saraujo		# Apply protect(1) to the PID if ${name}_oomprotect is set.
1218295949Saraujo		case "$rc_arg" in
1219295949Saraujo		start)
1220309130Saraujo			# We cannot use protect(1) inside jails.
1221309130Saraujo			if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1222309130Saraujo			    [ "$(sysctl -n security.jail.jailed)" -eq 0 ]; then
1223309130Saraujo				pid=$(check_process $command)
1224309130Saraujo				case $_oomprotect in
1225309130Saraujo				[Aa][Ll][Ll])
1226309130Saraujo					${PROTECT} -i -p ${pid}
1227309130Saraujo					;;
1228309130Saraujo				[Yy][Ee][Ss])
1229309130Saraujo					${PROTECT} -p ${pid}
1230309130Saraujo					;;
1231309130Saraujo				esac
1232295949Saraujo			fi	
1233295949Saraujo		;;
1234295949Saraujo		esac
1235295949Saraujo
1236116097Smtm		return $_return
123778344Sobrien	done
123878344Sobrien
123998186Sgordon	echo 1>&2 "$0: unknown directive '$rc_arg'."
1240150796Syar	rc_usage $_keywords
1241153152Syar	# not reached
124278344Sobrien}
124378344Sobrien
124478344Sobrien#
1245165565Syar# Helper functions for run_rc_command: common code.
1246165565Syar# They use such global variables besides the exported rc_* ones:
1247165565Syar#
1248165565Syar#	name	       R/W
1249165565Syar#	------------------
1250165565Syar#	_precmd		R
1251165565Syar#	_postcmd	R
1252165565Syar#	_return		W
1253165565Syar#
1254165565Syar_run_rc_precmd()
1255165565Syar{
1256165565Syar	check_required_before "$rc_arg" || return 1
1257165565Syar
1258165565Syar	if [ -n "$_precmd" ]; then
1259165565Syar		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1260165565Syar		eval "$_precmd $rc_extra_args"
1261165565Syar		_return=$?
1262165565Syar
1263165565Syar		# If precmd failed and force isn't set, request exit.
1264165565Syar		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1265165565Syar			return 1
1266165565Syar		fi
1267165565Syar	fi
1268165565Syar
1269165565Syar	check_required_after "$rc_arg" || return 1
1270165565Syar
1271165565Syar	return 0
1272165565Syar}
1273165565Syar
1274165565Syar_run_rc_postcmd()
1275165565Syar{
1276165565Syar	if [ -n "$_postcmd" ]; then
1277165565Syar		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1278165565Syar		eval "$_postcmd $rc_extra_args"
1279165565Syar		_return=$?
1280165565Syar	fi
1281165565Syar	return 0
1282165565Syar}
1283165565Syar
1284165565Syar_run_rc_doit()
1285165565Syar{
1286165565Syar	debug "run_rc_command: doit: $*"
1287165565Syar	eval "$@"
1288165565Syar	_return=$?
1289165565Syar
1290165565Syar	# If command failed and force isn't set, request exit.
1291165565Syar	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1292165565Syar		return 1
1293165565Syar	fi
1294165565Syar
1295165565Syar	return 0
1296165565Syar}
1297165565Syar
1298165565Syar_run_rc_notrunning()
1299165565Syar{
1300165565Syar	local _pidmsg
1301165565Syar
1302165565Syar	if [ -n "$pidfile" ]; then
1303165565Syar		_pidmsg=" (check $pidfile)."
1304165565Syar	else
1305165565Syar		_pidmsg=
1306165565Syar	fi
1307165565Syar	echo 1>&2 "${name} not running?${_pidmsg}"
1308165565Syar}
1309165565Syar
1310165565Syar_run_rc_killcmd()
1311165565Syar{
1312165565Syar	local _cmd
1313165565Syar
1314165565Syar	_cmd="kill -$1 $rc_pid"
1315165565Syar	if [ -n "$_user" ]; then
1316165565Syar		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1317165565Syar	fi
1318165565Syar	echo "$_cmd"
1319165565Syar}
1320165565Syar
1321165565Syar#
132278344Sobrien# run_rc_script file arg
132378344Sobrien#	Start the script `file' with `arg', and correctly handle the
1324201038Sdougb#	return value from the script.
1325286303Sngie#	If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1326286303Sngie#	an old-style startup file.
1327286303Sngie#	If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1328286303Sngie#	into the current environment if $rc_fast_and_loose is set; otherwise
1329286303Sngie#	it is run as a child process.
1330201038Sdougb#	If `file' appears to be a backup or scratch file, ignore it.
1331201038Sdougb#	Otherwise if it is executable run as a child process.
133278344Sobrien#
133378344Sobrienrun_rc_script()
133478344Sobrien{
133578344Sobrien	_file=$1
133678344Sobrien	_arg=$2
133778344Sobrien	if [ -z "$_file" -o -z "$_arg" ]; then
133878344Sobrien		err 3 'USAGE: run_rc_script file arg'
133978344Sobrien	fi
134078344Sobrien
134198186Sgordon	unset	name command command_args command_interpreter \
134298186Sgordon		extra_commands pidfile procname \
1343272393Shrs		rcvar rcvars rcvars_obsolete required_dirs required_files \
1344197144Shrs		required_vars
134598186Sgordon	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
134698186Sgordon
1347343046Skevans	rc_service="$_file"
134878344Sobrien	case "$_file" in
1349193118Sdougb	/etc/rc.d/*.sh)			# no longer allowed in the base
1350193118Sdougb		warn "Ignoring old-style startup script $_file"
135178344Sobrien		;;
1352153105Sdougb	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
135398186Sgordon		warn "Ignoring scratch file $_file"
135498186Sgordon		;;
135578344Sobrien	*)				# run in subshell
135698186Sgordon		if [ -x $_file ]; then
135798186Sgordon			if [ -n "$rc_fast_and_loose" ]; then
1358146490Sschweikh				set $_arg; . $_file
135998186Sgordon			else
1360231888Sdelphij				( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1361231888Sdelphij				  trap "echo Script $_file interrupted >&2 ; exit 1" 2
1362231888Sdelphij				  trap "echo Script $_file running >&2" 29
1363146490Sschweikh				  set $_arg; . $_file )
136498186Sgordon			fi
136598186Sgordon		fi
136678344Sobrien		;;
136778344Sobrien	esac
136878344Sobrien}
136978344Sobrien
137078344Sobrien#
1371290007Sdes# load_rc_config [service]
1372290007Sdes#	Source in the configuration file(s) for a given service.
1373290007Sdes#	If no service is specified, only the global configuration
1374290007Sdes#	file(s) will be loaded.
137578344Sobrien#
137678344Sobrienload_rc_config()
137778344Sobrien{
1378270698Shrs	local _name _rcvar_val _var _defval _v _msg _new _d
1379157653Sflz	_name=$1
138078344Sobrien
1381219612Sdougb	if ${_rc_conf_loaded:-false}; then
1382219612Sdougb		:
1383219612Sdougb	else
138498186Sgordon		if [ -r /etc/defaults/rc.conf ]; then
138598186Sgordon			debug "Sourcing /etc/defaults/rc.conf"
138698186Sgordon			. /etc/defaults/rc.conf
138798186Sgordon			source_rc_confs
138898186Sgordon		elif [ -r /etc/rc.conf ]; then
138998186Sgordon			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
139098186Sgordon			. /etc/rc.conf
139198186Sgordon		fi
1392126285Smtm		_rc_conf_loaded=true
139398186Sgordon	fi
1394179872Smtm
1395275359Sdes	# If a service name was specified, attempt to load
1396275359Sdes	# service-specific configuration
1397275359Sdes	if [ -n "$_name" ] ; then
1398286163Sjilles		for _d in /etc ${local_startup}; do
1399286163Sjilles			_d=${_d%/rc.d}
1400275359Sdes			if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1401275359Sdes				debug "Sourcing ${_d}/rc.conf.d/$_name"
1402275359Sdes				. ${_d}/rc.conf.d/"$_name"
1403275359Sdes			elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
1404275359Sdes				local _rc
1405275359Sdes				for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
1406275359Sdes					if [ -f "$_rc" ] ; then
1407275359Sdes						debug "Sourcing $_rc"
1408275359Sdes						. "$_rc"
1409275359Sdes					fi
1410275359Sdes				done
1411275359Sdes			fi
1412275359Sdes		done
1413275359Sdes	fi
1414270698Shrs
1415197144Shrs	# Set defaults if defined.
1416272393Shrs	for _var in $rcvar $rcvars; do
1417223227Sjilles		eval _defval=\$${_var}_defval
1418197144Shrs		if [ -n "$_defval" ]; then
1419197144Shrs			eval : \${$_var:=\$${_var}_defval}
1420197144Shrs		fi
1421197144Shrs	done
1422197144Shrs
1423197144Shrs	# check obsolete rc.conf variables
1424197144Shrs	for _var in $rcvars_obsolete; do
1425223227Sjilles		eval _v=\$$_var
1426223227Sjilles		eval _msg=\$${_var}_obsolete_msg
1427223227Sjilles		eval _new=\$${_var}_newvar
1428197144Shrs		case $_v in
1429197144Shrs		"")
1430197144Shrs			;;
1431197144Shrs		*)
1432197144Shrs			if [ -z "$_new" ]; then
1433197144Shrs				_msg="Ignored."
1434197144Shrs			else
1435197144Shrs				eval $_new=\"\$$_var\"
1436197144Shrs				if [ -z "$_msg" ]; then
1437197144Shrs					_msg="Use \$$_new instead."
1438197144Shrs				fi
1439197144Shrs			fi
1440197144Shrs			warn "\$$_var is obsolete.  $_msg"
1441197144Shrs			;;
1442197144Shrs		esac
1443197144Shrs	done
144478344Sobrien}
1445201036Sdougb
1446157473Sflz#
1447157653Sflz# load_rc_config_var name var
1448157653Sflz#	Read the rc.conf(5) var for name and set in the
1449157473Sflz#	current shell, using load_rc_config in a subshell to prevent
1450157473Sflz#	unwanted side effects from other variable assignments.
1451157473Sflz#
1452157473Sflzload_rc_config_var()
1453157473Sflz{
1454157473Sflz	if [ $# -ne 2 ]; then
1455157653Sflz		err 3 'USAGE: load_rc_config_var name var'
1456157473Sflz	fi
1457157473Sflz	eval $(eval '(
1458157473Sflz		load_rc_config '$1' >/dev/null;
1459157473Sflz                if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1460157473Sflz			echo '$2'=\'\''${'$2'}\'\'';
1461157473Sflz		fi
1462157473Sflz	)' )
1463157473Sflz}
146478344Sobrien
146578344Sobrien#
146678344Sobrien# rc_usage commands
146778344Sobrien#	Print a usage string for $0, with `commands' being a list of
146878344Sobrien#	valid commands.
146978344Sobrien#
147078344Sobrienrc_usage()
147178344Sobrien{
1472230007Srea	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
147378344Sobrien
147478344Sobrien	_sep=
1475126286Smtm	for _elem; do
147678344Sobrien		echo -n 1>&2 "$_sep$_elem"
147778344Sobrien		_sep="|"
147878344Sobrien	done
147978344Sobrien	echo 1>&2 ")"
148078344Sobrien	exit 1
148178344Sobrien}
148278344Sobrien
148378344Sobrien#
148478344Sobrien# err exitval message
148578344Sobrien#	Display message to stderr and log to the syslog, and exit with exitval.
148678344Sobrien#
148778344Sobrienerr()
148878344Sobrien{
148978344Sobrien	exitval=$1
149078344Sobrien	shift
149178344Sobrien
1492106643Sgordon	if [ -x /usr/bin/logger ]; then
1493106643Sgordon		logger "$0: ERROR: $*"
1494106643Sgordon	fi
1495106643Sgordon	echo 1>&2 "$0: ERROR: $*"
149678344Sobrien	exit $exitval
149778344Sobrien}
149878344Sobrien
149978344Sobrien#
150078344Sobrien# warn message
150178344Sobrien#	Display message to stderr and log to the syslog.
150278344Sobrien#
150378344Sobrienwarn()
150478344Sobrien{
1505106643Sgordon	if [ -x /usr/bin/logger ]; then
1506106643Sgordon		logger "$0: WARNING: $*"
1507106643Sgordon	fi
1508106643Sgordon	echo 1>&2 "$0: WARNING: $*"
150978344Sobrien}
151098186Sgordon
151198186Sgordon#
151298186Sgordon# info message
151398186Sgordon#	Display informational message to stdout and log to syslog.
151498186Sgordon#
151598186Sgordoninfo()
151698186Sgordon{
1517119170Smtm	case ${rc_info} in
1518119170Smtm	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1519119170Smtm		if [ -x /usr/bin/logger ]; then
1520119170Smtm			logger "$0: INFO: $*"
1521119170Smtm		fi
1522119170Smtm		echo "$0: INFO: $*"
1523119170Smtm		;;
1524119170Smtm	esac
152598186Sgordon}
152698186Sgordon
152798186Sgordon#
152898186Sgordon# debug message
1529106643Sgordon#	If debugging is enabled in rc.conf output message to stderr.
153098186Sgordon#	BEWARE that you don't call any subroutine that itself calls this
153198186Sgordon#	function.
153298186Sgordon#
153398186Sgordondebug()
153498186Sgordon{
153598186Sgordon	case ${rc_debug} in
153698186Sgordon	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1537106700Sgordon		if [ -x /usr/bin/logger ]; then
1538162947Syar			logger "$0: DEBUG: $*"
1539106700Sgordon		fi
1540146490Sschweikh		echo 1>&2 "$0: DEBUG: $*"
154198186Sgordon		;;
154298186Sgordon	esac
154398186Sgordon}
154498186Sgordon
154598186Sgordon#
154698186Sgordon# backup_file action file cur backup
154798186Sgordon#	Make a backup copy of `file' into `cur', and save the previous
154898186Sgordon#	version of `cur' as `backup' or use rcs for archiving.
154998186Sgordon#
155098186Sgordon#	This routine checks the value of the backup_uses_rcs variable,
155198186Sgordon#	which can be either YES or NO.
155298186Sgordon#
155398186Sgordon#	The `action' keyword can be one of the following:
155498186Sgordon#
155598186Sgordon#	add		`file' is now being backed up (and is possibly
155698186Sgordon#			being reentered into the backups system).  `cur'
155798186Sgordon#			is created and RCS files, if necessary, are
155898186Sgordon#			created as well.
155998186Sgordon#
156098186Sgordon#	update		`file' has changed and needs to be backed up.
156198186Sgordon#			If `cur' exists, it is copied to to `back' or
156298186Sgordon#			checked into RCS (if the repository file is old),
156398186Sgordon#			and then `file' is copied to `cur'.  Another RCS
156498186Sgordon#			check in done here if RCS is being used.
156598186Sgordon#
156698186Sgordon#	remove		`file' is no longer being tracked by the backups
156798186Sgordon#			system.  If RCS is not being used, `cur' is moved
156898186Sgordon#			to `back', otherwise an empty file is checked in,
156998186Sgordon#			and then `cur' is removed.
157098186Sgordon#
157198186Sgordon#
157298186Sgordonbackup_file()
157398186Sgordon{
157498186Sgordon	_action=$1
157598186Sgordon	_file=$2
157698186Sgordon	_cur=$3
157798186Sgordon	_back=$4
157898186Sgordon
157998186Sgordon	if checkyesno backup_uses_rcs; then
158098186Sgordon		_msg0="backup archive"
158198186Sgordon		_msg1="update"
158298186Sgordon
158398186Sgordon		# ensure that history file is not locked
158498186Sgordon		if [ -f $_cur,v ]; then
158598186Sgordon			rcs -q -u -U -M $_cur
158698186Sgordon		fi
158798186Sgordon
158898186Sgordon		# ensure after switching to rcs that the
158998186Sgordon		# current backup is not lost
159098186Sgordon		if [ -f $_cur ]; then
159198186Sgordon			# no archive, or current newer than archive
159298186Sgordon			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
159398186Sgordon				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
159498186Sgordon				rcs -q -kb -U $_cur
159598186Sgordon				co -q -f -u $_cur
159698186Sgordon			fi
159798186Sgordon		fi
159898186Sgordon
159998186Sgordon		case $_action in
160098186Sgordon		add|update)
160198186Sgordon			cp -p $_file $_cur
160298186Sgordon			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
160398186Sgordon			rcs -q -kb -U $_cur
160498186Sgordon			co -q -f -u $_cur
160598186Sgordon			chown root:wheel $_cur $_cur,v
160698186Sgordon			;;
160798186Sgordon		remove)
160898186Sgordon			cp /dev/null $_cur
160998186Sgordon			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
161098186Sgordon			rcs -q -kb -U $_cur
161198186Sgordon			chown root:wheel $_cur $_cur,v
161298186Sgordon			rm $_cur
161398186Sgordon			;;
161498186Sgordon		esac
161598186Sgordon	else
161698186Sgordon		case $_action in
161798186Sgordon		add|update)
161898186Sgordon			if [ -f $_cur ]; then
161998186Sgordon				cp -p $_cur $_back
162098186Sgordon			fi
162198186Sgordon			cp -p $_file $_cur
162298186Sgordon			chown root:wheel $_cur
162398186Sgordon			;;
162498186Sgordon		remove)
162598186Sgordon			mv -f $_cur $_back
162698186Sgordon			;;
162798186Sgordon		esac
162898186Sgordon	fi
162998186Sgordon}
1630119166Smtm
1631123344Smtm# make_symlink src link
1632123344Smtm#	Make a symbolic link 'link' to src from basedir. If the
1633123344Smtm#	directory in which link is to be created does not exist
1634123344Smtm#	a warning will be displayed and an error will be returned.
1635229783Suqs#	Returns 0 on success, 1 otherwise.
1636119166Smtm#
1637123344Smtmmake_symlink()
1638119166Smtm{
1639123344Smtm	local src link linkdir _me
1640123344Smtm	src="$1"
1641123344Smtm	link="$2"
1642123344Smtm	linkdir="`dirname $link`"
1643123344Smtm	_me="make_symlink()"
1644119166Smtm
1645123344Smtm	if [ -z "$src" -o -z "$link" ]; then
1646123344Smtm		warn "$_me: requires two arguments."
1647119166Smtm		return 1
1648119166Smtm	fi
1649123344Smtm	if [ ! -d "$linkdir" ]; then
1650160667Syar		warn "$_me: the directory $linkdir does not exist."
1651119166Smtm		return 1
1652119166Smtm	fi
1653146490Sschweikh	if ! ln -sf $src $link; then
1654123344Smtm		warn "$_me: unable to make a symbolic link from $link to $src"
1655119166Smtm		return 1
1656119166Smtm	fi
1657119166Smtm	return 0
1658119166Smtm}
1659119166Smtm
1660119166Smtm# devfs_rulesets_from_file file
1661119166Smtm#	Reads a set of devfs commands from file, and creates
1662119166Smtm#	the specified rulesets with their rules. Returns non-zero
1663119166Smtm#	if there was an error.
1664119166Smtm#
1665119166Smtmdevfs_rulesets_from_file()
1666119166Smtm{
1667248820Savg	local file _err _me _opts
1668119166Smtm	file="$1"
1669119166Smtm	_me="devfs_rulesets_from_file"
1670119166Smtm	_err=0
1671119166Smtm
1672119166Smtm	if [ -z "$file" ]; then
1673119166Smtm		warn "$_me: you must specify a file"
1674119166Smtm		return 1
1675119166Smtm	fi
1676119166Smtm	if [ ! -e "$file" ]; then
1677119166Smtm		debug "$_me: no such file ($file)"
1678119166Smtm		return 0
1679119166Smtm	fi
1680248820Savg
1681248820Savg	# Disable globbing so that the rule patterns are not expanded
1682248820Savg	# by accident with matching filesystem entries.
1683248820Savg	_opts=$-; set -f
1684248820Savg
1685119166Smtm	debug "reading rulesets from file ($file)"
1686119166Smtm	{ while read line
1687119166Smtm	do
1688119166Smtm		case $line in
1689119166Smtm		\#*)
1690119166Smtm			continue
1691119166Smtm			;;
1692119166Smtm		\[*\]*)
1693119166Smtm			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1694119166Smtm			if [ -z "$rulenum" ]; then
1695119166Smtm				warn "$_me: cannot extract rule number ($line)"
1696119166Smtm				_err=1
1697119166Smtm				break
1698119166Smtm			fi
1699119166Smtm			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1700119166Smtm			if [ -z "$rulename" ]; then
1701119166Smtm				warn "$_me: cannot extract rule name ($line)"
1702119166Smtm				_err=1
1703119166Smtm				break;
1704119166Smtm			fi
1705119166Smtm			eval $rulename=\$rulenum
1706119166Smtm			debug "found ruleset: $rulename=$rulenum"
1707146490Sschweikh			if ! /sbin/devfs rule -s $rulenum delset; then
1708119166Smtm				_err=1
1709119166Smtm				break
1710119166Smtm			fi
1711119166Smtm			;;
1712119166Smtm		*)
1713119166Smtm			rulecmd="${line%%"\#*"}"
1714119166Smtm			# evaluate the command incase it includes
1715119166Smtm			# other rules
1716119166Smtm			if [ -n "$rulecmd" ]; then
1717119166Smtm				debug "adding rule ($rulecmd)"
1718119166Smtm				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1719119166Smtm				then
1720119166Smtm					_err=1
1721119166Smtm					break
1722119166Smtm				fi
1723119166Smtm			fi
1724119166Smtm			;;
1725119166Smtm		esac
1726119166Smtm		if [ $_err -ne 0 ]; then
1727119166Smtm			debug "error in $_me"
1728119166Smtm			break
1729119166Smtm		fi
1730119166Smtm	done } < $file
1731248820Savg	case $_opts in *f*) ;; *) set +f ;; esac
1732119166Smtm	return $_err
1733119166Smtm}
1734119166Smtm
1735119166Smtm# devfs_init_rulesets
1736119166Smtm#	Initializes rulesets from configuration files. Returns
1737119166Smtm#	non-zero if there was an error.
1738119166Smtm#
1739119166Smtmdevfs_init_rulesets()
1740119166Smtm{
1741119166Smtm	local file _me
1742119166Smtm	_me="devfs_init_rulesets"
1743119166Smtm
1744119166Smtm	# Go through this only once
1745119166Smtm	if [ -n "$devfs_rulesets_init" ]; then
1746119166Smtm		debug "$_me: devfs rulesets already initialized"
1747119166Smtm		return
1748119166Smtm	fi
1749146490Sschweikh	for file in $devfs_rulesets; do
1750217090Sjh		if ! devfs_rulesets_from_file $file; then
1751217090Sjh			warn "$_me: could not read rules from $file"
1752217090Sjh			return 1
1753217090Sjh		fi
1754119166Smtm	done
1755119166Smtm	devfs_rulesets_init=1
1756119166Smtm	debug "$_me: devfs rulesets initialized"
1757119166Smtm	return 0
1758119166Smtm}
1759119166Smtm
1760119166Smtm# devfs_set_ruleset ruleset [dir]
1761151619Smaxim#	Sets the default ruleset of dir to ruleset. The ruleset argument
1762119166Smtm#	must be a ruleset name as specified in devfs.rules(5) file.
1763119166Smtm#	Returns non-zero if it could not set it successfully.
1764119166Smtm#
1765119166Smtmdevfs_set_ruleset()
1766119166Smtm{
1767119166Smtm	local devdir rs _me
1768119166Smtm	[ -n "$1" ] && eval rs=\$$1 || rs=
1769119166Smtm	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1770119166Smtm	_me="devfs_set_ruleset"
1771119166Smtm
1772119166Smtm	if [ -z "$rs" ]; then
1773119166Smtm		warn "$_me: you must specify a ruleset number"
1774119166Smtm		return 1
1775119166Smtm	fi
1776119166Smtm	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1777146490Sschweikh	if ! /sbin/devfs $devdir ruleset $rs; then
1778119166Smtm		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1779119166Smtm		return 1
1780119166Smtm	fi
1781119166Smtm	return 0
1782119166Smtm}
1783119166Smtm
1784119166Smtm# devfs_apply_ruleset ruleset [dir]
1785119166Smtm#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1786119166Smtm#	The ruleset argument must be a ruleset name as specified
1787119166Smtm#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1788119166Smtm#	if it could not apply the ruleset.
1789119166Smtm#
1790119166Smtmdevfs_apply_ruleset()
1791119166Smtm{
1792119166Smtm	local devdir rs _me
1793119166Smtm	[ -n "$1" ] && eval rs=\$$1 || rs=
1794119166Smtm	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1795119166Smtm	_me="devfs_apply_ruleset"
1796119166Smtm
1797119166Smtm	if [ -z "$rs" ]; then
1798119166Smtm		warn "$_me: you must specify a ruleset"
1799119166Smtm		return 1
1800119166Smtm	fi
1801119166Smtm	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1802146490Sschweikh	if ! /sbin/devfs $devdir rule -s $rs applyset; then
1803119166Smtm		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1804119166Smtm		return 1
1805119166Smtm	fi
1806119166Smtm	return 0
1807119166Smtm}
1808119166Smtm
1809119166Smtm# devfs_domount dir [ruleset]
1810119166Smtm#	Mount devfs on dir. If ruleset is specified it is set
1811119166Smtm#	on the mount-point. It must also be a ruleset name as specified
1812119166Smtm#	in a devfs.rules(5) file. Returns 0 on success.
1813119166Smtm#
1814119166Smtmdevfs_domount()
1815119166Smtm{
1816119166Smtm	local devdir rs _me
1817119166Smtm	devdir="$1"
1818119166Smtm	[ -n "$2" ] && rs=$2 || rs=
1819119166Smtm	_me="devfs_domount()"
1820119166Smtm
1821119166Smtm	if [ -z "$devdir" ]; then
1822119166Smtm		warn "$_me: you must specify a mount-point"
1823119166Smtm		return 1
1824119166Smtm	fi
1825119166Smtm	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1826146490Sschweikh	if ! mount -t devfs dev "$devdir"; then
1827119166Smtm		warn "$_me: Unable to mount devfs on $devdir"
1828119166Smtm		return 1
1829119166Smtm	fi
1830119166Smtm	if [ -n "$rs" ]; then
1831119166Smtm		devfs_init_rulesets
1832119166Smtm		devfs_set_ruleset $rs $devdir
1833124797Scperciva		devfs -m $devdir rule applyset
1834119166Smtm	fi
1835119166Smtm	return 0
1836119166Smtm}
1837119166Smtm
1838127345Sbrooks# Provide a function for normalizing the mounting of memory
1839127345Sbrooks# filesystems.  This should allow the rest of the code here to remain
1840127345Sbrooks# as close as possible between 5-current and 4-stable.
1841127345Sbrooks#   $1 = size
1842127345Sbrooks#   $2 = mount point
1843137451Skeramida#   $3 = (optional) extra mdmfs flags
1844146490Sschweikhmount_md()
1845146490Sschweikh{
1846127345Sbrooks	if [ -n "$3" ]; then
1847137451Skeramida		flags="$3"
1848127345Sbrooks	fi
1849327592Sian	/sbin/mdmfs $flags -s $1 ${mfs_type} $2
1850127345Sbrooks}
1851131550Scperciva
1852159828Syar# Code common to scripts that need to load a kernel module
1853159828Syar# if it isn't in the kernel yet. Syntax:
1854160666Syar#   load_kld [-e regex] [-m module] file
1855159828Syar# where -e or -m chooses the way to check if the module
1856159828Syar# is already loaded:
1857160666Syar#   regex is egrep'd in the output from `kldstat -v',
1858160666Syar#   module is passed to `kldstat -m'.
1859160666Syar# The default way is as though `-m file' were specified.
1860159828Syarload_kld()
1861159828Syar{
1862159828Syar	local _loaded _mod _opt _re
1863159828Syar
1864159828Syar	while getopts "e:m:" _opt; do
1865159828Syar		case "$_opt" in
1866159828Syar		e) _re="$OPTARG" ;;
1867159828Syar		m) _mod="$OPTARG" ;;
1868160666Syar		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1869159828Syar		esac
1870159828Syar	done
1871159828Syar	shift $(($OPTIND - 1))
1872160666Syar	if [ $# -ne 1 ]; then
1873160666Syar		err 3 'USAGE: load_kld [-e regex] [-m module] file'
1874160666Syar	fi
1875159828Syar	_mod=${_mod:-$1}
1876159828Syar	_loaded=false
1877159828Syar	if [ -n "$_re" ]; then
1878159828Syar		if kldstat -v | egrep -q -e "$_re"; then
1879159828Syar			_loaded=true
1880159828Syar		fi
1881159828Syar	else
1882159828Syar		if kldstat -q -m "$_mod"; then
1883159828Syar			_loaded=true
1884159828Syar		fi
1885159828Syar	fi
1886159828Syar	if ! $_loaded; then
1887159828Syar		if ! kldload "$1"; then
1888159828Syar			warn "Unable to load kernel module $1"
1889159828Syar			return 1
1890160666Syar		else
1891160666Syar			info "$1 kernel module loaded."
1892159828Syar		fi
1893160666Syar	else
1894160666Syar		debug "load_kld: $1 kernel module already loaded."
1895159828Syar	fi
1896159828Syar	return 0
1897159828Syar}
1898159828Syar
1899264243Sdteske# ltr str src dst [var]
1900149049Spjd#	Change every $src in $str to $dst.
1901149049Spjd#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1902264243Sdteske#	awk(1). If var is non-NULL, set it to the result.
1903149049Spjdltr()
1904149049Spjd{
1905264243Sdteske	local _str _src _dst _out _com _var
1906264243Sdteske	_str="$1"
1907264243Sdteske	_src="$2"
1908264243Sdteske	_dst="$3"
1909264243Sdteske	_var="$4"
1910149049Spjd	_out=""
1911149049Spjd
1912264243Sdteske	local IFS="${_src}"
1913149049Spjd	for _com in ${_str}; do
1914149049Spjd		if [ -z "${_out}" ]; then
1915149049Spjd			_out="${_com}"
1916149049Spjd		else
1917149049Spjd			_out="${_out}${_dst}${_com}"
1918149049Spjd		fi
1919149049Spjd	done
1920264243Sdteske	if [ -n "${_var}" ]; then
1921264243Sdteske		setvar "${_var}" "${_out}"
1922264243Sdteske	else
1923264243Sdteske		echo "${_out}"
1924264243Sdteske	fi
1925149049Spjd}
1926149049Spjd
1927149050Spjd# Creates a list of providers for GELI encryption.
1928149050Spjdgeli_make_list()
1929149050Spjd{
1930149050Spjd	local devices devices2
1931149050Spjd	local provider mountpoint type options rest
1932149050Spjd
1933149050Spjd	# Create list of GELI providers from fstab.
1934149050Spjd	while read provider mountpoint type options rest ; do
1935155570Sflz		case ":${options}" in
1936155570Sflz		:*noauto*)
1937155570Sflz			noauto=yes
1938155570Sflz			;;
1939155570Sflz		*)
1940155570Sflz			noauto=no
1941155570Sflz			;;
1942155570Sflz		esac
1943155570Sflz
1944149050Spjd		case ":${provider}" in
1945149050Spjd		:#*)
1946149050Spjd			continue
1947149050Spjd			;;
1948149050Spjd		*.eli)
1949149050Spjd			# Skip swap devices.
1950155570Sflz			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1951149050Spjd				continue
1952149050Spjd			fi
1953149050Spjd			devices="${devices} ${provider}"
1954149050Spjd			;;
1955149050Spjd		esac
1956149050Spjd	done < /etc/fstab
1957149050Spjd
1958149050Spjd	# Append providers from geli_devices.
1959149050Spjd	devices="${devices} ${geli_devices}"
1960149050Spjd
1961149050Spjd	for provider in ${devices}; do
1962149050Spjd		provider=${provider%.eli}
1963149050Spjd		provider=${provider#/dev/}
1964149050Spjd		devices2="${devices2} ${provider}"
1965149050Spjd	done
1966149050Spjd
1967149050Spjd	echo ${devices2}
1968149050Spjd}
1969149050Spjd
1970299349Strasz# Originally, root mount hold had to be released before mounting
1971299349Strasz# the root filesystem.  This delayed the boot, so it was changed
1972299349Strasz# to only wait if the root device isn't readily available.  This
1973299349Strasz# can result in rc scripts executing before all the devices - such
1974299349Strasz# as graid(8), or USB disks - can be accessed.  This function can
1975299349Strasz# be used to explicitly wait for root mount holds to be released.
1976299349Straszroot_hold_wait()
1977299349Strasz{
1978299349Strasz	local wait waited holders
1979299349Strasz
1980299349Strasz	waited=0
1981299349Strasz	while true; do
1982299349Strasz		holders="$(sysctl -n vfs.root_mount_hold)"
1983299349Strasz		if [ -z "${holders}" ]; then
1984299349Strasz			break;
1985299349Strasz		fi
1986299349Strasz		if [ ${waited} -eq 0 ]; then
1987299349Strasz			echo -n "Waiting ${root_hold_delay}s" \
1988299349Strasz			"for the root mount holders: ${holders}"
1989299349Strasz		else
1990299349Strasz			echo -n .
1991299349Strasz		fi
1992299349Strasz		if [ ${waited} -ge ${root_hold_delay} ]; then
1993299349Strasz			echo
1994299349Strasz			break
1995299349Strasz		fi
1996299349Strasz		sleep 1
1997299349Strasz		waited=$(($waited + 1))
1998299349Strasz	done
1999299349Strasz}
2000299349Strasz
2001153027Sdougb# Find scripts in local_startup directories that use the old syntax
2002153027Sdougb#
2003238416Skevlofind_local_scripts_old() {
2004153027Sdougb	zlist=''
2005153027Sdougb	slist=''
2006153027Sdougb	for dir in ${local_startup}; do
2007153027Sdougb		if [ -d "${dir}" ]; then
2008153027Sdougb			for file in ${dir}/[0-9]*.sh; do
2009153027Sdougb				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2010153027Sdougb				    continue
2011153027Sdougb				zlist="$zlist $file"
2012153027Sdougb			done
2013227366Sjilles			for file in ${dir}/[!0-9]*.sh; do
2014153027Sdougb				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2015153027Sdougb				    continue
2016153027Sdougb				slist="$slist $file"
2017153027Sdougb			done
2018153027Sdougb		fi
2019153027Sdougb	done
2020153027Sdougb}
2021153027Sdougb
2022238416Skevlofind_local_scripts_new() {
2023153027Sdougb	local_rc=''
2024153027Sdougb	for dir in ${local_startup}; do
2025153027Sdougb		if [ -d "${dir}" ]; then
2026153297Sdougb			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
2027153027Sdougb				case "$file" in
2028153027Sdougb				*.sample) ;;
2029153027Sdougb				*)	if [ -x "$file" ]; then
2030153027Sdougb						local_rc="${local_rc} ${file}"
2031153027Sdougb					fi
2032153027Sdougb					;;
2033153027Sdougb				esac
2034153027Sdougb			done
2035153027Sdougb		fi
2036153027Sdougb	done
2037153027Sdougb}
2038153027Sdougb
2039165565Syar# check_required_{before|after} command
2040165565Syar#	Check for things required by the command before and after its precmd,
2041165565Syar#	respectively.  The two separate functions are needed because some
2042165565Syar#	conditions should prevent precmd from being run while other things
2043165565Syar#	depend on precmd having already been run.
2044165565Syar#
2045165565Syarcheck_required_before()
2046165565Syar{
2047165565Syar	local _f
2048165565Syar
2049165565Syar	case "$1" in
2050165565Syar	start)
2051165565Syar		for _f in $required_vars; do
2052165565Syar			if ! checkyesno $_f; then
2053165565Syar				warn "\$${_f} is not enabled."
2054165565Syar				if [ -z "$rc_force" ]; then
2055165565Syar					return 1
2056165565Syar				fi
2057165565Syar			fi
2058165565Syar		done
2059165565Syar
2060165565Syar		for _f in $required_dirs; do
2061165565Syar			if [ ! -d "${_f}/." ]; then
2062165565Syar				warn "${_f} is not a directory."
2063165565Syar				if [ -z "$rc_force" ]; then
2064165565Syar					return 1
2065165565Syar				fi
2066165565Syar			fi
2067165565Syar		done
2068165565Syar
2069165565Syar		for _f in $required_files; do
2070165565Syar			if [ ! -r "${_f}" ]; then
2071165565Syar				warn "${_f} is not readable."
2072165565Syar				if [ -z "$rc_force" ]; then
2073165565Syar					return 1
2074165565Syar				fi
2075165565Syar			fi
2076165565Syar		done
2077165565Syar		;;
2078165565Syar	esac
2079165565Syar
2080165565Syar	return 0
2081165565Syar}
2082165565Syar
2083165565Syarcheck_required_after()
2084165565Syar{
2085165565Syar	local _f _args
2086165565Syar
2087165565Syar	case "$1" in
2088165565Syar	start)
2089165565Syar		for _f in $required_modules; do
2090165565Syar			case "${_f}" in
2091165565Syar				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
2092165565Syar				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
2093165565Syar				*)	_args="${_f}" ;;
2094165565Syar			esac
2095165565Syar			if ! load_kld ${_args}; then
2096165565Syar				if [ -z "$rc_force" ]; then
2097165565Syar					return 1
2098165565Syar				fi
2099165565Syar			fi
2100165565Syar		done
2101165565Syar		;;
2102165565Syar	esac
2103165565Syar
2104165565Syar	return 0
2105165565Syar}
2106165565Syar
2107271545Shrs# check_jail mib
2108271545Shrs#	Return true if security.jail.$mib exists and set to 1.
2109271545Shrs
2110271545Shrscheck_jail()
2111271545Shrs{
2112271545Shrs	local _mib _v
2113271545Shrs
2114271545Shrs	_mib=$1
2115271545Shrs	if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2116271545Shrs		case $_v in
2117271545Shrs		1)	return 0;;
2118271545Shrs		esac
2119271545Shrs	fi
2120271545Shrs	return 1
2121271545Shrs}
2122271545Shrs
2123222996Shrs# check_kern_features mib
2124222996Shrs#	Return existence of kern.features.* sysctl MIB as true or
2125222996Shrs#	false.  The result will be cached in $_rc_cache_kern_features_
2126222996Shrs#	namespace.  "0" means the kern.features.X exists.
2127222996Shrs
2128222996Shrscheck_kern_features()
2129222996Shrs{
2130222996Shrs	local _v
2131222996Shrs
2132222996Shrs	[ -n "$1" ] || return 1;
2133223292Sjilles	eval _v=\$_rc_cache_kern_features_$1
2134222996Shrs	[ -n "$_v" ] && return "$_v";
2135222996Shrs
2136222996Shrs	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2137222996Shrs		eval _rc_cache_kern_features_$1=0
2138222996Shrs		return 0
2139222996Shrs	else
2140222996Shrs		eval _rc_cache_kern_features_$1=1
2141222996Shrs		return 1
2142222996Shrs	fi
2143222996Shrs}
2144222996Shrs
2145243184Shrs# check_namevarlist var
2146243184Shrs#	Return "0" if ${name}_var is reserved in rc.subr.
2147243184Shrs
2148272976Shrs_rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend"
2149243184Shrscheck_namevarlist()
2150243184Shrs{
2151243184Shrs	local _v
2152243184Shrs
2153243184Shrs	for _v in $_rc_namevarlist; do
2154243184Shrs	case $1 in
2155243184Shrs	$_v)	return 0 ;;
2156243184Shrs	esac
2157243184Shrs	done
2158243184Shrs
2159243184Shrs	return 1
2160243184Shrs}
2161243184Shrs
2162197144Shrs# _echoonce var msg mode
2163197144Shrs#	mode=0: Echo $msg if ${$var} is empty.
2164197144Shrs#	        After doing echo, a string is set to ${$var}.
2165197144Shrs#
2166197144Shrs#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
2167197144Shrs#
2168197144Shrs_echoonce()
2169197144Shrs{
2170197144Shrs	local _var _msg _mode
2171223227Sjilles	eval _var=\$$1
2172197144Shrs	_msg=$2
2173197144Shrs	_mode=$3
2174197144Shrs
2175197144Shrs	case $_mode in
2176197144Shrs	1)	[ -n "$_var" ] && echo "$_msg" ;;
2177197144Shrs	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2178197144Shrs	esac
2179197144Shrs}
2180197144Shrs
2181332368Skevans# If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2182332368Skevans# still override this, but /etc/defaults/rc.conf can't unconditionally set this
2183332368Skevans# since it would undo what we've done here.
2184332368Skevansif kenv -q rc.debug > /dev/null ; then
2185332368Skevans	rc_debug=YES
2186332368Skevansfi
2187