xref: /freebsd/libexec/rc/rc.subr (revision 53bb5613a8a15363718b6e6de8d965bf9a2c5469)
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# rc_service provides the path to the service script that we are executing.
60# This is not being set here in an execution context, necessarily, so it's
61# really just a reasonable guess, and it will get overwritten later if
62# we are executing from some other means than direct execution by service(8)
63# or manual invocation of the service script.  The prime example of this is
64# during system startup, all rc scripts will be invoked via /etc/rc, so
65# run_rc_script will overwrite rc_service with the file being sourced.
66rc_service="$0"
67
68#
69#	functions
70#	---------
71
72# is_verified file
73#	if VERIEXEC is active check that $file is verified
74#
75VERIEXEC="/sbin/veriexec"
76if test -x $VERIEXEC && $VERIEXEC -i active > /dev/null 2>&1; then
77	is_verified() { $VERIEXEC -x $1; }
78else
79	is_verified() { return 0; }
80fi
81
82# indicate that we have vdot
83_VDOT_SH=:
84
85# current state of O_VERIFY
86o_verify()
87{
88	case $(echo $(set -o)) in
89	*verify" "off*) echo off;;
90	*verify" "on*) echo on;;
91	esac
92}
93
94##
95# o_verify_set want [save]
96#
97# record current state of verify in $save
98# and set it to $want if different
99#
100o_verify_set() {
101	local x=$(o_verify)
102
103	[ -z "$x" ] && return 0
104	[ -z "$2" ] || eval $2=$x
105	[ "$x" = "$1" ] && return 0
106	case "$1" in
107	on)
108		set -o verify
109		;;
110	off)
111		set +o verify
112		;;
113	esac
114}
115
116# for unverified files
117dotted=
118dot()
119{
120	local f verify
121
122	o_verify_set off verify
123	for f in "$@"; do
124		if [ -f $f -a -s $f ]; then
125			dotted="$dotted $f"
126			. $f
127		fi
128	done
129	o_verify_set $verify
130}
131
132# try for verified, fallback to safe
133sdot()
134{
135	local f
136
137	for f in "$@"; do
138		[ -f $f -a -s $f ] || continue
139		vdot $f || safe_dot $f
140	done
141}
142
143# convenience function - skip if not verified
144vdot()
145{
146	local f rc=0 verify
147
148	o_verify_set on verify
149	for f in "$@"; do
150		[ -f $f -a -s $f ] || continue
151		if is_verified $f 2> /dev/null; then
152			dotted="$dotted $f"
153			. $f
154		else
155			rc=80	# EAUTH
156		fi
157	done
158	o_verify_set $verify
159	return $rc
160}
161
162# Exists [test] file ...
163# report the first "file" that passes "test" (default -s).
164Exists()
165{
166	local f _t=-s
167
168	while :; do
169		: 1=$1
170		case "$1" in
171		-?)
172			_t=$1
173			shift
174			;;
175		*)
176			break
177			;;
178		esac
179	done
180
181	for f in "$@"; do
182		[ $_t $f ] || continue
183		echo $f
184		return 0
185	done
186	return 1
187}
188
189# do we have $1 (could be a function)
190have()
191{
192       type "$1" > /dev/null 2>&1
193}
194
195# provide consistent means of logging progress
196rc_log()
197{
198	date "+@ %s [%Y-%m-%d %H:%M:%S %Z] $*"
199}
200
201# only rc_log if tracing enabled
202# and $level >= $RC_LEVEL
203rc_trace()
204{
205	local level=$1; shift
206	local cf=/etc/rc.conf.d/rc_trace
207
208	if [ -z "$RC_LEVEL" ]; then
209		[ -f $cf ] || return
210		if [ -s $cf ]; then
211			# don't try to set RC_LEVEL without sed
212			if [ -n "$SED" ]; then
213				RC_LEVEL=$($SED -n '/^RC_LEVEL=/ { s/.*=//p;q; }' $cf)
214				RC_LEVEL=${RC_LEVEL:-0}
215			fi
216		else
217			RC_LEVEL=0
218		fi
219	fi
220	[ ${RC_LEVEL:-0} -ge ${level:-0} ] || return
221	rc_log "$@"
222}
223
224# list_vars pattern
225#	List variables matching glob pattern.
226#
227list_vars()
228{
229	# Localize 'set' option below.
230	local -
231	local IFS=$'\n' line varname
232
233	# Disable path expansion in unquoted 'for' parameters below.
234	set -o noglob
235
236	for line in $(set); do
237		varname="${line%%=*}"
238
239		case "$varname" in
240		"$line"|*[!a-zA-Z0-9_]*)
241			continue
242			;;
243		$1)
244			echo $varname
245			;;
246		esac
247	done
248}
249
250# set_rcvar [var] [defval] [desc]
251#
252#	Echo or define a rc.conf(5) variable name.  Global variable
253#	$rcvars is used.
254#
255#	If no argument is specified, echo "${name}_enable".
256#
257#	If only a var is specified, echo "${var}_enable".
258#
259#	If var and defval are specified, the ${var} is defined as
260#	rc.conf(5) variable and the default value is ${defvar}.  An
261#	optional argument $desc can also be specified to add a
262#	description for that.
263#
264set_rcvar()
265{
266	local _var
267
268	case $# in
269	0)	echo ${name}_enable ;;
270	1)	echo ${1}_enable ;;
271	*)
272		debug "set_rcvar: \$$1=$2 is added" \
273		    " as a rc.conf(5) variable."
274		_var=$1
275		rcvars="${rcvars# } $_var"
276		eval ${_var}_defval=\"$2\"
277		shift 2
278		eval ${_var}_desc=\"$*\"
279	;;
280	esac
281}
282
283# set_rcvar_obsolete oldvar [newvar] [msg]
284#	Define obsolete variable.
285#	Global variable $rcvars_obsolete is used.
286#
287set_rcvar_obsolete()
288{
289	local _var
290	_var=$1
291	debug "set_rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
292
293	rcvars_obsolete="${rcvars_obsolete# } $1"
294	eval ${1}_newvar=\"$2\"
295	shift 2
296	eval ${_var}_obsolete_msg=\"$*\"
297}
298
299#
300# force_depend script [rcvar]
301#	Force a service to start. Intended for use by services
302#	to resolve dependency issues.
303#	$1 - filename of script, in /etc/rc.d, to run
304#	$2 - name of the script's rcvar (minus the _enable)
305#
306force_depend()
307{
308	local _depend _dep_rcvar
309
310	_depend="$1"
311	_dep_rcvar="${2:-$1}_enable"
312
313	[ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
314	    checkyesno $_dep_rcvar && return 0
315
316	/etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
317
318	info "${name} depends on ${_depend}, which will be forced to start."
319	if ! /etc/rc.d/${_depend} forcestart; then
320		warn "Unable to force ${_depend}. It may already be running."
321		return 1
322	fi
323}
324
325#
326# checkyesno var
327#	Test $1 variable, and warn if not set to YES or NO.
328#	Return 0 if it's "yes" (et al), nonzero otherwise.
329#
330checkyesno()
331{
332	eval _value=\$${1}
333	debug "checkyesno: $1 is set to $_value."
334	case $_value in
335
336		#	"yes", "true", "on", or "1"
337	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
338		return 0
339		;;
340
341		#	"no", "false", "off", or "0"
342	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
343		return 1
344		;;
345	*)
346		warn "\$${1} is not set properly - see rc.conf(5)."
347		return 1
348		;;
349	esac
350}
351
352#
353# reverse_list list
354#	print the list in reverse order
355#
356reverse_list()
357{
358	_revlist=
359	for _revfile; do
360		_revlist="$_revfile $_revlist"
361	done
362	echo $_revlist
363}
364
365# stop_boot always
366#	If booting directly to multiuser or $always is enabled,
367#	send SIGTERM to the parent (/etc/rc) to abort the boot.
368#	Otherwise just exit.
369#
370stop_boot()
371{
372	local always
373
374	case $1 in
375		#	"yes", "true", "on", or "1"
376	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
377		always=true
378		;;
379	*)
380		always=false
381		;;
382	esac
383	if [ "$autoboot" = yes -o "$always" = true ]; then
384		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
385		kill -TERM ${RC_PID}
386	fi
387	exit 1
388}
389
390#
391# mount_critical_filesystems type
392#	Go through the list of critical filesystems as provided in
393#	the rc.conf(5) variable $critical_filesystems_${type}, checking
394#	each one to see if it is mounted, and if it is not, mounting it.
395#
396mount_critical_filesystems()
397{
398	eval _fslist=\$critical_filesystems_${1}
399	for _fs in $_fslist; do
400		mount | (
401			_ismounted=false
402			while read what _on on _type type; do
403				if [ $on = $_fs ]; then
404					_ismounted=true
405				fi
406			done
407			if $_ismounted; then
408				:
409			else
410				mount $_fs >/dev/null 2>&1
411			fi
412		)
413	done
414}
415
416#
417# check_pidfile pidfile procname [interpreter]
418#	Parses the first line of pidfile for a PID, and ensures
419#	that the process is running and matches procname.
420#	Prints the matching PID upon success, nothing otherwise.
421#	interpreter is optional; see _find_processes() for details.
422#
423check_pidfile()
424{
425	_pidfile=$1
426	_procname=$2
427	_interpreter=$3
428	if [ -z "$_pidfile" -o -z "$_procname" ]; then
429		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
430	fi
431	if [ ! -f $_pidfile ]; then
432		debug "pid file ($_pidfile): not readable."
433		return
434	fi
435	read _pid _junk < $_pidfile
436	if [ -z "$_pid" ]; then
437		debug "pid file ($_pidfile): no pid in file."
438		return
439	fi
440	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
441}
442
443#
444# check_process procname [interpreter]
445#	Ensures that a process (or processes) named procname is running.
446#	Prints a list of matching PIDs.
447#	interpreter is optional; see _find_processes() for details.
448#
449check_process()
450{
451	_procname=$1
452	_interpreter=$2
453	if [ -z "$_procname" ]; then
454		err 3 'USAGE: check_process procname [interpreter]'
455	fi
456	_find_processes $_procname ${_interpreter:-.} '-ax'
457}
458
459#
460# _find_processes procname interpreter psargs
461#	Search for procname in the output of ps generated by psargs.
462#	Prints the PIDs of any matching processes, space separated.
463#
464#	If interpreter == ".", check the following variations of procname
465#	against the first word of each command:
466#		procname
467#		`basename procname`
468#		`basename procname` + ":"
469#		"(" + `basename procname` + ")"
470#		"[" + `basename procname` + "]"
471#
472#	If interpreter != ".", read the first line of procname, remove the
473#	leading #!, normalise whitespace, append procname, and attempt to
474#	match that against each command, either as is, or with extra words
475#	at the end.  As an alternative, to deal with interpreted daemons
476#	using perl, the basename of the interpreter plus a colon is also
477#	tried as the prefix to procname.
478#
479_find_processes()
480{
481	if [ $# -ne 3 ]; then
482		err 3 'USAGE: _find_processes procname interpreter psargs'
483	fi
484	_procname=$1
485	_interpreter=$2
486	_psargs=$3
487
488	_pref=
489	if [ $_interpreter != "." ]; then	# an interpreted script
490		_script="${_chroot}${_chroot:+/}$_procname"
491		if [ -r "$_script" ]; then
492			read _interp < $_script	# read interpreter name
493			case "$_interp" in
494			\#!*)
495				_interp=${_interp#\#!}	# strip #!
496				set -- $_interp
497				case $1 in
498				*/bin/env)
499					shift	# drop env to get real name
500					;;
501				esac
502				if [ $_interpreter != $1 ]; then
503					warn "\$command_interpreter $_interpreter != $1"
504				fi
505				;;
506			*)
507				warn "no shebang line in $_script"
508				set -- $_interpreter
509				;;
510			esac
511		else
512			warn "cannot read shebang line from $_script"
513			set -- $_interpreter
514		fi
515		_interp="$* $_procname"		# cleanup spaces, add _procname
516		_interpbn=${1##*/}
517		_fp_args='_argv'
518		_fp_match='case "$_argv" in
519		    ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
520	else					# a normal daemon
521		_procnamebn=${_procname##*/}
522		_fp_args='_arg0 _argv'
523		_fp_match='case "$_arg0" in
524		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
525	fi
526
527	if checkyesno ${name}_svcj && [ "${_rc_svcj}" != jailing ]; then
528		JID=$(/usr/sbin/jls -j svcj-${name} jid 2>/dev/null)
529
530		case ${JID} in
531		''|*[!0-9]*)
532			# svcj-jail doesn't exist, fallback to host-check
533			JID=0
534			;;
535		esac
536	fi
537	_proccheck="\
538		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
539		while read _npid _jid '"$_fp_args"'; do
540			'"$_fp_match"'
541				if [ "$JID" -eq "$_jid" ];
542				then echo -n "$_pref$_npid";
543				_pref=" ";
544				fi
545				;;
546			esac
547		done'
548
549#	debug "in _find_processes: proccheck is ($_proccheck)."
550	eval $_proccheck
551}
552
553# sort_lite [-b] [-n] [-k POS] [-t SEP]
554#	A lite version of sort(1) (supporting a few options) that can be used
555#	before the real sort(1) is available (e.g., in scripts that run prior
556#	to mountcritremote). Requires only shell built-in functionality.
557#
558sort_lite()
559{
560	local funcname=sort_lite
561	local sort_sep="$IFS" sort_ignore_leading_space=
562	local sort_field=0 sort_strict_fields= sort_numeric=
563	local nitems=0 skip_leading=0 trim=
564
565	local OPTIND flag
566	while getopts bnk:t: flag; do
567		case "$flag" in
568		b) sort_ignore_leading_space=1 ;;
569		n) sort_numeric=1 sort_ignore_leading_space=1 ;;
570		k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
571			# NB: Unlike sort(1) only one POS allowed
572		t) sort_sep="$OPTARG"
573		   if [ ${#sort_sep} -gt 1 ]; then
574		   	echo "$funcname: multi-character tab \`$sort_sep'" >&2
575		   	return 1
576		   fi
577		   sort_strict_fields=1
578		   ;;
579		\?) return 1 ;;
580		esac
581	done
582	shift $(( $OPTIND - 1 ))
583
584	# Create transformation pattern to trim leading text if desired
585	case "$sort_field" in
586	""|[!0-9]*|*[!0-9.]*)
587		echo "$funcname: invalid sort field \`$sort_field'" >&2
588		return 1
589		;;
590	*.*)
591		skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
592		while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
593			trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
594		done
595	esac
596
597	# Copy input to series of local numbered variables
598	# NB: IFS of NULL preserves leading whitespace
599	local LINE
600	while IFS= read -r LINE || [ "$LINE" ]; do
601		nitems=$(( $nitems + 1 ))
602		local src_$nitems="$LINE"
603	done
604
605	#
606	# Sort numbered locals using insertion sort
607	#
608	local curitem curitem_orig curitem_mod curitem_haskey
609	local dest dest_orig dest_mod dest_haskey
610	local d gt n
611	local i=1
612	while [ $i -le $nitems ]; do
613		curitem_haskey=1 # Assume sort field (-k POS) exists
614		eval curitem=\"\$src_$i\"
615		curitem_mod="$curitem" # for modified comparison
616		curitem_orig="$curitem" # for original comparison
617
618		# Trim leading whitespace if desired
619		if [ "$sort_ignore_leading_space" ]; then
620			while case "$curitem_orig" in
621				[$IFS]*) : ;; *) false; esac
622			do
623				curitem_orig="${curitem_orig#?}"
624			done
625			curitem_mod="$curitem_orig"
626		fi
627
628		# Shift modified comparison value if sort field (-k POS) is > 1
629		n=$sort_field
630		while [ $n -gt 1 ]; do
631			case "$curitem_mod" in
632			*[$sort_sep]*)
633				# Cut text up-to (and incl.) first separator
634				curitem_mod="${curitem_mod#*[$sort_sep]}"
635
636				# Skip NULLs unless strict field splitting
637				[ "$sort_strict_fields" ] ||
638					[ "${curitem_mod%%[$sort_sep]*}" ] ||
639					[ $n -eq 2 ] ||
640					continue
641				;;
642			*)
643				# Asked for a field that doesn't exist
644				curitem_haskey= break
645			esac
646			n=$(( $n - 1 ))
647		done
648
649		# Trim trailing words if sort field >= 1
650		[ $sort_field -ge 1 -a "$sort_numeric" ] &&
651			curitem_mod="${curitem_mod%%[$sort_sep]*}"
652
653		# Apply optional trim (-k POS.TRIM) to cut leading characters
654		curitem_mod="${curitem_mod#$trim}"
655
656		# Determine the type of modified comparison to use initially
657		# NB: Prefer numerical if requested but fallback to standard
658		case "$curitem_mod" in
659		""|[!0-9]*) # NULL or begins with non-number
660			gt=">"
661			[ "$sort_numeric" ] && curitem_mod=0
662			;;
663		*)
664			if [ "$sort_numeric" ]; then
665				gt="-gt"
666				curitem_mod="${curitem_mod%%[!0-9]*}"
667					# NB: trailing non-digits removed
668					# otherwise numeric comparison fails
669			else
670				gt=">"
671			fi
672		esac
673
674		# If first time through, short-circuit below position-search
675		if [ $i -le 1 ]; then
676			d=0
677		else
678			d=1
679		fi
680
681		#
682		# Find appropriate element position
683		#
684		while [ $d -gt 0 ]
685		do
686			dest_haskey=$curitem_haskey
687			eval dest=\"\$dest_$d\"
688			dest_mod="$dest" # for modified comparison
689			dest_orig="$dest" # for original comparison
690
691			# Trim leading whitespace if desired
692			if [ "$sort_ignore_leading_space" ]; then
693				while case "$dest_orig" in
694					[$IFS]*) : ;; *) false; esac
695				do
696					dest_orig="${dest_orig#?}"
697				done
698				dest_mod="$dest_orig"
699			fi
700
701			# Shift modified value if sort field (-k POS) is > 1
702			n=$sort_field
703			while [ $n -gt 1 ]; do
704				case "$dest_mod" in
705				*[$sort_sep]*)
706					# Cut text up-to (and incl.) 1st sep
707					dest_mod="${dest_mod#*[$sort_sep]}"
708
709					# Skip NULLs unless strict fields
710					[ "$sort_strict_fields" ] ||
711					    [ "${dest_mod%%[$sort_sep]*}" ] ||
712					    [ $n -eq 2 ] ||
713					    continue
714					;;
715				*)
716					# Asked for a field that doesn't exist
717					dest_haskey= break
718				esac
719				n=$(( $n - 1 ))
720			done
721
722			# Trim trailing words if sort field >= 1
723			[ $sort_field -ge 1 -a "$sort_numeric" ] &&
724				dest_mod="${dest_mod%%[$sort_sep]*}"
725
726			# Apply optional trim (-k POS.TRIM), cut leading chars
727			dest_mod="${dest_mod#$trim}"
728
729			# Determine type of modified comparison to use
730			# NB: Prefer numerical if requested, fallback to std
731			case "$dest_mod" in
732			""|[!0-9]*) # NULL or begins with non-number
733				gt=">"
734				[ "$sort_numeric" ] && dest_mod=0
735				;;
736			*)
737				if [ "$sort_numeric" ]; then
738					gt="-gt"
739					dest_mod="${dest_mod%%[!0-9]*}"
740						# NB: kill trailing non-digits
741						# for numeric comparison safety
742				else
743					gt=">"
744				fi
745			esac
746
747			# Break if we've found the proper element position
748			if [ "$curitem_haskey" -a "$dest_haskey" ]; then
749				if [ "$dest_mod" = "$curitem_mod" ]; then
750					[ "$dest_orig" ">" "$curitem_orig" ] &&
751						break
752				elif [ "$dest_mod" $gt "$curitem_mod" ] \
753					2> /dev/null
754				then
755					break
756				fi
757			else
758				[ "$dest_orig" ">" "$curitem_orig" ] && break
759			fi
760
761			# Break if we've hit the end
762			[ $d -ge $i ] && break
763
764			d=$(( $d + 1 ))
765		done
766
767		# Shift remaining positions forward, making room for new item
768		n=$i
769		while [ $n -ge $d ]; do
770			# Shift destination item forward one placement
771			eval dest_$(( $n + 1 ))=\"\$dest_$n\"
772			n=$(( $n - 1 ))
773		done
774
775		# Place the element
776		if [ $i -eq 1 ]; then
777			local dest_1="$curitem"
778		else
779			local dest_$d="$curitem"
780		fi
781
782		i=$(( $i + 1 ))
783	done
784
785	# Print sorted results
786	d=1
787	while [ $d -le $nitems ]; do
788		eval echo \"\$dest_$d\"
789		d=$(( $d + 1 ))
790	done
791}
792
793#
794# wait_for_pids pid [pid ...]
795#	spins until none of the pids exist
796#
797wait_for_pids()
798{
799	local _list _prefix _nlist _j
800
801	_list="$@"
802	if [ -z "$_list" ]; then
803		return
804	fi
805	_prefix=
806	while true; do
807		_nlist="";
808		for _j in $_list; do
809			if kill -0 $_j 2>/dev/null; then
810				_nlist="${_nlist}${_nlist:+ }$_j"
811				[ -n "$_prefix" ] && sleep 1
812			fi
813		done
814		if [ -z "$_nlist" ]; then
815			break
816		fi
817		_list=$_nlist
818		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
819		_prefix=", "
820		pwait $_list 2>/dev/null
821	done
822	if [ -n "$_prefix" ]; then
823		echo "."
824	fi
825}
826
827#
828# get_pidfile_from_conf string file
829#
830#	Takes a string to search for in the specified file.
831#	Ignores lines with traditional comment characters.
832#
833# Example:
834#
835# if get_pidfile_from_conf string file; then
836#	pidfile="$_pidfile_from_conf"
837# else
838#	pidfile='appropriate default'
839# fi
840#
841get_pidfile_from_conf()
842{
843	if [ -z "$1" -o -z "$2" ]; then
844		err 3 "USAGE: get_pidfile_from_conf string file ($name)"
845	fi
846
847	local string file line
848
849	string="$1" ; file="$2"
850
851	if [ ! -s "$file" ]; then
852		err 3 "get_pidfile_from_conf: $file does not exist ($name)"
853	fi
854
855	while read line; do
856		case "$line" in
857		*[#\;]*${string}*)	continue ;;
858		*${string}*)		break ;;
859		esac
860	done < $file
861
862	if [ -n "$line" ]; then
863		line=${line#*/}
864		_pidfile_from_conf="/${line%%[\"\;]*}"
865	else
866		return 1
867	fi
868}
869
870#
871# check_startmsgs
872#	If rc_quiet is set (usually as a result of using faststart at
873#	boot time) check if rc_startmsgs is enabled.
874#
875check_startmsgs()
876{
877	if [ -n "$rc_quiet" ]; then
878		checkyesno rc_startmsgs
879	else
880		return 0
881	fi
882}
883
884#
885# startmsg
886#	Preferred method to use when displaying start messages in lieu of echo.
887#
888startmsg()
889{
890	check_startmsgs && echo "$@"
891}
892
893#
894# run_rc_command argument
895#	Search for argument in the list of supported commands, which is:
896#		"start stop restart rcvar status poll ${extra_commands}"
897#	If there's a match, run ${argument}_cmd or the default method
898#	(see below).
899#
900#	If argument has a given prefix, then change the operation as follows:
901#		Prefix	Operation
902#		------	---------
903#		fast	Skip the pid check, and set rc_fast=yes, rc_quiet=yes
904#		force	Set ${rcvar} to YES, and set rc_force=yes
905#		one	Set ${rcvar} to YES
906#		quiet	Don't output some diagnostics, and set rc_quiet=yes
907#
908#	The following globals are used:
909#
910#	Name		Needed	Purpose
911#	----		------	-------
912#	name		y	Name of script.
913#
914#	command		n	Full path to command.
915#				Not needed if ${rc_arg}_cmd is set for
916#				each keyword.
917#
918#	command_args	n	Optional args/shell directives for command.
919#
920#	command_interpreter n	If not empty, command is interpreted, so
921#				call check_{pidfile,process}() appropriately.
922#
923#	desc		n	Description of script.
924#
925#	extra_commands	n	List of extra commands supported.
926#
927#	pidfile		n	If set, use check_pidfile $pidfile $command,
928#				otherwise use check_process $command.
929#				In either case, only check if $command is set.
930#
931#	procname	n	Process name to check for instead of $command.
932#
933#	rcvar		n	This is checked with checkyesno to determine
934#				if the action should be run.
935#
936#	${name}_program	n	Full path to command.
937#				Meant to be used in /etc/rc.conf to override
938#				${command}.
939#
940#	${name}_chroot	n	Directory to chroot to before running ${command}
941#				Requires /usr to be mounted.
942#
943#	${name}_chdir	n	Directory to cd to before running ${command}
944#				(if not using ${name}_chroot).
945#
946#	${name}_cpuset	n	A list of CPUs to run ${command} on.
947#				Requires /usr to be mounted.
948#
949#	${name}_flags	n	Arguments to call ${command} with.
950#				NOTE:	$flags from the parent environment
951#					can be used to override this.
952#
953#	${name}_env	n	Environment variables to run ${command} with.
954#
955#	${name}_env_file n	File to source variables to run ${command} with.
956#
957#	${name}_fib	n	Routing table number to run ${command} with.
958#
959#	${name}_nice	n	Nice level to run ${command} at.
960#
961#	${name}_oomprotect n	Don't kill ${command} when swap space is exhausted.
962#
963#	${name}_umask	n	The file creation mask to run ${command} with.
964#
965#	${name}_user	n	User to run ${command} as, using su(1) if not
966#				using ${name}_chroot.
967#				Requires /usr to be mounted.
968#
969#	${name}_group	n	Group to run chrooted ${command} as.
970#				Requires /usr to be mounted.
971#
972#	${name}_groups	n	Comma separated list of supplementary groups
973#				to run the chrooted ${command} with.
974#				Requires /usr to be mounted.
975#
976#	${name}_prepend	n	Command added before ${command}.
977#
978#	${name}_setup	n	Command executed during start, restart and
979#				reload before ${rc_arg}_precmd is run.
980#
981#	${name}_login_class n	Login class to use, else "daemon".
982#
983#	${name}_limits	n	limits(1) to apply to ${command}.
984#
985#	${name}_offcmd	n	If set, run during start
986#				if a service is not enabled.
987#
988#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
989#				Otherwise, use default command (see below)
990#
991#	${rc_arg}_precmd n	If set, run just before performing the
992#				${rc_arg}_cmd method in the default
993#				operation (i.e, after checking for required
994#				bits and process (non)existence).
995#				If this completes with a non-zero exit code,
996#				don't run ${rc_arg}_cmd.
997#
998#	${rc_arg}_postcmd n	If set, run just after performing the
999#				${rc_arg}_cmd method, if that method
1000#				returned a zero exit code.
1001#
1002#	required_dirs	n	If set, check for the existence of the given
1003#				directories before running a (re)start command.
1004#
1005#	required_files	n	If set, check for the readability of the given
1006#				files before running a (re)start command.
1007#
1008#	required_modules n	If set, ensure the given kernel modules are
1009#				loaded before running a (re)start command.
1010#				The check and possible loads are actually
1011#				done after start_precmd so that the modules
1012#				aren't loaded in vain, should the precmd
1013#				return a non-zero status to indicate a error.
1014#				If a word in the list looks like "foo:bar",
1015#				"foo" is the KLD file name and "bar" is the
1016#				module name.  If a word looks like "foo~bar",
1017#				"foo" is the KLD file name and "bar" is a
1018#				egrep(1) pattern matching the module name.
1019#				Otherwise the module name is assumed to be
1020#				the same as the KLD file name, which is most
1021#				common.  See load_kld().
1022#
1023#	required_vars	n	If set, perform checkyesno on each of the
1024#				listed variables before running the default
1025#				(re)start command.
1026#
1027#	Default behaviour for a given argument, if no override method is
1028#	provided:
1029#
1030#	Argument	Default behaviour
1031#	--------	-----------------
1032#	start		if !running && checkyesno ${rcvar}
1033#				${command}
1034#
1035#	stop		if ${pidfile}
1036#				rc_pid=$(check_pidfile $pidfile $command)
1037#			else
1038#				rc_pid=$(check_process $command)
1039#			kill $sig_stop $rc_pid
1040#			wait_for_pids $rc_pid
1041#			($sig_stop defaults to TERM.)
1042#
1043#	reload		Similar to stop, except use $sig_reload instead,
1044#			and don't wait_for_pids.
1045#			$sig_reload defaults to HUP.
1046#			Note that `reload' isn't provided by default,
1047#			it should be enabled via $extra_commands.
1048#
1049#	restart		Run `stop' then `start'.
1050#
1051#	status		Show if ${command} is running, etc.
1052#
1053#	poll		Wait for ${command} to exit.
1054#
1055#	rcvar		Display what rc.conf variable is used (if any).
1056#
1057#	enabled		Return true if the service is enabled.
1058#
1059#	describe	Show the service's description
1060#
1061#	extracommands	Show the service's extra commands
1062#
1063#	Variables available to methods, and after run_rc_command() has
1064#	completed:
1065#
1066#	Variable	Purpose
1067#	--------	-------
1068#	rc_arg		Argument to command, after fast/force/one processing
1069#			performed
1070#
1071#	rc_flags	Flags to start the default command with.
1072#			Defaults to ${name}_flags, unless overridden
1073#			by $flags from the environment.
1074#			This variable may be changed by the precmd method.
1075#
1076#	rc_service	Path to the service being executed, in case the service
1077#			needs to re-invoke itself.
1078#
1079#	rc_pid		PID of command (if appropriate)
1080#
1081#	rc_fast		Not empty if "fast" was provided (q.v.)
1082#
1083#	rc_force	Not empty if "force" was provided (q.v.)
1084#
1085#	rc_quiet	Not empty if "quiet" was provided
1086#
1087#
1088run_rc_command()
1089{
1090	_return=0
1091	rc_arg=$1
1092	if [ -z "$name" ]; then
1093		err 3 'run_rc_command: $name is not set.'
1094	fi
1095
1096	DebugOn rc:all rc:all:$rc_arg rc:$name rc:$name:$rc_arg $name:$rc_arg
1097
1098	# Don't repeat the first argument when passing additional command-
1099	# line arguments to the command subroutines.
1100	#
1101	shift 1
1102	rc_extra_args="$*"
1103
1104	_rc_prefix=
1105	case "$rc_arg" in
1106	fast*)				# "fast" prefix; don't check pid
1107		rc_arg=${rc_arg#fast}
1108		rc_fast=yes
1109		rc_quiet=yes
1110		;;
1111	force*)				# "force" prefix; always run
1112		rc_force=yes
1113		_rc_prefix=force
1114		rc_arg=${rc_arg#${_rc_prefix}}
1115		if [ -n "${rcvar}" ]; then
1116			eval ${rcvar}=YES
1117		fi
1118		;;
1119	one*)				# "one" prefix; set ${rcvar}=yes
1120		_rc_prefix=one
1121		rc_arg=${rc_arg#${_rc_prefix}}
1122		if [ -n "${rcvar}" ]; then
1123			eval ${rcvar}=YES
1124		fi
1125		;;
1126	quiet*)				# "quiet" prefix; omit some messages
1127		_rc_prefix=quiet
1128		rc_arg=${rc_arg#${_rc_prefix}}
1129		rc_quiet=yes
1130		;;
1131	esac
1132
1133	eval _override_command=\$${name}_program
1134	command=${_override_command:-$command}
1135
1136	_keywords="start stop restart rcvar enable disable delete enabled describe extracommands $extra_commands"
1137	rc_pid=
1138	_pidcmd=
1139	_procname=${procname:-${command}}
1140
1141	eval _cpuset=\$${name}_cpuset
1142
1143	# Loose validation of the configured cpuset; just make sure it starts
1144	# with a number.  There have also been cases in the past where a hyphen
1145	# in a service name has caused eval errors, which trickle down into
1146	# various variables; don't let a situation like that break a bunch of
1147	# services just because of cpuset(1).
1148	case "$_cpuset" in
1149	[0-9]*)	;;
1150	*)	_cpuset="" ;;
1151	esac
1152
1153	_cpusetcmd=
1154	if [ -n "$_cpuset" ]; then
1155		_cpusetcmd="$CPUSET -l $_cpuset"
1156	fi
1157
1158	# If a specific jail has a specific svcj request, honor it (YES/NO).
1159	# If not (variable empty), evaluate the global svcj catch-all.
1160	# A global YES can be overriden by a specific NO, and a global NO is overriden
1161	# by a specific YES.
1162	eval _svcj=\$${name}_svcj
1163	if [ -z "$_svcj" ]; then
1164		_svcj=${svcj_all_enable}
1165		if [ -z "$_svcj" ]; then
1166			eval ${name}_svcj=NO
1167		fi
1168	fi
1169
1170					# setup pid check command
1171	if [ -n "$_procname" ]; then
1172		if [ -n "$pidfile" ]; then
1173			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
1174		else
1175			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
1176		fi
1177		_keywords="${_keywords} status poll"
1178	else
1179		if [ ! -z "${status_cmd}" ]
1180		then
1181			_keywords="${_keywords} status"
1182		fi
1183	fi
1184
1185	if [ -z "$rc_arg" ]; then
1186		rc_usage $_keywords
1187	fi
1188
1189	if [ "$rc_arg" = "enabled" ] ; then
1190		checkyesno ${rcvar}
1191		return $?
1192	fi
1193
1194	if [ -n "$flags" ]; then	# allow override from environment
1195		rc_flags=$flags
1196	else
1197		eval rc_flags=\$${name}_flags
1198	fi
1199	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
1200	    _nice=\$${name}_nice	_user=\$${name}_user \
1201	    _group=\$${name}_group	_groups=\$${name}_groups \
1202	    _fib=\$${name}_fib		_env=\$${name}_env \
1203	    _prepend=\$${name}_prepend	_login_class=\${${name}_login_class:-daemon} \
1204	    _limits=\$${name}_limits	_oomprotect=\$${name}_oomprotect \
1205	    _setup=\$${name}_setup	_env_file=\$${name}_env_file \
1206	    _umask=\$${name}_umask	_svcj_options=\$${name}_svcj_options
1207
1208	if [ -n "$_env_file" ] && [ -r "${_env_file}" ]; then	# load env from file
1209		set -a
1210		. $_env_file
1211		set +a
1212	fi
1213
1214	if [ -n "$_user" ]; then	# unset $_user if running as that user
1215		if [ "$_user" = "$(eval $IDCMD)" ]; then
1216			unset _user
1217		fi
1218	fi
1219
1220	if [ -n "$_svcj_options" ]; then	# translate service jail options
1221		_svcj_cmd_options=""
1222
1223		_svcj_sysvipc_x=0
1224		for _svcj_option in $_svcj_options; do
1225			case "$_svcj_option" in
1226				mlock)
1227					_svcj_cmd_options="allow.mlock ${_svcj_cmd_options}"
1228					;;
1229				netv4)
1230					_svcj_cmd_options="ip4=inherit allow.reserved_ports ${_svcj_cmd_options}"
1231					;;
1232				netv6)
1233					_svcj_cmd_options="ip6=inherit allow.reserved_ports ${_svcj_cmd_options}"
1234					;;
1235				net_basic)
1236					_svcj_cmd_options="ip4=inherit ip6=inherit allow.reserved_ports ${_svcj_cmd_options}"
1237					;;
1238				net_raw)
1239					_svcj_cmd_options="allow.raw_sockets ${_svcj_cmd_options}"
1240					;;
1241				net_all)
1242					_svcj_cmd_options="allow.socket_af allow.raw_sockets allow.reserved_ports ip4=inherit ip6=inherit ${_svcj_cmd_options}"
1243					;;
1244				nfsd)
1245					_svcj_cmd_options="allow.nfsd enforce_statfs=1 ${_svcj_cmd_options}"
1246					;;
1247				sysvipc)
1248					_svcj_sysvipc_x=$((${_svcj_sysvipc_x} + 1))
1249					_svcj_cmd_options="sysvmsg=inherit sysvsem=inherit sysvshm=inherit  ${_svcj_cmd_options}"
1250					;;
1251				sysvipcnew)
1252					_svcj_sysvipc_x=$((${_svcj_sysvipc_x} + 1))
1253					_svcj_cmd_options="sysvmsg=new sysvsem=new sysvshm=new ${_svcj_cmd_options}"
1254					;;
1255				vmm)
1256					_svcj_cmd_options="allow.vmm ${_svcj_cmd_options}"
1257					;;
1258				*)
1259					echo ${name}: unknown service jail option: $_svcj_option
1260					;;
1261			esac
1262		done
1263		if [ ${_svcj_sysvipc_x} -gt 1 ]; then
1264			echo -n "ERROR: more than one sysvipc option is "
1265			echo "specified in ${name}_svcj_options: $_svcj_options"
1266			return 1
1267		fi
1268	fi
1269
1270	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
1271
1272	for _elem in $_keywords; do
1273		if [ "$_elem" != "$rc_arg" ]; then
1274			continue
1275		fi
1276					# if ${rcvar} is set, $1 is not "rcvar", "describe",
1277					# "enable", "delete" or "status", and ${rc_pid} is
1278					# not set, run:
1279					#	checkyesno ${rcvar}
1280					# and return if that failed
1281					#
1282		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
1283		    -a "$rc_arg" != "delete" -a "$rc_arg" != "enable" \
1284		    -a "$rc_arg" != "describe" -a "$rc_arg" != "status" ] ||
1285		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
1286			if ! checkyesno ${rcvar}; then
1287			    [ "$rc_arg" = "start" ] && _run_rc_offcmd
1288			    if [ -z "${rc_quiet}" ]; then
1289				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
1290				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
1291				echo "instead of '${rc_arg}'."
1292			    fi
1293			    return 0
1294			fi
1295		fi
1296
1297		if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1298			if [ -z "$rc_quiet" ]; then
1299				echo 1>&2 "${name} already running? " \
1300				    "(pid=$rc_pid)."
1301			fi
1302			return 1
1303		fi
1304
1305		# if there's a custom ${XXX_cmd},
1306		# run that instead of the default
1307		#
1308		eval _cmd=\$${rc_arg}_cmd \
1309		     _precmd=\$${rc_arg}_precmd \
1310		     _postcmd=\$${rc_arg}_postcmd
1311
1312		if [ -n "$_cmd" ]; then
1313			rc_trace 1 "$_cmd"
1314			if [ -n "$_env" ]; then
1315				eval "export -- $_env"
1316			fi
1317
1318			if [ "${_rc_svcj}" != jailing ]; then
1319				# service can redefine all so
1320				# check for valid setup target
1321				if [ "$rc_arg" = 'start' -o \
1322				    "$rc_arg" = 'restart' -o \
1323				    "$rc_arg" = 'reload' ]; then
1324					_run_rc_setup || \
1325					    warn "failed to setup ${name}"
1326				fi
1327				_run_rc_precmd || return 1
1328			fi
1329			if ! checkyesno ${name}_svcj; then
1330				_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || return 1
1331			else
1332				case "$rc_arg" in
1333				start)
1334					if [ "${_rc_svcj}" != jailing ]; then
1335						_return=1
1336						_do_jailing=1
1337
1338						if check_jail jailed; then
1339							if [ $(${SYSCTL_N} security.jail.children.max) -eq 0 ]; then
1340								echo ERROR: jail parameter children.max is set to 0, can not create a new service jail.
1341								_do_jailing=0
1342							else
1343								_free_jails=$(($(${SYSCTL_N} security.jail.children.max) - $(${SYSCTL_N} security.jail.children.cur)))
1344								if [ ${_free_jails} -eq 0 ]; then
1345									echo ERROR: max number of jail children reached, can not create a new service jail.
1346									_do_jailing=0
1347
1348								fi
1349							fi
1350						fi
1351						if [ ${_do_jailing} -eq 1 ]; then
1352							$JAIL_CMD -c $_svcj_generic_params $_svcj_cmd_options \
1353							    exec.start="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}start $rc_extra_args" \
1354							    exec.stop="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}stop $rc_extra_args" \
1355							    exec.consolelog="/var/log/svcj_${name}_console.log" \
1356							    name=svcj-${name} && _return=0
1357						fi
1358					else
1359						_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || _return=1
1360					fi
1361					;;
1362				stop)
1363					if [ "${_rc_svcj}" != jailing ]; then
1364						$SERVICE -E _rc_svcj=jailing -j svcj-${name} ${name} ${_rc_prefix}stop $rc_extra_args || _return=1
1365						$JAIL_CMD -r svcj-${name} 2>/dev/null
1366					else
1367						_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || _return=1
1368					fi
1369					;;
1370				restart|status) ;; # no special case needed for svcj or handled somewhere else
1371				*)
1372					eval _rc_svcj_extra_cmd=\$${name}_${rc_arg}_svcj_enable
1373					: ${_rc_svcj_extra_cmd:=NO}
1374					if checkyesno _rc_svcj_extra_cmd && [ "${_rc_svcj}" != jailing ]; then
1375						$SERVICE -v -E _rc_svcj=jailing -j svcj-${name} ${name} ${_rc_prefix}${rc_arg} $rc_extra_args || _return=1
1376					else
1377						_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || _return=1
1378					fi
1379					;;
1380				esac
1381			fi
1382			if [ "${_rc_svcj}" != jailing ]; then
1383				_run_rc_postcmd
1384			fi
1385			return $_return
1386		fi
1387
1388		case "$rc_arg" in	# default operations...
1389
1390		describe)
1391			if [ -n "$desc" ]; then
1392				echo "$desc"
1393			fi
1394			;;
1395
1396		extracommands)
1397			echo "$extra_commands"
1398			;;
1399
1400		enable)
1401			_out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=YES") &&
1402				echo "$name enabled in ${_out%%:*}"
1403			;;
1404
1405		disable)
1406			_out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=NO") &&
1407				echo "$name disabled in ${_out%%:*}"
1408			;;
1409
1410		delete)
1411			_files=
1412			for _file in $(/usr/sbin/sysrc -lEs "$name"); do
1413				_out=$(/usr/sbin/sysrc -Fif $_file "$rcvar") && _files="$_files $_file"
1414			done
1415			/usr/sbin/sysrc -x "$rcvar" && echo "$rcvar deleted in ${_files# }"
1416				# delete file in rc.conf.d if desired and empty.
1417			checkyesno service_delete_empty || _files=
1418			for _file in $_files; do
1419				[ "$_file" = "${_file#*/rc.conf.d/}" ] && continue
1420				[ $(/usr/bin/stat -f%z $_file) -gt 0 ] && continue
1421				/bin/rm "$_file" && echo "Empty file $_file removed"
1422			done
1423			;;
1424
1425		status)
1426			_run_rc_precmd || return 1
1427			if [ -n "$rc_pid" ]; then
1428				echo "${name} is running as pid $rc_pid."
1429			else
1430				echo "${name} is not running."
1431				return 1
1432			fi
1433			_run_rc_postcmd
1434			;;
1435
1436		start)
1437			if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1438				warn "run_rc_command: cannot run $command"
1439				return 1
1440			fi
1441
1442			if [ "${_rc_svcj}" != jailing ]; then
1443				_run_rc_setup || warn "failed to setup ${name}"
1444
1445				if ! _run_rc_precmd; then
1446					warn "failed precmd routine for ${name}"
1447					return 1
1448				fi
1449			fi
1450
1451			if checkyesno ${name}_svcj; then
1452				if [ "${_rc_svcj}" != jailing ]; then
1453					if check_jail jailed; then
1454						if [ $(${SYSCTL_N} security.jail.children.max) -eq 0 ]; then
1455							echo ERROR: jail parameter children.max is set to 0, can not create a new service jail.
1456							return 1
1457						else
1458							_free_jails=$(($(${SYSCTL_N} security.jail.children.max) - $(${SYSCTL_N} security.jail.children.cur)))
1459							if [ ${_free_jails} -eq 0 ]; then
1460								echo ERROR: max number of jail children reached, can not create a new service jail.
1461								return 1
1462							fi
1463						fi
1464					fi
1465					$JAIL_CMD -c $_svcj_generic_params $_svcj_cmd_options\
1466					    exec.start="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}start $rc_extra_args" \
1467					    exec.stop="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}stop $rc_extra_args" \
1468					    exec.consolelog="/var/log/svcj_${name}_console.log" \
1469					    name=svcj-${name} || return 1
1470				fi
1471			fi
1472
1473			# setup the full command to run
1474			#
1475			startmsg "Starting ${name}."
1476			if [ -n "$_chroot" ]; then
1477				_cd=
1478				_doit="\
1479${_nice:+nice -n $_nice }\
1480$_cpusetcmd \
1481${_fib:+setfib -F $_fib }\
1482${_env:+env $_env }\
1483chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1484$_chroot $command $rc_flags $command_args"
1485			else
1486				_cd="${_chdir:+cd $_chdir && }"
1487				_doit="\
1488${_fib:+setfib -F $_fib }\
1489${_env:+env $_env }\
1490$_cpusetcmd $command $rc_flags $command_args"
1491				if [ -n "$_user" ]; then
1492				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1493				fi
1494				if [ -n "$_nice" ]; then
1495					if [ -z "$_user" ]; then
1496						_doit="sh -c \"$_doit\""
1497					fi
1498					_doit="nice -n $_nice $_doit"
1499				fi
1500				if [ -n "$_prepend" ]; then
1501					_doit="$_prepend $_doit"
1502				fi
1503			fi
1504
1505			# Prepend default limits
1506			_doit="$_cd limits -C $_login_class $_limits $_doit"
1507
1508			local _really_run_it=true
1509			if checkyesno ${name}_svcj; then
1510				if [ "${_rc_svcj}" != jailing ]; then
1511					_really_run_it=false
1512				fi
1513			fi
1514
1515			if [ "$_really_run_it" = true ]; then
1516				# run the full command
1517				#
1518				if ! _run_rc_doit "$_doit"; then
1519					warn "failed to start ${name}"
1520					return 1
1521				fi
1522			fi
1523
1524			if [ "${_rc_svcj}" != jailing ]; then
1525				# finally, run postcmd
1526				#
1527				_run_rc_postcmd
1528			fi
1529			;;
1530
1531		stop)
1532			if [ -z "$rc_pid" ]; then
1533				[ -n "$rc_fast" ] && return 0
1534				_run_rc_notrunning
1535				return 1
1536			fi
1537
1538			_run_rc_precmd || return 1
1539
1540			# send the signal to stop
1541			#
1542			echo "Stopping ${name}."
1543			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1544			_run_rc_doit "$_doit" || return 1
1545
1546			# wait for the command to exit,
1547			# and run postcmd.
1548			wait_for_pids $rc_pid
1549
1550			if checkyesno ${name}_svcj; then
1551				# remove service jail
1552				$JAIL_CMD -r svcj-${name} 2>/dev/null
1553			fi
1554
1555			_run_rc_postcmd
1556			;;
1557
1558		reload)
1559			if [ -z "$rc_pid" ]; then
1560				_run_rc_notrunning
1561				return 1
1562			fi
1563
1564			_run_rc_setup || warn "failed to setup ${name}"
1565
1566			_run_rc_precmd || return 1
1567
1568			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1569			_run_rc_doit "$_doit" || return 1
1570
1571			_run_rc_postcmd
1572			;;
1573
1574		restart)
1575			_run_rc_setup || warn "failed to setup ${name}"
1576
1577			# prevent restart being called more
1578			# than once by any given script
1579			#
1580			if ${_rc_restart_done:-false}; then
1581				return 0
1582			fi
1583			_rc_restart_done=true
1584
1585			_run_rc_precmd || return 1
1586
1587			# run those in a subshell to keep global variables
1588			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1589			( run_rc_command ${_rc_prefix}start $rc_extra_args )
1590			_return=$?
1591			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1592
1593			_run_rc_postcmd
1594			;;
1595
1596		poll)
1597			_run_rc_precmd || return 1
1598			if [ -n "$rc_pid" ]; then
1599				wait_for_pids $rc_pid
1600			fi
1601			_run_rc_postcmd
1602			;;
1603
1604		rcvar)
1605			echo -n "# $name"
1606			if [ -n "$desc" ]; then
1607				echo " : $desc"
1608			else
1609				echo ""
1610			fi
1611			echo "#"
1612			# Get unique vars in $rcvar $rcvars
1613			for _v in $rcvar $rcvars; do
1614				case $v in
1615				$_v\ *|\ *$_v|*\ $_v\ *) ;;
1616				*)	v="${v# } $_v" ;;
1617				esac
1618			done
1619
1620			# Display variables.
1621			for _v in $v; do
1622				if [ -z "$_v" ]; then
1623					continue
1624				fi
1625
1626				eval _desc=\$${_v}_desc
1627				eval _defval=\$${_v}_defval
1628				_h="-"
1629
1630				eval echo \"$_v=\\\"\$$_v\\\"\"
1631				# decode multiple lines of _desc
1632				while [ -n "$_desc" ]; do
1633					case $_desc in
1634					*^^*)
1635						echo "# $_h ${_desc%%^^*}"
1636						_desc=${_desc#*^^}
1637						_h=" "
1638						;;
1639					*)
1640						echo "# $_h ${_desc}"
1641						break
1642						;;
1643					esac
1644				done
1645				echo "#   (default: \"$_defval\")"
1646			done
1647			echo ""
1648			;;
1649
1650		*)
1651			rc_usage $_keywords
1652			;;
1653
1654		esac
1655
1656		# Apply protect(1) to the PID if ${name}_oomprotect is set.
1657		case "$rc_arg" in
1658		start)
1659			# We cannot use protect(1) inside jails.
1660			if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1661			    [ "$(sysctl -n security.jail.jailed)" -eq 0 ]; then
1662				[ -z "${rc_pid}" ] && eval $_pidcmd
1663				case $_oomprotect in
1664				[Aa][Ll][Ll])
1665					${PROTECT} -d -i -p ${rc_pid}
1666					;;
1667				[Yy][Ee][Ss])
1668					${PROTECT} -p ${rc_pid}
1669					;;
1670				esac
1671			fi
1672		;;
1673		esac
1674
1675		return $_return
1676	done
1677
1678	echo 1>&2 "$0: unknown directive '$rc_arg'."
1679	rc_usage $_keywords
1680	# not reached
1681}
1682
1683#
1684# Helper functions for run_rc_command: common code.
1685# They use such global variables besides the exported rc_* ones:
1686#
1687#	name	       R/W
1688#	------------------
1689#	_offcmd		R
1690#	_precmd		R
1691#	_postcmd	R
1692#	_return		W
1693#	_setup		R
1694#
1695_run_rc_offcmd()
1696{
1697	eval _offcmd=\$${name}_offcmd
1698	if [ -n "$_offcmd" ]; then
1699		if [ -n "$_env" ]; then
1700			eval "export -- $_env"
1701		fi
1702		debug "run_rc_command: ${name}_offcmd: $_offcmd $rc_extra_args"
1703		eval "$_offcmd $rc_extra_args"
1704		_return=$?
1705	fi
1706	return 0
1707}
1708
1709_run_rc_precmd()
1710{
1711	check_required_before "$rc_arg" || return 1
1712
1713	if [ -n "$_precmd" ]; then
1714		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1715		eval "$_precmd $rc_extra_args"
1716		_return=$?
1717
1718		# If precmd failed and force isn't set, request exit.
1719		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1720			return 1
1721		fi
1722	fi
1723
1724	check_required_after "$rc_arg" || return 1
1725
1726	return 0
1727}
1728
1729_run_rc_postcmd()
1730{
1731	if [ -n "$_postcmd" ]; then
1732		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1733		eval "$_postcmd $rc_extra_args"
1734		_return=$?
1735	fi
1736	return 0
1737}
1738
1739_run_rc_setup()
1740{
1741	# prevent multiple execution on restart => stop/start split
1742	if ! ${_rc_restart_done:-false} && [ -n "$_setup" ]; then
1743		debug "run_rc_command: ${rc_arg}_setup: $_setup"
1744		eval "$_setup"
1745		_return=$?
1746		if [ $_return -ne 0 ]; then
1747			return 1
1748		fi
1749	fi
1750	return 0
1751}
1752
1753_run_rc_doit()
1754{
1755	local _m
1756
1757	debug "run_rc_command: doit: $*"
1758	_m=$(umask)
1759	${_umask:+umask ${_umask}}
1760	eval "$@"
1761	_return=$?
1762	umask ${_m}
1763
1764	# If command failed and force isn't set, request exit.
1765	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1766		return 1
1767	fi
1768
1769	return 0
1770}
1771
1772_run_rc_notrunning()
1773{
1774	local _pidmsg
1775
1776	if [ -n "$pidfile" ]; then
1777		_pidmsg=" (check $pidfile)."
1778	else
1779		_pidmsg=
1780	fi
1781	echo 1>&2 "${name} not running?${_pidmsg}"
1782}
1783
1784_run_rc_killcmd()
1785{
1786	local _cmd
1787
1788	_cmd="kill -$1 $rc_pid"
1789	if [ -n "$_user" ]; then
1790		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1791	fi
1792	echo "$_cmd"
1793}
1794
1795#
1796# run_rc_script file arg
1797#	Start the script `file' with `arg', and correctly handle the
1798#	return value from the script.
1799#	If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1800#	an old-style startup file.
1801#	If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1802#	into the current environment if $rc_fast_and_loose is set; otherwise
1803#	it is run as a child process.
1804#	If `file' appears to be a backup or scratch file, ignore it.
1805#	Otherwise if it is executable run as a child process.
1806#
1807run_rc_script()
1808{
1809	_file=$1
1810	_arg=$2
1811	if [ -z "$_file" -o -z "$_arg" ]; then
1812		err 3 'USAGE: run_rc_script file arg'
1813	fi
1814
1815	unset	name command command_args command_interpreter \
1816		extra_commands pidfile procname \
1817		rcvar rcvars rcvars_obsolete required_dirs required_files \
1818		required_vars
1819	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1820
1821	rc_trace 0 "$_file $_arg"
1822	# don't use it if we don't trust it
1823	is_verified $_file || return
1824
1825	rc_service="$_file"
1826	case "$_file" in
1827	/etc/rc.d/*.sh)			# no longer allowed in the base
1828		warn "Ignoring old-style startup script $_file"
1829		;;
1830	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
1831		warn "Ignoring scratch file $_file"
1832		;;
1833	*)				# run in subshell
1834		if [ -x $_file ]; then
1835			DebugOn $_file $_file:$_arg rc:${_file##*/} rc:${_file##*/}:$_arg ${_file##*/} ${_file##*/}:$_arg
1836
1837			if [ -n "$rc_boottrace" ]; then
1838				boottrace_fn "$_file" "$_arg"
1839			elif [ -n "$rc_fast_and_loose" ]; then
1840				set $_arg; . $_file
1841			else
1842				( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1843				  trap "echo Script $_file interrupted >&2 ; exit 1" 2
1844				  trap "echo Script $_file running >&2" 29
1845				  set $_arg; . $_file )
1846			fi
1847			DebugOff rc=$? $_file $_file:$_arg rc:${_file##*/} rc:${_file##*/}:$_arg ${_file##*/} ${_file##*/}:$_arg
1848		fi
1849		;;
1850	esac
1851}
1852
1853#
1854# run_rc_scripts [options] file [...]
1855#
1856# Call `run_rc_script' for each "file" unless already listed in
1857# $_rc_elem_done.
1858#
1859# Options:
1860#
1861#	--arg "arg"
1862#		Pass "arg" to `run_rc_script' default is $_boot.
1863#
1864#	--break "marker"
1865#		If any "file" matches "marker" stop processing.
1866#
1867_rc_elem_done=
1868run_rc_scripts()
1869{
1870	local _arg=${_boot}
1871	local _rc_elem
1872	local _rc_breaks=
1873
1874	while :; do
1875		case "$1" in
1876		--arg)
1877                        _arg="$2"
1878                        shift 2
1879                        ;;
1880		--break)
1881                        _rc_breaks="$_rc_breaks $2"
1882                        shift 2
1883                        ;;
1884		*)
1885                        break
1886                        ;;
1887		esac
1888	done
1889	for _rc_elem in "$@"; do
1890		: _rc_elem=$_rc_elem
1891		case " $_rc_elem_done " in
1892		*" $_rc_elem "*)
1893                        continue
1894                        ;;
1895		esac
1896		run_rc_script ${_rc_elem} ${_arg}
1897		_rc_elem_done="$_rc_elem_done $_rc_elem"
1898		case " $_rc_breaks " in
1899		*" ${_rc_elem##*/} "*)
1900                        break
1901                        ;;
1902		esac
1903	done
1904}
1905
1906boottrace_fn()
1907{
1908	local _file _arg
1909	_file=$1
1910	_arg=$2
1911
1912	if [ -n "$rc_fast_and_loose" ]; then
1913		boottrace_sysctl "$_file start"
1914		set $_arg; . $_file
1915		boottrace_sysctl "$_file done"
1916	else
1917		_boot="${_boot}" rc_fast="${rc_fast}" autoboot="${autoboot}" \
1918		    $boottrace_cmd "$_file" "$_arg"
1919	fi
1920}
1921
1922boottrace_sysctl()
1923{
1924	${SYSCTL} kern.boottrace.boottrace="$1"
1925}
1926
1927#
1928# load_rc_config [service]
1929#	Source in the configuration file(s) for a given service.
1930#	If no service is specified, only the global configuration
1931#	file(s) will be loaded.
1932#
1933load_rc_config()
1934{
1935	local _name _rcvar_val _var _defval _v _msg _new _d _dot
1936	_name=$1
1937	_dot=${load_rc_config_reader:-dot}
1938
1939	case "$_dot" in
1940	dot|[sv]dot)
1941		;;
1942	*)	warn "Ignoring invalid load_rc_config_reader"
1943		_dot=dot
1944		;;
1945	esac
1946	case "$1" in
1947	-s|--safe)
1948                _dot=sdot
1949                _name=$2
1950                shift
1951                ;;
1952	-v|--verify)
1953                _dot=vdot
1954                _name=$2
1955                shift
1956                ;;
1957	esac
1958
1959	DebugOn rc:$_name $_name
1960
1961	if ${_rc_conf_loaded:-false}; then
1962		:
1963	else
1964		if [ -r /etc/defaults/rc.conf ]; then
1965			debug "Sourcing /etc/defaults/rc.conf"
1966			$_dot /etc/defaults/rc.conf
1967			source_rc_confs
1968		elif [ -r /etc/rc.conf ]; then
1969			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1970			$_dot /etc/rc.conf
1971		fi
1972		_rc_conf_loaded=true
1973	fi
1974
1975	# If a service name was specified, attempt to load
1976	# service-specific configuration
1977	if [ -n "$_name" ] ; then
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# If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2732# still override this, but /etc/defaults/rc.conf can't unconditionally set this
2733# since it would undo what we've done here.
2734if kenv -q rc.debug > /dev/null ; then
2735	rc_debug=YES
2736fi
2737
2738boottrace_cmd=`command -v boottrace`
2739if [ -n "$boottrace_cmd" ] && [ "`${SYSCTL_N} -q kern.boottrace.enabled`" = "1" ]; then
2740	rc_boottrace=YES
2741fi
2742
2743SED=${SED:-$(Exists -x /usr/bin/sed /rescue/sed)}
2744
2745# Allow for local additions and overrides.
2746# Use vdot to ensure the file has not been tampered with.
2747vdot /etc/local.rc.subr
2748
2749# Avoid noise - when we do not have /usr mounted,
2750# and we cannot use safe_dot without sed.
2751if ! have basename; then
2752	basename()
2753	{
2754		local b=${1%$2}
2755		echo ${b##*/}
2756	}
2757	tty()
2758	{
2759		return 0
2760	}
2761	# we cannot use safe_dot without sed
2762	[ -z "$SED" ] && _SAFE_EVAL_SH=:
2763fi
2764# safe_eval.sh provides safe_dot - for untrusted files
2765$_SAFE_EVAL_SH vdot /libexec/safe_eval.sh
2766$_DEBUG_SH vdot /libexec/debug.sh
2767
2768# Ensure we can still operate if debug.sh and
2769# safe_eval.sh are not found.
2770if ! have DebugOn; then
2771	DebugOn() { return 0; }
2772	DebugOff() {
2773		local _rc=0
2774		while :
2775		do
2776			case "$1" in
2777			-[eo]) shift;; # ignore it
2778			rc=*) eval "_$1"; shift;;
2779			*) break;;
2780			esac
2781		done
2782		return $_rc
2783	}
2784fi
2785if ! have safe_dot; then
2786	safe_dot() { dot "$@"; }
2787fi
2788