xref: /freebsd/libexec/rc/rc.subr (revision da5137ab)
1# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2# $FreeBSD$
3#
4# Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
5# All rights reserved.
6#
7# This code is derived from software contributed to The NetBSD Foundation
8# by Luke Mewburn.
9#
10# Redistribution and use in source and binary forms, with or without
11# modification, are permitted provided that the following conditions
12# are met:
13# 1. Redistributions of source code must retain the above copyright
14#    notice, this list of conditions and the following disclaimer.
15# 2. Redistributions in binary form must reproduce the above copyright
16#    notice, this list of conditions and the following disclaimer in the
17#    documentation and/or other materials provided with the distribution.
18#
19# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29# POSSIBILITY OF SUCH DAMAGE.
30#
31# rc.subr
32#	functions used by various rc scripts
33#
34
35: ${RC_PID:=$$}; export RC_PID
36
37#
38#	Operating System dependent/independent variables
39#
40
41if [ -n "${_rc_subr_loaded}" ]; then
42	return
43fi
44
45_rc_subr_loaded="YES"
46
47SYSCTL="/sbin/sysctl"
48SYSCTL_N="${SYSCTL} -n"
49SYSCTL_W="${SYSCTL}"
50PROTECT="/usr/bin/protect"
51ID="/usr/bin/id"
52IDCMD="if [ -x $ID ]; then $ID -un; fi"
53PS="/bin/ps -ww"
54JID=0
55# rc_service provides the path to the service script that we are executing.
56# This is not being set here in an execution context, necessarily, so it's
57# really just a reasonable guess, and it will get overwritten later if
58# we are executing from some other means than direct execution by service(8)
59# or manual invocation of the service script.  The prime example of this is
60# during system startup, all rc scripts will be invoked via /etc/rc, so
61# run_rc_script will overwrite rc_service with the file being sourced.
62rc_service="$0"
63
64#
65#	functions
66#	---------
67
68# list_vars pattern
69#	List variables matching glob pattern.
70#
71list_vars()
72{
73	# Localize 'set' option below.
74	local -
75	local IFS=$'\n' line varname
76
77	# Disable path expansion in unquoted 'for' parameters below.
78	set -o noglob
79
80	for line in $(set); do
81		varname="${line%%=*}"
82
83		case "$varname" in
84		"$line"|*[!a-zA-Z0-9_]*)
85			continue
86			;;
87		$1)
88			echo $varname
89			;;
90		esac
91	done
92}
93
94# set_rcvar [var] [defval] [desc]
95#
96#	Echo or define a rc.conf(5) variable name.  Global variable
97#	$rcvars is used.
98#
99#	If no argument is specified, echo "${name}_enable".
100#
101#	If only a var is specified, echo "${var}_enable".
102#
103#	If var and defval are specified, the ${var} is defined as
104#	rc.conf(5) variable and the default value is ${defvar}.  An
105#	optional argument $desc can also be specified to add a
106#	description for that.
107#
108set_rcvar()
109{
110	local _var
111
112	case $# in
113	0)	echo ${name}_enable ;;
114	1)	echo ${1}_enable ;;
115	*)
116		debug "set_rcvar: \$$1=$2 is added" \
117		    " as a rc.conf(5) variable."
118		_var=$1
119		rcvars="${rcvars# } $_var"
120		eval ${_var}_defval=\"$2\"
121		shift 2
122		eval ${_var}_desc=\"$*\"
123	;;
124	esac
125}
126
127# set_rcvar_obsolete oldvar [newvar] [msg]
128#	Define obsolete variable.
129#	Global variable $rcvars_obsolete is used.
130#
131set_rcvar_obsolete()
132{
133	local _var
134	_var=$1
135	debug "set_rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
136
137	rcvars_obsolete="${rcvars_obsolete# } $1"
138	eval ${1}_newvar=\"$2\"
139	shift 2
140	eval ${_var}_obsolete_msg=\"$*\"
141}
142
143#
144# force_depend script [rcvar]
145#	Force a service to start. Intended for use by services
146#	to resolve dependency issues.
147#	$1 - filename of script, in /etc/rc.d, to run
148#	$2 - name of the script's rcvar (minus the _enable)
149#
150force_depend()
151{
152	local _depend _dep_rcvar
153
154	_depend="$1"
155	_dep_rcvar="${2:-$1}_enable"
156
157	[ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
158	    checkyesno $_dep_rcvar && return 0
159
160	/etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
161
162	info "${name} depends on ${_depend}, which will be forced to start."
163	if ! /etc/rc.d/${_depend} forcestart; then
164		warn "Unable to force ${_depend}. It may already be running."
165		return 1
166	fi
167}
168
169#
170# checkyesno var
171#	Test $1 variable, and warn if not set to YES or NO.
172#	Return 0 if it's "yes" (et al), nonzero otherwise.
173#
174checkyesno()
175{
176	eval _value=\$${1}
177	debug "checkyesno: $1 is set to $_value."
178	case $_value in
179
180		#	"yes", "true", "on", or "1"
181	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
182		return 0
183		;;
184
185		#	"no", "false", "off", or "0"
186	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
187		return 1
188		;;
189	*)
190		warn "\$${1} is not set properly - see rc.conf(5)."
191		return 1
192		;;
193	esac
194}
195
196#
197# reverse_list list
198#	print the list in reverse order
199#
200reverse_list()
201{
202	_revlist=
203	for _revfile; do
204		_revlist="$_revfile $_revlist"
205	done
206	echo $_revlist
207}
208
209# stop_boot always
210#	If booting directly to multiuser or $always is enabled,
211#	send SIGTERM to the parent (/etc/rc) to abort the boot.
212#	Otherwise just exit.
213#
214stop_boot()
215{
216	local always
217
218	case $1 in
219		#	"yes", "true", "on", or "1"
220        [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
221		always=true
222		;;
223	*)
224		always=false
225		;;
226	esac
227	if [ "$autoboot" = yes -o "$always" = true ]; then
228		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
229		kill -TERM ${RC_PID}
230	fi
231	exit 1
232}
233
234#
235# mount_critical_filesystems type
236#	Go through the list of critical filesystems as provided in
237#	the rc.conf(5) variable $critical_filesystems_${type}, checking
238#	each one to see if it is mounted, and if it is not, mounting it.
239#
240mount_critical_filesystems()
241{
242	eval _fslist=\$critical_filesystems_${1}
243	for _fs in $_fslist; do
244		mount | (
245			_ismounted=false
246			while read what _on on _type type; do
247				if [ $on = $_fs ]; then
248					_ismounted=true
249				fi
250			done
251			if $_ismounted; then
252				:
253			else
254				mount $_fs >/dev/null 2>&1
255			fi
256		)
257	done
258}
259
260#
261# check_pidfile pidfile procname [interpreter]
262#	Parses the first line of pidfile for a PID, and ensures
263#	that the process is running and matches procname.
264#	Prints the matching PID upon success, nothing otherwise.
265#	interpreter is optional; see _find_processes() for details.
266#
267check_pidfile()
268{
269	_pidfile=$1
270	_procname=$2
271	_interpreter=$3
272	if [ -z "$_pidfile" -o -z "$_procname" ]; then
273		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
274	fi
275	if [ ! -f $_pidfile ]; then
276		debug "pid file ($_pidfile): not readable."
277		return
278	fi
279	read _pid _junk < $_pidfile
280	if [ -z "$_pid" ]; then
281		debug "pid file ($_pidfile): no pid in file."
282		return
283	fi
284	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
285}
286
287#
288# check_process procname [interpreter]
289#	Ensures that a process (or processes) named procname is running.
290#	Prints a list of matching PIDs.
291#	interpreter is optional; see _find_processes() for details.
292#
293check_process()
294{
295	_procname=$1
296	_interpreter=$2
297	if [ -z "$_procname" ]; then
298		err 3 'USAGE: check_process procname [interpreter]'
299	fi
300	_find_processes $_procname ${_interpreter:-.} '-ax'
301}
302
303#
304# _find_processes procname interpreter psargs
305#	Search for procname in the output of ps generated by psargs.
306#	Prints the PIDs of any matching processes, space separated.
307#
308#	If interpreter == ".", check the following variations of procname
309#	against the first word of each command:
310#		procname
311#		`basename procname`
312#		`basename procname` + ":"
313#		"(" + `basename procname` + ")"
314#		"[" + `basename procname` + "]"
315#
316#	If interpreter != ".", read the first line of procname, remove the
317#	leading #!, normalise whitespace, append procname, and attempt to
318#	match that against each command, either as is, or with extra words
319#	at the end.  As an alternative, to deal with interpreted daemons
320#	using perl, the basename of the interpreter plus a colon is also
321#	tried as the prefix to procname.
322#
323_find_processes()
324{
325	if [ $# -ne 3 ]; then
326		err 3 'USAGE: _find_processes procname interpreter psargs'
327	fi
328	_procname=$1
329	_interpreter=$2
330	_psargs=$3
331
332	_pref=
333	if [ $_interpreter != "." ]; then	# an interpreted script
334		_script="${_chroot}${_chroot:+/}$_procname"
335		if [ -r "$_script" ]; then
336			read _interp < $_script	# read interpreter name
337			case "$_interp" in
338			\#!*)
339				_interp=${_interp#\#!}	# strip #!
340				set -- $_interp
341				case $1 in
342				*/bin/env)
343					shift	# drop env to get real name
344					;;
345				esac
346				if [ $_interpreter != $1 ]; then
347					warn "\$command_interpreter $_interpreter != $1"
348				fi
349				;;
350			*)
351				warn "no shebang line in $_script"
352				set -- $_interpreter
353				;;
354			esac
355		else
356			warn "cannot read shebang line from $_script"
357			set -- $_interpreter
358		fi
359		_interp="$* $_procname"		# cleanup spaces, add _procname
360		_interpbn=${1##*/}
361		_fp_args='_argv'
362		_fp_match='case "$_argv" in
363		    ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
364	else					# a normal daemon
365		_procnamebn=${_procname##*/}
366		_fp_args='_arg0 _argv'
367		_fp_match='case "$_arg0" in
368		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
369	fi
370
371	_proccheck="\
372		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
373		while read _npid _jid '"$_fp_args"'; do
374			'"$_fp_match"'
375				if [ "$JID" -eq "$_jid" ];
376				then echo -n "$_pref$_npid";
377				_pref=" ";
378				fi
379				;;
380			esac
381		done'
382
383#	debug "in _find_processes: proccheck is ($_proccheck)."
384	eval $_proccheck
385}
386
387# sort_lite [-b] [-n] [-k POS] [-t SEP]
388#	A lite version of sort(1) (supporting a few options) that can be used
389#	before the real sort(1) is available (e.g., in scripts that run prior
390#	to mountcritremote). Requires only shell built-in functionality.
391#
392sort_lite()
393{
394	local funcname=sort_lite
395	local sort_sep="$IFS" sort_ignore_leading_space=
396	local sort_field=0 sort_strict_fields= sort_numeric=
397	local nitems=0 skip_leading=0 trim=
398
399	local OPTIND flag
400	while getopts bnk:t: flag; do
401		case "$flag" in
402		b) sort_ignore_leading_space=1 ;;
403		n) sort_numeric=1 sort_ignore_leading_space=1 ;;
404		k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
405			# NB: Unlike sort(1) only one POS allowed
406		t) sort_sep="$OPTARG"
407		   if [ ${#sort_sep} -gt 1 ]; then
408		   	echo "$funcname: multi-character tab \`$sort_sep'" >&2
409		   	return 1
410		   fi
411		   sort_strict_fields=1
412		   ;;
413		\?) return 1 ;;
414		esac
415	done
416	shift $(( $OPTIND - 1 ))
417
418	# Create transformation pattern to trim leading text if desired
419	case "$sort_field" in
420	""|[!0-9]*|*[!0-9.]*)
421		echo "$funcname: invalid sort field \`$sort_field'" >&2
422		return 1
423		;;
424	*.*)
425		skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
426		while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
427			trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
428		done
429	esac
430
431	# Copy input to series of local numbered variables
432	# NB: IFS of NULL preserves leading whitespace
433	local LINE
434	while IFS= read -r LINE || [ "$LINE" ]; do
435		nitems=$(( $nitems + 1 ))
436		local src_$nitems="$LINE"
437	done
438
439	#
440	# Sort numbered locals using insertion sort
441	#
442	local curitem curitem_orig curitem_mod curitem_haskey
443	local dest dest_orig dest_mod dest_haskey
444	local d gt n
445	local i=1
446	while [ $i -le $nitems ]; do
447		curitem_haskey=1 # Assume sort field (-k POS) exists
448		eval curitem=\"\$src_$i\"
449		curitem_mod="$curitem" # for modified comparison
450		curitem_orig="$curitem" # for original comparison
451
452		# Trim leading whitespace if desired
453		if [ "$sort_ignore_leading_space" ]; then
454			while case "$curitem_orig" in
455				[$IFS]*) : ;; *) false; esac
456			do
457				curitem_orig="${curitem_orig#?}"
458			done
459			curitem_mod="$curitem_orig"
460		fi
461
462		# Shift modified comparison value if sort field (-k POS) is > 1
463		n=$sort_field
464		while [ $n -gt 1 ]; do
465			case "$curitem_mod" in
466			*[$sort_sep]*)
467				# Cut text up-to (and incl.) first separator
468				curitem_mod="${curitem_mod#*[$sort_sep]}"
469
470				# Skip NULLs unless strict field splitting
471				[ "$sort_strict_fields" ] ||
472					[ "${curitem_mod%%[$sort_sep]*}" ] ||
473					[ $n -eq 2 ] ||
474					continue
475				;;
476			*)
477				# Asked for a field that doesn't exist
478				curitem_haskey= break
479			esac
480			n=$(( $n - 1 ))
481		done
482
483		# Trim trailing words if sort field >= 1
484		[ $sort_field -ge 1 -a "$sort_numeric" ] &&
485			curitem_mod="${curitem_mod%%[$sort_sep]*}"
486
487		# Apply optional trim (-k POS.TRIM) to cut leading characters
488		curitem_mod="${curitem_mod#$trim}"
489
490		# Determine the type of modified comparison to use initially
491		# NB: Prefer numerical if requested but fallback to standard
492		case "$curitem_mod" in
493		""|[!0-9]*) # NULL or begins with non-number
494			gt=">"
495			[ "$sort_numeric" ] && curitem_mod=0
496			;;
497		*)
498			if [ "$sort_numeric" ]; then
499				gt="-gt"
500				curitem_mod="${curitem_mod%%[!0-9]*}"
501					# NB: trailing non-digits removed
502					# otherwise numeric comparison fails
503			else
504				gt=">"
505			fi
506		esac
507
508		# If first time through, short-circuit below position-search
509		if [ $i -le 1 ]; then
510			d=0
511		else
512			d=1
513		fi
514
515		#
516		# Find appropriate element position
517		#
518		while [ $d -gt 0 ]
519		do
520			dest_haskey=$curitem_haskey
521			eval dest=\"\$dest_$d\"
522			dest_mod="$dest" # for modified comparison
523			dest_orig="$dest" # for original comparison
524
525			# Trim leading whitespace if desired
526			if [ "$sort_ignore_leading_space" ]; then
527				while case "$dest_orig" in
528					[$IFS]*) : ;; *) false; esac
529				do
530					dest_orig="${dest_orig#?}"
531				done
532				dest_mod="$dest_orig"
533			fi
534
535			# Shift modified value if sort field (-k POS) is > 1
536			n=$sort_field
537			while [ $n -gt 1 ]; do
538				case "$dest_mod" in
539				*[$sort_sep]*)
540					# Cut text up-to (and incl.) 1st sep
541					dest_mod="${dest_mod#*[$sort_sep]}"
542
543					# Skip NULLs unless strict fields
544					[ "$sort_strict_fields" ] ||
545					    [ "${dest_mod%%[$sort_sep]*}" ] ||
546					    [ $n -eq 2 ] ||
547					    continue
548					;;
549				*)
550					# Asked for a field that doesn't exist
551					dest_haskey= break
552				esac
553				n=$(( $n - 1 ))
554			done
555
556			# Trim trailing words if sort field >= 1
557			[ $sort_field -ge 1 -a "$sort_numeric" ] &&
558				dest_mod="${dest_mod%%[$sort_sep]*}"
559
560			# Apply optional trim (-k POS.TRIM), cut leading chars
561			dest_mod="${dest_mod#$trim}"
562
563			# Determine type of modified comparison to use
564			# NB: Prefer numerical if requested, fallback to std
565			case "$dest_mod" in
566			""|[!0-9]*) # NULL or begins with non-number
567				gt=">"
568				[ "$sort_numeric" ] && dest_mod=0
569				;;
570			*)
571				if [ "$sort_numeric" ]; then
572					gt="-gt"
573					dest_mod="${dest_mod%%[!0-9]*}"
574						# NB: kill trailing non-digits
575						# for numeric comparison safety
576				else
577					gt=">"
578				fi
579			esac
580
581			# Break if we've found the proper element position
582			if [ "$curitem_haskey" -a "$dest_haskey" ]; then
583				if [ "$dest_mod" = "$curitem_mod" ]; then
584					[ "$dest_orig" ">" "$curitem_orig" ] &&
585						break
586				elif [ "$dest_mod" $gt "$curitem_mod" ] \
587					2> /dev/null
588				then
589					break
590				fi
591			else
592				[ "$dest_orig" ">" "$curitem_orig" ] && break
593			fi
594
595			# Break if we've hit the end
596			[ $d -ge $i ] && break
597
598			d=$(( $d + 1 ))
599		done
600
601		# Shift remaining positions forward, making room for new item
602		n=$i
603		while [ $n -ge $d ]; do
604			# Shift destination item forward one placement
605			eval dest_$(( $n + 1 ))=\"\$dest_$n\"
606			n=$(( $n - 1 ))
607		done
608
609		# Place the element
610		if [ $i -eq 1 ]; then
611			local dest_1="$curitem"
612		else
613			local dest_$d="$curitem"
614		fi
615
616		i=$(( $i + 1 ))
617	done
618
619	# Print sorted results
620	d=1
621	while [ $d -le $nitems ]; do
622		eval echo \"\$dest_$d\"
623		d=$(( $d + 1 ))
624	done
625}
626
627#
628# wait_for_pids pid [pid ...]
629#	spins until none of the pids exist
630#
631wait_for_pids()
632{
633	local _list _prefix _nlist _j
634
635	_list="$@"
636	if [ -z "$_list" ]; then
637		return
638	fi
639	_prefix=
640	while true; do
641		_nlist="";
642		for _j in $_list; do
643			if kill -0 $_j 2>/dev/null; then
644				_nlist="${_nlist}${_nlist:+ }$_j"
645				[ -n "$_prefix" ] && sleep 1
646			fi
647		done
648		if [ -z "$_nlist" ]; then
649			break
650		fi
651		_list=$_nlist
652		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
653		_prefix=", "
654		pwait $_list 2>/dev/null
655	done
656	if [ -n "$_prefix" ]; then
657		echo "."
658	fi
659}
660
661#
662# get_pidfile_from_conf string file
663#
664#	Takes a string to search for in the specified file.
665#	Ignores lines with traditional comment characters.
666#
667# Example:
668#
669# if get_pidfile_from_conf string file; then
670#	pidfile="$_pidfile_from_conf"
671# else
672#	pidfile='appropriate default'
673# fi
674#
675get_pidfile_from_conf()
676{
677	if [ -z "$1" -o -z "$2" ]; then
678		err 3 "USAGE: get_pidfile_from_conf string file ($name)"
679	fi
680
681	local string file line
682
683	string="$1" ; file="$2"
684
685	if [ ! -s "$file" ]; then
686		err 3 "get_pidfile_from_conf: $file does not exist ($name)"
687	fi
688
689	while read line; do
690		case "$line" in
691		*[#\;]*${string}*)	continue ;;
692		*${string}*)		break ;;
693		esac
694	done < $file
695
696	if [ -n "$line" ]; then
697		line=${line#*/}
698		_pidfile_from_conf="/${line%%[\"\;]*}"
699	else
700		return 1
701	fi
702}
703
704#
705# check_startmsgs
706#	If rc_quiet is set (usually as a result of using faststart at
707#	boot time) check if rc_startmsgs is enabled.
708#
709check_startmsgs()
710{
711	if [ -n "$rc_quiet" ]; then
712		checkyesno rc_startmsgs
713	else
714		return 0
715	fi
716}
717
718#
719# startmsg
720#	Preferred method to use when displaying start messages in lieu of echo.
721#
722startmsg()
723{
724	check_startmsgs && echo "$@"
725}
726
727#
728# run_rc_command argument
729#	Search for argument in the list of supported commands, which is:
730#		"start stop restart rcvar status poll ${extra_commands}"
731#	If there's a match, run ${argument}_cmd or the default method
732#	(see below).
733#
734#	If argument has a given prefix, then change the operation as follows:
735#		Prefix	Operation
736#		------	---------
737#		fast	Skip the pid check, and set rc_fast=yes, rc_quiet=yes
738#		force	Set ${rcvar} to YES, and set rc_force=yes
739#		one	Set ${rcvar} to YES
740#		quiet	Don't output some diagnostics, and set rc_quiet=yes
741#
742#	The following globals are used:
743#
744#	Name		Needed	Purpose
745#	----		------	-------
746#	name		y	Name of script.
747#
748#	command		n	Full path to command.
749#				Not needed if ${rc_arg}_cmd is set for
750#				each keyword.
751#
752#	command_args	n	Optional args/shell directives for command.
753#
754#	command_interpreter n	If not empty, command is interpreted, so
755#				call check_{pidfile,process}() appropriately.
756#
757#	desc		n	Description of script.
758#
759#	extra_commands	n	List of extra commands supported.
760#
761#	pidfile		n	If set, use check_pidfile $pidfile $command,
762#				otherwise use check_process $command.
763#				In either case, only check if $command is set.
764#
765#	procname	n	Process name to check for instead of $command.
766#
767#	rcvar		n	This is checked with checkyesno to determine
768#				if the action should be run.
769#
770#	${name}_program	n	Full path to command.
771#				Meant to be used in /etc/rc.conf to override
772#				${command}.
773#
774#	${name}_chroot	n	Directory to chroot to before running ${command}
775#				Requires /usr to be mounted.
776#
777#	${name}_chdir	n	Directory to cd to before running ${command}
778#				(if not using ${name}_chroot).
779#
780#	${name}_flags	n	Arguments to call ${command} with.
781#				NOTE:	$flags from the parent environment
782#					can be used to override this.
783#
784#	${name}_env	n	Environment variables to run ${command} with.
785#
786#	${name}_env_file n	File to source variables to run ${command} with.
787#
788#	${name}_fib	n	Routing table number to run ${command} with.
789#
790#	${name}_nice	n	Nice level to run ${command} at.
791#
792#	${name}_oomprotect n	Don't kill ${command} when swap space is exhausted.
793#
794#	${name}_user	n	User to run ${command} as, using su(1) if not
795#				using ${name}_chroot.
796#				Requires /usr to be mounted.
797#
798#	${name}_group	n	Group to run chrooted ${command} as.
799#				Requires /usr to be mounted.
800#
801#	${name}_groups	n	Comma separated list of supplementary groups
802#				to run the chrooted ${command} with.
803#				Requires /usr to be mounted.
804#
805#	${name}_prepend	n	Command added before ${command}.
806#
807#	${name}_login_class n	Login class to use, else "daemon".
808#
809#	${name}_limits	n	limits(1) to apply to ${command}.
810#
811#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
812#				Otherwise, use default command (see below)
813#
814#	${rc_arg}_precmd n	If set, run just before performing the
815#				${rc_arg}_cmd method in the default
816#				operation (i.e, after checking for required
817#				bits and process (non)existence).
818#				If this completes with a non-zero exit code,
819#				don't run ${rc_arg}_cmd.
820#
821#	${rc_arg}_postcmd n	If set, run just after performing the
822#				${rc_arg}_cmd method, if that method
823#				returned a zero exit code.
824#
825#	required_dirs	n	If set, check for the existence of the given
826#				directories before running a (re)start command.
827#
828#	required_files	n	If set, check for the readability of the given
829#				files before running a (re)start command.
830#
831#	required_modules n	If set, ensure the given kernel modules are
832#				loaded before running a (re)start command.
833#				The check and possible loads are actually
834#				done after start_precmd so that the modules
835#				aren't loaded in vain, should the precmd
836#				return a non-zero status to indicate a error.
837#				If a word in the list looks like "foo:bar",
838#				"foo" is the KLD file name and "bar" is the
839#				module name.  If a word looks like "foo~bar",
840#				"foo" is the KLD file name and "bar" is a
841#				egrep(1) pattern matching the module name.
842#				Otherwise the module name is assumed to be
843#				the same as the KLD file name, which is most
844#				common.  See load_kld().
845#
846#	required_vars	n	If set, perform checkyesno on each of the
847#				listed variables before running the default
848#				(re)start command.
849#
850#	Default behaviour for a given argument, if no override method is
851#	provided:
852#
853#	Argument	Default behaviour
854#	--------	-----------------
855#	start		if !running && checkyesno ${rcvar}
856#				${command}
857#
858#	stop		if ${pidfile}
859#				rc_pid=$(check_pidfile $pidfile $command)
860#			else
861#				rc_pid=$(check_process $command)
862#			kill $sig_stop $rc_pid
863#			wait_for_pids $rc_pid
864#			($sig_stop defaults to TERM.)
865#
866#	reload		Similar to stop, except use $sig_reload instead,
867#			and doesn't wait_for_pids.
868#			$sig_reload defaults to HUP.
869#			Note that `reload' isn't provided by default,
870#			it should be enabled via $extra_commands.
871#
872#	restart		Run `stop' then `start'.
873#
874#	status		Show if ${command} is running, etc.
875#
876#	poll		Wait for ${command} to exit.
877#
878#	rcvar		Display what rc.conf variable is used (if any).
879#
880#	enabled		Return true if the service is enabled.
881#
882#	describe	Show the service's description
883#
884#	extracommands	Show the service's extra commands
885#
886#	Variables available to methods, and after run_rc_command() has
887#	completed:
888#
889#	Variable	Purpose
890#	--------	-------
891#	rc_arg		Argument to command, after fast/force/one processing
892#			performed
893#
894#	rc_flags	Flags to start the default command with.
895#			Defaults to ${name}_flags, unless overridden
896#			by $flags from the environment.
897#			This variable may be changed by the precmd method.
898#
899#       rc_service      Path to the service being executed, in case the service
900#                       needs to re-invoke itself.
901#
902#	rc_pid		PID of command (if appropriate)
903#
904#	rc_fast		Not empty if "fast" was provided (q.v.)
905#
906#	rc_force	Not empty if "force" was provided (q.v.)
907#
908#	rc_quiet	Not empty if "quiet" was provided
909#
910#
911run_rc_command()
912{
913	_return=0
914	rc_arg=$1
915	if [ -z "$name" ]; then
916		err 3 'run_rc_command: $name is not set.'
917	fi
918
919	# Don't repeat the first argument when passing additional command-
920	# line arguments to the command subroutines.
921	#
922	shift 1
923	rc_extra_args="$*"
924
925	_rc_prefix=
926	case "$rc_arg" in
927	fast*)				# "fast" prefix; don't check pid
928		rc_arg=${rc_arg#fast}
929		rc_fast=yes
930		rc_quiet=yes
931		;;
932	force*)				# "force" prefix; always run
933		rc_force=yes
934		_rc_prefix=force
935		rc_arg=${rc_arg#${_rc_prefix}}
936		if [ -n "${rcvar}" ]; then
937			eval ${rcvar}=YES
938		fi
939		;;
940	one*)				# "one" prefix; set ${rcvar}=yes
941		_rc_prefix=one
942		rc_arg=${rc_arg#${_rc_prefix}}
943		if [ -n "${rcvar}" ]; then
944			eval ${rcvar}=YES
945		fi
946		;;
947	quiet*)				# "quiet" prefix; omit some messages
948		_rc_prefix=quiet
949		rc_arg=${rc_arg#${_rc_prefix}}
950		rc_quiet=yes
951		;;
952	esac
953
954	eval _override_command=\$${name}_program
955	command=${_override_command:-$command}
956
957	_keywords="start stop restart rcvar enable disable delete enabled describe extracommands $extra_commands"
958	rc_pid=
959	_pidcmd=
960	_procname=${procname:-${command}}
961
962					# setup pid check command
963	if [ -n "$_procname" ]; then
964		if [ -n "$pidfile" ]; then
965			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
966		else
967			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
968		fi
969		_keywords="${_keywords} status poll"
970	else
971		if [ ! -z "${status_cmd}" ]
972		then
973			_keywords="${_keywords} status"
974		fi
975	fi
976
977	if [ -z "$rc_arg" ]; then
978		rc_usage $_keywords
979	fi
980
981	if [ "$rc_arg" = "enabled" ] ; then
982		checkyesno ${rcvar}
983		return $?
984	fi
985
986	if [ -n "$flags" ]; then	# allow override from environment
987		rc_flags=$flags
988	else
989		eval rc_flags=\$${name}_flags
990	fi
991	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
992	    _nice=\$${name}_nice	_user=\$${name}_user \
993	    _group=\$${name}_group	_groups=\$${name}_groups \
994	    _fib=\$${name}_fib		_env=\$${name}_env \
995	    _prepend=\$${name}_prepend	_login_class=\${${name}_login_class:-daemon} \
996	    _limits=\$${name}_limits    _oomprotect=\$${name}_oomprotect \
997	    _env_file=\$${name}_env_file
998
999	if [ -n "$_env_file" ] && [ -r "${_env_file}" ]; then	# load env from file
1000		set -a
1001		. $_env_file
1002		set +a
1003	fi
1004
1005	if [ -n "$_user" ]; then	# unset $_user if running as that user
1006		if [ "$_user" = "$(eval $IDCMD)" ]; then
1007			unset _user
1008		fi
1009	fi
1010
1011	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
1012
1013	for _elem in $_keywords; do
1014		if [ "$_elem" != "$rc_arg" ]; then
1015			continue
1016		fi
1017					# if ${rcvar} is set, $1 is not "rcvar", "describe",
1018					# "enable" or "delete", and ${rc_pid} is not set, run:
1019					#	checkyesno ${rcvar}
1020					# and return if that failed
1021					#
1022		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
1023		    -a "$rc_arg" != "delete" -a "$rc_arg" != "enable" \
1024		    -a "$rc_arg" != "describe" ] ||
1025		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
1026			if ! checkyesno ${rcvar}; then
1027				if [ -n "${rc_quiet}" ]; then
1028					return 0
1029				fi
1030				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
1031				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
1032				echo "instead of '${rc_arg}'."
1033				return 0
1034			fi
1035		fi
1036
1037		if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1038			if [ -z "$rc_quiet" ]; then
1039				echo 1>&2 "${name} already running? " \
1040				    "(pid=$rc_pid)."
1041			fi
1042			return 1
1043		fi
1044
1045					# if there's a custom ${XXX_cmd},
1046					# run that instead of the default
1047					#
1048		eval _cmd=\$${rc_arg}_cmd \
1049		     _precmd=\$${rc_arg}_precmd \
1050		     _postcmd=\$${rc_arg}_postcmd
1051
1052		if [ -n "$_cmd" ]; then
1053			if [ -n "$_env" ]; then
1054				eval "export -- $_env"
1055			fi
1056			_run_rc_precmd || return 1
1057			_run_rc_doit "$_cmd $rc_extra_args" || return 1
1058			_run_rc_postcmd
1059			return $_return
1060		fi
1061
1062		case "$rc_arg" in	# default operations...
1063
1064		describe)
1065			if [ -n "$desc" ]; then
1066				echo "$desc"
1067			fi
1068			;;
1069
1070		extracommands)
1071			echo "$extra_commands"
1072			;;
1073
1074		enable)
1075			_out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=YES") &&
1076				echo "$name enabled in ${_out%%:*}"
1077			;;
1078
1079		disable)
1080			_out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=NO") &&
1081				echo "$name disabled in ${_out%%:*}"
1082			;;
1083
1084		delete)
1085			_files=
1086			for _file in $(sysrc -lEs "$name"); do
1087				_out=$(sysrc -Fif $_file "$rcvar") && _files="$_files $_file"
1088			done
1089			/usr/sbin/sysrc -x "$rcvar" && echo "$rcvar deleted in ${_files# }"
1090				# delete file in rc.conf.d if desired and empty.
1091			checkyesno service_delete_empty || _files=
1092			for _file in $_files; do
1093				[ "$_file" = "${_file#*/rc.conf.d/}" ] && continue
1094				[ $(/usr/bin/stat -f%z $_file) -gt 0 ] && continue
1095				/bin/rm "$_file" && echo "Empty file $_file removed"
1096			done
1097			;;
1098
1099		status)
1100			_run_rc_precmd || return 1
1101			if [ -n "$rc_pid" ]; then
1102				echo "${name} is running as pid $rc_pid."
1103			else
1104				echo "${name} is not running."
1105				return 1
1106			fi
1107			_run_rc_postcmd
1108			;;
1109
1110		start)
1111			if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1112				warn "run_rc_command: cannot run $command"
1113				return 1
1114			fi
1115
1116			if ! _run_rc_precmd; then
1117				warn "failed precmd routine for ${name}"
1118				return 1
1119			fi
1120
1121					# setup the full command to run
1122					#
1123			startmsg "Starting ${name}."
1124			if [ -n "$_chroot" ]; then
1125				_cd=
1126				_doit="\
1127${_nice:+nice -n $_nice }\
1128${_fib:+setfib -F $_fib }\
1129${_env:+env $_env }\
1130chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1131$_chroot $command $rc_flags $command_args"
1132			else
1133				_cd="${_chdir:+cd $_chdir && }"
1134				_doit="\
1135${_fib:+setfib -F $_fib }\
1136${_env:+env $_env }\
1137$command $rc_flags $command_args"
1138				if [ -n "$_user" ]; then
1139				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1140				fi
1141				if [ -n "$_nice" ]; then
1142					if [ -z "$_user" ]; then
1143						_doit="sh -c \"$_doit\""
1144					fi
1145					_doit="nice -n $_nice $_doit"
1146				fi
1147				if [ -n "$_prepend" ]; then
1148					_doit="$_prepend $_doit"
1149				fi
1150			fi
1151
1152					# Prepend default limits
1153			_doit="$_cd limits -C $_login_class $_limits $_doit"
1154
1155					# run the full command
1156					#
1157			if ! _run_rc_doit "$_doit"; then
1158				warn "failed to start ${name}"
1159				return 1
1160			fi
1161
1162					# finally, run postcmd
1163					#
1164			_run_rc_postcmd
1165			;;
1166
1167		stop)
1168			if [ -z "$rc_pid" ]; then
1169				[ -n "$rc_fast" ] && return 0
1170				_run_rc_notrunning
1171				return 1
1172			fi
1173
1174			_run_rc_precmd || return 1
1175
1176					# send the signal to stop
1177					#
1178			echo "Stopping ${name}."
1179			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1180			_run_rc_doit "$_doit" || return 1
1181
1182					# wait for the command to exit,
1183					# and run postcmd.
1184			wait_for_pids $rc_pid
1185
1186			_run_rc_postcmd
1187			;;
1188
1189		reload)
1190			if [ -z "$rc_pid" ]; then
1191				_run_rc_notrunning
1192				return 1
1193			fi
1194
1195			_run_rc_precmd || return 1
1196
1197			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1198			_run_rc_doit "$_doit" || return 1
1199
1200			_run_rc_postcmd
1201			;;
1202
1203		restart)
1204					# prevent restart being called more
1205					# than once by any given script
1206					#
1207			if ${_rc_restart_done:-false}; then
1208				return 0
1209			fi
1210			_rc_restart_done=true
1211
1212			_run_rc_precmd || return 1
1213
1214			# run those in a subshell to keep global variables
1215			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1216			( run_rc_command ${_rc_prefix}start $rc_extra_args )
1217			_return=$?
1218			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1219
1220			_run_rc_postcmd
1221			;;
1222
1223		poll)
1224			_run_rc_precmd || return 1
1225			if [ -n "$rc_pid" ]; then
1226				wait_for_pids $rc_pid
1227			fi
1228			_run_rc_postcmd
1229			;;
1230
1231		rcvar)
1232			echo -n "# $name"
1233			if [ -n "$desc" ]; then
1234				echo " : $desc"
1235			else
1236				echo ""
1237			fi
1238			echo "#"
1239			# Get unique vars in $rcvar $rcvars
1240			for _v in $rcvar $rcvars; do
1241				case $v in
1242				$_v\ *|\ *$_v|*\ $_v\ *) ;;
1243				*)	v="${v# } $_v" ;;
1244				esac
1245			done
1246
1247			# Display variables.
1248			for _v in $v; do
1249				if [ -z "$_v" ]; then
1250					continue
1251				fi
1252
1253				eval _desc=\$${_v}_desc
1254				eval _defval=\$${_v}_defval
1255				_h="-"
1256
1257				eval echo \"$_v=\\\"\$$_v\\\"\"
1258				# decode multiple lines of _desc
1259				while [ -n "$_desc" ]; do
1260					case $_desc in
1261					*^^*)
1262						echo "# $_h ${_desc%%^^*}"
1263						_desc=${_desc#*^^}
1264						_h=" "
1265						;;
1266					*)
1267						echo "# $_h ${_desc}"
1268						break
1269						;;
1270					esac
1271				done
1272				echo "#   (default: \"$_defval\")"
1273			done
1274			echo ""
1275			;;
1276
1277		*)
1278			rc_usage $_keywords
1279			;;
1280
1281		esac
1282
1283		# Apply protect(1) to the PID if ${name}_oomprotect is set.
1284		case "$rc_arg" in
1285		start)
1286			# We cannot use protect(1) inside jails.
1287			if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1288			    [ "$(sysctl -n security.jail.jailed)" -eq 0 ]; then
1289				[ -z "${rc_pid}" ] && eval $_pidcmd
1290				case $_oomprotect in
1291				[Aa][Ll][Ll])
1292					${PROTECT} -i -p ${rc_pid}
1293					;;
1294				[Yy][Ee][Ss])
1295					${PROTECT} -p ${rc_pid}
1296					;;
1297				esac
1298			fi
1299		;;
1300		esac
1301
1302		return $_return
1303	done
1304
1305	echo 1>&2 "$0: unknown directive '$rc_arg'."
1306	rc_usage $_keywords
1307	# not reached
1308}
1309
1310#
1311# Helper functions for run_rc_command: common code.
1312# They use such global variables besides the exported rc_* ones:
1313#
1314#	name	       R/W
1315#	------------------
1316#	_precmd		R
1317#	_postcmd	R
1318#	_return		W
1319#
1320_run_rc_precmd()
1321{
1322	check_required_before "$rc_arg" || return 1
1323
1324	if [ -n "$_precmd" ]; then
1325		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1326		eval "$_precmd $rc_extra_args"
1327		_return=$?
1328
1329		# If precmd failed and force isn't set, request exit.
1330		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1331			return 1
1332		fi
1333	fi
1334
1335	check_required_after "$rc_arg" || return 1
1336
1337	return 0
1338}
1339
1340_run_rc_postcmd()
1341{
1342	if [ -n "$_postcmd" ]; then
1343		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1344		eval "$_postcmd $rc_extra_args"
1345		_return=$?
1346	fi
1347	return 0
1348}
1349
1350_run_rc_doit()
1351{
1352	debug "run_rc_command: doit: $*"
1353	eval "$@"
1354	_return=$?
1355
1356	# If command failed and force isn't set, request exit.
1357	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1358		return 1
1359	fi
1360
1361	return 0
1362}
1363
1364_run_rc_notrunning()
1365{
1366	local _pidmsg
1367
1368	if [ -n "$pidfile" ]; then
1369		_pidmsg=" (check $pidfile)."
1370	else
1371		_pidmsg=
1372	fi
1373	echo 1>&2 "${name} not running?${_pidmsg}"
1374}
1375
1376_run_rc_killcmd()
1377{
1378	local _cmd
1379
1380	_cmd="kill -$1 $rc_pid"
1381	if [ -n "$_user" ]; then
1382		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1383	fi
1384	echo "$_cmd"
1385}
1386
1387#
1388# run_rc_script file arg
1389#	Start the script `file' with `arg', and correctly handle the
1390#	return value from the script.
1391#	If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1392#	an old-style startup file.
1393#	If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1394#	into the current environment if $rc_fast_and_loose is set; otherwise
1395#	it is run as a child process.
1396#	If `file' appears to be a backup or scratch file, ignore it.
1397#	Otherwise if it is executable run as a child process.
1398#
1399run_rc_script()
1400{
1401	_file=$1
1402	_arg=$2
1403	if [ -z "$_file" -o -z "$_arg" ]; then
1404		err 3 'USAGE: run_rc_script file arg'
1405	fi
1406
1407	unset	name command command_args command_interpreter \
1408		extra_commands pidfile procname \
1409		rcvar rcvars rcvars_obsolete required_dirs required_files \
1410		required_vars
1411	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1412
1413	rc_service="$_file"
1414	case "$_file" in
1415	/etc/rc.d/*.sh)			# no longer allowed in the base
1416		warn "Ignoring old-style startup script $_file"
1417		;;
1418	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
1419		warn "Ignoring scratch file $_file"
1420		;;
1421	*)				# run in subshell
1422		if [ -x $_file ]; then
1423			if [ -n "$rc_boottrace" ]; then
1424				boottrace_fn "$_file" "$_arg"
1425			elif [ -n "$rc_fast_and_loose" ]; then
1426				set $_arg; . $_file
1427			else
1428				( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1429				  trap "echo Script $_file interrupted >&2 ; exit 1" 2
1430				  trap "echo Script $_file running >&2" 29
1431				  set $_arg; . $_file )
1432			fi
1433		fi
1434		;;
1435	esac
1436}
1437
1438boottrace_fn()
1439{
1440	local _file _arg
1441	_file=$1
1442	_arg=$2
1443
1444	if [ -n "$rc_fast_and_loose" ]; then
1445		boottrace_sysctl "$_file start"
1446		set $_arg; . $_file
1447		boottrace_sysctl "$_file done"
1448	else
1449		$boottrace_cmd "$_file" "$_arg"
1450	fi
1451}
1452
1453boottrace_sysctl()
1454{
1455	${SYSCTL} kern.boottrace.boottrace="$1"
1456}
1457
1458#
1459# load_rc_config [service]
1460#	Source in the configuration file(s) for a given service.
1461#	If no service is specified, only the global configuration
1462#	file(s) will be loaded.
1463#
1464load_rc_config()
1465{
1466	local _name _rcvar_val _var _defval _v _msg _new _d
1467	_name=$1
1468
1469	if ${_rc_conf_loaded:-false}; then
1470		:
1471	else
1472		if [ -r /etc/defaults/rc.conf ]; then
1473			debug "Sourcing /etc/defaults/rc.conf"
1474			. /etc/defaults/rc.conf
1475			source_rc_confs
1476		elif [ -r /etc/rc.conf ]; then
1477			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1478			. /etc/rc.conf
1479		fi
1480		_rc_conf_loaded=true
1481	fi
1482
1483	# If a service name was specified, attempt to load
1484	# service-specific configuration
1485	if [ -n "$_name" ] ; then
1486		for _d in /etc ${local_startup}; do
1487			_d=${_d%/rc.d}
1488			if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1489				debug "Sourcing ${_d}/rc.conf.d/$_name"
1490				. ${_d}/rc.conf.d/"$_name"
1491			elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
1492				local _rc
1493				for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
1494					if [ -f "$_rc" ] ; then
1495						debug "Sourcing $_rc"
1496						. "$_rc"
1497					fi
1498				done
1499			fi
1500		done
1501	fi
1502
1503	# Set defaults if defined.
1504	for _var in $rcvar $rcvars; do
1505		eval _defval=\$${_var}_defval
1506		if [ -n "$_defval" ]; then
1507			eval : \${$_var:=\$${_var}_defval}
1508		fi
1509	done
1510
1511	# check obsolete rc.conf variables
1512	for _var in $rcvars_obsolete; do
1513		eval _v=\$$_var
1514		eval _msg=\$${_var}_obsolete_msg
1515		eval _new=\$${_var}_newvar
1516		case $_v in
1517		"")
1518			;;
1519		*)
1520			if [ -z "$_new" ]; then
1521				_msg="Ignored."
1522			else
1523				eval $_new=\"\$$_var\"
1524				if [ -z "$_msg" ]; then
1525					_msg="Use \$$_new instead."
1526				fi
1527			fi
1528			warn "\$$_var is obsolete.  $_msg"
1529			;;
1530		esac
1531	done
1532}
1533
1534#
1535# load_rc_config_var name var
1536#	Read the rc.conf(5) var for name and set in the
1537#	current shell, using load_rc_config in a subshell to prevent
1538#	unwanted side effects from other variable assignments.
1539#
1540load_rc_config_var()
1541{
1542	if [ $# -ne 2 ]; then
1543		err 3 'USAGE: load_rc_config_var name var'
1544	fi
1545	eval $(eval '(
1546		load_rc_config '$1' >/dev/null;
1547                if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1548			echo '$2'=\'\''${'$2'}\'\'';
1549		fi
1550	)' )
1551}
1552
1553#
1554# rc_usage commands
1555#	Print a usage string for $0, with `commands' being a list of
1556#	valid commands.
1557#
1558rc_usage()
1559{
1560	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1561
1562	_sep=
1563	for _elem; do
1564		echo -n 1>&2 "$_sep$_elem"
1565		_sep="|"
1566	done
1567	echo 1>&2 ")"
1568	exit 1
1569}
1570
1571#
1572# err exitval message
1573#	Display message to stderr and log to the syslog, and exit with exitval.
1574#
1575err()
1576{
1577	exitval=$1
1578	shift
1579
1580	if [ -x /usr/bin/logger ]; then
1581		logger "$0: ERROR: $*"
1582	fi
1583	echo 1>&2 "$0: ERROR: $*"
1584	exit $exitval
1585}
1586
1587#
1588# warn message
1589#	Display message to stderr and log to the syslog.
1590#
1591warn()
1592{
1593	if [ -x /usr/bin/logger ]; then
1594		logger "$0: WARNING: $*"
1595	fi
1596	echo 1>&2 "$0: WARNING: $*"
1597}
1598
1599#
1600# info message
1601#	Display informational message to stdout and log to syslog.
1602#
1603info()
1604{
1605	case ${rc_info} in
1606	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1607		if [ -x /usr/bin/logger ]; then
1608			logger "$0: INFO: $*"
1609		fi
1610		echo "$0: INFO: $*"
1611		;;
1612	esac
1613}
1614
1615#
1616# debug message
1617#	If debugging is enabled in rc.conf output message to stderr.
1618#	BEWARE that you don't call any subroutine that itself calls this
1619#	function.
1620#
1621debug()
1622{
1623	case ${rc_debug} in
1624	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1625		if [ -x /usr/bin/logger ]; then
1626			logger "$0: DEBUG: $*"
1627		fi
1628		echo 1>&2 "$0: DEBUG: $*"
1629		;;
1630	esac
1631}
1632
1633#
1634# backup_file action file cur backup
1635#	Make a backup copy of `file' into `cur', and save the previous
1636#	version of `cur' as `backup'.
1637#
1638#	The `action' keyword can be one of the following:
1639#
1640#	add		`file' is now being backed up (and is possibly
1641#			being reentered into the backups system).  `cur'
1642#			is created.
1643#
1644#	update		`file' has changed and needs to be backed up.
1645#			If `cur' exists, it is copied to `back'
1646#			and then `file' is copied to `cur'.
1647#
1648#	remove		`file' is no longer being tracked by the backups
1649#			system.  `cur' is moved `back'.
1650#
1651#
1652backup_file()
1653{
1654	_action=$1
1655	_file=$2
1656	_cur=$3
1657	_back=$4
1658
1659	case $_action in
1660	add|update)
1661		if [ -f $_cur ]; then
1662			cp -p $_cur $_back
1663		fi
1664		cp -p $_file $_cur
1665		chown root:wheel $_cur
1666		;;
1667	remove)
1668		mv -f $_cur $_back
1669		;;
1670	esac
1671}
1672
1673# make_symlink src link
1674#	Make a symbolic link 'link' to src from basedir. If the
1675#	directory in which link is to be created does not exist
1676#	a warning will be displayed and an error will be returned.
1677#	Returns 0 on success, 1 otherwise.
1678#
1679make_symlink()
1680{
1681	local src link linkdir _me
1682	src="$1"
1683	link="$2"
1684	linkdir="`dirname $link`"
1685	_me="make_symlink()"
1686
1687	if [ -z "$src" -o -z "$link" ]; then
1688		warn "$_me: requires two arguments."
1689		return 1
1690	fi
1691	if [ ! -d "$linkdir" ]; then
1692		warn "$_me: the directory $linkdir does not exist."
1693		return 1
1694	fi
1695	if ! ln -sf $src $link; then
1696		warn "$_me: unable to make a symbolic link from $link to $src"
1697		return 1
1698	fi
1699	return 0
1700}
1701
1702# devfs_rulesets_from_file file
1703#	Reads a set of devfs commands from file, and creates
1704#	the specified rulesets with their rules. Returns non-zero
1705#	if there was an error.
1706#
1707devfs_rulesets_from_file()
1708{
1709	local file _err _me _opts
1710	file="$1"
1711	_me="devfs_rulesets_from_file"
1712	_err=0
1713
1714	if [ -z "$file" ]; then
1715		warn "$_me: you must specify a file"
1716		return 1
1717	fi
1718	if [ ! -e "$file" ]; then
1719		debug "$_me: no such file ($file)"
1720		return 0
1721	fi
1722
1723	# Disable globbing so that the rule patterns are not expanded
1724	# by accident with matching filesystem entries.
1725	_opts=$-; set -f
1726
1727	debug "reading rulesets from file ($file)"
1728	{ while read line
1729	do
1730		case $line in
1731		\#*)
1732			continue
1733			;;
1734		\[*\]*)
1735			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1736			if [ -z "$rulenum" ]; then
1737				warn "$_me: cannot extract rule number ($line)"
1738				_err=1
1739				break
1740			fi
1741			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1742			if [ -z "$rulename" ]; then
1743				warn "$_me: cannot extract rule name ($line)"
1744				_err=1
1745				break;
1746			fi
1747			eval $rulename=\$rulenum
1748			debug "found ruleset: $rulename=$rulenum"
1749			if ! /sbin/devfs rule -s $rulenum delset; then
1750				_err=1
1751				break
1752			fi
1753			;;
1754		*)
1755			rulecmd="${line%%"\#*"}"
1756			# evaluate the command incase it includes
1757			# other rules
1758			if [ -n "$rulecmd" ]; then
1759				debug "adding rule ($rulecmd)"
1760				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1761				then
1762					_err=1
1763					break
1764				fi
1765			fi
1766			;;
1767		esac
1768		if [ $_err -ne 0 ]; then
1769			debug "error in $_me"
1770			break
1771		fi
1772	done } < $file
1773	case $_opts in *f*) ;; *) set +f ;; esac
1774	return $_err
1775}
1776
1777# devfs_init_rulesets
1778#	Initializes rulesets from configuration files. Returns
1779#	non-zero if there was an error.
1780#
1781devfs_init_rulesets()
1782{
1783	local file _me
1784	_me="devfs_init_rulesets"
1785
1786	# Go through this only once
1787	if [ -n "$devfs_rulesets_init" ]; then
1788		debug "$_me: devfs rulesets already initialized"
1789		return
1790	fi
1791	for file in $devfs_rulesets; do
1792		if ! devfs_rulesets_from_file $file; then
1793			warn "$_me: could not read rules from $file"
1794			return 1
1795		fi
1796	done
1797	devfs_rulesets_init=1
1798	debug "$_me: devfs rulesets initialized"
1799	return 0
1800}
1801
1802# devfs_set_ruleset ruleset [dir]
1803#	Sets the default ruleset of dir to ruleset. The ruleset argument
1804#	must be a ruleset name as specified in devfs.rules(5) file.
1805#	Returns non-zero if it could not set it successfully.
1806#
1807devfs_set_ruleset()
1808{
1809	local devdir rs _me
1810	[ -n "$1" ] && eval rs=\$$1 || rs=
1811	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1812	_me="devfs_set_ruleset"
1813
1814	if [ -z "$rs" ]; then
1815		warn "$_me: you must specify a ruleset number"
1816		return 1
1817	fi
1818	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1819	if ! /sbin/devfs $devdir ruleset $rs; then
1820		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1821		return 1
1822	fi
1823	return 0
1824}
1825
1826# devfs_apply_ruleset ruleset [dir]
1827#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1828#	The ruleset argument must be a ruleset name as specified
1829#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1830#	if it could not apply the ruleset.
1831#
1832devfs_apply_ruleset()
1833{
1834	local devdir rs _me
1835	[ -n "$1" ] && eval rs=\$$1 || rs=
1836	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1837	_me="devfs_apply_ruleset"
1838
1839	if [ -z "$rs" ]; then
1840		warn "$_me: you must specify a ruleset"
1841		return 1
1842	fi
1843	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1844	if ! /sbin/devfs $devdir rule -s $rs applyset; then
1845		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1846		return 1
1847	fi
1848	return 0
1849}
1850
1851# devfs_domount dir [ruleset]
1852#	Mount devfs on dir. If ruleset is specified it is set
1853#	on the mount-point. It must also be a ruleset name as specified
1854#	in a devfs.rules(5) file. Returns 0 on success.
1855#
1856devfs_domount()
1857{
1858	local devdir rs _me
1859	devdir="$1"
1860	[ -n "$2" ] && rs=$2 || rs=
1861	_me="devfs_domount()"
1862
1863	if [ -z "$devdir" ]; then
1864		warn "$_me: you must specify a mount-point"
1865		return 1
1866	fi
1867	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1868	if ! mount -t devfs dev "$devdir"; then
1869		warn "$_me: Unable to mount devfs on $devdir"
1870		return 1
1871	fi
1872	if [ -n "$rs" ]; then
1873		devfs_init_rulesets
1874		devfs_set_ruleset $rs $devdir
1875		devfs -m $devdir rule applyset
1876	fi
1877	return 0
1878}
1879
1880# Provide a function for normalizing the mounting of memory
1881# filesystems.  This should allow the rest of the code here to remain
1882# as close as possible between 5-current and 4-stable.
1883#   $1 = size
1884#   $2 = mount point
1885#   $3 = (optional) extra mdmfs flags
1886mount_md()
1887{
1888	if [ -n "$3" ]; then
1889		flags="$3"
1890	fi
1891	/sbin/mdmfs $flags -s $1 ${mfs_type} $2
1892}
1893
1894# Code common to scripts that need to load a kernel module
1895# if it isn't in the kernel yet. Syntax:
1896#   load_kld [-e regex] [-m module] file
1897# where -e or -m chooses the way to check if the module
1898# is already loaded:
1899#   regex is egrep'd in the output from `kldstat -v',
1900#   module is passed to `kldstat -m'.
1901# The default way is as though `-m file' were specified.
1902load_kld()
1903{
1904	local _loaded _mod _opt _re
1905
1906	while getopts "e:m:" _opt; do
1907		case "$_opt" in
1908		e) _re="$OPTARG" ;;
1909		m) _mod="$OPTARG" ;;
1910		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1911		esac
1912	done
1913	shift $(($OPTIND - 1))
1914	if [ $# -ne 1 ]; then
1915		err 3 'USAGE: load_kld [-e regex] [-m module] file'
1916	fi
1917	_mod=${_mod:-$1}
1918	_loaded=false
1919	if [ -n "$_re" ]; then
1920		if kldstat -v | egrep -q -e "$_re"; then
1921			_loaded=true
1922		fi
1923	else
1924		if kldstat -q -m "$_mod"; then
1925			_loaded=true
1926		fi
1927	fi
1928	if ! $_loaded; then
1929		if ! kldload "$1"; then
1930			warn "Unable to load kernel module $1"
1931			return 1
1932		else
1933			info "$1 kernel module loaded."
1934		fi
1935	else
1936		debug "load_kld: $1 kernel module already loaded."
1937	fi
1938	return 0
1939}
1940
1941# ltr str src dst [var]
1942#	Change every $src in $str to $dst.
1943#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1944#	awk(1). If var is non-NULL, set it to the result.
1945ltr()
1946{
1947	local _str _src _dst _out _com _var
1948	_str="$1"
1949	_src="$2"
1950	_dst="$3"
1951	_var="$4"
1952	_out=""
1953
1954	local IFS="${_src}"
1955	for _com in ${_str}; do
1956		if [ -z "${_out}" ]; then
1957			_out="${_com}"
1958		else
1959			_out="${_out}${_dst}${_com}"
1960		fi
1961	done
1962	if [ -n "${_var}" ]; then
1963		setvar "${_var}" "${_out}"
1964	else
1965		echo "${_out}"
1966	fi
1967}
1968
1969# Creates a list of providers for GELI encryption.
1970geli_make_list()
1971{
1972	local devices devices2
1973	local provider mountpoint type options rest
1974
1975	# Create list of GELI providers from fstab.
1976	while read provider mountpoint type options rest ; do
1977		case ":${options}" in
1978		:*noauto*)
1979			noauto=yes
1980			;;
1981		*)
1982			noauto=no
1983			;;
1984		esac
1985
1986		case ":${provider}" in
1987		:#*)
1988			continue
1989			;;
1990		*.eli)
1991			# Skip swap devices.
1992			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1993				continue
1994			fi
1995			devices="${devices} ${provider}"
1996			;;
1997		esac
1998	done < /etc/fstab
1999
2000	# Append providers from geli_devices.
2001	devices="${devices} ${geli_devices}"
2002
2003	for provider in ${devices}; do
2004		provider=${provider%.eli}
2005		provider=${provider#/dev/}
2006		devices2="${devices2} ${provider}"
2007	done
2008
2009	echo ${devices2}
2010}
2011
2012# Originally, root mount hold had to be released before mounting
2013# the root filesystem.  This delayed the boot, so it was changed
2014# to only wait if the root device isn't readily available.  This
2015# can result in rc scripts executing before all the devices - such
2016# as graid(8), or USB disks - can be accessed.  This function can
2017# be used to explicitly wait for root mount holds to be released.
2018root_hold_wait()
2019{
2020	local wait waited holders
2021
2022	waited=0
2023	while true; do
2024		holders="$(sysctl -n vfs.root_mount_hold)"
2025		if [ -z "${holders}" ]; then
2026			break;
2027		fi
2028		if [ ${waited} -eq 0 ]; then
2029			echo -n "Waiting ${root_hold_delay}s" \
2030			"for the root mount holders: ${holders}"
2031		else
2032			echo -n .
2033		fi
2034		if [ ${waited} -ge ${root_hold_delay} ]; then
2035			echo
2036			break
2037		fi
2038		sleep 1
2039		waited=$(($waited + 1))
2040	done
2041}
2042
2043# Find scripts in local_startup directories that use the old syntax
2044#
2045find_local_scripts_old() {
2046	zlist=''
2047	slist=''
2048	for dir in ${local_startup}; do
2049		if [ -d "${dir}" ]; then
2050			for file in ${dir}/[0-9]*.sh; do
2051				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2052				    continue
2053				zlist="$zlist $file"
2054			done
2055			for file in ${dir}/[!0-9]*.sh; do
2056				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2057				    continue
2058				slist="$slist $file"
2059			done
2060		fi
2061	done
2062}
2063
2064find_local_scripts_new() {
2065	local_rc=''
2066	for dir in ${local_startup}; do
2067		if [ -d "${dir}" ]; then
2068			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
2069				case "$file" in
2070				*.sample) ;;
2071				*)	if [ -x "$file" ]; then
2072						local_rc="${local_rc} ${file}"
2073					fi
2074					;;
2075				esac
2076			done
2077		fi
2078	done
2079}
2080
2081# check_required_{before|after} command
2082#	Check for things required by the command before and after its precmd,
2083#	respectively.  The two separate functions are needed because some
2084#	conditions should prevent precmd from being run while other things
2085#	depend on precmd having already been run.
2086#
2087check_required_before()
2088{
2089	local _f
2090
2091	case "$1" in
2092	start)
2093		for _f in $required_vars; do
2094			if ! checkyesno $_f; then
2095				warn "\$${_f} is not enabled."
2096				if [ -z "$rc_force" ]; then
2097					return 1
2098				fi
2099			fi
2100		done
2101
2102		for _f in $required_dirs; do
2103			if [ ! -d "${_f}/." ]; then
2104				warn "${_f} is not a directory."
2105				if [ -z "$rc_force" ]; then
2106					return 1
2107				fi
2108			fi
2109		done
2110
2111		for _f in $required_files; do
2112			if [ ! -r "${_f}" ]; then
2113				warn "${_f} is not readable."
2114				if [ -z "$rc_force" ]; then
2115					return 1
2116				fi
2117			fi
2118		done
2119		;;
2120	esac
2121
2122	return 0
2123}
2124
2125check_required_after()
2126{
2127	local _f _args
2128
2129	case "$1" in
2130	start)
2131		for _f in $required_modules; do
2132			case "${_f}" in
2133				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
2134				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
2135				*)	_args="${_f}" ;;
2136			esac
2137			if ! load_kld ${_args}; then
2138				if [ -z "$rc_force" ]; then
2139					return 1
2140				fi
2141			fi
2142		done
2143		;;
2144	esac
2145
2146	return 0
2147}
2148
2149# check_jail mib
2150#	Return true if security.jail.$mib exists and set to 1.
2151
2152check_jail()
2153{
2154	local _mib _v
2155
2156	_mib=$1
2157	if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2158		case $_v in
2159		1)	return 0;;
2160		esac
2161	fi
2162	return 1
2163}
2164
2165# check_kern_features mib
2166#	Return existence of kern.features.* sysctl MIB as true or
2167#	false.  The result will be cached in $_rc_cache_kern_features_
2168#	namespace.  "0" means the kern.features.X exists.
2169
2170check_kern_features()
2171{
2172	local _v
2173
2174	[ -n "$1" ] || return 1;
2175	eval _v=\$_rc_cache_kern_features_$1
2176	[ -n "$_v" ] && return "$_v";
2177
2178	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2179		eval _rc_cache_kern_features_$1=0
2180		return 0
2181	else
2182		eval _rc_cache_kern_features_$1=1
2183		return 1
2184	fi
2185}
2186
2187# check_namevarlist var
2188#	Return "0" if ${name}_var is reserved in rc.subr.
2189
2190_rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend"
2191check_namevarlist()
2192{
2193	local _v
2194
2195	for _v in $_rc_namevarlist; do
2196	case $1 in
2197	$_v)	return 0 ;;
2198	esac
2199	done
2200
2201	return 1
2202}
2203
2204# _echoonce var msg mode
2205#	mode=0: Echo $msg if ${$var} is empty.
2206#	        After doing echo, a string is set to ${$var}.
2207#
2208#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
2209#
2210_echoonce()
2211{
2212	local _var _msg _mode
2213	eval _var=\$$1
2214	_msg=$2
2215	_mode=$3
2216
2217	case $_mode in
2218	1)	[ -n "$_var" ] && echo "$_msg" ;;
2219	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2220	esac
2221}
2222
2223# If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2224# still override this, but /etc/defaults/rc.conf can't unconditionally set this
2225# since it would undo what we've done here.
2226if kenv -q rc.debug > /dev/null ; then
2227	rc_debug=YES
2228fi
2229
2230boottrace_cmd=`command -v boottrace`
2231if [ -n "$boottrace_cmd" ] && [ "`${SYSCTL_N} -q kern.boottrace.enabled`" = "1" ]; then
2232	rc_boottrace=YES
2233fi
2234