rc.subr revision 230374
1101099Srwatson# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2145412Strhodes# $FreeBSD: head/etc/rc.subr 230374 2012-01-20 10:31:27Z dougb $
3126097Srwatson#
4145412Strhodes# Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
5101099Srwatson# All rights reserved.
6101099Srwatson#
7101099Srwatson# This code is derived from software contributed to The NetBSD Foundation
8145412Strhodes# by Luke Mewburn.
9101099Srwatson#
10106393Srwatson# Redistribution and use in source and binary forms, with or without
11106393Srwatson# modification, are permitted provided that the following conditions
12106393Srwatson# are met:
13106393Srwatson# 1. Redistributions of source code must retain the above copyright
14101099Srwatson#    notice, this list of conditions and the following disclaimer.
15101099Srwatson# 2. Redistributions in binary form must reproduce the above copyright
16101099Srwatson#    notice, this list of conditions and the following disclaimer in the
17101099Srwatson#    documentation and/or other materials provided with the distribution.
18101099Srwatson#
19101099Srwatson# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20101099Srwatson# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21101099Srwatson# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22101099Srwatson# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23101099Srwatson# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24101099Srwatson# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25101099Srwatson# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26101099Srwatson# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27101099Srwatson# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28101099Srwatson# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29101099Srwatson# POSSIBILITY OF SUCH DAMAGE.
30101099Srwatson#
31101099Srwatson# rc.subr
32101099Srwatson#	functions used by various rc scripts
33101099Srwatson#
34101099Srwatson
35101099Srwatson: ${RC_PID:=$$}; export RC_PID
36101099Srwatson
37101099Srwatson#
38136774Srwatson#	Operating System dependent/independent variables
39101099Srwatson#
40101099Srwatson
41101099Srwatsonif [ -z "${_rc_subr_loaded}" ]; then
42101099Srwatson
43101099Srwatson_rc_subr_loaded="YES"
44101099Srwatson
45101099SrwatsonSYSCTL="/sbin/sysctl"
46101099SrwatsonSYSCTL_N="${SYSCTL} -n"
47101099SrwatsonSYSCTL_W="${SYSCTL}"
48101099SrwatsonID="/usr/bin/id"
49101099SrwatsonIDCMD="if [ -x $ID ]; then $ID -un; fi"
50157986SdwmalonePS="/bin/ps -ww"
51145412StrhodesJID=`$PS -p $$ -o jid=`
52101099Srwatson
53101099Srwatson#
54101099Srwatson#	functions
55145412Strhodes#	---------
56101099Srwatson
57101099Srwatson# set_rcvar_obsolete oldvar [newvar] [msg]
58101099Srwatson#	Define obsolete variable.
59101099Srwatson#	Global variable $rcvars_obsolete is used.
60101099Srwatson#
61101099Srwatsonset_rcvar_obsolete()
62101099Srwatson{
63101099Srwatson	local _var
64101099Srwatson	_var=$1
65134132Strhodes	debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
66157986Sdwmalone
67101099Srwatson	rcvars_obsolete="${rcvars_obsolete# } $1"
68101099Srwatson	eval ${1}_newvar=\"$2\"
69101099Srwatson	shift 2
70101099Srwatson	eval ${_var}_obsolete_msg=\"$*\"
71101099Srwatson}
72101099Srwatson
73101099Srwatson#
74101099Srwatson# force_depend script
75101099Srwatson#	Force a service to start. Intended for use by services
76101099Srwatson#	to resolve dependency issues. It is assumed the caller
77101099Srwatson#	has check to make sure this call is necessary
78101099Srwatson#	$1 - filename of script, in /etc/rc.d, to run
79145412Strhodes#
80145412Strhodesforce_depend()
81101099Srwatson{
82101099Srwatson	_depend="$1"
83101099Srwatson
84101099Srwatson	info "${name} depends on ${_depend}, which will be forced to start."
85101099Srwatson	if ! /etc/rc.d/${_depend} forcestart; then
86101099Srwatson		warn "Unable to force ${_depend}. It may already be running."
87101099Srwatson		return 1
88101099Srwatson	fi
89101099Srwatson	return 0
90101099Srwatson}
91101099Srwatson
92101099Srwatson#
93101099Srwatson# checkyesno var
94101099Srwatson#	Test $1 variable, and warn if not set to YES or NO.
95101099Srwatson#	Return 0 if it's "yes" (et al), nonzero otherwise.
96101099Srwatson#
97157986Sdwmalonecheckyesno()
98101099Srwatson{
99101099Srwatson	eval _value=\$${1}
100101099Srwatson	debug "checkyesno: $1 is set to $_value."
101101099Srwatson	case $_value in
102101099Srwatson
103157986Sdwmalone		#	"yes", "true", "on", or "1"
104157986Sdwmalone	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
105101099Srwatson		return 0
106134132Strhodes		;;
107145412Strhodes
108134132Strhodes		#	"no", "false", "off", or "0"
109134132Strhodes	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
110134132Strhodes		return 1
111134132Strhodes		;;
112134132Strhodes	*)
113134132Strhodes		warn "\$${1} is not set properly - see rc.conf(5)."
114134132Strhodes		return 1
115134131Strhodes		;;
116134131Strhodes	esac
117134131Strhodes}
118134131Strhodes
119101099Srwatson#
120134131Strhodes# reverse_list list
121134131Strhodes#	print the list in reverse order
122135039Strhodes#
123134131Strhodesreverse_list()
124134131Strhodes{
125134131Strhodes	_revlist=
126101099Srwatson	for _revfile; do
127101099Srwatson		_revlist="$_revfile $_revlist"
128101099Srwatson	done
129157986Sdwmalone	echo $_revlist
130101099Srwatson}
131101099Srwatson
132157986Sdwmalone# stop_boot always
133101099Srwatson#	If booting directly to multiuser or $always is enabled,
134101099Srwatson#	send SIGTERM to the parent (/etc/rc) to abort the boot.
135157986Sdwmalone#	Otherwise just exit.
136157986Sdwmalone#
137157986Sdwmalonestop_boot()
138157986Sdwmalone{
139157986Sdwmalone	local always
140157986Sdwmalone
141157986Sdwmalone	case $1 in
142157986Sdwmalone		#	"yes", "true", "on", or "1"
143157986Sdwmalone        [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
144157986Sdwmalone		always=true
145136739Srwatson		;;
146101099Srwatson	*)
147101099Srwatson		always=false
148101099Srwatson		;;
149101099Srwatson	esac
150101099Srwatson	if [ "$autoboot" = yes -o "$always" = true ]; then
151101099Srwatson		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
152101099Srwatson		kill -TERM ${RC_PID}
153101099Srwatson	fi
154101099Srwatson	exit 1
155101099Srwatson}
156101099Srwatson
157101099Srwatson#
158145412Strhodes# mount_critical_filesystems type
159101099Srwatson#	Go through the list of critical filesystems as provided in
160101099Srwatson#	the rc.conf(5) variable $critical_filesystems_${type}, checking
161101099Srwatson#	each one to see if it is mounted, and if it is not, mounting it.
162101099Srwatson#
163101099Srwatsonmount_critical_filesystems()
164101099Srwatson{
165101099Srwatson	eval _fslist=\$critical_filesystems_${1}
166101099Srwatson	for _fs in $_fslist; do
167101099Srwatson		mount | (
168154386Scsjp			_ismounted=false
169101099Srwatson			while read what _on on _type type; do
170101099Srwatson				if [ $on = $_fs ]; then
171145412Strhodes					_ismounted=true
172145412Strhodes				fi
173145412Strhodes			done
174101099Srwatson			if $_ismounted; then
175101099Srwatson				:
176145412Strhodes			else
177145412Strhodes				mount $_fs >/dev/null 2>&1
178101099Srwatson			fi
179101099Srwatson		)
180145412Strhodes	done
181145412Strhodes}
182145412Strhodes
183145412Strhodes#
184145412Strhodes# check_pidfile pidfile procname [interpreter]
185145412Strhodes#	Parses the first line of pidfile for a PID, and ensures
186101099Srwatson#	that the process is running and matches procname.
187145412Strhodes#	Prints the matching PID upon success, nothing otherwise.
188145412Strhodes#	interpreter is optional; see _find_processes() for details.
189145412Strhodes#
190145412Strhodescheck_pidfile()
191145412Strhodes{
192145412Strhodes	_pidfile=$1
193101099Srwatson	_procname=$2
194145412Strhodes	_interpreter=$3
195145412Strhodes	if [ -z "$_pidfile" -o -z "$_procname" ]; then
196145412Strhodes		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
197145412Strhodes	fi
198145412Strhodes	if [ ! -f $_pidfile ]; then
199145412Strhodes		debug "pid file ($_pidfile): not readable."
200145412Strhodes		return
201145412Strhodes	fi
202145412Strhodes	read _pid _junk < $_pidfile
203145412Strhodes	if [ -z "$_pid" ]; then
204145412Strhodes		debug "pid file ($_pidfile): no pid in file."
205101099Srwatson		return
206101099Srwatson	fi
207145412Strhodes	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
208101099Srwatson}
209101099Srwatson
210101099Srwatson#
211101099Srwatson# check_process procname [interpreter]
212101099Srwatson#	Ensures that a process (or processes) named procname is running.
213145412Strhodes#	Prints a list of matching PIDs.
214145412Strhodes#	interpreter is optional; see _find_processes() for details.
215145412Strhodes#
216101099Srwatsoncheck_process()
217101099Srwatson{
218101099Srwatson	_procname=$1
219101099Srwatson	_interpreter=$2
220101099Srwatson	if [ -z "$_procname" ]; then
221101099Srwatson		err 3 'USAGE: check_process procname [interpreter]'
222101099Srwatson	fi
223145412Strhodes	_find_processes $_procname ${_interpreter:-.} '-ax'
224145412Strhodes}
225145412Strhodes
226145412Strhodes#
227148482Strhodes# _find_processes procname interpreter psargs
228145412Strhodes#	Search for procname in the output of ps generated by psargs.
229145412Strhodes#	Prints the PIDs of any matching processes, space separated.
230148482Strhodes#
231101099Srwatson#	If interpreter == ".", check the following variations of procname
232101099Srwatson#	against the first word of each command:
233101099Srwatson#		procname
234101099Srwatson#		`basename procname`
235101099Srwatson#		`basename procname` + ":"
236101099Srwatson#		"(" + `basename procname` + ")"
237101099Srwatson#		"[" + `basename procname` + "]"
238101099Srwatson#
239101099Srwatson#	If interpreter != ".", read the first line of procname, remove the
240101099Srwatson#	leading #!, normalise whitespace, append procname, and attempt to
241145412Strhodes#	match that against each command, either as is, or with extra words
242145412Strhodes#	at the end.  As an alternative, to deal with interpreted daemons
243101099Srwatson#	using perl, the basename of the interpreter plus a colon is also
244101099Srwatson#	tried as the prefix to procname.
245101099Srwatson#
246101099Srwatson_find_processes()
247101099Srwatson{
248101099Srwatson	if [ $# -ne 3 ]; then
249101099Srwatson		err 3 'USAGE: _find_processes procname interpreter psargs'
250145412Strhodes	fi
251145412Strhodes	_procname=$1
252145412Strhodes	_interpreter=$2
253101099Srwatson	_psargs=$3
254101099Srwatson
255101099Srwatson	_pref=
256101099Srwatson	if [ $_interpreter != "." ]; then	# an interpreted script
257101099Srwatson		_script=${_chroot}${_chroot:+"/"}$_procname
258157986Sdwmalone		if [ -r $_script ]; then
259101099Srwatson			read _interp < $_script	# read interpreter name
260101099Srwatson			case "$_interp" in
261157986Sdwmalone			\#!*)
262101099Srwatson				_interp=${_interp#\#!}	# strip #!
263101099Srwatson				set -- $_interp
264101099Srwatson				case $1 in
265101099Srwatson				*/bin/env)
266145412Strhodes					shift	# drop env to get real name
267157986Sdwmalone					;;
268157986Sdwmalone				esac
269157986Sdwmalone				if [ $_interpreter != $1 ]; then
270157986Sdwmalone					warn "\$command_interpreter $_interpreter != $1"
271157986Sdwmalone				fi
272157986Sdwmalone				;;
273157986Sdwmalone			*)
274101099Srwatson				warn "no shebang line in $_script"
275157986Sdwmalone				set -- $_interpreter
276101099Srwatson				;;
277101099Srwatson			esac
278101099Srwatson		else
279101099Srwatson			warn "cannot read shebang line from $_script"
280101099Srwatson			set -- $_interpreter
281101099Srwatson		fi
282157986Sdwmalone		_interp="$* $_procname"		# cleanup spaces, add _procname
283157986Sdwmalone		_interpbn=${1##*/}
284157986Sdwmalone		_fp_args='_argv'
285157986Sdwmalone		_fp_match='case "$_argv" in
286157986Sdwmalone		    ${_interp}|"${_interp} "*|"${_interpbn}: ${_procname}"*)'
287101099Srwatson	else					# a normal daemon
288157986Sdwmalone		_procnamebn=${_procname##*/}
289157986Sdwmalone		_fp_args='_arg0 _argv'
290157986Sdwmalone		_fp_match='case "$_arg0" in
291157986Sdwmalone		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
292157986Sdwmalone	fi
293157986Sdwmalone
294157986Sdwmalone	_proccheck="\
295157986Sdwmalone		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
296157986Sdwmalone		while read _npid _jid '"$_fp_args"'; do
297157986Sdwmalone			'"$_fp_match"'
298157986Sdwmalone				if [ "$JID" -eq "$_jid" ];
299157986Sdwmalone				then echo -n "$_pref$_npid";
300101099Srwatson				_pref=" ";
301101099Srwatson				fi
302101099Srwatson				;;
303101099Srwatson			esac
304101099Srwatson		done'
305101099Srwatson
306157986Sdwmalone#	debug "in _find_processes: proccheck is ($_proccheck)."
307157986Sdwmalone	eval $_proccheck
308157986Sdwmalone}
309157986Sdwmalone
310157986Sdwmalone#
311157986Sdwmalone# wait_for_pids pid [pid ...]
312157986Sdwmalone#	spins until none of the pids exist
313157986Sdwmalone#
314157986Sdwmalonewait_for_pids()
315157986Sdwmalone{
316157986Sdwmalone	local _list _prefix _nlist _j
317101099Srwatson
318101099Srwatson	_list="$@"
319101099Srwatson	if [ -z "$_list" ]; then
320157986Sdwmalone		return
321157986Sdwmalone	fi
322157986Sdwmalone	_prefix=
323101099Srwatson	while true; do
324157986Sdwmalone		_nlist="";
325101099Srwatson		for _j in $_list; do
326101099Srwatson			if kill -0 $_j 2>/dev/null; then
327101099Srwatson				_nlist="${_nlist}${_nlist:+ }$_j"
328101099Srwatson				[ -n "$_prefix" ] && sleep 1
329101099Srwatson			fi
330101099Srwatson		done
331157986Sdwmalone		if [ -z "$_nlist" ]; then
332157986Sdwmalone			break
333157986Sdwmalone		fi
334101099Srwatson		_list=$_nlist
335157986Sdwmalone		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
336101099Srwatson		_prefix=", "
337101099Srwatson		pwait $_list 2>/dev/null
338101099Srwatson	done
339101099Srwatson	if [ -n "$_prefix" ]; then
340101099Srwatson		echo "."
341101099Srwatson	fi
342157986Sdwmalone}
343157986Sdwmalone
344157986Sdwmalone#
345157986Sdwmalone# get_pidfile_from_conf string file
346157986Sdwmalone#
347157986Sdwmalone#	Takes a string to search for in the specified file.
348157986Sdwmalone#	Ignores lines with traditional comment characters.
349157986Sdwmalone#
350157986Sdwmalone# Example:
351157986Sdwmalone#
352157986Sdwmalone# if get_pidfile_from_conf string file; then
353157986Sdwmalone#	pidfile="$_pidfile_from_conf"
354157986Sdwmalone# else
355157986Sdwmalone#	pidfile='appropriate default'
356157986Sdwmalone# fi
357157986Sdwmalone#
358157986Sdwmaloneget_pidfile_from_conf()
359157986Sdwmalone{
360157986Sdwmalone	if [ -z "$1" -o -z "$2" ]; then
361157986Sdwmalone		err 3 "USAGE: get_pidfile_from_conf string file ($name)"
362157986Sdwmalone	fi
363157986Sdwmalone
364157986Sdwmalone	local string file line
365157986Sdwmalone
366157986Sdwmalone	string="$1" ; file="$2"
367157986Sdwmalone
368157986Sdwmalone	if [ ! -s "$file" ]; then
369157986Sdwmalone		err 3 "get_pidfile_from_conf: $file does not exist ($name)"
370157986Sdwmalone	fi
371157986Sdwmalone
372157986Sdwmalone	while read line; do
373157986Sdwmalone		case "$line" in
374157986Sdwmalone		*[#\;]*${string}*)	continue ;;
375157986Sdwmalone		*${string}*)		break ;;
376157986Sdwmalone		esac
377157986Sdwmalone	done < $file
378157986Sdwmalone
379157986Sdwmalone	if [ -n "$line" ]; then
380157986Sdwmalone		line=${line#*/}
381157986Sdwmalone		_pidfile_from_conf="/${line%%[\"\;]*}"
382157986Sdwmalone	else
383157986Sdwmalone		return 1
384157986Sdwmalone	fi
385157986Sdwmalone}
386157986Sdwmalone
387157986Sdwmalone#
388157986Sdwmalone# check_startmsgs
389157986Sdwmalone#	If rc_quiet is set (usually as a result of using faststart at
390157986Sdwmalone#	boot time) check if rc_startmsgs is enabled.
391157986Sdwmalone#
392157986Sdwmalonecheck_startmsgs()
393157986Sdwmalone{
394157986Sdwmalone	if [ -n "$rc_quiet" ]; then
395157986Sdwmalone		checkyesno rc_startmsgs
396157986Sdwmalone	else
397157986Sdwmalone		return 0
398157986Sdwmalone	fi
399157986Sdwmalone}
400157986Sdwmalone
401157986Sdwmalone#
402157986Sdwmalone# run_rc_command argument
403157986Sdwmalone#	Search for argument in the list of supported commands, which is:
404157986Sdwmalone#		"start stop restart rcvar status poll ${extra_commands}"
405157986Sdwmalone#	If there's a match, run ${argument}_cmd or the default method
406157986Sdwmalone#	(see below).
407157986Sdwmalone#
408157986Sdwmalone#	If argument has a given prefix, then change the operation as follows:
409157986Sdwmalone#		Prefix	Operation
410157986Sdwmalone#		------	---------
411157986Sdwmalone#		fast	Skip the pid check, and set rc_fast=yes, rc_quiet=yes
412157986Sdwmalone#		force	Set ${rcvar} to YES, and set rc_force=yes
413157986Sdwmalone#		one	Set ${rcvar} to YES
414157986Sdwmalone#		quiet	Don't output some diagnostics, and set rc_quiet=yes
415157986Sdwmalone#
416157986Sdwmalone#	The following globals are used:
417157986Sdwmalone#
418157986Sdwmalone#	Name		Needed	Purpose
419157986Sdwmalone#	----		------	-------
420157986Sdwmalone#	name		y	Name of script.
421157986Sdwmalone#
422157986Sdwmalone#	command		n	Full path to command.
423157986Sdwmalone#				Not needed if ${rc_arg}_cmd is set for
424157986Sdwmalone#				each keyword.
425157986Sdwmalone#
426157986Sdwmalone#	command_args	n	Optional args/shell directives for command.
427157986Sdwmalone#
428157986Sdwmalone#	command_interpreter n	If not empty, command is interpreted, so
429157986Sdwmalone#				call check_{pidfile,process}() appropriately.
430157986Sdwmalone#
431157986Sdwmalone#	desc		n	Description of script.
432101099Srwatson#
433101099Srwatson#	extra_commands	n	List of extra commands supported.
434101099Srwatson#
435101099Srwatson#	pidfile		n	If set, use check_pidfile $pidfile $command,
436134132Strhodes#				otherwise use check_process $command.
437134132Strhodes#				In either case, only check if $command is set.
438134132Strhodes#
439157986Sdwmalone#	procname	n	Process name to check for instead of $command.
440134132Strhodes#
441101099Srwatson#	rcvar		n	This is checked with checkyesno to determine
442145412Strhodes#				if the action should be run.
443134131Strhodes#
444145412Strhodes#	${name}_program	n	Full path to command.
445145412Strhodes#				Meant to be used in /etc/rc.conf to override
446134131Strhodes#				${command}.
447134131Strhodes#
448134131Strhodes#	${name}_chroot	n	Directory to chroot to before running ${command}
449134131Strhodes#				Requires /usr to be mounted.
450134131Strhodes#
451101099Srwatson#	${name}_chdir	n	Directory to cd to before running ${command}
452101099Srwatson#				(if not using ${name}_chroot).
453101099Srwatson#
454157986Sdwmalone#	${name}_flags	n	Arguments to call ${command} with.
455106212Srwatson#				NOTE:	$flags from the parent environment
456101099Srwatson#					can be used to override this.
457101099Srwatson#
458101099Srwatson#	${name}_nice	n	Nice level to run ${command} at.
459132563Srwatson#
460132563Srwatson#	${name}_user	n	User to run ${command} as, using su(1) if not
461132563Srwatson#				using ${name}_chroot.
462145412Strhodes#				Requires /usr to be mounted.
463101099Srwatson#
464101099Srwatson#	${name}_group	n	Group to run chrooted ${command} as.
465101099Srwatson#				Requires /usr to be mounted.
466101099Srwatson#
467108376Srwatson#	${name}_groups	n	Comma separated list of supplementary groups
468145412Strhodes#				to run the chrooted ${command} with.
469108376Srwatson#				Requires /usr to be mounted.
470108376Srwatson#
471136739Srwatson#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
472136739Srwatson#				Otherwise, use default command (see below)
473136739Srwatson#
474108376Srwatson#	${rc_arg}_precmd n	If set, run just before performing the
475108376Srwatson#				${rc_arg}_cmd method in the default
476157986Sdwmalone#				operation (i.e, after checking for required
477157986Sdwmalone#				bits and process (non)existence).
478134131Strhodes#				If this completes with a non-zero exit code,
479134131Strhodes#				don't run ${rc_arg}_cmd.
480145412Strhodes#
481145412Strhodes#	${rc_arg}_postcmd n	If set, run just after performing the
482101099Srwatson#				${rc_arg}_cmd method, if that method
483145412Strhodes#				returned a zero exit code.
484101099Srwatson#
485145412Strhodes#	required_dirs	n	If set, check for the existence of the given
486101099Srwatson#				directories before running a (re)start command.
487101099Srwatson#
488101099Srwatson#	required_files	n	If set, check for the readability of the given
489101099Srwatson#				files before running a (re)start command.
490156300Sdwmalone#
491112575Srwatson#	required_modules n	If set, ensure the given kernel modules are
492156300Sdwmalone#				loaded before running a (re)start command.
493112575Srwatson#				The check and possible loads are actually
494112575Srwatson#				done after start_precmd so that the modules
495112575Srwatson#				aren't loaded in vain, should the precmd
496112575Srwatson#				return a non-zero status to indicate a error.
497112575Srwatson#				If a word in the list looks like "foo:bar",
498112575Srwatson#				"foo" is the KLD file name and "bar" is the
499112575Srwatson#				module name.  If a word looks like "foo~bar",
500112575Srwatson#				"foo" is the KLD file name and "bar" is a
501156300Sdwmalone#				egrep(1) pattern matching the module name.
502157986Sdwmalone#				Otherwise the module name is assumed to be
503112575Srwatson#				the same as the KLD file name, which is most
504112575Srwatson#				common.  See load_kld().
505112575Srwatson#
506156300Sdwmalone#	required_vars	n	If set, perform checkyesno on each of the
507156300Sdwmalone#				listed variables before running the default
508156300Sdwmalone#				(re)start command.
509156300Sdwmalone#
510156300Sdwmalone#	Default behaviour for a given argument, if no override method is
511156300Sdwmalone#	provided:
512156300Sdwmalone#
513156300Sdwmalone#	Argument	Default behaviour
514101099Srwatson#	--------	-----------------
515106212Srwatson#	start		if !running && checkyesno ${rcvar}
516101099Srwatson#				${command}
517101099Srwatson#
518156300Sdwmalone#	stop		if ${pidfile}
519101099Srwatson#				rc_pid=$(check_pidfile $pidfile $command)
520101099Srwatson#			else
521101099Srwatson#				rc_pid=$(check_process $command)
522101099Srwatson#			kill $sig_stop $rc_pid
523101099Srwatson#			wait_for_pids $rc_pid
524101099Srwatson#			($sig_stop defaults to TERM.)
525101099Srwatson#
526156300Sdwmalone#	reload		Similar to stop, except use $sig_reload instead,
527101099Srwatson#			and doesn't wait_for_pids.
528101099Srwatson#			$sig_reload defaults to HUP.
529101099Srwatson#			Note that `reload' isn't provided by default,
530101099Srwatson#			it should be enabled via $extra_commands.
531101099Srwatson#
532101099Srwatson#	restart		Run `stop' then `start'.
533101099Srwatson#
534156300Sdwmalone#	status		Show if ${command} is running, etc.
535101099Srwatson#
536101099Srwatson#	poll		Wait for ${command} to exit.
537101099Srwatson#
538101099Srwatson#	rcvar		Display what rc.conf variable is used (if any).
539101099Srwatson#
540101099Srwatson#	Variables available to methods, and after run_rc_command() has
541101099Srwatson#	completed:
542156300Sdwmalone#
543101099Srwatson#	Variable	Purpose
544101099Srwatson#	--------	-------
545101099Srwatson#	rc_arg		Argument to command, after fast/force/one processing
546101099Srwatson#			performed
547101099Srwatson#
548101099Srwatson#	rc_flags	Flags to start the default command with.
549101099Srwatson#			Defaults to ${name}_flags, unless overridden
550101099Srwatson#			by $flags from the environment.
551101099Srwatson#			This variable may be changed by the precmd method.
552156300Sdwmalone#
553101099Srwatson#	rc_pid		PID of command (if appropriate)
554101099Srwatson#
555101099Srwatson#	rc_fast		Not empty if "fast" was provided (q.v.)
556156300Sdwmalone#
557101099Srwatson#	rc_force	Not empty if "force" was provided (q.v.)
558101099Srwatson#
559101099Srwatson#	rc_quiet	Not empty if "quiet" was provided
560101099Srwatson#
561101099Srwatson#
562101099Srwatsonrun_rc_command()
563101099Srwatson{
564156300Sdwmalone	_return=0
565101099Srwatson	rc_arg=$1
566101099Srwatson	if [ -z "$name" ]; then
567101099Srwatson		err 3 'run_rc_command: $name is not set.'
568119202Srwatson	fi
569119202Srwatson
570119202Srwatson	# Don't repeat the first argument when passing additional command-
571119202Srwatson	# line arguments to the command subroutines.
572156300Sdwmalone	#
573119202Srwatson	shift 1
574119202Srwatson	rc_extra_args="$*"
575119202Srwatson
576101099Srwatson	_rc_prefix=
577106648Srwatson	case "$rc_arg" in
578106648Srwatson	fast*)				# "fast" prefix; don't check pid
579101099Srwatson		rc_arg=${rc_arg#fast}
580101099Srwatson		rc_fast=yes
581156300Sdwmalone		rc_quiet=yes
582101099Srwatson		;;
583101099Srwatson	force*)				# "force" prefix; always run
584101099Srwatson		rc_force=yes
585101099Srwatson		_rc_prefix=force
586101099Srwatson		rc_arg=${rc_arg#${_rc_prefix}}
587101099Srwatson		if [ -n "${rcvar}" ]; then
588101099Srwatson			eval ${rcvar}=YES
589156300Sdwmalone		fi
590101099Srwatson		;;
591101099Srwatson	one*)				# "one" prefix; set ${rcvar}=yes
592101099Srwatson		_rc_prefix=one
593101099Srwatson		rc_arg=${rc_arg#${_rc_prefix}}
594101099Srwatson		if [ -n "${rcvar}" ]; then
595101099Srwatson			eval ${rcvar}=YES
596101099Srwatson		fi
597156300Sdwmalone		;;
598101099Srwatson	quiet*)				# "quiet" prefix; omit some messages
599101099Srwatson		_rc_prefix=quiet
600101099Srwatson		rc_arg=${rc_arg#${_rc_prefix}}
601104530Srwatson		rc_quiet=yes
602104530Srwatson		;;
603104530Srwatson	esac
604104530Srwatson
605104530Srwatson	eval _override_command=\$${name}_program
606104530Srwatson	command=${_override_command:-$command}
607156300Sdwmalone
608104530Srwatson	_keywords="start stop restart rcvar $extra_commands"
609104530Srwatson	rc_pid=
610104530Srwatson	_pidcmd=
611156300Sdwmalone	_procname=${procname:-${command}}
612104530Srwatson
613104530Srwatson					# setup pid check command
614104530Srwatson	if [ -n "$_procname" ]; then
615104530Srwatson		if [ -n "$pidfile" ]; then
616104530Srwatson			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
617104530Srwatson		else
618119202Srwatson			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
619119202Srwatson		fi
620119202Srwatson		if [ -n "$_pidcmd" ]; then
621119202Srwatson			_keywords="${_keywords} status poll"
622156300Sdwmalone		fi
623119202Srwatson	fi
624119202Srwatson
625119202Srwatson	if [ -z "$rc_arg" ]; then
626101099Srwatson		rc_usage $_keywords
627101099Srwatson	fi
628101099Srwatson
629117247Srwatson	if [ -n "$flags" ]; then	# allow override from environment
630156300Sdwmalone		rc_flags=$flags
631101099Srwatson	else
632101099Srwatson		eval rc_flags=\$${name}_flags
633101099Srwatson	fi
634101099Srwatson	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
635106212Srwatson	    _nice=\$${name}_nice	_user=\$${name}_user \
636101099Srwatson	    _group=\$${name}_group	_groups=\$${name}_groups
637101099Srwatson
638156300Sdwmalone	if [ -n "$_user" ]; then	# unset $_user if running as that user
639101099Srwatson		if [ "$_user" = "$(eval $IDCMD)" ]; then
640101099Srwatson			unset _user
641101099Srwatson		fi
642101099Srwatson	fi
643101099Srwatson
644101099Srwatson	[ -z "$autoboot" ] && eval $_pidcmd	# determine the pid if necessary
645101099Srwatson
646156300Sdwmalone	for _elem in $_keywords; do
647101099Srwatson		if [ "$_elem" != "$rc_arg" ]; then
648101099Srwatson			continue
649101099Srwatson		fi
650101099Srwatson					# if ${rcvar} is set, $1 is not "rcvar"
651101099Srwatson					# and ${rc_pid} is not set, then run
652101099Srwatson					#	checkyesno ${rcvar}
653101099Srwatson					# and return if that failed
654156300Sdwmalone					#
655101099Srwatson		if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
656101099Srwatson		    [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
657101099Srwatson			if ! checkyesno ${rcvar}; then
658101099Srwatson				if [ -n "${rc_quiet}" ]; then
659101099Srwatson					return 0
660101099Srwatson				fi
661101099Srwatson				echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
662101099Srwatson				echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
663101099Srwatson				echo "instead of '${rc_arg}'."
664156300Sdwmalone				return 0
665101099Srwatson			fi
666101099Srwatson		fi
667156300Sdwmalone
668101099Srwatson					# if there's a custom ${XXX_cmd},
669101099Srwatson					# run that instead of the default
670101099Srwatson					#
671101099Srwatson		eval _cmd=\$${rc_arg}_cmd \
672101099Srwatson		     _precmd=\$${rc_arg}_precmd \
673101099Srwatson		     _postcmd=\$${rc_arg}_postcmd
674101099Srwatson
675101099Srwatson		if [ -n "$_cmd" ]; then
676101099Srwatson			_run_rc_precmd || return 1
677101099Srwatson			_run_rc_doit "$_cmd $rc_extra_args" || return 1
678101099Srwatson			_run_rc_postcmd
679156300Sdwmalone			return $_return
680101099Srwatson		fi
681101099Srwatson
682101099Srwatson		case "$rc_arg" in	# default operations...
683156300Sdwmalone
684156300Sdwmalone		status)
685101099Srwatson			_run_rc_precmd || return 1
686101099Srwatson			if [ -n "$rc_pid" ]; then
687101099Srwatson				echo "${name} is running as pid $rc_pid."
688101099Srwatson			else
689101099Srwatson				echo "${name} is not running."
690101099Srwatson				return 1
691101099Srwatson			fi
692101099Srwatson			_run_rc_postcmd
693101099Srwatson			;;
694156300Sdwmalone
695101099Srwatson		start)
696101099Srwatson			if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
697101099Srwatson				echo 1>&2 "${name} already running? (pid=$rc_pid)."
698101099Srwatson				return 1
699101099Srwatson			fi
700101099Srwatson
701101099Srwatson			if [ ! -x ${_chroot}${_chroot:+"/"}${command} ]; then
702156300Sdwmalone				warn "run_rc_command: cannot run $command"
703101099Srwatson				return 1
704101099Srwatson			fi
705101099Srwatson
706101099Srwatson			if ! _run_rc_precmd; then
707101099Srwatson				warn "failed precmd routine for ${name}"
708101099Srwatson				return 1
709101099Srwatson			fi
710156300Sdwmalone
711101099Srwatson					# setup the full command to run
712101099Srwatson					#
713101099Srwatson			check_startmsgs && echo "Starting ${name}."
714101099Srwatson			if [ -n "$_chroot" ]; then
715101099Srwatson				_doit="\
716101099Srwatson${_nice:+nice -n $_nice }\
717101099Srwatsonchroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
718156300Sdwmalone$_chroot $command $rc_flags $command_args"
719101099Srwatson			else
720101099Srwatson				_doit="\
721101099Srwatson${_chdir:+cd $_chdir && }\
722101099Srwatson$command $rc_flags $command_args"
723101099Srwatson				if [ -n "$_user" ]; then
724101099Srwatson				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
725101099Srwatson				fi
726156300Sdwmalone				if [ -n "$_nice" ]; then
727101099Srwatson					if [ -z "$_user" ]; then
728101099Srwatson						_doit="sh -c \"$_doit\""
729101099Srwatson					fi
730101099Srwatson					_doit="nice -n $_nice $_doit"
731101099Srwatson				fi
732101099Srwatson			fi
733101099Srwatson
734156300Sdwmalone					# run the full command
735101099Srwatson					#
736101099Srwatson			if ! _run_rc_doit "$_doit"; then
737101099Srwatson				warn "failed to start ${name}"
738101099Srwatson				return 1
739101099Srwatson			fi
740101099Srwatson
741101099Srwatson					# finally, run postcmd
742156300Sdwmalone					#
743101099Srwatson			_run_rc_postcmd
744101099Srwatson			;;
745101099Srwatson
746102129Srwatson		stop)
747102129Srwatson			if [ -z "$rc_pid" ]; then
748101099Srwatson				[ -n "$rc_fast" ] && return 0
749101099Srwatson				_run_rc_notrunning
750156300Sdwmalone				return 1
751101099Srwatson			fi
752101099Srwatson
753106217Srwatson			_run_rc_precmd || return 1
754101099Srwatson
755106217Srwatson					# send the signal to stop
756106217Srwatson					#
757112575Srwatson			echo "Stopping ${name}."
758106217Srwatson			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
759106217Srwatson			_run_rc_doit "$_doit" || return 1
760106217Srwatson
761106217Srwatson					# wait for the command to exit,
762106217Srwatson					# and run postcmd.
763106217Srwatson			wait_for_pids $rc_pid
764119202Srwatson
765106217Srwatson			_run_rc_postcmd
766106217Srwatson			;;
767106217Srwatson
768106217Srwatson		reload)
769119202Srwatson			if [ -z "$rc_pid" ]; then
770106217Srwatson				_run_rc_notrunning
771106217Srwatson				return 1
772106217Srwatson			fi
773106217Srwatson
774106217Srwatson			_run_rc_precmd || return 1
775106217Srwatson
776106217Srwatson			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
777106217Srwatson			_run_rc_doit "$_doit" || return 1
778106217Srwatson
779106217Srwatson			_run_rc_postcmd
780106217Srwatson			;;
781106217Srwatson
782106217Srwatson		restart)
783106217Srwatson					# prevent restart being called more
784101099Srwatson					# than once by any given script
785101099Srwatson					#
786112717Srwatson			if ${_rc_restart_done:-false}; then
787101099Srwatson				return 0
788			fi
789			_rc_restart_done=true
790
791			_run_rc_precmd || return 1
792
793			# run those in a subshell to keep global variables
794			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
795			( run_rc_command ${_rc_prefix}start $rc_extra_args )
796			_return=$?
797			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
798
799			_run_rc_postcmd
800			;;
801
802		poll)
803			_run_rc_precmd || return 1
804			if [ -n "$rc_pid" ]; then
805				wait_for_pids $rc_pid
806			fi
807			_run_rc_postcmd
808			;;
809
810		rcvar)
811			echo -n "# $name"
812			if [ -n "$desc" ]; then
813				echo " : $desc"
814			else
815				echo ""
816			fi
817			echo "#"
818			# Get unique vars in $rcvar
819			for _v in $rcvar; do
820				case $v in
821				$_v\ *|\ *$_v|*\ $_v\ *) ;;
822				*)	v="${v# } $_v" ;;
823				esac
824			done
825
826			# Display variables.
827			for _v in $v; do
828				if [ -z "$_v" ]; then
829					continue
830				fi
831
832				eval _desc=\$${_v}_desc
833				eval _defval=\$${_v}_defval
834				_h="-"
835
836				eval echo \"$_v=\\\"\$$_v\\\"\"
837				# decode multiple lines of _desc
838				while [ -n "$_desc" ]; do
839					case $_desc in
840					*^^*)
841						echo "# $_h ${_desc%%^^*}"
842						_desc=${_desc#*^^}
843						_h=" "
844						;;
845					*)
846						echo "# $_h ${_desc}"
847						break
848						;;
849					esac
850				done
851				echo "#   (default: \"$_defval\")"
852			done
853			echo ""
854			;;
855
856		*)
857			rc_usage $_keywords
858			;;
859
860		esac
861		return $_return
862	done
863
864	echo 1>&2 "$0: unknown directive '$rc_arg'."
865	rc_usage $_keywords
866	# not reached
867}
868
869#
870# Helper functions for run_rc_command: common code.
871# They use such global variables besides the exported rc_* ones:
872#
873#	name	       R/W
874#	------------------
875#	_precmd		R
876#	_postcmd	R
877#	_return		W
878#
879_run_rc_precmd()
880{
881	check_required_before "$rc_arg" || return 1
882
883	if [ -n "$_precmd" ]; then
884		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
885		eval "$_precmd $rc_extra_args"
886		_return=$?
887
888		# If precmd failed and force isn't set, request exit.
889		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
890			return 1
891		fi
892	fi
893
894	check_required_after "$rc_arg" || return 1
895
896	return 0
897}
898
899_run_rc_postcmd()
900{
901	if [ -n "$_postcmd" ]; then
902		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
903		eval "$_postcmd $rc_extra_args"
904		_return=$?
905	fi
906	return 0
907}
908
909_run_rc_doit()
910{
911	debug "run_rc_command: doit: $*"
912	eval "$@"
913	_return=$?
914
915	# If command failed and force isn't set, request exit.
916	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
917		return 1
918	fi
919
920	return 0
921}
922
923_run_rc_notrunning()
924{
925	local _pidmsg
926
927	if [ -n "$pidfile" ]; then
928		_pidmsg=" (check $pidfile)."
929	else
930		_pidmsg=
931	fi
932	echo 1>&2 "${name} not running?${_pidmsg}"
933}
934
935_run_rc_killcmd()
936{
937	local _cmd
938
939	_cmd="kill -$1 $rc_pid"
940	if [ -n "$_user" ]; then
941		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
942	fi
943	echo "$_cmd"
944}
945
946#
947# run_rc_script file arg
948#	Start the script `file' with `arg', and correctly handle the
949#	return value from the script.
950#	If `file' ends with `.sh', it's sourced into the current environment
951#	when $rc_fast_and_loose is set, otherwise it is run as a child process.
952#	If `file' appears to be a backup or scratch file, ignore it.
953#	Otherwise if it is executable run as a child process.
954#
955run_rc_script()
956{
957	_file=$1
958	_arg=$2
959	if [ -z "$_file" -o -z "$_arg" ]; then
960		err 3 'USAGE: run_rc_script file arg'
961	fi
962
963	unset	name command command_args command_interpreter \
964		extra_commands pidfile procname \
965		rcvar rcvars_obsolete required_dirs required_files \
966		required_vars
967	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
968
969	case "$_file" in
970	/etc/rc.d/*.sh)			# no longer allowed in the base
971		warn "Ignoring old-style startup script $_file"
972		;;
973	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
974		warn "Ignoring scratch file $_file"
975		;;
976	*)				# run in subshell
977		if [ -x $_file ]; then
978			if [ -n "$rc_fast_and_loose" ]; then
979				set $_arg; . $_file
980			else
981				( trap "echo Script $_file interrupted; kill -QUIT $$" 3
982				  trap "echo Script $_file interrupted; exit 1" 2
983				  trap "echo Script $_file running" 29
984				  set $_arg; . $_file )
985			fi
986		fi
987		;;
988	esac
989}
990
991#
992# load_rc_config name
993#	Source in the configuration file for a given name.
994#
995load_rc_config()
996{
997	local _name _rcvar_val _var _defval _v _msg _new
998	_name=$1
999	if [ -z "$_name" ]; then
1000		err 3 'USAGE: load_rc_config name'
1001	fi
1002
1003	if ${_rc_conf_loaded:-false}; then
1004		:
1005	else
1006		if [ -r /etc/defaults/rc.conf ]; then
1007			debug "Sourcing /etc/defaults/rc.conf"
1008			. /etc/defaults/rc.conf
1009			source_rc_confs
1010		elif [ -r /etc/rc.conf ]; then
1011			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1012			. /etc/rc.conf
1013		fi
1014		_rc_conf_loaded=true
1015	fi
1016	if [ -f /etc/rc.conf.d/"$_name" ]; then
1017		debug "Sourcing /etc/rc.conf.d/${_name}"
1018		. /etc/rc.conf.d/"$_name"
1019	fi
1020
1021	# Set defaults if defined.
1022	for _var in $rcvar; do
1023		eval _defval=\$${_var}_defval
1024		if [ -n "$_defval" ]; then
1025			eval : \${$_var:=\$${_var}_defval}
1026		fi
1027	done
1028
1029	# check obsolete rc.conf variables
1030	for _var in $rcvars_obsolete; do
1031		eval _v=\$$_var
1032		eval _msg=\$${_var}_obsolete_msg
1033		eval _new=\$${_var}_newvar
1034		case $_v in
1035		"")
1036			;;
1037		*)
1038			if [ -z "$_new" ]; then
1039				_msg="Ignored."
1040			else
1041				eval $_new=\"\$$_var\"
1042				if [ -z "$_msg" ]; then
1043					_msg="Use \$$_new instead."
1044				fi
1045			fi
1046			warn "\$$_var is obsolete.  $_msg"
1047			;;
1048		esac
1049	done
1050}
1051
1052#
1053# load_rc_config_var name var
1054#	Read the rc.conf(5) var for name and set in the
1055#	current shell, using load_rc_config in a subshell to prevent
1056#	unwanted side effects from other variable assignments.
1057#
1058load_rc_config_var()
1059{
1060	if [ $# -ne 2 ]; then
1061		err 3 'USAGE: load_rc_config_var name var'
1062	fi
1063	eval $(eval '(
1064		load_rc_config '$1' >/dev/null;
1065                if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1066			echo '$2'=\'\''${'$2'}\'\'';
1067		fi
1068	)' )
1069}
1070
1071#
1072# rc_usage commands
1073#	Print a usage string for $0, with `commands' being a list of
1074#	valid commands.
1075#
1076rc_usage()
1077{
1078	echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1079
1080	_sep=
1081	for _elem; do
1082		echo -n 1>&2 "$_sep$_elem"
1083		_sep="|"
1084	done
1085	echo 1>&2 ")"
1086	exit 1
1087}
1088
1089#
1090# err exitval message
1091#	Display message to stderr and log to the syslog, and exit with exitval.
1092#
1093err()
1094{
1095	exitval=$1
1096	shift
1097
1098	if [ -x /usr/bin/logger ]; then
1099		logger "$0: ERROR: $*"
1100	fi
1101	echo 1>&2 "$0: ERROR: $*"
1102	exit $exitval
1103}
1104
1105#
1106# warn message
1107#	Display message to stderr and log to the syslog.
1108#
1109warn()
1110{
1111	if [ -x /usr/bin/logger ]; then
1112		logger "$0: WARNING: $*"
1113	fi
1114	echo 1>&2 "$0: WARNING: $*"
1115}
1116
1117#
1118# info message
1119#	Display informational message to stdout and log to syslog.
1120#
1121info()
1122{
1123	case ${rc_info} in
1124	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1125		if [ -x /usr/bin/logger ]; then
1126			logger "$0: INFO: $*"
1127		fi
1128		echo "$0: INFO: $*"
1129		;;
1130	esac
1131}
1132
1133#
1134# debug message
1135#	If debugging is enabled in rc.conf output message to stderr.
1136#	BEWARE that you don't call any subroutine that itself calls this
1137#	function.
1138#
1139debug()
1140{
1141	case ${rc_debug} in
1142	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1143		if [ -x /usr/bin/logger ]; then
1144			logger "$0: DEBUG: $*"
1145		fi
1146		echo 1>&2 "$0: DEBUG: $*"
1147		;;
1148	esac
1149}
1150
1151#
1152# backup_file action file cur backup
1153#	Make a backup copy of `file' into `cur', and save the previous
1154#	version of `cur' as `backup' or use rcs for archiving.
1155#
1156#	This routine checks the value of the backup_uses_rcs variable,
1157#	which can be either YES or NO.
1158#
1159#	The `action' keyword can be one of the following:
1160#
1161#	add		`file' is now being backed up (and is possibly
1162#			being reentered into the backups system).  `cur'
1163#			is created and RCS files, if necessary, are
1164#			created as well.
1165#
1166#	update		`file' has changed and needs to be backed up.
1167#			If `cur' exists, it is copied to to `back' or
1168#			checked into RCS (if the repository file is old),
1169#			and then `file' is copied to `cur'.  Another RCS
1170#			check in done here if RCS is being used.
1171#
1172#	remove		`file' is no longer being tracked by the backups
1173#			system.  If RCS is not being used, `cur' is moved
1174#			to `back', otherwise an empty file is checked in,
1175#			and then `cur' is removed.
1176#
1177#
1178backup_file()
1179{
1180	_action=$1
1181	_file=$2
1182	_cur=$3
1183	_back=$4
1184
1185	if checkyesno backup_uses_rcs; then
1186		_msg0="backup archive"
1187		_msg1="update"
1188
1189		# ensure that history file is not locked
1190		if [ -f $_cur,v ]; then
1191			rcs -q -u -U -M $_cur
1192		fi
1193
1194		# ensure after switching to rcs that the
1195		# current backup is not lost
1196		if [ -f $_cur ]; then
1197			# no archive, or current newer than archive
1198			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1199				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1200				rcs -q -kb -U $_cur
1201				co -q -f -u $_cur
1202			fi
1203		fi
1204
1205		case $_action in
1206		add|update)
1207			cp -p $_file $_cur
1208			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1209			rcs -q -kb -U $_cur
1210			co -q -f -u $_cur
1211			chown root:wheel $_cur $_cur,v
1212			;;
1213		remove)
1214			cp /dev/null $_cur
1215			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1216			rcs -q -kb -U $_cur
1217			chown root:wheel $_cur $_cur,v
1218			rm $_cur
1219			;;
1220		esac
1221	else
1222		case $_action in
1223		add|update)
1224			if [ -f $_cur ]; then
1225				cp -p $_cur $_back
1226			fi
1227			cp -p $_file $_cur
1228			chown root:wheel $_cur
1229			;;
1230		remove)
1231			mv -f $_cur $_back
1232			;;
1233		esac
1234	fi
1235}
1236
1237# make_symlink src link
1238#	Make a symbolic link 'link' to src from basedir. If the
1239#	directory in which link is to be created does not exist
1240#	a warning will be displayed and an error will be returned.
1241#	Returns 0 on success, 1 otherwise.
1242#
1243make_symlink()
1244{
1245	local src link linkdir _me
1246	src="$1"
1247	link="$2"
1248	linkdir="`dirname $link`"
1249	_me="make_symlink()"
1250
1251	if [ -z "$src" -o -z "$link" ]; then
1252		warn "$_me: requires two arguments."
1253		return 1
1254	fi
1255	if [ ! -d "$linkdir" ]; then
1256		warn "$_me: the directory $linkdir does not exist."
1257		return 1
1258	fi
1259	if ! ln -sf $src $link; then
1260		warn "$_me: unable to make a symbolic link from $link to $src"
1261		return 1
1262	fi
1263	return 0
1264}
1265
1266# devfs_rulesets_from_file file
1267#	Reads a set of devfs commands from file, and creates
1268#	the specified rulesets with their rules. Returns non-zero
1269#	if there was an error.
1270#
1271devfs_rulesets_from_file()
1272{
1273	local file _err _me
1274	file="$1"
1275	_me="devfs_rulesets_from_file"
1276	_err=0
1277
1278	if [ -z "$file" ]; then
1279		warn "$_me: you must specify a file"
1280		return 1
1281	fi
1282	if [ ! -e "$file" ]; then
1283		debug "$_me: no such file ($file)"
1284		return 0
1285	fi
1286	debug "reading rulesets from file ($file)"
1287	{ while read line
1288	do
1289		case $line in
1290		\#*)
1291			continue
1292			;;
1293		\[*\]*)
1294			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1295			if [ -z "$rulenum" ]; then
1296				warn "$_me: cannot extract rule number ($line)"
1297				_err=1
1298				break
1299			fi
1300			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1301			if [ -z "$rulename" ]; then
1302				warn "$_me: cannot extract rule name ($line)"
1303				_err=1
1304				break;
1305			fi
1306			eval $rulename=\$rulenum
1307			debug "found ruleset: $rulename=$rulenum"
1308			if ! /sbin/devfs rule -s $rulenum delset; then
1309				_err=1
1310				break
1311			fi
1312			;;
1313		*)
1314			rulecmd="${line%%"\#*"}"
1315			# evaluate the command incase it includes
1316			# other rules
1317			if [ -n "$rulecmd" ]; then
1318				debug "adding rule ($rulecmd)"
1319				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1320				then
1321					_err=1
1322					break
1323				fi
1324			fi
1325			;;
1326		esac
1327		if [ $_err -ne 0 ]; then
1328			debug "error in $_me"
1329			break
1330		fi
1331	done } < $file
1332	return $_err
1333}
1334
1335# devfs_init_rulesets
1336#	Initializes rulesets from configuration files. Returns
1337#	non-zero if there was an error.
1338#
1339devfs_init_rulesets()
1340{
1341	local file _me
1342	_me="devfs_init_rulesets"
1343
1344	# Go through this only once
1345	if [ -n "$devfs_rulesets_init" ]; then
1346		debug "$_me: devfs rulesets already initialized"
1347		return
1348	fi
1349	for file in $devfs_rulesets; do
1350		if ! devfs_rulesets_from_file $file; then
1351			warn "$_me: could not read rules from $file"
1352			return 1
1353		fi
1354	done
1355	devfs_rulesets_init=1
1356	debug "$_me: devfs rulesets initialized"
1357	return 0
1358}
1359
1360# devfs_set_ruleset ruleset [dir]
1361#	Sets the default ruleset of dir to ruleset. The ruleset argument
1362#	must be a ruleset name as specified in devfs.rules(5) file.
1363#	Returns non-zero if it could not set it successfully.
1364#
1365devfs_set_ruleset()
1366{
1367	local devdir rs _me
1368	[ -n "$1" ] && eval rs=\$$1 || rs=
1369	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1370	_me="devfs_set_ruleset"
1371
1372	if [ -z "$rs" ]; then
1373		warn "$_me: you must specify a ruleset number"
1374		return 1
1375	fi
1376	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1377	if ! /sbin/devfs $devdir ruleset $rs; then
1378		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1379		return 1
1380	fi
1381	return 0
1382}
1383
1384# devfs_apply_ruleset ruleset [dir]
1385#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1386#	The ruleset argument must be a ruleset name as specified
1387#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1388#	if it could not apply the ruleset.
1389#
1390devfs_apply_ruleset()
1391{
1392	local devdir rs _me
1393	[ -n "$1" ] && eval rs=\$$1 || rs=
1394	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1395	_me="devfs_apply_ruleset"
1396
1397	if [ -z "$rs" ]; then
1398		warn "$_me: you must specify a ruleset"
1399		return 1
1400	fi
1401	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1402	if ! /sbin/devfs $devdir rule -s $rs applyset; then
1403		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1404		return 1
1405	fi
1406	return 0
1407}
1408
1409# devfs_domount dir [ruleset]
1410#	Mount devfs on dir. If ruleset is specified it is set
1411#	on the mount-point. It must also be a ruleset name as specified
1412#	in a devfs.rules(5) file. Returns 0 on success.
1413#
1414devfs_domount()
1415{
1416	local devdir rs _me
1417	devdir="$1"
1418	[ -n "$2" ] && rs=$2 || rs=
1419	_me="devfs_domount()"
1420
1421	if [ -z "$devdir" ]; then
1422		warn "$_me: you must specify a mount-point"
1423		return 1
1424	fi
1425	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1426	if ! mount -t devfs dev "$devdir"; then
1427		warn "$_me: Unable to mount devfs on $devdir"
1428		return 1
1429	fi
1430	if [ -n "$rs" ]; then
1431		devfs_init_rulesets
1432		devfs_set_ruleset $rs $devdir
1433		devfs -m $devdir rule applyset
1434	fi
1435	return 0
1436}
1437
1438# devfs_mount_jail dir [ruleset]
1439#	Mounts a devfs file system appropriate for jails
1440#	on the directory dir. If ruleset is specified, the ruleset
1441#	it names will be used instead.  If present, ruleset must
1442#	be the name of a ruleset as defined in a devfs.rules(5) file.
1443#	This function returns non-zero if an error occurs.
1444#
1445devfs_mount_jail()
1446{
1447	local jdev rs _me
1448	jdev="$1"
1449	[ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1450	_me="devfs_mount_jail"
1451
1452	devfs_init_rulesets
1453	if ! devfs_domount "$jdev" $rs; then
1454		warn "$_me: devfs was not mounted on $jdev"
1455		return 1
1456	fi
1457	return 0
1458}
1459
1460# Provide a function for normalizing the mounting of memory
1461# filesystems.  This should allow the rest of the code here to remain
1462# as close as possible between 5-current and 4-stable.
1463#   $1 = size
1464#   $2 = mount point
1465#   $3 = (optional) extra mdmfs flags
1466mount_md()
1467{
1468	if [ -n "$3" ]; then
1469		flags="$3"
1470	fi
1471	/sbin/mdmfs $flags -s $1 md $2
1472}
1473
1474# Code common to scripts that need to load a kernel module
1475# if it isn't in the kernel yet. Syntax:
1476#   load_kld [-e regex] [-m module] file
1477# where -e or -m chooses the way to check if the module
1478# is already loaded:
1479#   regex is egrep'd in the output from `kldstat -v',
1480#   module is passed to `kldstat -m'.
1481# The default way is as though `-m file' were specified.
1482load_kld()
1483{
1484	local _loaded _mod _opt _re
1485
1486	while getopts "e:m:" _opt; do
1487		case "$_opt" in
1488		e) _re="$OPTARG" ;;
1489		m) _mod="$OPTARG" ;;
1490		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1491		esac
1492	done
1493	shift $(($OPTIND - 1))
1494	if [ $# -ne 1 ]; then
1495		err 3 'USAGE: load_kld [-e regex] [-m module] file'
1496	fi
1497	_mod=${_mod:-$1}
1498	_loaded=false
1499	if [ -n "$_re" ]; then
1500		if kldstat -v | egrep -q -e "$_re"; then
1501			_loaded=true
1502		fi
1503	else
1504		if kldstat -q -m "$_mod"; then
1505			_loaded=true
1506		fi
1507	fi
1508	if ! $_loaded; then
1509		if ! kldload "$1"; then
1510			warn "Unable to load kernel module $1"
1511			return 1
1512		else
1513			info "$1 kernel module loaded."
1514		fi
1515	else
1516		debug "load_kld: $1 kernel module already loaded."
1517	fi
1518	return 0
1519}
1520
1521# ltr str src dst
1522#	Change every $src in $str to $dst.
1523#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1524#	awk(1).
1525ltr()
1526{
1527	local _str _src _dst _out _com
1528	_str=$1
1529	_src=$2
1530	_dst=$3
1531	_out=""
1532
1533	IFS=${_src}
1534	for _com in ${_str}; do
1535		if [ -z "${_out}" ]; then
1536			_out="${_com}"
1537		else
1538			_out="${_out}${_dst}${_com}"
1539		fi
1540	done
1541	echo "${_out}"
1542}
1543
1544# Creates a list of providers for GELI encryption.
1545geli_make_list()
1546{
1547	local devices devices2
1548	local provider mountpoint type options rest
1549
1550	# Create list of GELI providers from fstab.
1551	while read provider mountpoint type options rest ; do
1552		case ":${options}" in
1553		:*noauto*)
1554			noauto=yes
1555			;;
1556		*)
1557			noauto=no
1558			;;
1559		esac
1560
1561		case ":${provider}" in
1562		:#*)
1563			continue
1564			;;
1565		*.eli)
1566			# Skip swap devices.
1567			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1568				continue
1569			fi
1570			devices="${devices} ${provider}"
1571			;;
1572		esac
1573	done < /etc/fstab
1574
1575	# Append providers from geli_devices.
1576	devices="${devices} ${geli_devices}"
1577
1578	for provider in ${devices}; do
1579		provider=${provider%.eli}
1580		provider=${provider#/dev/}
1581		devices2="${devices2} ${provider}"
1582	done
1583
1584	echo ${devices2}
1585}
1586
1587# Find scripts in local_startup directories that use the old syntax
1588#
1589find_local_scripts_old () {
1590	zlist=''
1591	slist=''
1592	for dir in ${local_startup}; do
1593		if [ -d "${dir}" ]; then
1594			for file in ${dir}/[0-9]*.sh; do
1595				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1596				    continue
1597				zlist="$zlist $file"
1598			done
1599			for file in ${dir}/[!0-9]*.sh; do
1600				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1601				    continue
1602				slist="$slist $file"
1603			done
1604		fi
1605	done
1606}
1607
1608find_local_scripts_new () {
1609	local_rc=''
1610	for dir in ${local_startup}; do
1611		if [ -d "${dir}" ]; then
1612			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1613				case "$file" in
1614				*.sample) ;;
1615				*)	if [ -x "$file" ]; then
1616						local_rc="${local_rc} ${file}"
1617					fi
1618					;;
1619				esac
1620			done
1621		fi
1622	done
1623}
1624
1625# check_required_{before|after} command
1626#	Check for things required by the command before and after its precmd,
1627#	respectively.  The two separate functions are needed because some
1628#	conditions should prevent precmd from being run while other things
1629#	depend on precmd having already been run.
1630#
1631check_required_before()
1632{
1633	local _f
1634
1635	case "$1" in
1636	start)
1637		for _f in $required_vars; do
1638			if ! checkyesno $_f; then
1639				warn "\$${_f} is not enabled."
1640				if [ -z "$rc_force" ]; then
1641					return 1
1642				fi
1643			fi
1644		done
1645
1646		for _f in $required_dirs; do
1647			if [ ! -d "${_f}/." ]; then
1648				warn "${_f} is not a directory."
1649				if [ -z "$rc_force" ]; then
1650					return 1
1651				fi
1652			fi
1653		done
1654
1655		for _f in $required_files; do
1656			if [ ! -r "${_f}" ]; then
1657				warn "${_f} is not readable."
1658				if [ -z "$rc_force" ]; then
1659					return 1
1660				fi
1661			fi
1662		done
1663		;;
1664	esac
1665
1666	return 0
1667}
1668
1669check_required_after()
1670{
1671	local _f _args
1672
1673	case "$1" in
1674	start)
1675		for _f in $required_modules; do
1676			case "${_f}" in
1677				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
1678				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
1679				*)	_args="${_f}" ;;
1680			esac
1681			if ! load_kld ${_args}; then
1682				if [ -z "$rc_force" ]; then
1683					return 1
1684				fi
1685			fi
1686		done
1687		;;
1688	esac
1689
1690	return 0
1691}
1692
1693# check_kern_features mib
1694#	Return existence of kern.features.* sysctl MIB as true or
1695#	false.  The result will be cached in $_rc_cache_kern_features_
1696#	namespace.  "0" means the kern.features.X exists.
1697
1698check_kern_features()
1699{
1700	local _v
1701
1702	[ -n "$1" ] || return 1;
1703	eval _v=\$_rc_cache_kern_features_$1
1704	[ -n "$_v" ] && return "$_v";
1705
1706	if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1707		eval _rc_cache_kern_features_$1=0
1708		return 0
1709	else
1710		eval _rc_cache_kern_features_$1=1
1711		return 1
1712	fi
1713}
1714
1715# _echoonce var msg mode
1716#	mode=0: Echo $msg if ${$var} is empty.
1717#	        After doing echo, a string is set to ${$var}.
1718#
1719#	mode=1: Echo $msg if ${$var} is a string with non-zero length.
1720#
1721_echoonce()
1722{
1723	local _var _msg _mode
1724	eval _var=\$$1
1725	_msg=$2
1726	_mode=$3
1727
1728	case $_mode in
1729	1)	[ -n "$_var" ] && echo "$_msg" ;;
1730	*)	[ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1731	esac
1732}
1733
1734fi # [ -z "${_rc_subr_loaded}" ]
1735
1736_rc_subr_loaded=:
1737