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