rc.subr revision 139949
1# $NetBSD: rc.subr,v 1.60 2003/07/26 05:13:47 lukem Exp $
2# $FreeBSD: head/etc/rc.subr 139949 2005-01-09 23:46:37Z keramida $
3#
4# Copyright (c) 1997-2002 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# 3. All advertising materials mentioning features or use of this software
19#    must display the following acknowledgement:
20#        This product includes software developed by the NetBSD
21#        Foundation, Inc. and its contributors.
22# 4. Neither the name of The NetBSD Foundation nor the names of its
23#    contributors may be used to endorse or promote products derived
24#    from this software without specific prior written permission.
25#
26# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36# POSSIBILITY OF SUCH DAMAGE.
37#
38# rc.subr
39#	functions used by various rc scripts
40#
41
42#
43#	Operating System dependent/independent variables
44#
45
46if [ -z "${_rc_subr_loaded}" ]; then
47
48_rc_subr_loaded="YES"
49
50SYSCTL="/sbin/sysctl"
51SYSCTL_N="${SYSCTL} -n"
52CMD_OSTYPE="${SYSCTL_N} kern.ostype"
53OSTYPE=`${CMD_OSTYPE}`
54ID="/usr/bin/id"
55IDCMD="if [ -x $ID ]; then $ID -un; fi"
56
57case ${OSTYPE} in
58FreeBSD)
59	SYSCTL_W="${SYSCTL}"
60	;;
61NetBSD)
62	SYSCTL_W="${SYSCTL} -w"
63	;;
64esac
65
66#
67#	functions
68#	---------
69
70#
71# set_rcvar base_var
72#	Set the variable name enabling a specific service.
73#	FreeBSD uses ${service}_enable, while NetBSD uses
74#	just the name of the service. For example:
75#	FreeBSD: sendmail_enable="YES"
76#	NetBSD : sendmail="YES"
77#	$1 - if $name is not the base to work of off, specify
78#	     a different one
79#
80set_rcvar()
81{
82	if [ -z "$1" ]; then
83		base_var=${name}
84	else
85		base_var="$1"
86	fi
87
88	case ${OSTYPE} in
89	FreeBSD)
90		echo ${base_var}_enable
91		;;
92	NetBSD)
93		echo ${base_var}
94		;;
95	*)
96		echo 'XXX'
97		;;
98	esac
99}
100
101#
102# force_depend script
103#	Force a service to start. Intended for use by services
104#	to resolve dependency issues. It is assumed the caller
105#	has check to make sure this call is necessary
106#	$1 - filename of script, in /etc/rc.d, to run
107#
108force_depend()
109{
110	_depend="$1"
111
112	info "${name} depends on ${_depend}, which will be forced to start."
113	if ! /etc/rc.d/${_depend} forcestart ; then
114		warn "Unable to force ${_depend}. It may already be running."
115		return 1
116	fi
117	return 0
118}
119
120#
121# checkyesno var
122#	Test $1 variable, and warn if not set to YES or NO.
123#	Return 0 if it's "yes" (et al), nonzero otherwise.
124#
125checkyesno()
126{
127	eval _value=\$${1}
128	debug "checkyesno: $1 is set to $_value."
129	case $_value in
130
131		#	"yes", "true", "on", or "1"
132	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
133		return 0
134		;;
135
136		#	"no", "false", "off", or "0"
137	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
138		return 1
139		;;
140	*)
141		warn "\$${1} is not set properly - see rc.conf(5)."
142		return 1
143		;;
144	esac
145}
146
147# reverse_list list
148#	print the list in reverse order
149#
150reverse_list()
151{
152	_revlist=
153	for _revfile; do
154		_revlist="$_revfile $_revlist"
155	done
156	echo $_revlist
157}
158
159#
160# mount_critical_filesystems type
161#	Go through the list of critical filesystems as provided in
162#	the rc.conf(5) variable $critical_filesystems_${type}, checking
163#	each one to see if it is mounted, and if it is not, mounting it.
164#
165mount_critical_filesystems()
166{
167	eval _fslist=\$critical_filesystems_${1}
168	for _fs in $_fslist; do
169		mount | (
170			_ismounted=false
171			while read what _on on _type type; do
172				if [ $on = $_fs ]; then
173					_ismounted=true
174				fi
175			done
176			if $_ismounted; then
177				:
178			else
179				mount $_fs >/dev/null 2>&1
180			fi
181		)
182	done
183}
184
185#
186# check_pidfile pidfile procname [interpreter]
187#	Parses the first line of pidfile for a PID, and ensures
188#	that the process is running and matches procname.
189#	Prints the matching PID upon success, nothing otherwise.
190#	interpreter is optional; see _find_processes() for details.
191#
192check_pidfile()
193{
194	_pidfile=$1
195	_procname=$2
196	_interpreter=$3
197	if [ -z "$_pidfile" -o -z "$_procname" ]; then
198		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
199	fi
200	if [ ! -f $_pidfile ]; then
201		debug "pid file ($_pidfile): not readable."
202		return
203	fi
204	read _pid _junk < $_pidfile
205	if [ -z "$_pid" ]; then
206		debug "pid file ($_pidfile): no pid in file."
207		return
208	fi
209	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
210}
211
212#
213# check_process procname [interpreter]
214#	Ensures that a process (or processes) named procname is running.
215#	Prints a list of matching PIDs.
216#	interpreter is optional; see _find_processes() for details.
217#
218check_process()
219{
220	_procname=$1
221	_interpreter=$2
222	if [ -z "$_procname" ]; then
223		err 3 'USAGE: check_process procname [interpreter]'
224	fi
225	_find_processes $_procname ${_interpreter:-.} '-ax'
226}
227
228#
229# _find_processes procname interpreter psargs
230#	Search for procname in the output of ps generated by psargs.
231#	Prints the PIDs of any matching processes, space separated.
232#
233#	If interpreter == ".", check the following variations of procname
234#	against the first word of each command:
235#		procname
236#		`basename procname`
237#		`basename procname` + ":"
238#		"(" + `basename procname` + ")"
239#
240#	If interpreter != ".", read the first line of procname, remove the
241#	leading #!, normalise whitespace, append procname, and attempt to
242#	match that against each command, either as is, or with extra words
243#	at the end.
244#
245_find_processes()
246{
247	if [ $# -ne 3 ]; then
248		err 3 'USAGE: _find_processes procname interpreter psargs'
249	fi
250	_procname=$1
251	_interpreter=$2
252	_psargs=$3
253
254	_pref=
255	if [ $_interpreter != "." ]; then	# an interpreted script
256		read _interp < $_procname	# read interpreter name
257		_interp=${_interp#\#!}		# strip #!
258		set -- $_interp
259		if [ $_interpreter != $1 ]; then
260			warn "\$command_interpreter $_interpreter != $1"
261		fi
262		_interp="$* $_procname"		# cleanup spaces, add _procname
263		_fp_args='_argv'
264		_fp_match='case "$_argv" in
265		    ${_interp}|"${_interp} "*)'
266	else					# a normal daemon
267		_procnamebn=${_procname##*/}
268		_fp_args='_arg0 _argv'
269		_fp_match='case "$_arg0" in
270		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")'
271	fi
272
273	_proccheck='
274		ps 2>/dev/null -o "pid,command" '"$_psargs"' |
275		while read _npid '"$_fp_args"'; do
276			case "$_npid" in
277			    PID)
278				continue ;;
279			esac ; '"$_fp_match"'
280				echo -n "$_pref$_npid" ;
281				_pref=" "
282				;;
283			esac
284		done'
285
286#	debug "in _find_processes: proccheck is ($_proccheck)."
287	eval $_proccheck
288}
289
290#
291# wait_for_pids pid [pid ...]
292#	spins until none of the pids exist
293#
294wait_for_pids()
295{
296	_list="$@"
297	if [ -z "$_list" ]; then
298		return
299	fi
300	_prefix=
301	while true; do
302		_nlist="";
303		for _j in $_list; do
304			if kill -0 $_j 2>/dev/null; then
305				_nlist="${_nlist}${_nlist:+ }$_j"
306			fi
307		done
308		if [ -z "$_nlist" ]; then
309			break
310		fi
311		_list=$_nlist
312		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
313		_prefix=", "
314		sleep 2
315	done
316	if [ -n "$_prefix" ]; then
317		echo "."
318	fi
319}
320
321#
322# run_rc_command argument
323#	Search for argument in the list of supported commands, which is:
324#		"start stop restart rcvar status poll ${extra_commands}"
325#	If there's a match, run ${argument}_cmd or the default method
326#	(see below).
327#
328#	If argument has a given prefix, then change the operation as follows:
329#		Prefix	Operation
330#		------	---------
331#		fast	Skip the pid check, and set rc_fast=yes
332#		force	Set ${rcvar} to YES, and set rc_force=yes
333#		one	Set ${rcvar} to YES
334#
335#	The following globals are used:
336#
337#	Name		Needed	Purpose
338#	----		------	-------
339#	name		y	Name of script.
340#
341#	command		n	Full path to command.
342#				Not needed if ${rc_arg}_cmd is set for
343#				each keyword.
344#
345#	command_args	n	Optional args/shell directives for command.
346#
347#	command_interpreter n	If not empty, command is interpreted, so
348#				call check_{pidfile,process}() appropriately.
349#
350#	extra_commands	n	List of extra commands supported.
351#
352#	pidfile		n	If set, use check_pidfile $pidfile $command,
353#				otherwise use check_process $command.
354#				In either case, only check if $command is set.
355#
356#	procname	n	Process name to check for instead of $command.
357#
358#	rcvar		n	This is checked with checkyesno to determine
359#				if the action should be run.
360#
361#	${name}_chroot	n	Directory to chroot to before running ${command}
362#				Requires /usr to be mounted.
363#
364#	${name}_chdir	n	Directory to cd to before running ${command}
365#				(if not using ${name}_chroot).
366#
367#	${name}_flags	n	Arguments to call ${command} with.
368#				NOTE:	$flags from the parent environment
369#					can be used to override this.
370#
371#	${name}_nice	n	Nice level to run ${command} at.
372#
373#	${name}_user	n	User to run ${command} as, using su(1) if not
374#				using ${name}_chroot.
375#				Requires /usr to be mounted.
376#
377#	${name}_group	n	Group to run chrooted ${command} as.
378#				Requires /usr to be mounted.
379#
380#	${name}_groups	n	Comma separated list of supplementary groups
381#				to run the chrooted ${command} with.
382#				Requires /usr to be mounted.
383#
384#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
385#				Otherwise, use default command (see below)
386#
387#	${rc_arg}_precmd n	If set, run just before performing the
388#				${rc_arg}_cmd method in the default
389#				operation (i.e, after checking for required
390#				bits and process (non)existence).
391#				If this completes with a non-zero exit code,
392#				don't run ${rc_arg}_cmd.
393#
394#	${rc_arg}_postcmd n	If set, run just after performing the
395#				${rc_arg}_cmd method, if that method
396#				returned a zero exit code.
397#
398#	required_dirs	n	If set, check for the existence of the given
399#				directories before running the default
400#				(re)start command.
401#
402#	required_files	n	If set, check for the readability of the given
403#				files before running the default (re)start
404#				command.
405#
406#	required_vars	n	If set, perform checkyesno on each of the
407#				listed variables before running the default
408#				(re)start command.
409#
410#	Default behaviour for a given argument, if no override method is
411#	provided:
412#
413#	Argument	Default behaviour
414#	--------	-----------------
415#	start		if !running && checkyesno ${rcvar}
416#				${command}
417#
418#	stop		if ${pidfile}
419#				rc_pid=$(check_pidfile $pidfile $command)
420#			else
421#				rc_pid=$(check_process $command)
422#			kill $sig_stop $rc_pid
423#			wait_for_pids $rc_pid
424#			($sig_stop defaults to TERM.)
425#
426#	reload		Similar to stop, except use $sig_reload instead,
427#			and doesn't wait_for_pids.
428#			$sig_reload defaults to HUP.
429#
430#	restart		Run `stop' then `start'.
431#
432#	status		Show if ${command} is running, etc.
433#
434#	poll		Wait for ${command} to exit.
435#
436#	rcvar		Display what rc.conf variable is used (if any).
437#
438#	Variables available to methods, and after run_rc_command() has
439#	completed:
440#
441#	Variable	Purpose
442#	--------	-------
443#	rc_arg		Argument to command, after fast/force/one processing
444#			performed
445#
446#	rc_flags	Flags to start the default command with.
447#			Defaults to ${name}_flags, unless overridden
448#			by $flags from the environment.
449#			This variable may be changed by the precmd method.
450#
451#	rc_pid		PID of command (if appropriate)
452#
453#	rc_fast		Not empty if "fast" was provided (q.v.)
454#
455#	rc_force	Not empty if "force" was provided (q.v.)
456#
457#
458run_rc_command()
459{
460	_return=0
461	rc_arg=$1
462	if [ -z "$name" ]; then
463		err 3 'run_rc_command: $name is not set.'
464	fi
465
466	# Don't repeat the first argument when passing additional command-
467	# line arguments to the command subroutines.
468	#
469	shift 1
470	rc_extra_args="$*"
471
472	_rc_prefix=
473	case "$rc_arg" in
474	fast*)				# "fast" prefix; don't check pid
475		rc_arg=${rc_arg#fast}
476		rc_fast=yes
477		;;
478	force*)				# "force prefix; always run
479		rc_force=yes
480		_rc_prefix=force
481		rc_arg=${rc_arg#${_rc_prefix}}
482		if [ -n "${rcvar}" ]; then
483			eval ${rcvar}=YES
484		fi
485		;;
486	one*)				# "one" prefix; set ${rcvar}=yes
487		_rc_prefix=one
488		rc_arg=${rc_arg#${_rc_prefix}}
489		if [ -n "${rcvar}" ]; then
490			eval ${rcvar}=YES
491		fi
492		;;
493	esac
494
495	eval _overide_command=\$${name}_program
496	if [ -n "$_overide_command" ]; then
497		command=$_overide_command
498	fi
499
500	_keywords="start stop restart rcvar $extra_commands"
501	rc_pid=
502	_pidcmd=
503	_procname=${procname:-${command}}
504
505					# setup pid check command
506	if [ -n "$_procname" ]; then
507		if [ -n "$pidfile" ]; then
508			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
509		else
510			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
511		fi
512		if [ -n "$_pidcmd" ]; then
513			_keywords="${_keywords} status poll"
514		fi
515	fi
516
517	if [ -z "$rc_arg" ]; then
518		rc_usage "$_keywords"
519	fi
520
521	if [ -n "$flags" ]; then	# allow override from environment
522		rc_flags=$flags
523	else
524		eval rc_flags=\$${name}_flags
525	fi
526	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
527	    _nice=\$${name}_nice	_user=\$${name}_user \
528	    _group=\$${name}_group	_groups=\$${name}_groups
529
530	if [ -n "$_user" ]; then	# unset $_user if running as that user
531		if [ "$_user" = "$(eval $IDCMD)" ]; then
532			unset _user
533		fi
534	fi
535
536					# if ${rcvar} is set, and $1 is not
537					# "rcvar", then run
538					#	checkyesno ${rcvar}
539					# and return if that failed
540					#
541	if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
542		if ! checkyesno ${rcvar}; then
543			return 0
544		fi
545	fi
546
547	eval $_pidcmd			# determine the pid if necessary
548
549	for _elem in $_keywords; do
550		if [ "$_elem" != "$rc_arg" ]; then
551			continue
552		fi
553
554					# if there's a custom ${XXX_cmd},
555					# run that instead of the default
556					#
557		eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \
558		    _postcmd=\$${rc_arg}_postcmd
559		if [ -n "$_cmd" ]; then
560					# if the precmd failed and force
561					# isn't set, exit
562					#
563			if [ -n "$_precmd" ]; then
564				debug "run_rc_command: evaluating ${_precmd}()."
565				eval $_precmd $rc_extra_args
566				_return=$?
567				[ $_return -ne 0 ] && [ -z "$rc_force" ] &&
568				    return 1
569			fi
570
571			if [ -n "$_cmd" ]; then
572				debug "run_rc_command: evaluating ${_cmd}()."
573				eval $_cmd $rc_extra_args
574				_return=$?
575				[ $_return -ne 0 ] && [ -z "$rc_force" ] &&
576				    return 1
577			fi
578
579			if [ -n "$_postcmd" ]; then
580				debug "run_rc_command: evaluating ${_postcmd}()."
581				 eval $_postcmd $rc_extra_args
582				_return=$?
583			fi
584			return $_return
585		fi
586
587		case "$rc_arg" in	# default operations...
588
589		status)
590			if [ -n "$rc_pid" ]; then
591				echo "${name} is running as pid $rc_pid."
592			else
593				echo "${name} is not running."
594				return 1
595			fi
596			;;
597
598		start)
599			if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
600				echo "${name} already running? (pid=$rc_pid)."
601				exit 1
602			fi
603
604			if [ ! -x ${_chroot}${command} ]; then
605				info "run_rc_command: cannot run ($command)."
606				return 0
607			fi
608
609					# check for required variables,
610					# directories, and files
611					#
612			for _f in $required_vars; do
613				if ! checkyesno $_f; then
614					warn "\$${_f} is not set."
615					if [ -z "$rc_force" ]; then
616						return 1
617					fi
618				fi
619			done
620			for _f in $required_dirs; do
621				if [ ! -d "${_f}/." ]; then
622					warn "${_f} is not a directory."
623					if [ -z "$rc_force" ]; then
624						return 1
625					fi
626				fi
627			done
628			for _f in $required_files; do
629				if [ ! -r "${_f}" ]; then
630					warn "${_f} is not readable."
631					if [ -z "$rc_force" ]; then
632						return 1
633					fi
634				fi
635			done
636
637					# if the precmd failed and force
638					# isn't set, exit
639					#
640			if [ -n "${_precmd}" ]; then
641				debug "run_rc_command: evaluating ${_precmd}()."
642				eval $_precmd
643				_return=$?
644				[ $_return -ne 0 ] && [ -z "$rc_force" ] &&
645				    return 1
646			fi
647
648					# setup the command to run, and run it
649					#
650			echo "Starting ${name}."
651			if [ -n "$_chroot" ]; then
652				_doit="\
653${_nice:+nice -n $_nice }\
654chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
655$_chroot $command $rc_flags $command_args"
656			else
657				_doit="\
658${_chdir:+cd $_chdir; }\
659${_nice:+nice -n $_nice }\
660$command $rc_flags $command_args"
661				if [ -n "$_user" ]; then
662				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
663				fi
664			fi
665
666					# if the cmd failed and force
667					# isn't set, exit
668					#
669			debug "run_rc_command: _doit: $_doit"
670			eval $_doit
671			_return=$?
672			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
673
674					# finally, run postcmd
675					#
676			if [ -n "${_postcmd}" ]; then
677				debug "run_rc_command: evaluating ${_postcmd}()."
678				eval $_postcmd
679			fi
680			;;
681
682		stop)
683			if [ -z "$rc_pid" ]; then
684				[ -n "$rc_fast" ] && exit 0
685				if [ -n "$pidfile" ]; then
686					echo \
687				    "${name} not running? (check $pidfile)."
688				else
689					echo "${name} not running?"
690				fi
691				exit 1
692			fi
693
694					# if the precmd failed and force
695					# isn't set, exit
696					#
697			if [ -n "$_precmd" ]; then
698				eval $_precmd
699				_return=$?
700				[ $_return -ne 0 ] && [ -z "$rc_force" ] &&
701				    return 1
702			fi
703
704					# send the signal to stop
705					#
706			echo "Stopping ${name}."
707			_doit="kill -${sig_stop:-TERM} $rc_pid"
708			if [ -n "$_user" ]; then
709				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
710			fi
711
712					# if the stop cmd failed and force
713					# isn't set, exit
714					#
715			eval $_doit
716			_return=$?
717			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
718
719					# wait for the command to exit,
720					# and run postcmd.
721			wait_for_pids $rc_pid
722			if [ -n "$_postcmd" ]; then
723				eval $_postcmd
724				_return=$?
725			fi
726			;;
727
728		reload)
729			if [ -z "$rc_pid" ]; then
730				if [ -n "$pidfile" ]; then
731					echo \
732				    "${name} not running? (check $pidfile)."
733				else
734					echo "${name} not running?"
735				fi
736				exit 1
737			fi
738			echo "Reloading ${name} config files."
739			if [ -n "$_precmd" ]; then
740				eval $_precmd
741				_return=$?
742				[ $_return -ne 0 ] && [ -z "$rc_force" ] &&
743				    return 1
744			fi
745			_doit="kill -${sig_reload:-HUP} $rc_pid"
746			if [ -n "$_user" ]; then
747				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
748			fi
749			eval $_doit
750			_return=$?
751			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
752			if [ -n "$_postcmd" ]; then
753				eval $_postcmd
754				_return=$?
755			fi
756			;;
757
758		restart)
759			if [ -n "$_precmd" ]; then
760				eval $_precmd $rc_extra_args
761				_return=$?
762				[ $_return -ne 0 ] && [ -z "$rc_force" ] &&
763				    return 1
764			fi
765					# prevent restart being called more
766					# than once by any given script
767					#
768			if ${_rc_restart_done:-false}; then
769				return 0
770			fi
771			_rc_restart_done=true
772
773			( $0 ${_rc_prefix}stop $rc_extra_args )
774			$0 ${_rc_prefix}start $rc_extra_args
775
776			if [ -n "$_postcmd" ]; then
777				eval $_postcmd $rc_extra_args
778				_return=$?
779			fi
780			;;
781
782		poll)
783			if [ -n "$rc_pid" ]; then
784				wait_for_pids $rc_pid
785			fi
786			;;
787
788		rcvar)
789			echo "# $name"
790			if [ -n "$rcvar" ]; then
791				if checkyesno ${rcvar}; then
792					echo "\$${rcvar}=YES"
793				else
794					echo "\$${rcvar}=NO"
795				fi
796			fi
797			;;
798
799		*)
800			rc_usage "$_keywords"
801			;;
802
803		esac
804		return $_return
805	done
806
807	echo 1>&2 "$0: unknown directive '$rc_arg'."
808	rc_usage "$_keywords"
809	exit 1
810}
811
812#
813# run_rc_script file arg
814#	Start the script `file' with `arg', and correctly handle the
815#	return value from the script.  If `file' ends with `.sh', it's
816#	sourced into the current environment.  If `file' appears to be
817#	a backup or scratch file, ignore it.  Otherwise if it's
818#	executable run as a child process.
819#
820run_rc_script()
821{
822	_file=$1
823	_arg=$2
824	if [ -z "$_file" -o -z "$_arg" ]; then
825		err 3 'USAGE: run_rc_script file arg'
826	fi
827
828	unset	name command command_args command_interpreter \
829		extra_commands pidfile procname \
830		rcvar required_dirs required_files required_vars
831	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
832
833	case "$_file" in
834	*.sh)				# run in current shell
835		set $_arg ; . $_file
836		;;
837	*[~#]|*.OLD|*.orig|*,v)		# scratch file; skip
838		warn "Ignoring scratch file $_file"
839		;;
840	*)				# run in subshell
841		if [ -x $_file ]; then
842			if [ -n "$rc_fast_and_loose" ]; then
843				set $_arg ; . $_file
844			else
845				( trap "echo Script $_file interrupted; kill -QUIT $$" 3
846				  trap "echo Script $_file interrupted; exit 1" 2
847				  set $_arg ; . $_file )
848			fi
849		fi
850		;;
851	esac
852}
853
854#
855# load_rc_config
856#	Source in the configuration file for a given command.
857#
858load_rc_config()
859{
860	_command=$1
861	if [ -z "$_command" ]; then
862		err 3 'USAGE: load_rc_config command'
863	fi
864
865	if ${_rc_conf_loaded:-false}; then
866		:
867	else
868		if [ -r /etc/defaults/rc.conf ]; then
869			debug "Sourcing /etc/defaults/rc.conf"
870			. /etc/defaults/rc.conf
871			source_rc_confs
872		elif [ -r /etc/rc.conf ]; then
873			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
874			. /etc/rc.conf
875		fi
876		_rc_conf_loaded=true
877	fi
878	if [ -f /etc/rc.conf.d/"$_command" ]; then
879		debug "Sourcing /etc/rc.conf.d/${_command}"
880		. /etc/rc.conf.d/"$_command"
881	fi
882
883	# XXX - Deprecated variable name support
884	#
885	case ${OSTYPE} in
886	FreeBSD)
887        	[ -n "$portmap_enable" ] && rpcbind_enable="$portmap_enable"
888        	[ -n "$portmap_program" ] && rpcbind_program="$portmap_program"
889        	[ -n "$portmap_flags" ] && rpcbind_flags="$portmap_flags"
890        	[ -n "$single_mountd_enable" ] && mountd_enable="$single_mountd_enable"
891        	[ -n "$xntpd_enable" ] && ntpd_enable="$xntpd_enable"
892        	[ -n "$xntpd_program" ] && ntpd_program="$xntpd_program"
893        	[ -n "$xntpd_flags" ] && ntpd_flags="$xntpd_flags"
894		[ -n "$dhcp_program" ] && dhclient_program="$dhcp_program"
895		[ -n "$dhcp_flags" ] && dhclient_flags="$dhcp_flags"
896        	;;
897	esac
898
899}
900
901#
902# rc_usage commands
903#	Print a usage string for $0, with `commands' being a list of
904#	valid commands.
905#
906rc_usage()
907{
908	echo -n 1>&2 "Usage: $0 [fast|force|one]("
909
910	_sep=
911	for _elem; do
912		echo -n 1>&2 "$_sep$_elem"
913		_sep="|"
914	done
915	echo 1>&2 ")"
916	exit 1
917}
918
919#
920# err exitval message
921#	Display message to stderr and log to the syslog, and exit with exitval.
922#
923err()
924{
925	exitval=$1
926	shift
927
928	if [ -x /usr/bin/logger ]; then
929		logger "$0: ERROR: $*"
930	fi
931	echo 1>&2 "$0: ERROR: $*"
932	exit $exitval
933}
934
935#
936# warn message
937#	Display message to stderr and log to the syslog.
938#
939warn()
940{
941	if [ -x /usr/bin/logger ]; then
942		logger "$0: WARNING: $*"
943	fi
944	echo 1>&2 "$0: WARNING: $*"
945}
946
947#
948# info message
949#	Display informational message to stdout and log to syslog.
950#
951info()
952{
953	case ${rc_info} in
954	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
955		if [ -x /usr/bin/logger ]; then
956			logger "$0: INFO: $*"
957		fi
958		echo "$0: INFO: $*"
959		;;
960	esac
961}
962
963#
964# debug message
965#	If debugging is enabled in rc.conf output message to stderr.
966#	BEWARE that you don't call any subroutine that itself calls this
967#	function.
968#
969debug()
970{
971	case ${rc_debug} in
972	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
973		if [ -x /usr/bin/logger ]; then
974			logger "$0: INFO: $*"
975		fi
976        	echo 1>&2 "$0: DEBUG: $*"
977		;;
978	esac
979}
980
981#
982# backup_file action file cur backup
983#	Make a backup copy of `file' into `cur', and save the previous
984#	version of `cur' as `backup' or use rcs for archiving.
985#
986#	This routine checks the value of the backup_uses_rcs variable,
987#	which can be either YES or NO.
988#
989#	The `action' keyword can be one of the following:
990#
991#	add		`file' is now being backed up (and is possibly
992#			being reentered into the backups system).  `cur'
993#			is created and RCS files, if necessary, are
994#			created as well.
995#
996#	update		`file' has changed and needs to be backed up.
997#			If `cur' exists, it is copied to to `back' or
998#			checked into RCS (if the repository file is old),
999#			and then `file' is copied to `cur'.  Another RCS
1000#			check in done here if RCS is being used.
1001#
1002#	remove		`file' is no longer being tracked by the backups
1003#			system.  If RCS is not being used, `cur' is moved
1004#			to `back', otherwise an empty file is checked in,
1005#			and then `cur' is removed.
1006#
1007#
1008backup_file()
1009{
1010	_action=$1
1011	_file=$2
1012	_cur=$3
1013	_back=$4
1014
1015	if checkyesno backup_uses_rcs; then
1016		_msg0="backup archive"
1017		_msg1="update"
1018
1019		# ensure that history file is not locked
1020		if [ -f $_cur,v ]; then
1021			rcs -q -u -U -M $_cur
1022		fi
1023
1024		# ensure after switching to rcs that the
1025		# current backup is not lost
1026		if [ -f $_cur ]; then
1027			# no archive, or current newer than archive
1028			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1029				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1030				rcs -q -kb -U $_cur
1031				co -q -f -u $_cur
1032			fi
1033		fi
1034
1035		case $_action in
1036		add|update)
1037			cp -p $_file $_cur
1038			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1039			rcs -q -kb -U $_cur
1040			co -q -f -u $_cur
1041			chown root:wheel $_cur $_cur,v
1042			;;
1043		remove)
1044			cp /dev/null $_cur
1045			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1046			rcs -q -kb -U $_cur
1047			chown root:wheel $_cur $_cur,v
1048			rm $_cur
1049			;;
1050		esac
1051	else
1052		case $_action in
1053		add|update)
1054			if [ -f $_cur ]; then
1055				cp -p $_cur $_back
1056			fi
1057			cp -p $_file $_cur
1058			chown root:wheel $_cur
1059			;;
1060		remove)
1061			mv -f $_cur $_back
1062			;;
1063		esac
1064	fi
1065}
1066
1067# make_symlink src link
1068#	Make a symbolic link 'link' to src from basedir. If the
1069#	directory in which link is to be created does not exist
1070#	a warning will be displayed and an error will be returned.
1071#	Returns 0 on sucess, 1 otherwise.
1072#
1073make_symlink()
1074{
1075	local src link linkdir _me
1076	src="$1"
1077	link="$2"
1078	linkdir="`dirname $link`"
1079	_me="make_symlink()"
1080
1081	if [ -z "$src" -o -z "$link" ]; then
1082		warn "$_me: requires two arguments."
1083		return 1
1084	fi
1085	if [ ! -d "$linkdir" ]; then
1086		warn "$_me: the directory $linkdir does not exist"
1087		return 1
1088	fi
1089	if ! ln -sf $src $link ; then
1090		warn "$_me: unable to make a symbolic link from $link to $src"
1091		return 1
1092	fi
1093	return 0
1094}
1095
1096# devfs_rulesets_from_file file
1097#	Reads a set of devfs commands from file, and creates
1098#	the specified rulesets with their rules. Returns non-zero
1099#	if there was an error.
1100#
1101devfs_rulesets_from_file()
1102{
1103	local file _err _me
1104	file="$1"
1105	_me="devfs_rulesets_from_file"
1106	_err=0
1107
1108	if [ -z "$file" ]; then
1109		warn "$_me: you must specify a file"
1110		return 1
1111	fi
1112	if [ ! -e "$file" ]; then
1113		debug "$_me: no such file ($file)"
1114		return 0
1115	fi
1116	debug "reading rulesets from file ($file)"
1117	{ while read line
1118	do
1119		case $line in
1120		\#*)
1121			continue
1122			;;
1123		\[*\]*)
1124			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1125			if [ -z "$rulenum" ]; then
1126				warn "$_me: cannot extract rule number ($line)"
1127				_err=1
1128				break
1129			fi
1130			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1131			if [ -z "$rulename" ]; then
1132				warn "$_me: cannot extract rule name ($line)"
1133				_err=1
1134				break;
1135			fi
1136			eval $rulename=\$rulenum
1137			debug "found ruleset: $rulename=$rulenum"
1138			if ! /sbin/devfs rule -s $rulenum delset ; then
1139				_err=1
1140				break
1141			fi
1142			;;
1143		*)
1144			rulecmd="${line%%"\#*"}"
1145			# evaluate the command incase it includes
1146			# other rules
1147			if [ -n "$rulecmd" ]; then
1148				debug "adding rule ($rulecmd)"
1149				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1150				then
1151					_err=1
1152					break
1153				fi
1154			fi
1155			;;
1156		esac
1157		if [ $_err -ne 0 ]; then
1158			debug "error in $_me"
1159			break
1160		fi
1161	done } < $file
1162	return $_err
1163}
1164
1165# devfs_init_rulesets
1166#	Initializes rulesets from configuration files. Returns
1167#	non-zero if there was an error.
1168#
1169devfs_init_rulesets()
1170{
1171	local file _me
1172	_me="devfs_init_rulesets"
1173
1174	# Go through this only once
1175	if [ -n "$devfs_rulesets_init" ]; then
1176		debug "$_me: devfs rulesets already initialized"
1177		return
1178	fi
1179	for file in $devfs_rulesets ; do
1180		devfs_rulesets_from_file $file || return 1
1181	done
1182	devfs_rulesets_init=1
1183	debug "$_me: devfs rulesets initialized"
1184	return 0
1185}
1186
1187# devfs_set_ruleset ruleset [dir]
1188#	Sets the default ruleset of dir to ruleset. The ruleset arguement
1189#	must be a ruleset name as specified in devfs.rules(5) file.
1190#	Returns non-zero if it could not set it successfully.
1191#
1192devfs_set_ruleset()
1193{
1194	local devdir rs _me
1195	[ -n "$1" ] && eval rs=\$$1 || rs=
1196	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1197	_me="devfs_set_ruleset"
1198
1199	if [ -z "$rs" ]; then
1200		warn "$_me: you must specify a ruleset number"
1201		return 1
1202	fi
1203	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1204	if ! /sbin/devfs $devdir ruleset $rs ; then
1205		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1206		return 1
1207	fi
1208	return 0
1209}
1210
1211# devfs_apply_ruleset ruleset [dir]
1212#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1213#	The ruleset argument must be a ruleset name as specified
1214#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1215#	if it could not apply the ruleset.
1216#
1217devfs_apply_ruleset()
1218{
1219	local devdir rs _me
1220	[ -n "$1" ] && eval rs=\$$1 || rs=
1221	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1222	_me="devfs_apply_ruleset"
1223
1224	if [ -z "$rs" ]; then
1225		warn "$_me: you must specify a ruleset"
1226		return 1
1227	fi
1228	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1229	if ! /sbin/devfs $devdir rule -s $rs applyset ; then
1230		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1231		return 1
1232	fi
1233	return 0
1234}
1235
1236# devfs_domount dir [ruleset]
1237#	Mount devfs on dir. If ruleset is specified it is set
1238#	on the mount-point. It must also be a ruleset name as specified
1239#	in a devfs.rules(5) file. Returns 0 on success.
1240#
1241devfs_domount()
1242{
1243	local devdir rs _me
1244	devdir="$1"
1245	[ -n "$2" ] && rs=$2 || rs=
1246	_me="devfs_domount()"
1247
1248	if [ -z "$devdir" ]; then
1249		warn "$_me: you must specify a mount-point"
1250		return 1
1251	fi
1252	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1253	if ! mount -t devfs dev "$devdir" ; then
1254		warn "$_me: Unable to mount devfs on $devdir"
1255		return 1
1256	fi
1257	if [ -n "$rs" ]; then
1258		devfs_init_rulesets
1259		devfs_set_ruleset $rs $devdir
1260		devfs -m $devdir rule applyset
1261	fi
1262	return 0
1263}
1264
1265# devfs_mount_jail dir [ruleset]
1266#	Mounts a devfs file system appropriate for jails
1267#	on the directory dir. If ruleset is specified, the ruleset
1268#	it names will be used instead.  If present, ruleset must
1269#	be the name of a ruleset as defined in a devfs.rules(5) file.
1270#	This function returns non-zero if an error occurs.
1271#
1272devfs_mount_jail()
1273{
1274	local jdev rs _me
1275	jdev="$1"
1276	[ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1277	_me="devfs_mount_jail"
1278
1279	devfs_init_rulesets
1280	if ! devfs_domount "$jdev" $rs ; then
1281		warn "$_me: devfs was not mounted on $jdev"
1282		return 1
1283	fi
1284	return 0
1285}
1286
1287# Provide a function for normalizing the mounting of memory
1288# filesystems.  This should allow the rest of the code here to remain
1289# as close as possible between 5-current and 4-stable.
1290#   $1 = size
1291#   $2 = mount point
1292#   $3 = (optional) extra mdmfs flags
1293mount_md() {
1294	if [ -n "$3" ]; then
1295		flags="$3"
1296	fi
1297	/sbin/mdmfs $flags -s $1 -M md $2
1298}
1299
1300fi
1301