xref: /freebsd/libexec/rc/rc.subr (revision f1c4c3daccbaf3820f0e2224de53df12fc952fcc)
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 -o $_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_ip4_addrs=""
1218	_svcj_ip6_addrs=""
1219	_svcj_cmd_options=""
1220
1221	if [ -n "$_svcj_ipaddrs" ]; then
1222		_svcj_ip="new"
1223
1224		for addr in $_svcj_ipaddrs; do
1225			case $addr in
1226				*:*) _svcj_ip6_addrs="$addr,${_svcj_ip6_addrs}" ;;
1227				*) _svcj_ip4_addrs="$addr,${_svcj_ip4_addrs}" ;;
1228			esac
1229		done
1230	else
1231		_svcj_ip="inherit"
1232	fi
1233
1234	if check_kern_features inet; then
1235		_svcj_ip4="ip4=${_svcj_ip}"
1236		if [ -n "$_svcj_ip4_addrs" ]; then
1237			_svcj_cmd_options="ip4.addr=${_svcj_ip4_addrs%*,} ${_svcj_cmd_options}"
1238		fi
1239	else
1240		if [ -n "$_svcj_ip4_addrs" ]; then
1241			warn "$rc_service: ${name}_svcj_ipaddrs contains at least one IPv4 address, but IPv4 is not enabled in the kernel; IPv4 addresses will be ignored."
1242		fi
1243	fi
1244
1245	if check_kern_features inet6; then
1246		_svcj_ip6="ip6=${_svcj_ip}"
1247		if [ -n "$_svcj_ip6_addrs" ]; then
1248			_svcj_cmd_options="ip6.addr=${_svcj_ip6_addrs%*,} ${_svcj_cmd_options}"
1249		fi
1250	else
1251		if [ -n "$_svcj_ip6_addrs" ]; then
1252			warn "$rc_service: ${name}_svcj_ipaddrs contains at least one IPv6 address, but IPv6 is not enabled in the kernel; IPv6 addresses will be ignored."
1253		fi
1254	fi
1255
1256	if [ -n "$_svcj_options" ]; then	# translate service jail options
1257		_svcj_sysvipc_x=0
1258		for _svcj_option in $_svcj_options; do
1259			case "$_svcj_option" in
1260				mlock)
1261					_svcj_cmd_options="allow.mlock ${_svcj_cmd_options}"
1262					;;
1263				netv4)
1264					_svcj_cmd_options="${_svcj_ip4} allow.reserved_ports ${_svcj_cmd_options}"
1265					;;
1266				netv6)
1267					_svcj_cmd_options="${_svcj_ip6} allow.reserved_ports ${_svcj_cmd_options}"
1268					;;
1269				net_basic)
1270					_svcj_cmd_options="${_svcj_ip4} ${_svcj_ip6} allow.reserved_ports ${_svcj_cmd_options}"
1271					;;
1272				net_raw)
1273					_svcj_cmd_options="allow.raw_sockets ${_svcj_cmd_options}"
1274					;;
1275				net_all)
1276					_svcj_cmd_options="allow.socket_af allow.raw_sockets allow.reserved_ports ${_svcj_ip4} ${_svcj_ip6} ${_svcj_cmd_options}"
1277					;;
1278				nfsd)
1279					_svcj_cmd_options="allow.nfsd enforce_statfs=1 ${_svcj_cmd_options}"
1280					;;
1281				routing)
1282					_svcj_cmd_options="allow.routing ${_svcj_cmd_options}"
1283					;;
1284				settime)
1285					_svcj_cmd_options="allow.settime ${_svcj_cmd_options}"
1286					;;
1287				sysvipc)
1288					_svcj_sysvipc_x=$((${_svcj_sysvipc_x} + 1))
1289					_svcj_cmd_options="sysvmsg=inherit sysvsem=inherit sysvshm=inherit  ${_svcj_cmd_options}"
1290					;;
1291				sysvipcnew)
1292					_svcj_sysvipc_x=$((${_svcj_sysvipc_x} + 1))
1293					_svcj_cmd_options="sysvmsg=new sysvsem=new sysvshm=new ${_svcj_cmd_options}"
1294					;;
1295				vmm)
1296					_svcj_cmd_options="allow.vmm ${_svcj_cmd_options}"
1297					;;
1298				*)
1299					echo ${name}: unknown service jail option: $_svcj_option
1300					;;
1301			esac
1302		done
1303		if [ ${_svcj_sysvipc_x} -gt 1 ]; then
1304			echo -n "ERROR: more than one sysvipc option is "
1305			echo "specified in ${name}_svcj_options: $_svcj_options"
1306			return 1
1307		fi
1308	fi
1309
1310	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
1311
1312	for _elem in $_keywords; do
1313		if [ "$_elem" != "$rc_arg" ]; then
1314			continue
1315		fi
1316					# if ${rcvar} is set, $1 is not "rcvar", "describe",
1317					# "enable", "delete" or "status", and ${rc_pid} is
1318					# not set, run:
1319					#	checkyesno ${rcvar}
1320					# and return if that failed
1321					#
1322		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
1323		    -a "$rc_arg" != "delete" -a "$rc_arg" != "enable" \
1324		    -a "$rc_arg" != "describe" -a "$rc_arg" != "status" ] ||
1325		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
1326			if ! checkyesno ${rcvar}; then
1327			    [ "$rc_arg" = "start" ] && _run_rc_offcmd
1328			    if [ -z "${rc_quiet}" ]; then
1329				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
1330				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
1331				echo "instead of '${rc_arg}'."
1332			    fi
1333			    return 0
1334			fi
1335		fi
1336
1337		if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1338			if [ -z "$rc_quiet" ]; then
1339				echo 1>&2 "${name} already running? " \
1340				    "(pid=$rc_pid)."
1341			fi
1342			return 1
1343		fi
1344
1345		# if there's a custom ${XXX_cmd},
1346		# run that instead of the default
1347		#
1348		eval _cmd=\$${rc_arg}_cmd \
1349		     _precmd=\$${rc_arg}_precmd \
1350		     _postcmd=\$${rc_arg}_postcmd
1351
1352		if [ -n "$_cmd" ]; then
1353			if [ "$_cmd" != : ]; then
1354				rc_trace 1 "$_cmd"
1355			fi
1356			if [ -n "$_env" ]; then
1357				eval "export -- $_env"
1358			fi
1359
1360			if [ "${_rc_svcj}" != jailing ]; then
1361				# service can redefine all so
1362				# check for valid setup target
1363				if [ "$rc_arg" = 'start' -o \
1364				    "$rc_arg" = 'restart' -o \
1365				    "$rc_arg" = 'reload' ]; then
1366					_run_rc_setup || \
1367					    warn "failed to setup ${name}"
1368				fi
1369				_run_rc_precmd || return 1
1370			fi
1371			if ! checkyesno ${name}_svcj; then
1372				_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || return 1
1373			else
1374				case "$rc_arg" in
1375				start)
1376					if [ "${_rc_svcj}" != jailing ]; then
1377						_return=1
1378						_do_jailing=1
1379
1380						if check_jail jailed; then
1381							if [ $(${SYSCTL_N} security.jail.children.max) -eq 0 ]; then
1382								echo ERROR: jail parameter children.max is set to 0, can not create a new service jail.
1383								_do_jailing=0
1384							else
1385								_free_jails=$(($(${SYSCTL_N} security.jail.children.max) - $(${SYSCTL_N} security.jail.children.cur)))
1386								if [ ${_free_jails} -eq 0 ]; then
1387									echo ERROR: max number of jail children reached, can not create a new service jail.
1388									_do_jailing=0
1389
1390								fi
1391							fi
1392						fi
1393						if [ ${_do_jailing} -eq 1 ]; then
1394							$JAIL_CMD -c $_svcj_generic_params $_svcj_cmd_options \
1395							    exec.start="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}start $rc_extra_args" \
1396							    exec.stop="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}stop $rc_extra_args" \
1397							    exec.consolelog="/var/log/svcj_${name}_console.log" \
1398							    name=svcj-${name} && _return=0
1399						fi
1400					else
1401						_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || _return=1
1402					fi
1403					;;
1404				stop)
1405					if [ "${_rc_svcj}" != jailing ]; then
1406						$SERVICE -E _rc_svcj=jailing -j svcj-${name} ${name} ${_rc_prefix}stop $rc_extra_args || _return=1
1407						$JAIL_CMD -r svcj-${name} 2>/dev/null
1408					else
1409						_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || _return=1
1410					fi
1411					;;
1412				restart|status) ;; # no special case needed for svcj or handled somewhere else
1413				*)
1414					eval _rc_svcj_extra_cmd=\$${name}_${rc_arg}_svcj_enable
1415					: ${_rc_svcj_extra_cmd:=NO}
1416					if checkyesno _rc_svcj_extra_cmd && [ "${_rc_svcj}" != jailing ]; then
1417						$SERVICE -v -E _rc_svcj=jailing -j svcj-${name} ${name} ${_rc_prefix}${rc_arg} $rc_extra_args || _return=1
1418					else
1419						_run_rc_doit "$_cpusetcmd $_cmd $rc_extra_args" || _return=1
1420					fi
1421					;;
1422				esac
1423			fi
1424			if [ "${_rc_svcj}" != jailing ]; then
1425				_run_rc_postcmd
1426			fi
1427			return $_return
1428		fi
1429
1430		case "$rc_arg" in	# default operations...
1431
1432		describe)
1433			if [ -n "$desc" ]; then
1434				echo "$desc"
1435			fi
1436			;;
1437
1438		extracommands)
1439			echo "$extra_commands"
1440			;;
1441
1442		enable)
1443			_out=$(write_rcvar "$rcvar" "YES") &&
1444				echo "$name enabled in $_out"
1445			;;
1446
1447		disable)
1448			_out=$(write_rcvar "$rcvar" "NO") &&
1449				echo "$name disabled in $_out"
1450			;;
1451
1452		delete)
1453			delete_rcvar "$rcvar"
1454			;;
1455
1456		status)
1457			_run_rc_precmd || return 1
1458			if [ -n "$rc_pid" ]; then
1459				echo "${name} is running as pid $rc_pid."
1460			else
1461				echo "${name} is not running."
1462				return 1
1463			fi
1464			_run_rc_postcmd
1465			;;
1466
1467		start)
1468			if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1469				warn "run_rc_command: cannot run $command"
1470				return 1
1471			fi
1472
1473			if [ "${_rc_svcj}" != jailing ]; then
1474				_run_rc_setup || warn "failed to setup ${name}"
1475
1476				if ! _run_rc_precmd; then
1477					warn "failed precmd routine for ${name}"
1478					return 1
1479				fi
1480			fi
1481
1482			if checkyesno ${name}_svcj; then
1483				if [ "${_rc_svcj}" != jailing ]; then
1484					if check_jail jailed; then
1485						if [ $(${SYSCTL_N} security.jail.children.max) -eq 0 ]; then
1486							echo ERROR: jail parameter children.max is set to 0, can not create a new service jail.
1487							return 1
1488						else
1489							_free_jails=$(($(${SYSCTL_N} security.jail.children.max) - $(${SYSCTL_N} security.jail.children.cur)))
1490							if [ ${_free_jails} -eq 0 ]; then
1491								echo ERROR: max number of jail children reached, can not create a new service jail.
1492								return 1
1493							fi
1494						fi
1495					fi
1496					$JAIL_CMD -c $_svcj_generic_params $_svcj_cmd_options\
1497					    exec.start="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}start $rc_extra_args" \
1498					    exec.stop="${SERVICE} -E _rc_svcj=jailing ${name} ${_rc_prefix}stop $rc_extra_args" \
1499					    exec.consolelog="/var/log/svcj_${name}_console.log" \
1500					    name=svcj-${name} || return 1
1501				fi
1502			fi
1503
1504			# setup the full command to run
1505			#
1506			startmsg "Starting ${name}."
1507			if [ -n "$_chroot" ]; then
1508				_cd=
1509				_doit="\
1510${_nice:+nice -n $_nice }\
1511$_cpusetcmd \
1512${_fib:+setfib -F $_fib }\
1513${_env:+env $_env }\
1514chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1515$_chroot $command $rc_flags $command_args"
1516			else
1517				_cd="${_chdir:+cd $_chdir && }"
1518				_doit="\
1519${_fib:+setfib -F $_fib }\
1520${_env:+env $_env }\
1521$_cpusetcmd $command $rc_flags $command_args"
1522				if [ -n "$_user" ]; then
1523				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1524				fi
1525				if [ -n "$_nice" ]; then
1526					if [ -z "$_user" ]; then
1527						_doit="sh -c \"$_doit\""
1528					fi
1529					_doit="nice -n $_nice $_doit"
1530				fi
1531				if [ -n "$_prepend" ]; then
1532					_doit="$_prepend $_doit"
1533				fi
1534			fi
1535
1536			# Prepend default limits
1537			_doit="$_cd limits -C $_login_class $_limits $_doit"
1538
1539			local _really_run_it=true
1540			if checkyesno ${name}_svcj; then
1541				if [ "${_rc_svcj}" != jailing ]; then
1542					_really_run_it=false
1543				fi
1544			fi
1545
1546			if [ "$_really_run_it" = true ]; then
1547				# run the full command
1548				#
1549				if ! _run_rc_doit "$_doit"; then
1550					warn "failed to start ${name}"
1551					return 1
1552				fi
1553			fi
1554
1555			if [ "${_rc_svcj}" != jailing ]; then
1556				# finally, run postcmd
1557				#
1558				_run_rc_postcmd
1559			fi
1560			;;
1561
1562		stop)
1563			if [ -z "$rc_pid" ]; then
1564				[ -n "$rc_fast" ] && return 0
1565				_run_rc_notrunning
1566				return 1
1567			fi
1568
1569			_run_rc_precmd || return 1
1570
1571			# send the signal to stop
1572			#
1573			echo "Stopping ${name}."
1574			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1575			_run_rc_doit "$_doit" || return 1
1576
1577			# wait for the command to exit,
1578			# and run postcmd.
1579			wait_for_pids $rc_pid
1580
1581			if checkyesno ${name}_svcj; then
1582				# remove service jail
1583				$JAIL_CMD -r svcj-${name} 2>/dev/null
1584			fi
1585
1586			_run_rc_postcmd
1587			;;
1588
1589		reload)
1590			if [ -z "$rc_pid" ]; then
1591				_run_rc_notrunning
1592				return 1
1593			fi
1594
1595			_run_rc_setup || warn "failed to setup ${name}"
1596
1597			_run_rc_precmd || return 1
1598
1599			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1600			_run_rc_doit "$_doit" || return 1
1601
1602			_run_rc_postcmd
1603			;;
1604
1605		restart)
1606			_run_rc_setup || warn "failed to setup ${name}"
1607
1608			# prevent restart being called more
1609			# than once by any given script
1610			#
1611			if ${_rc_restart_done:-false}; then
1612				return 0
1613			fi
1614			_rc_restart_done=true
1615
1616			_run_rc_precmd || return 1
1617
1618			# run those in a subshell to keep global variables
1619			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1620			( run_rc_command ${_rc_prefix}start $rc_extra_args )
1621			_return=$?
1622			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1623
1624			_run_rc_postcmd
1625			;;
1626
1627		poll)
1628			_run_rc_precmd || return 1
1629			if [ -n "$rc_pid" ]; then
1630				wait_for_pids $rc_pid
1631			fi
1632			_run_rc_postcmd
1633			;;
1634
1635		rcvar)
1636			echo -n "# $name"
1637			if [ -n "$desc" ]; then
1638				echo " : $desc"
1639			else
1640				echo ""
1641			fi
1642			echo "#"
1643			# Get unique vars in $rcvar $rcvars
1644			for _v in $rcvar $rcvars; do
1645				case $v in
1646				$_v\ *|\ *$_v|*\ $_v\ *) ;;
1647				*)	v="${v# } $_v" ;;
1648				esac
1649			done
1650
1651			# Display variables.
1652			for _v in $v; do
1653				if [ -z "$_v" ]; then
1654					continue
1655				fi
1656
1657				eval _desc=\$${_v}_desc
1658				eval _defval=\$${_v}_defval
1659				_h="-"
1660
1661				eval echo \"$_v=\\\"\$$_v\\\"\"
1662				# decode multiple lines of _desc
1663				while [ -n "$_desc" ]; do
1664					case $_desc in
1665					*^^*)
1666						echo "# $_h ${_desc%%^^*}"
1667						_desc=${_desc#*^^}
1668						_h=" "
1669						;;
1670					*)
1671						echo "# $_h ${_desc}"
1672						break
1673						;;
1674					esac
1675				done
1676				echo "#   (default: \"$_defval\")"
1677			done
1678			echo ""
1679			;;
1680
1681		*)
1682			rc_usage $_keywords
1683			;;
1684
1685		esac
1686
1687		# Apply protect(1) to the PID if ${name}_oomprotect is set.
1688		case "$rc_arg" in
1689		start)
1690			# We cannot use protect(1) inside jails.
1691			if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1692			    ! check_jail jailed; then
1693				[ -z "${rc_pid}" ] && eval $_pidcmd
1694				case $_oomprotect in
1695				[Aa][Ll][Ll])
1696					${PROTECT} -d -i -p ${rc_pid}
1697					;;
1698				[Yy][Ee][Ss])
1699					${PROTECT} -p ${rc_pid}
1700					;;
1701				esac
1702			fi
1703		;;
1704		esac
1705
1706		return $_return
1707	done
1708
1709	echo 1>&2 "$0: unknown directive '$rc_arg'."
1710	rc_usage $_keywords
1711	# not reached
1712}
1713
1714#
1715# Helper functions for run_rc_command: common code.
1716# They use such global variables besides the exported rc_* ones:
1717#
1718#	name	       R/W
1719#	------------------
1720#	_offcmd		R
1721#	_precmd		R
1722#	_postcmd	R
1723#	_return		W
1724#	_setup		R
1725#
1726_run_rc_offcmd()
1727{
1728	eval _offcmd=\$${name}_offcmd
1729	if [ -n "$_offcmd" ]; then
1730		if [ -n "$_env" ]; then
1731			eval "export -- $_env"
1732		fi
1733		debug "run_rc_command: ${name}_offcmd: $_offcmd $rc_extra_args"
1734		eval "$_offcmd $rc_extra_args"
1735		_return=$?
1736	fi
1737	return 0
1738}
1739
1740_run_rc_precmd()
1741{
1742	check_required_before "$rc_arg" || return 1
1743
1744	if [ -n "$_precmd" ]; then
1745		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1746		eval "$_precmd $rc_extra_args"
1747		_return=$?
1748
1749		# If precmd failed and force isn't set, request exit.
1750		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1751			return 1
1752		fi
1753	fi
1754
1755	check_required_after "$rc_arg" || return 1
1756
1757	return 0
1758}
1759
1760_run_rc_postcmd()
1761{
1762	if [ -n "$_postcmd" ]; then
1763		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1764		eval "$_postcmd $rc_extra_args"
1765		_return=$?
1766	fi
1767	return 0
1768}
1769
1770_run_rc_setup()
1771{
1772	# prevent multiple execution on restart => stop/start split
1773	if ! ${_rc_restart_done:-false} && [ -n "$_setup" ]; then
1774		debug "run_rc_command: ${rc_arg}_setup: $_setup"
1775		eval "$_setup"
1776		_return=$?
1777		if [ $_return -ne 0 ]; then
1778			return 1
1779		fi
1780	fi
1781	return 0
1782}
1783
1784_run_rc_doit()
1785{
1786	local _m
1787
1788	debug "run_rc_command: doit: $*"
1789	_m=$(umask)
1790	${_umask:+umask ${_umask}}
1791	eval "$@"
1792	_return=$?
1793	umask ${_m}
1794
1795	# If command failed and force isn't set, request exit.
1796	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1797		return 1
1798	fi
1799
1800	return 0
1801}
1802
1803_run_rc_notrunning()
1804{
1805	local _pidmsg
1806
1807	if [ -n "$pidfile" ]; then
1808		_pidmsg=" (check $pidfile)."
1809	else
1810		_pidmsg=
1811	fi
1812	echo 1>&2 "${name} not running?${_pidmsg}"
1813}
1814
1815_run_rc_killcmd()
1816{
1817	local _cmd
1818
1819	_cmd="kill -$1 $rc_pid"
1820	if [ -n "$_user" ]; then
1821		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1822	fi
1823	echo "$_cmd"
1824}
1825
1826#
1827# run_rc_script file arg
1828#	Start the script `file' with `arg', and correctly handle the
1829#	return value from the script.
1830#	If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1831#	an old-style startup file.
1832#	If `file' appears to be a backup or scratch file, ignore it.
1833#	Otherwise if it is executable run as a child process.
1834#
1835run_rc_script()
1836{
1837	_file=$1
1838	_arg=$2
1839	if [ -z "$_file" -o -z "$_arg" ]; then
1840		err 3 'USAGE: run_rc_script file arg'
1841	fi
1842
1843	unset	name command command_args command_interpreter \
1844		extra_commands pidfile procname \
1845		rcvar rcvars rcvars_obsolete required_dirs required_files \
1846		required_vars
1847	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1848
1849	rc_trace 0 "$_file $_arg"
1850	# don't use it if we don't trust it
1851	is_verified $_file || return
1852
1853	rc_service="$_file"
1854	case "$_file" in
1855	/etc/rc.d/*.sh)			# no longer allowed in the base
1856		warn "Ignoring old-style startup script $_file"
1857		;;
1858	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
1859		warn "Ignoring scratch file $_file"
1860		;;
1861	*)				# run in subshell
1862		if [ -x $_file ]; then
1863			DebugOn $_file $_file:$_arg rc:${_file##*/} rc:${_file##*/}:$_arg ${_file##*/} ${_file##*/}:$_arg
1864
1865			if [ -n "$rc_boottrace" ]; then
1866				boottrace_fn "$_file" "$_arg"
1867			else
1868				( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1869				  trap "echo Script $_file interrupted >&2 ; exit 1" 2
1870				  trap "echo Script $_file running >&2" 29
1871				  set $_arg; . $_file )
1872			fi
1873			DebugOff rc=$? $_file $_file:$_arg rc:${_file##*/} rc:${_file##*/}:$_arg ${_file##*/} ${_file##*/}:$_arg
1874		fi
1875		;;
1876	esac
1877}
1878
1879#
1880# run_rc_scripts [options] file [...]
1881#
1882# Call `run_rc_script' for each "file" unless already listed in
1883# $_rc_elem_done.
1884#
1885# Options:
1886#
1887#	--arg "arg"
1888#		Pass "arg" to `run_rc_script' default is $_boot.
1889#
1890#	--break "marker"
1891#		If any "file" matches "marker" stop processing.
1892#
1893_rc_elem_done=
1894run_rc_scripts()
1895{
1896	local _arg=${_boot}
1897	local _rc_elem
1898	local _rc_breaks=
1899
1900	while :; do
1901		case "$1" in
1902		--arg)
1903                        _arg="$2"
1904                        shift 2
1905                        ;;
1906		--break)
1907                        _rc_breaks="$_rc_breaks $2"
1908                        shift 2
1909                        ;;
1910		*)
1911                        break
1912                        ;;
1913		esac
1914	done
1915	for _rc_elem in "$@"; do
1916		: _rc_elem=$_rc_elem
1917		case " $_rc_elem_done " in
1918		*" $_rc_elem "*)
1919                        continue
1920                        ;;
1921		esac
1922		run_rc_script ${_rc_elem} ${_arg}
1923		_rc_elem_done="$_rc_elem_done $_rc_elem"
1924		case " $_rc_breaks " in
1925		*" ${_rc_elem##*/} "*)
1926                        break
1927                        ;;
1928		esac
1929	done
1930}
1931
1932boottrace_fn()
1933{
1934	local _file _arg
1935	_file=$1
1936	_arg=$2
1937
1938	_boot="${_boot}" rc_fast="${rc_fast}" autoboot="${autoboot}" \
1939	    $boottrace_cmd "$_file" "$_arg"
1940}
1941
1942#
1943# load_rc_config [service]
1944#	Source in the configuration file(s) for a given service.
1945#	If no service is specified, only the global configuration
1946#	file(s) will be loaded.
1947#
1948load_rc_config()
1949{
1950	local _name _rcvar_val _var _defval _v _msg _new _d _dot
1951	_name=$1
1952	_dot=${load_rc_config_reader:-dot}
1953
1954	case "$_dot" in
1955	dot|[sv]dot)
1956		;;
1957	*)	warn "Ignoring invalid load_rc_config_reader"
1958		_dot=dot
1959		;;
1960	esac
1961	case "$1" in
1962	-s|--safe)
1963                _dot=sdot
1964                _name=$2
1965                shift
1966                ;;
1967	-v|--verify)
1968                _dot=vdot
1969                _name=$2
1970                shift
1971                ;;
1972	esac
1973
1974	DebugOn rc:$_name $_name
1975
1976	if ${_rc_conf_loaded:-false}; then
1977		:
1978	else
1979		if [ -r /etc/defaults/rc.conf ]; then
1980			debug "Sourcing /etc/defaults/rc.conf"
1981			$_dot /etc/defaults/rc.conf
1982			source_rc_confs
1983		elif [ -r /etc/rc.conf ]; then
1984			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1985			$_dot /etc/rc.conf
1986		fi
1987		_rc_conf_loaded=true
1988	fi
1989
1990	# If a service name was specified, attempt to load
1991	# service-specific configuration
1992	if [ -n "$_name" ] ; then
1993		_loaded_services="${_loaded_services} ${_name}"
1994		for _d in /etc ${local_startup}; do
1995			_d=${_d%/rc.d}
1996			if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1997				debug "Sourcing ${_d}/rc.conf.d/$_name"
1998				$_dot ${_d}/rc.conf.d/"$_name"
1999			elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
2000				local _rc
2001				for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
2002					if [ -f "$_rc" ] ; then
2003						debug "Sourcing $_rc"
2004						$_dot "$_rc"
2005					fi
2006				done
2007			fi
2008		done
2009	fi
2010
2011	# Set defaults if defined.
2012	for _var in $rcvar $rcvars; do
2013		eval _defval=\$${_var}_defval
2014		if [ -n "$_defval" ]; then
2015			eval : \${$_var:=\$${_var}_defval}
2016		fi
2017	done
2018
2019	# check obsolete rc.conf variables
2020	for _var in $rcvars_obsolete; do
2021		eval _v=\$$_var
2022		eval _msg=\$${_var}_obsolete_msg
2023		eval _new=\$${_var}_newvar
2024		case $_v in
2025		"")
2026			;;
2027		*)
2028			if [ -z "$_new" ]; then
2029				_msg="Ignored."
2030			else
2031				eval $_new=\"\$$_var\"
2032				if [ -z "$_msg" ]; then
2033					_msg="Use \$$_new instead."
2034				fi
2035			fi
2036			warn "\$$_var is obsolete.  $_msg"
2037			;;
2038		esac
2039	done
2040}
2041
2042#
2043# load_rc_config_var name var
2044#	Read the rc.conf(5) var for name and set in the
2045#	current shell, using load_rc_config in a subshell to prevent
2046#	unwanted side effects from other variable assignments.
2047#
2048load_rc_config_var()
2049{
2050	if [ $# -ne 2 ]; then
2051		err 3 'USAGE: load_rc_config_var name var'
2052	fi
2053	eval $(eval '(
2054		load_rc_config '$1' >/dev/null;
2055		if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
2056			echo '$2'=\'\''${'$2'}\'\'';
2057		fi
2058	)' )
2059}
2060
2061#
2062# rc_usage commands
2063#	Print a usage string for $0, with `commands' being a list of
2064#	valid commands.
2065#
2066rc_usage()
2067{
2068	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
2069
2070	_sep=
2071	for _elem; do
2072		echo -n 1>&2 "$_sep$_elem"
2073		_sep="|"
2074	done
2075	echo 1>&2 ")"
2076	exit 1
2077}
2078
2079#
2080# err exitval message
2081#	Display message to stderr and log to the syslog, and exit with exitval.
2082#
2083err()
2084{
2085	exitval=$1
2086	shift
2087
2088	if [ -x /usr/bin/logger ]; then
2089		logger "$0: ERROR: $*"
2090	fi
2091	echo 1>&2 "$0: ERROR: $*"
2092	exit $exitval
2093}
2094
2095#
2096# warn message
2097#	Display message to stderr and log to the syslog.
2098#
2099warn()
2100{
2101	if [ -x /usr/bin/logger ]; then
2102		logger "$0: WARNING: $*"
2103	fi
2104	echo 1>&2 "$0: WARNING: $*"
2105}
2106
2107#
2108# info message
2109#	Display informational message to stdout and log to syslog.
2110#
2111info()
2112{
2113	case ${rc_info} in
2114	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
2115		if [ -x /usr/bin/logger ]; then
2116			logger "$0: INFO: $*"
2117		fi
2118		echo "$0: INFO: $*"
2119		;;
2120	esac
2121}
2122
2123#
2124# debug message
2125#	If debugging is enabled in rc.conf output message to stderr.
2126#	BEWARE that you don't call any subroutine that itself calls this
2127#	function.
2128#
2129debug()
2130{
2131	case ${rc_debug} in
2132	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
2133		if [ -x /usr/bin/logger ]; then
2134			logger "$0: DEBUG: $*"
2135		fi
2136		echo 1>&2 "$0: DEBUG: $*"
2137		;;
2138	esac
2139}
2140
2141#
2142# backup_file action file cur backup
2143#	Make a backup copy of `file' into `cur', and save the previous
2144#	version of `cur' as `backup'.
2145#
2146#	The `action' keyword can be one of the following:
2147#
2148#	add		`file' is now being backed up (and is possibly
2149#			being reentered into the backups system).  `cur'
2150#			is created.
2151#
2152#	update		`file' has changed and needs to be backed up.
2153#			If `cur' exists, it is copied to `back'
2154#			and then `file' is copied to `cur'.
2155#
2156#	remove		`file' is no longer being tracked by the backups
2157#			system.  `cur' is moved `back'.
2158#
2159#
2160backup_file()
2161{
2162	_action=$1
2163	_file=$2
2164	_cur=$3
2165	_back=$4
2166
2167	case $_action in
2168	add|update)
2169		if [ -f $_cur ]; then
2170			cp -p $_cur $_back
2171		fi
2172		cp -p $_file $_cur
2173		chown root:wheel $_cur
2174		;;
2175	remove)
2176		mv -f $_cur $_back
2177		;;
2178	esac
2179}
2180
2181# make_symlink src link
2182#	Make a symbolic link 'link' to src from basedir. If the
2183#	directory in which link is to be created does not exist
2184#	a warning will be displayed and an error will be returned.
2185#	Returns 0 on success, 1 otherwise.
2186#
2187make_symlink()
2188{
2189	local src link linkdir _me
2190	src="$1"
2191	link="$2"
2192	linkdir="`dirname $link`"
2193	_me="make_symlink()"
2194
2195	if [ -z "$src" -o -z "$link" ]; then
2196		warn "$_me: requires two arguments."
2197		return 1
2198	fi
2199	if [ ! -d "$linkdir" ]; then
2200		warn "$_me: the directory $linkdir does not exist."
2201		return 1
2202	fi
2203	if ! ln -sf $src $link; then
2204		warn "$_me: unable to make a symbolic link from $link to $src"
2205		return 1
2206	fi
2207	return 0
2208}
2209
2210# devfs_rulesets_from_file file
2211#	Reads a set of devfs commands from file, and creates
2212#	the specified rulesets with their rules. Returns non-zero
2213#	if there was an error.
2214#
2215devfs_rulesets_from_file()
2216{
2217	local file _err _me _opts
2218	file="$1"
2219	_me="devfs_rulesets_from_file"
2220	_err=0
2221
2222	if [ -z "$file" ]; then
2223		warn "$_me: you must specify a file"
2224		return 1
2225	fi
2226	if [ ! -e "$file" ]; then
2227		debug "$_me: no such file ($file)"
2228		return 0
2229	fi
2230
2231	# Disable globbing so that the rule patterns are not expanded
2232	# by accident with matching filesystem entries.
2233	_opts=$-; set -f
2234
2235	debug "reading rulesets from file ($file)"
2236	{ while read line
2237	do
2238		case $line in
2239		\#*)
2240			continue
2241			;;
2242		\[*\]*)
2243			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
2244			if [ -z "$rulenum" ]; then
2245				warn "$_me: cannot extract rule number ($line)"
2246				_err=1
2247				break
2248			fi
2249			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
2250			if [ -z "$rulename" ]; then
2251				warn "$_me: cannot extract rule name ($line)"
2252				_err=1
2253				break;
2254			fi
2255			eval $rulename=\$rulenum
2256			debug "found ruleset: $rulename=$rulenum"
2257			if ! /sbin/devfs rule -s $rulenum delset; then
2258				_err=1
2259				break
2260			fi
2261			;;
2262		*)
2263			rulecmd="${line%%"\#*"}"
2264			# evaluate the command incase it includes
2265			# other rules
2266			if [ -n "$rulecmd" ]; then
2267				debug "adding rule ($rulecmd)"
2268				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
2269				then
2270					_err=1
2271					break
2272				fi
2273			fi
2274			;;
2275		esac
2276		if [ $_err -ne 0 ]; then
2277			debug "error in $_me"
2278			break
2279		fi
2280	done } < $file
2281	case $_opts in *f*) ;; *) set +f ;; esac
2282	return $_err
2283}
2284
2285# devfs_init_rulesets
2286#	Initializes rulesets from configuration files. Returns
2287#	non-zero if there was an error.
2288#
2289devfs_init_rulesets()
2290{
2291	local file _me
2292	_me="devfs_init_rulesets"
2293
2294	# Go through this only once
2295	if [ -n "$devfs_rulesets_init" ]; then
2296		debug "$_me: devfs rulesets already initialized"
2297		return
2298	fi
2299	for file in $devfs_rulesets; do
2300		if ! devfs_rulesets_from_file $file; then
2301			warn "$_me: could not read rules from $file"
2302			return 1
2303		fi
2304	done
2305	devfs_rulesets_init=1
2306	debug "$_me: devfs rulesets initialized"
2307	return 0
2308}
2309
2310# devfs_set_ruleset ruleset [dir]
2311#	Sets the default ruleset of dir to ruleset. The ruleset argument
2312#	must be a ruleset name as specified in devfs.rules(5) file.
2313#	Returns non-zero if it could not set it successfully.
2314#
2315devfs_set_ruleset()
2316{
2317	local devdir rs _me
2318	[ -n "$1" ] && eval rs=\$$1 || rs=
2319	[ -n "$2" ] && devdir="-m "$2"" || devdir=
2320	_me="devfs_set_ruleset"
2321
2322	if [ -z "$rs" ]; then
2323		warn "$_me: you must specify a ruleset number"
2324		return 1
2325	fi
2326	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
2327	if ! /sbin/devfs $devdir ruleset $rs; then
2328		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
2329		return 1
2330	fi
2331	return 0
2332}
2333
2334# devfs_apply_ruleset ruleset [dir]
2335#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
2336#	The ruleset argument must be a ruleset name as specified
2337#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
2338#	if it could not apply the ruleset.
2339#
2340devfs_apply_ruleset()
2341{
2342	local devdir rs _me
2343	[ -n "$1" ] && eval rs=\$$1 || rs=
2344	[ -n "$2" ] && devdir="-m "$2"" || devdir=
2345	_me="devfs_apply_ruleset"
2346
2347	if [ -z "$rs" ]; then
2348		warn "$_me: you must specify a ruleset"
2349		return 1
2350	fi
2351	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
2352	if ! /sbin/devfs $devdir rule -s $rs applyset; then
2353		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
2354		return 1
2355	fi
2356	return 0
2357}
2358
2359# devfs_domount dir [ruleset]
2360#	Mount devfs on dir. If ruleset is specified it is set
2361#	on the mount-point. It must also be a ruleset name as specified
2362#	in a devfs.rules(5) file. Returns 0 on success.
2363#
2364devfs_domount()
2365{
2366	local devdir rs _me
2367	devdir="$1"
2368	[ -n "$2" ] && rs=$2 || rs=
2369	_me="devfs_domount()"
2370
2371	if [ -z "$devdir" ]; then
2372		warn "$_me: you must specify a mount-point"
2373		return 1
2374	fi
2375	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
2376	if ! mount -t devfs dev "$devdir"; then
2377		warn "$_me: Unable to mount devfs on $devdir"
2378		return 1
2379	fi
2380	if [ -n "$rs" ]; then
2381		devfs_init_rulesets
2382		devfs_set_ruleset $rs $devdir
2383		devfs -m $devdir rule applyset
2384	fi
2385	return 0
2386}
2387
2388# Provide a function for normalizing the mounting of memory
2389# filesystems.  This should allow the rest of the code here to remain
2390# as close as possible between 5-current and 4-stable.
2391#   $1 = size
2392#   $2 = mount point
2393#   $3 = (optional) extra mdmfs flags
2394mount_md()
2395{
2396	if [ -n "$3" ]; then
2397		flags="$3"
2398	fi
2399	/sbin/mdmfs $flags -s $1 ${mfs_type} $2
2400}
2401
2402# Code common to scripts that need to load a kernel module
2403# if it isn't in the kernel yet. Syntax:
2404#   load_kld [-e regex] [-m module] file
2405# where -e or -m chooses the way to check if the module
2406# is already loaded:
2407#   regex is egrep'd in the output from `kldstat -v',
2408#   module is passed to `kldstat -m'.
2409# The default way is as though `-m file' were specified.
2410load_kld()
2411{
2412	local _loaded _mod _opt _re
2413
2414	while getopts "e:m:" _opt; do
2415		case "$_opt" in
2416		e) _re="$OPTARG" ;;
2417		m) _mod="$OPTARG" ;;
2418		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
2419		esac
2420	done
2421	shift $(($OPTIND - 1))
2422	if [ $# -ne 1 ]; then
2423		err 3 'USAGE: load_kld [-e regex] [-m module] file'
2424	fi
2425	_mod=${_mod:-$1}
2426	_loaded=false
2427	if [ -n "$_re" ]; then
2428		if kldstat -v | egrep -q -e "$_re"; then
2429			_loaded=true
2430		fi
2431	else
2432		if kldstat -q -m "$_mod"; then
2433			_loaded=true
2434		fi
2435	fi
2436	if ! $_loaded; then
2437		if ! kldload "$1"; then
2438			warn "Unable to load kernel module $1"
2439			return 1
2440		else
2441			info "$1 kernel module loaded."
2442			if [ -f "/etc/sysctl.kld.d/$1.conf" ]; then
2443				sysctl -f "/etc/sysctl.kld.d/$1.conf"
2444			fi
2445		fi
2446	else
2447		debug "load_kld: $1 kernel module already loaded."
2448	fi
2449	return 0
2450}
2451
2452# ltr str src dst [var]
2453#	Change every $src in $str to $dst.
2454#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
2455#	awk(1). If var is non-NULL, set it to the result.
2456ltr()
2457{
2458	local _str _src _dst _out _com _var
2459	_str="$1"
2460	_src="$2"
2461	_dst="$3"
2462	_var="$4"
2463	_out=""
2464
2465	local IFS="${_src}"
2466	for _com in ${_str}; do
2467		if [ -z "${_out}" ]; then
2468			_out="${_com}"
2469		else
2470			_out="${_out}${_dst}${_com}"
2471		fi
2472	done
2473	if [ -n "${_var}" ]; then
2474		setvar "${_var}" "${_out}"
2475	else
2476		echo "${_out}"
2477	fi
2478}
2479
2480# Creates a list of providers for GELI encryption.
2481geli_make_list()
2482{
2483	local devices devices2
2484	local provider mountpoint type options rest
2485
2486	# Create list of GELI providers from fstab.
2487	while read provider mountpoint type options rest ; do
2488		case ":${options}" in
2489		:*noauto*)
2490			noauto=yes
2491			;;
2492		*)
2493			noauto=no
2494			;;
2495		esac
2496
2497		case ":${provider}" in
2498		:#*)
2499			continue
2500			;;
2501		*.eli)
2502			# Skip swap devices.
2503			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
2504				continue
2505			fi
2506			devices="${devices} ${provider}"
2507			;;
2508		esac
2509	done < /etc/fstab
2510
2511	# Append providers from geli_devices.
2512	devices="${devices} ${geli_devices}"
2513
2514	for provider in ${devices}; do
2515		provider=${provider%.eli}
2516		provider=${provider#/dev/}
2517		devices2="${devices2} ${provider}"
2518	done
2519
2520	echo ${devices2}
2521}
2522
2523# Originally, root mount hold had to be released before mounting
2524# the root filesystem.  This delayed the boot, so it was changed
2525# to only wait if the root device isn't readily available.  This
2526# can result in rc scripts executing before all the devices - such
2527# as graid(8), or USB disks - can be accessed.  This function can
2528# be used to explicitly wait for root mount holds to be released.
2529root_hold_wait()
2530{
2531	local wait waited holders
2532
2533	waited=0
2534	while true; do
2535		holders="$(sysctl -n vfs.root_mount_hold)"
2536		if [ -z "${holders}" ]; then
2537			break;
2538		fi
2539		if [ ${waited} -eq 0 ]; then
2540			echo -n "Waiting ${root_hold_delay}s" \
2541			"for the root mount holders: ${holders}"
2542		else
2543			echo -n .
2544		fi
2545		if [ ${waited} -ge ${root_hold_delay} ]; then
2546			echo
2547			break
2548		fi
2549		sleep 1
2550		waited=$(($waited + 1))
2551	done
2552}
2553
2554# Find scripts in local_startup directories that use the old syntax
2555#
2556find_local_scripts_old() {
2557	zlist=''
2558	slist=''
2559	for dir in ${local_startup}; do
2560		if [ -d "${dir}" ]; then
2561			for file in ${dir}/[0-9]*.sh; do
2562				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2563				    continue
2564				zlist="$zlist $file"
2565			done
2566			for file in ${dir}/[!0-9]*.sh; do
2567				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2568				    continue
2569				slist="$slist $file"
2570			done
2571		fi
2572	done
2573}
2574
2575find_local_scripts_new() {
2576	local_rc=''
2577	for dir in ${local_startup}; do
2578		if [ -d "${dir}" ]; then
2579			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
2580				case "$file" in
2581				*.sample|*.pkgsave) ;;
2582				*)	if [ -x "$file" ]; then
2583						local_rc="${local_rc} ${file}"
2584					fi
2585					;;
2586				esac
2587			done
2588		fi
2589	done
2590}
2591
2592find_system_scripts() {
2593	system_rc=''
2594	for file in /etc/rc.d/*; do
2595		case "${file##*/}" in
2596		*.pkgsave) ;;
2597		*)	if [ -x "$file" ]; then
2598				system_rc="${system_rc} ${file}"
2599			fi
2600			;;
2601		esac
2602	done
2603}
2604
2605# check_required_{before|after} command
2606#	Check for things required by the command before and after its precmd,
2607#	respectively.  The two separate functions are needed because some
2608#	conditions should prevent precmd from being run while other things
2609#	depend on precmd having already been run.
2610#
2611check_required_before()
2612{
2613	local _f
2614
2615	case "$1" in
2616	start)
2617		for _f in $required_vars; do
2618			if ! checkyesno $_f; then
2619				warn "\$${_f} is not enabled."
2620				if [ -z "$rc_force" ]; then
2621					return 1
2622				fi
2623			fi
2624		done
2625
2626		for _f in $required_dirs; do
2627			if [ ! -d "${_f}/." ]; then
2628				warn "${_f} is not a directory."
2629				if [ -z "$rc_force" ]; then
2630					return 1
2631				fi
2632			fi
2633		done
2634
2635		for _f in $required_files; do
2636			if [ ! -r "${_f}" ]; then
2637				warn "${_f} is not readable."
2638				if [ -z "$rc_force" ]; then
2639					return 1
2640				fi
2641			fi
2642		done
2643		;;
2644	esac
2645
2646	return 0
2647}
2648
2649check_required_after()
2650{
2651	local _f _args
2652
2653	case "$1" in
2654	start)
2655		for _f in $required_modules; do
2656			case "${_f}" in
2657				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
2658				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
2659				*)	_args="${_f}" ;;
2660			esac
2661			if ! load_kld ${_args}; then
2662				if [ -z "$rc_force" ]; then
2663					return 1
2664				fi
2665			fi
2666		done
2667		;;
2668	esac
2669
2670	return 0
2671}
2672
2673# check_jail mib
2674#	Return true if security.jail.$mib exists and is set to 1.
2675
2676check_jail()
2677{
2678	local _mib _v
2679
2680	_mib=$1
2681	if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2682		case $_v in
2683		1)	return 0;;
2684		esac
2685	fi
2686	return 1
2687}
2688
2689# check_kern_features mib
2690#	Return existence of kern.features.* sysctl MIB as true or
2691#	false.  The result will be cached in $_rc_cache_kern_features_
2692#	namespace.  "0" means the kern.features.X exists.
2693
2694check_kern_features()
2695{
2696	local _v
2697
2698	[ -n "$1" ] || return 1;
2699	eval _v=\$_rc_cache_kern_features_$1
2700	[ -n "$_v" ] && return "$_v";
2701
2702	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2703		eval _rc_cache_kern_features_$1=0
2704		return 0
2705	else
2706		eval _rc_cache_kern_features_$1=1
2707		return 1
2708	fi
2709}
2710
2711# check_namevarlist var
2712#	Return "0" if ${name}_var is reserved in rc.subr.
2713
2714_rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend setup"
2715check_namevarlist()
2716{
2717	local _v
2718
2719	for _v in $_rc_namevarlist; do
2720	case $1 in
2721	$_v)	return 0 ;;
2722	esac
2723	done
2724
2725	return 1
2726}
2727
2728# _echoonce var msg mode
2729#	mode=0: Echo $msg if ${$var} is empty.
2730#	        After doing echo, a string is set to ${$var}.
2731#
2732#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
2733#
2734_echoonce()
2735{
2736	local _var _msg _mode
2737	eval _var=\$$1
2738	_msg=$2
2739	_mode=$3
2740
2741	case $_mode in
2742	1)	[ -n "$_var" ] && echo "$_msg" ;;
2743	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2744	esac
2745}
2746
2747# _find_rcvar var
2748#	Find the rc.conf file (other than /etc/defaults/rc.conf) that sets $var.
2749_find_rcvar()
2750{
2751	local _var _dir _files
2752
2753	[ -n "$1" ] || return 1
2754	_var="$1"; shift
2755
2756	_files="/etc/rc.conf"
2757	for _dir in /etc ${local_startup}; do
2758		for _name in $_loaded_services; do
2759			_files="${_dir%/rc.d}/rc.conf.d/${_name} ${_files}"
2760		done
2761	done
2762
2763	/usr/bin/grep 2>/dev/null -rl "^${_var}=" $_files | /usr/bin/head -1
2764}
2765
2766# write_rcvar var value
2767#	Add or replace the rc var $var with the value $value.
2768#	Look for a current setting of $var in /etc/rc.conf or /etc/rc.conf.d/$name,
2769#	and if found, modify it there; otherwise, append to /etc/rc.conf.
2770write_rcvar()
2771{
2772	local _var _value _file _dir
2773
2774	[ -n "$1" ] || return 1
2775	_var="$1"; shift
2776	[ -n "$1" ] || return 1
2777	_value="$1"; shift
2778
2779	_file="$(_find_rcvar "$_var")"
2780	if [ -n "$_file" ]; then
2781		local _=$'\01'
2782		/usr/bin/sed -i '' "s${_}^${_var}=.*${_}${_var}=\"$_value\"${_}" "$_file"
2783		echo $_file
2784		return
2785	fi
2786
2787	for _dir in /etc ${local_startup}; do
2788		_file="${_dir%/rc.d}/rc.conf.d/${name}"
2789		if [ -f "$_file" ]; then
2790			echo "${_var}=\"${_value}\"" >>"$_file"
2791			echo "$_file"
2792			return
2793		fi
2794	done
2795
2796	echo "${_var}=\"${_value}\"" >>/etc/rc.conf
2797	echo "/etc/rc.conf"
2798}
2799
2800# delete_rcvar var
2801#	Remove the rc var $var.
2802#	Look for a current setting of $var in /etc/rc.conf or /etc/rc.conf.d/$name,
2803#	and if found, remove it.  If service_delete_empty is enabled, and the
2804#	resulting file is empty, also delete the file.
2805delete_rcvar()
2806{
2807	local _var _files
2808
2809	[ -n "$1" ] || return 1
2810	_var="$1"; shift
2811
2812	_file="$(_find_rcvar "$_var")"
2813	if [ -n "$_file" ]; then
2814		/usr/bin/sed -i '' "/^${_var}=/d" "$_file"
2815		echo "$_var deleted in $_file"
2816
2817		if checkyesno service_delete_empty && [ ! -s "$_file" ]; then
2818			/bin/rm -f "$_file"
2819			echo "Empty file $_file removed"
2820		fi
2821	fi
2822}
2823
2824# If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2825# still override this, but /etc/defaults/rc.conf can't unconditionally set this
2826# since it would undo what we've done here.
2827if kenv -q rc.debug > /dev/null ; then
2828	rc_debug=YES
2829fi
2830
2831boottrace_cmd=`command -v boottrace`
2832if [ -n "$boottrace_cmd" ] && [ "`${SYSCTL_N} -q kern.boottrace.enabled`" = "1" ]; then
2833	rc_boottrace=YES
2834fi
2835
2836SED=${SED:-$(Exists -x /usr/bin/sed /rescue/sed)}
2837
2838# Allow for local additions and overrides.
2839# Use vdot to ensure the file has not been tampered with.
2840vdot /etc/local.rc.subr
2841
2842# Avoid noise - when we do not have /usr mounted,
2843# and we cannot use safe_dot without sed.
2844if ! have basename; then
2845	basename()
2846	{
2847		local b=${1%$2}
2848		echo ${b##*/}
2849	}
2850	tty()
2851	{
2852		return 0
2853	}
2854	# we cannot use safe_dot without sed
2855	[ -z "$SED" ] && _SAFE_EVAL_SH=:
2856fi
2857# safe_eval.sh provides safe_dot - for untrusted files
2858$_SAFE_EVAL_SH vdot /libexec/safe_eval.sh
2859$_DEBUG_SH vdot /libexec/debug.sh
2860
2861# Ensure we can still operate if debug.sh and
2862# safe_eval.sh are not found.
2863if ! have DebugOn; then
2864	DebugOn() { return 0; }
2865	DebugOff() {
2866		local _rc=0
2867		while :
2868		do
2869			case "$1" in
2870			-[eo]) shift;; # ignore it
2871			rc=*) eval "_$1"; shift;;
2872			*) break;;
2873			esac
2874		done
2875		return $_rc
2876	}
2877fi
2878if ! have safe_dot; then
2879	safe_dot() { dot "$@"; }
2880fi
2881