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