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