rc.subr revision 165684
1# $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2# $FreeBSD: head/etc/rc.subr 165684 2006-12-31 11:07:29Z yar $
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# 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: ${rcvar_manpage:='rc.conf(5)'}
43
44#
45#	Operating System dependent/independent variables
46#
47
48if [ -z "${_rc_subr_loaded}" ]; then
49
50_rc_subr_loaded="YES"
51
52SYSCTL="/sbin/sysctl"
53SYSCTL_N="${SYSCTL} -n"
54CMD_OSTYPE="${SYSCTL_N} kern.ostype"
55OSTYPE=`${CMD_OSTYPE}`
56ID="/usr/bin/id"
57IDCMD="if [ -x $ID ]; then $ID -un; fi"
58PS="/bin/ps -ww"
59JID=`$PS -p $$ -o jid=`
60
61case ${OSTYPE} in
62FreeBSD)
63	SYSCTL_W="${SYSCTL}"
64	;;
65NetBSD)
66	SYSCTL_W="${SYSCTL} -w"
67	;;
68esac
69
70#
71#	functions
72#	---------
73
74#
75# set_rcvar base_var
76#	Set the variable name enabling a specific service.
77#	FreeBSD uses ${service}_enable, while NetBSD uses
78#	just the name of the service. For example:
79#	FreeBSD: sendmail_enable="YES"
80#	NetBSD : sendmail="YES"
81#	$1 - if $name is not the base to work of off, specify
82#	     a different one
83#
84set_rcvar()
85{
86	if [ -z "$1" ]; then
87		base_var=${name}
88	else
89		base_var="$1"
90	fi
91
92	case ${OSTYPE} in
93	FreeBSD)
94		echo ${base_var}_enable
95		;;
96	NetBSD)
97		echo ${base_var}
98		;;
99	*)
100		echo 'XXX'
101		;;
102	esac
103}
104
105#
106# force_depend script
107#	Force a service to start. Intended for use by services
108#	to resolve dependency issues. It is assumed the caller
109#	has check to make sure this call is necessary
110#	$1 - filename of script, in /etc/rc.d, to run
111#
112force_depend()
113{
114	_depend="$1"
115
116	info "${name} depends on ${_depend}, which will be forced to start."
117	if ! /etc/rc.d/${_depend} forcestart; then
118		warn "Unable to force ${_depend}. It may already be running."
119		return 1
120	fi
121	return 0
122}
123
124#
125# checkyesno var
126#	Test $1 variable, and warn if not set to YES or NO.
127#	Return 0 if it's "yes" (et al), nonzero otherwise.
128#
129checkyesno()
130{
131	eval _value=\$${1}
132	debug "checkyesno: $1 is set to $_value."
133	case $_value in
134
135		#	"yes", "true", "on", or "1"
136	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
137		return 0
138		;;
139
140		#	"no", "false", "off", or "0"
141	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
142		return 1
143		;;
144	*)
145		warn "\$${1} is not set properly - see ${rcvar_manpage}."
146		return 1
147		;;
148	esac
149}
150
151#
152# reverse_list list
153#	print the list in reverse order
154#
155reverse_list()
156{
157	_revlist=
158	for _revfile; do
159		_revlist="$_revfile $_revlist"
160	done
161	echo $_revlist
162}
163
164#
165# mount_critical_filesystems type
166#	Go through the list of critical filesystems as provided in
167#	the rc.conf(5) variable $critical_filesystems_${type}, checking
168#	each one to see if it is mounted, and if it is not, mounting it.
169#
170mount_critical_filesystems()
171{
172	eval _fslist=\$critical_filesystems_${1}
173	for _fs in $_fslist; do
174		mount | (
175			_ismounted=false
176			while read what _on on _type type; do
177				if [ $on = $_fs ]; then
178					_ismounted=true
179				fi
180			done
181			if $_ismounted; then
182				:
183			else
184				mount $_fs >/dev/null 2>&1
185			fi
186		)
187	done
188}
189
190#
191# check_pidfile pidfile procname [interpreter]
192#	Parses the first line of pidfile for a PID, and ensures
193#	that the process is running and matches procname.
194#	Prints the matching PID upon success, nothing otherwise.
195#	interpreter is optional; see _find_processes() for details.
196#
197check_pidfile()
198{
199	_pidfile=$1
200	_procname=$2
201	_interpreter=$3
202	if [ -z "$_pidfile" -o -z "$_procname" ]; then
203		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
204	fi
205	if [ ! -f $_pidfile ]; then
206		debug "pid file ($_pidfile): not readable."
207		return
208	fi
209	read _pid _junk < $_pidfile
210	if [ -z "$_pid" ]; then
211		debug "pid file ($_pidfile): no pid in file."
212		return
213	fi
214	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
215}
216
217#
218# check_process procname [interpreter]
219#	Ensures that a process (or processes) named procname is running.
220#	Prints a list of matching PIDs.
221#	interpreter is optional; see _find_processes() for details.
222#
223check_process()
224{
225	_procname=$1
226	_interpreter=$2
227	if [ -z "$_procname" ]; then
228		err 3 'USAGE: check_process procname [interpreter]'
229	fi
230	_find_processes $_procname ${_interpreter:-.} '-ax'
231}
232
233#
234# _find_processes procname interpreter psargs
235#	Search for procname in the output of ps generated by psargs.
236#	Prints the PIDs of any matching processes, space separated.
237#
238#	If interpreter == ".", check the following variations of procname
239#	against the first word of each command:
240#		procname
241#		`basename procname`
242#		`basename procname` + ":"
243#		"(" + `basename procname` + ")"
244#		"[" + `basename procname` + "]"
245#
246#	If interpreter != ".", read the first line of procname, remove the
247#	leading #!, normalise whitespace, append procname, and attempt to
248#	match that against each command, either as is, or with extra words
249#	at the end.  As an alternative, to deal with interpreted daemons
250#	using perl, the basename of the interpreter plus a colon is also
251#	tried as the prefix to procname.
252#
253_find_processes()
254{
255	if [ $# -ne 3 ]; then
256		err 3 'USAGE: _find_processes procname interpreter psargs'
257	fi
258	_procname=$1
259	_interpreter=$2
260	_psargs=$3
261
262	_pref=
263	if [ $_interpreter != "." ]; then	# an interpreted script
264		read _interp < ${_chroot:-}/$_procname	# read interpreter name
265		_interp=${_interp#\#!}		# strip #!
266		set -- $_interp
267		case $1 in
268		*/bin/env)
269			shift			# drop env to get real name
270			;;
271		esac
272		if [ $_interpreter != $1 ]; then
273			warn "\$command_interpreter $_interpreter != $1"
274		fi
275		_interp="$* $_procname"		# cleanup spaces, add _procname
276		_interpbn=${1##*/}
277		_fp_args='_argv'
278		_fp_match='case "$_argv" in
279		    ${_interp}|"${_interp} "*|"${_interpbn}: ${_procname}"*)'
280	else					# a normal daemon
281		_procnamebn=${_procname##*/}
282		_fp_args='_arg0 _argv'
283		_fp_match='case "$_arg0" in
284		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
285	fi
286
287	_proccheck="\
288		$PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
289		while read _npid _jid '"$_fp_args"'; do
290			'"$_fp_match"'
291				if [ "$JID" -eq "$_jid" ];
292				then echo -n "$_pref$_npid";
293				_pref=" ";
294				fi
295				;;
296			esac
297		done'
298
299#	debug "in _find_processes: proccheck is ($_proccheck)."
300	eval $_proccheck
301}
302
303#
304# wait_for_pids pid [pid ...]
305#	spins until none of the pids exist
306#
307wait_for_pids()
308{
309	_list="$@"
310	if [ -z "$_list" ]; then
311		return
312	fi
313	_prefix=
314	while true; do
315		_nlist="";
316		for _j in $_list; do
317			if kill -0 $_j 2>/dev/null; then
318				_nlist="${_nlist}${_nlist:+ }$_j"
319			fi
320		done
321		if [ -z "$_nlist" ]; then
322			break
323		fi
324		_list=$_nlist
325		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
326		_prefix=", "
327		sleep 2
328	done
329	if [ -n "$_prefix" ]; then
330		echo "."
331	fi
332}
333
334#
335# run_rc_command argument
336#	Search for argument in the list of supported commands, which is:
337#		"start stop restart rcvar status poll ${extra_commands}"
338#	If there's a match, run ${argument}_cmd or the default method
339#	(see below).
340#
341#	If argument has a given prefix, then change the operation as follows:
342#		Prefix	Operation
343#		------	---------
344#		fast	Skip the pid check, and set rc_fast=yes
345#		force	Set ${rcvar} to YES, and set rc_force=yes
346#		one	Set ${rcvar} to YES
347#
348#	The following globals are used:
349#
350#	Name		Needed	Purpose
351#	----		------	-------
352#	name		y	Name of script.
353#
354#	command		n	Full path to command.
355#				Not needed if ${rc_arg}_cmd is set for
356#				each keyword.
357#
358#	command_args	n	Optional args/shell directives for command.
359#
360#	command_interpreter n	If not empty, command is interpreted, so
361#				call check_{pidfile,process}() appropriately.
362#
363#	extra_commands	n	List of extra commands supported.
364#
365#	pidfile		n	If set, use check_pidfile $pidfile $command,
366#				otherwise use check_process $command.
367#				In either case, only check if $command is set.
368#
369#	procname	n	Process name to check for instead of $command.
370#
371#	rcvar		n	This is checked with checkyesno to determine
372#				if the action should be run.
373#
374#	${name}_program	n	Full path to command.
375#				Meant to be used in /etc/rc.conf to override
376#				${command}.
377#
378#	${name}_chroot	n	Directory to chroot to before running ${command}
379#				Requires /usr to be mounted.
380#
381#	${name}_chdir	n	Directory to cd to before running ${command}
382#				(if not using ${name}_chroot).
383#
384#	${name}_flags	n	Arguments to call ${command} with.
385#				NOTE:	$flags from the parent environment
386#					can be used to override this.
387#
388#	${name}_nice	n	Nice level to run ${command} at.
389#
390#	${name}_user	n	User to run ${command} as, using su(1) if not
391#				using ${name}_chroot.
392#				Requires /usr to be mounted.
393#
394#	${name}_group	n	Group to run chrooted ${command} as.
395#				Requires /usr to be mounted.
396#
397#	${name}_groups	n	Comma separated list of supplementary groups
398#				to run the chrooted ${command} with.
399#				Requires /usr to be mounted.
400#
401#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
402#				Otherwise, use default command (see below)
403#
404#	${rc_arg}_precmd n	If set, run just before performing the
405#				${rc_arg}_cmd method in the default
406#				operation (i.e, after checking for required
407#				bits and process (non)existence).
408#				If this completes with a non-zero exit code,
409#				don't run ${rc_arg}_cmd.
410#
411#	${rc_arg}_postcmd n	If set, run just after performing the
412#				${rc_arg}_cmd method, if that method
413#				returned a zero exit code.
414#
415#	required_dirs	n	If set, check for the existence of the given
416#				directories before running a (re)start command.
417#
418#	required_files	n	If set, check for the readability of the given
419#				files before running a (re)start command.
420#
421#	required_modules n	If set, ensure the given kernel modules are
422#				loaded before running a (re)start command.
423#				The check and possible loads are actually
424#				done after start_precmd so that the modules
425#				aren't loaded in vain, should the precmd
426#				return a non-zero status to indicate a error.
427#				If a word in the list looks like "foo:bar",
428#				"foo" is the KLD file name and "bar" is the
429#				module name.  If a word looks like "foo~bar",
430#				"foo" is the KLD file name and "bar" is a
431#				egrep(1) pattern matching the module name.
432#				Otherwise the module name is assumed to be
433#				the same as the KLD file name, which is most
434#				common.  See load_kld().
435#
436#	required_vars	n	If set, perform checkyesno on each of the
437#				listed variables before running the default
438#				(re)start command.
439#
440#	Default behaviour for a given argument, if no override method is
441#	provided:
442#
443#	Argument	Default behaviour
444#	--------	-----------------
445#	start		if !running && checkyesno ${rcvar}
446#				${command}
447#
448#	stop		if ${pidfile}
449#				rc_pid=$(check_pidfile $pidfile $command)
450#			else
451#				rc_pid=$(check_process $command)
452#			kill $sig_stop $rc_pid
453#			wait_for_pids $rc_pid
454#			($sig_stop defaults to TERM.)
455#
456#	reload		Similar to stop, except use $sig_reload instead,
457#			and doesn't wait_for_pids.
458#			$sig_reload defaults to HUP.
459#			Note that `reload' isn't provided by default,
460#			it should be enabled via $extra_commands.
461#
462#	restart		Run `stop' then `start'.
463#
464#	status		Show if ${command} is running, etc.
465#
466#	poll		Wait for ${command} to exit.
467#
468#	rcvar		Display what rc.conf variable is used (if any).
469#
470#	Variables available to methods, and after run_rc_command() has
471#	completed:
472#
473#	Variable	Purpose
474#	--------	-------
475#	rc_arg		Argument to command, after fast/force/one processing
476#			performed
477#
478#	rc_flags	Flags to start the default command with.
479#			Defaults to ${name}_flags, unless overridden
480#			by $flags from the environment.
481#			This variable may be changed by the precmd method.
482#
483#	rc_pid		PID of command (if appropriate)
484#
485#	rc_fast		Not empty if "fast" was provided (q.v.)
486#
487#	rc_force	Not empty if "force" was provided (q.v.)
488#
489#
490run_rc_command()
491{
492	_return=0
493	rc_arg=$1
494	if [ -z "$name" ]; then
495		err 3 'run_rc_command: $name is not set.'
496	fi
497
498	# Don't repeat the first argument when passing additional command-
499	# line arguments to the command subroutines.
500	#
501	shift 1
502	rc_extra_args="$*"
503
504	_rc_prefix=
505	case "$rc_arg" in
506	fast*)				# "fast" prefix; don't check pid
507		rc_arg=${rc_arg#fast}
508		rc_fast=yes
509		;;
510	force*)				# "force prefix; always run
511		rc_force=yes
512		_rc_prefix=force
513		rc_arg=${rc_arg#${_rc_prefix}}
514		if [ -n "${rcvar}" ]; then
515			eval ${rcvar}=YES
516		fi
517		;;
518	one*)				# "one" prefix; set ${rcvar}=yes
519		_rc_prefix=one
520		rc_arg=${rc_arg#${_rc_prefix}}
521		if [ -n "${rcvar}" ]; then
522			eval ${rcvar}=YES
523		fi
524		;;
525	esac
526
527	eval _override_command=\$${name}_program
528	command=${command:+${_override_command:-$command}}
529
530	_keywords="start stop restart rcvar $extra_commands"
531	rc_pid=
532	_pidcmd=
533	_procname=${procname:-${command}}
534
535					# setup pid check command
536	if [ -n "$_procname" ]; then
537		if [ -n "$pidfile" ]; then
538			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
539		else
540			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
541		fi
542		if [ -n "$_pidcmd" ]; then
543			_keywords="${_keywords} status poll"
544		fi
545	fi
546
547	if [ -z "$rc_arg" ]; then
548		rc_usage $_keywords
549	fi
550
551	if [ -n "$flags" ]; then	# allow override from environment
552		rc_flags=$flags
553	else
554		eval rc_flags=\$${name}_flags
555	fi
556	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
557	    _nice=\$${name}_nice	_user=\$${name}_user \
558	    _group=\$${name}_group	_groups=\$${name}_groups
559
560	if [ -n "$_user" ]; then	# unset $_user if running as that user
561		if [ "$_user" = "$(eval $IDCMD)" ]; then
562			unset _user
563		fi
564	fi
565
566					# if ${rcvar} is set, and $1 is not
567					# "rcvar", then run
568					#	checkyesno ${rcvar}
569					# and return if that failed
570					#
571	if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
572		if ! checkyesno ${rcvar}; then
573			return 0
574		fi
575	fi
576
577	eval $_pidcmd			# determine the pid if necessary
578
579	for _elem in $_keywords; do
580		if [ "$_elem" != "$rc_arg" ]; then
581			continue
582		fi
583					# if there's a custom ${XXX_cmd},
584					# run that instead of the default
585					#
586		eval _cmd=\$${rc_arg}_cmd \
587		     _precmd=\$${rc_arg}_precmd \
588		     _postcmd=\$${rc_arg}_postcmd
589
590		if [ -n "$_cmd" ]; then
591			_run_rc_precmd || return 1
592			_run_rc_doit "$_cmd $rc_extra_args" || return 1
593			_run_rc_postcmd
594			return $_return
595		fi
596
597		case "$rc_arg" in	# default operations...
598
599		status)
600			_run_rc_precmd || return 1
601			if [ -n "$rc_pid" ]; then
602				echo "${name} is running as pid $rc_pid."
603			else
604				echo "${name} is not running."
605				return 1
606			fi
607			_run_rc_postcmd
608			;;
609
610		start)
611			if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
612				echo 1>&2 "${name} already running? (pid=$rc_pid)."
613				return 1
614			fi
615
616			if [ ! -x ${_chroot}${command} ]; then
617				warn "run_rc_command: cannot run $command"
618				return 1
619			fi
620
621			_run_rc_precmd || return 1
622
623					# setup the full command to run
624					#
625			echo "Starting ${name}."
626			if [ -n "$_chroot" ]; then
627				_doit="\
628${_nice:+nice -n $_nice }\
629chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
630$_chroot $command $rc_flags $command_args"
631			else
632				_doit="\
633${_chdir:+cd $_chdir && }\
634$command $rc_flags $command_args"
635				if [ -n "$_user" ]; then
636				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
637				fi
638				if [ -n "$_nice" ]; then
639					if [ -z "$_user" ]; then
640						_doit="sh -c \"$_doit\""
641					fi	
642					_doit="nice -n $_nice $_doit"
643				fi
644			fi
645
646					# run the full command
647					#
648			_run_rc_doit "$_doit" || return 1
649
650					# finally, run postcmd
651					#
652			_run_rc_postcmd
653			;;
654
655		stop)
656			if [ -z "$rc_pid" ]; then
657				[ -n "$rc_fast" ] && return 0
658				_run_rc_notrunning
659				return 1
660			fi
661
662			_run_rc_precmd || return 1
663
664					# send the signal to stop
665					#
666			echo "Stopping ${name}."
667			_doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
668			_run_rc_doit "$_doit" || return 1
669
670					# wait for the command to exit,
671					# and run postcmd.
672			wait_for_pids $rc_pid
673
674			_run_rc_postcmd
675			;;
676
677		reload)
678			if [ -z "$rc_pid" ]; then
679				_run_rc_notrunning
680				return 1
681			fi
682
683			_run_rc_precmd || return 1
684
685			_doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
686			_run_rc_doit "$_doit" || return 1
687
688			_run_rc_postcmd
689			;;
690
691		restart)
692					# prevent restart being called more
693					# than once by any given script
694					#
695			if ${_rc_restart_done:-false}; then
696				return 0
697			fi
698			_rc_restart_done=true
699
700			_run_rc_precmd || return 1
701
702			# run those in a subshell to keep global variables
703			( run_rc_command ${_rc_prefix}stop $rc_extra_args )
704			( run_rc_command ${_rc_prefix}start $rc_extra_args )
705			_return=$?
706			[ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
707
708			_run_rc_postcmd
709			;;
710
711		poll)
712			_run_rc_precmd || return 1
713			if [ -n "$rc_pid" ]; then
714				wait_for_pids $rc_pid
715			fi
716			_run_rc_postcmd
717			;;
718
719		rcvar)
720			echo "# $name"
721			if [ -n "$rcvar" ]; then
722				if checkyesno ${rcvar}; then
723					echo "${rcvar}=YES"
724				else
725					echo "${rcvar}=NO"
726				fi
727			fi
728			;;
729
730		*)
731			rc_usage $_keywords
732			;;
733
734		esac
735		return $_return
736	done
737
738	echo 1>&2 "$0: unknown directive '$rc_arg'."
739	rc_usage $_keywords
740	# not reached
741}
742
743#
744# Helper functions for run_rc_command: common code.
745# They use such global variables besides the exported rc_* ones:
746#
747#	name	       R/W
748#	------------------
749#	_precmd		R
750#	_postcmd	R
751#	_return		W
752#
753_run_rc_precmd()
754{
755	check_required_before "$rc_arg" || return 1
756
757	if [ -n "$_precmd" ]; then
758		debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
759		eval "$_precmd $rc_extra_args"
760		_return=$?
761
762		# If precmd failed and force isn't set, request exit.
763		if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
764			return 1
765		fi
766	fi
767
768	check_required_after "$rc_arg" || return 1
769
770	return 0
771}
772
773_run_rc_postcmd()
774{
775	if [ -n "$_postcmd" ]; then
776		debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
777		eval "$_postcmd $rc_extra_args"
778		_return=$?
779	fi
780	return 0
781}
782
783_run_rc_doit()
784{
785	debug "run_rc_command: doit: $*"
786	eval "$@"
787	_return=$?
788
789	# If command failed and force isn't set, request exit.
790	if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
791		return 1
792	fi
793
794	return 0
795}
796
797_run_rc_notrunning()
798{
799	local _pidmsg
800
801	if [ -n "$pidfile" ]; then
802		_pidmsg=" (check $pidfile)."
803	else
804		_pidmsg=
805	fi
806	echo 1>&2 "${name} not running?${_pidmsg}"
807}
808
809_run_rc_killcmd()
810{
811	local _cmd
812
813	_cmd="kill -$1 $rc_pid"
814	if [ -n "$_user" ]; then
815		_cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
816	fi
817	echo "$_cmd"
818}
819
820#
821# run_rc_script file arg
822#	Start the script `file' with `arg', and correctly handle the
823#	return value from the script.  If `file' ends with `.sh', it's
824#	sourced into the current environment.  If `file' appears to be
825#	a backup or scratch file, ignore it.  Otherwise if it's
826#	executable run as a child process.
827#
828run_rc_script()
829{
830	_file=$1
831	_arg=$2
832	if [ -z "$_file" -o -z "$_arg" ]; then
833		err 3 'USAGE: run_rc_script file arg'
834	fi
835
836	unset	name command command_args command_interpreter \
837		extra_commands pidfile procname \
838		rcvar required_dirs required_files required_vars
839	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
840
841	case "$_file" in
842	/etc/rc.d/*.sh)			# run in current shell
843		set $_arg; . $_file
844		;;
845	*[~#]|*.OLD|*.bak|*.orig|*,v)	# scratch file; skip
846		warn "Ignoring scratch file $_file"
847		;;
848	*)				# run in subshell
849		if [ -x $_file ]; then
850			if [ -n "$rc_fast_and_loose" ]; then
851				set $_arg; . $_file
852			else
853				( trap "echo Script $_file interrupted; kill -QUIT $$" 3
854				  trap "echo Script $_file interrupted; exit 1" 2
855				  set $_arg; . $_file )
856			fi
857		fi
858		;;
859	esac
860}
861
862#
863# load_rc_config name
864#	Source in the configuration file for a given name.
865#
866load_rc_config()
867{
868	_name=$1
869	if [ -z "$_name" ]; then
870		err 3 'USAGE: load_rc_config name'
871	fi
872
873	if ${_rc_conf_loaded:-false}; then
874		:
875	else
876		if [ -r /etc/defaults/rc.conf ]; then
877			debug "Sourcing /etc/defaults/rc.conf"
878			. /etc/defaults/rc.conf
879			source_rc_confs
880		elif [ -r /etc/rc.conf ]; then
881			debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
882			. /etc/rc.conf
883		fi
884		_rc_conf_loaded=true
885	fi
886	if [ -f /etc/rc.conf.d/"$_name" ]; then
887		debug "Sourcing /etc/rc.conf.d/${_name}"
888		. /etc/rc.conf.d/"$_name"
889	fi
890
891	# XXX - Deprecated variable name support
892	#
893	case ${OSTYPE} in
894	FreeBSD)
895		[ -n "$portmap_enable" ] && rpcbind_enable="$portmap_enable"
896		[ -n "$portmap_program" ] && rpcbind_program="$portmap_program"
897		[ -n "$portmap_flags" ] && rpcbind_flags="$portmap_flags"
898		[ -n "$single_mountd_enable" ] && mountd_enable="$single_mountd_enable"
899		[ -n "$xntpd_enable" ] && ntpd_enable="$xntpd_enable"
900		[ -n "$xntpd_program" ] && ntpd_program="$xntpd_program"
901		[ -n "$xntpd_flags" ] && ntpd_flags="$xntpd_flags"
902		[ -n "$dhcp_program" ] && dhclient_program="$dhcp_program"
903		[ -n "$dhcp_flags" ] && dhclient_flags="$dhcp_flags"
904		;;
905	esac
906}
907  
908#
909# load_rc_config_var name var
910#	Read the rc.conf(5) var for name and set in the
911#	current shell, using load_rc_config in a subshell to prevent
912#	unwanted side effects from other variable assignments.
913#
914load_rc_config_var()
915{
916	if [ $# -ne 2 ]; then
917		err 3 'USAGE: load_rc_config_var name var'
918	fi
919	eval $(eval '(
920		load_rc_config '$1' >/dev/null;
921                if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
922			echo '$2'=\'\''${'$2'}\'\'';
923		fi
924	)' )
925}
926
927#
928# rc_usage commands
929#	Print a usage string for $0, with `commands' being a list of
930#	valid commands.
931#
932rc_usage()
933{
934	echo -n 1>&2 "Usage: $0 [fast|force|one]("
935
936	_sep=
937	for _elem; do
938		echo -n 1>&2 "$_sep$_elem"
939		_sep="|"
940	done
941	echo 1>&2 ")"
942	exit 1
943}
944
945#
946# err exitval message
947#	Display message to stderr and log to the syslog, and exit with exitval.
948#
949err()
950{
951	exitval=$1
952	shift
953
954	if [ -x /usr/bin/logger ]; then
955		logger "$0: ERROR: $*"
956	fi
957	echo 1>&2 "$0: ERROR: $*"
958	exit $exitval
959}
960
961#
962# warn message
963#	Display message to stderr and log to the syslog.
964#
965warn()
966{
967	if [ -x /usr/bin/logger ]; then
968		logger "$0: WARNING: $*"
969	fi
970	echo 1>&2 "$0: WARNING: $*"
971}
972
973#
974# info message
975#	Display informational message to stdout and log to syslog.
976#
977info()
978{
979	case ${rc_info} in
980	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
981		if [ -x /usr/bin/logger ]; then
982			logger "$0: INFO: $*"
983		fi
984		echo "$0: INFO: $*"
985		;;
986	esac
987}
988
989#
990# debug message
991#	If debugging is enabled in rc.conf output message to stderr.
992#	BEWARE that you don't call any subroutine that itself calls this
993#	function.
994#
995debug()
996{
997	case ${rc_debug} in
998	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
999		if [ -x /usr/bin/logger ]; then
1000			logger "$0: DEBUG: $*"
1001		fi
1002		echo 1>&2 "$0: DEBUG: $*"
1003		;;
1004	esac
1005}
1006
1007#
1008# backup_file action file cur backup
1009#	Make a backup copy of `file' into `cur', and save the previous
1010#	version of `cur' as `backup' or use rcs for archiving.
1011#
1012#	This routine checks the value of the backup_uses_rcs variable,
1013#	which can be either YES or NO.
1014#
1015#	The `action' keyword can be one of the following:
1016#
1017#	add		`file' is now being backed up (and is possibly
1018#			being reentered into the backups system).  `cur'
1019#			is created and RCS files, if necessary, are
1020#			created as well.
1021#
1022#	update		`file' has changed and needs to be backed up.
1023#			If `cur' exists, it is copied to to `back' or
1024#			checked into RCS (if the repository file is old),
1025#			and then `file' is copied to `cur'.  Another RCS
1026#			check in done here if RCS is being used.
1027#
1028#	remove		`file' is no longer being tracked by the backups
1029#			system.  If RCS is not being used, `cur' is moved
1030#			to `back', otherwise an empty file is checked in,
1031#			and then `cur' is removed.
1032#
1033#
1034backup_file()
1035{
1036	_action=$1
1037	_file=$2
1038	_cur=$3
1039	_back=$4
1040
1041	if checkyesno backup_uses_rcs; then
1042		_msg0="backup archive"
1043		_msg1="update"
1044
1045		# ensure that history file is not locked
1046		if [ -f $_cur,v ]; then
1047			rcs -q -u -U -M $_cur
1048		fi
1049
1050		# ensure after switching to rcs that the
1051		# current backup is not lost
1052		if [ -f $_cur ]; then
1053			# no archive, or current newer than archive
1054			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1055				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1056				rcs -q -kb -U $_cur
1057				co -q -f -u $_cur
1058			fi
1059		fi
1060
1061		case $_action in
1062		add|update)
1063			cp -p $_file $_cur
1064			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1065			rcs -q -kb -U $_cur
1066			co -q -f -u $_cur
1067			chown root:wheel $_cur $_cur,v
1068			;;
1069		remove)
1070			cp /dev/null $_cur
1071			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1072			rcs -q -kb -U $_cur
1073			chown root:wheel $_cur $_cur,v
1074			rm $_cur
1075			;;
1076		esac
1077	else
1078		case $_action in
1079		add|update)
1080			if [ -f $_cur ]; then
1081				cp -p $_cur $_back
1082			fi
1083			cp -p $_file $_cur
1084			chown root:wheel $_cur
1085			;;
1086		remove)
1087			mv -f $_cur $_back
1088			;;
1089		esac
1090	fi
1091}
1092
1093# make_symlink src link
1094#	Make a symbolic link 'link' to src from basedir. If the
1095#	directory in which link is to be created does not exist
1096#	a warning will be displayed and an error will be returned.
1097#	Returns 0 on sucess, 1 otherwise.
1098#
1099make_symlink()
1100{
1101	local src link linkdir _me
1102	src="$1"
1103	link="$2"
1104	linkdir="`dirname $link`"
1105	_me="make_symlink()"
1106
1107	if [ -z "$src" -o -z "$link" ]; then
1108		warn "$_me: requires two arguments."
1109		return 1
1110	fi
1111	if [ ! -d "$linkdir" ]; then
1112		warn "$_me: the directory $linkdir does not exist."
1113		return 1
1114	fi
1115	if ! ln -sf $src $link; then
1116		warn "$_me: unable to make a symbolic link from $link to $src"
1117		return 1
1118	fi
1119	return 0
1120}
1121
1122# devfs_rulesets_from_file file
1123#	Reads a set of devfs commands from file, and creates
1124#	the specified rulesets with their rules. Returns non-zero
1125#	if there was an error.
1126#
1127devfs_rulesets_from_file()
1128{
1129	local file _err _me
1130	file="$1"
1131	_me="devfs_rulesets_from_file"
1132	_err=0
1133
1134	if [ -z "$file" ]; then
1135		warn "$_me: you must specify a file"
1136		return 1
1137	fi
1138	if [ ! -e "$file" ]; then
1139		debug "$_me: no such file ($file)"
1140		return 0
1141	fi
1142	debug "reading rulesets from file ($file)"
1143	{ while read line
1144	do
1145		case $line in
1146		\#*)
1147			continue
1148			;;
1149		\[*\]*)
1150			rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1151			if [ -z "$rulenum" ]; then
1152				warn "$_me: cannot extract rule number ($line)"
1153				_err=1
1154				break
1155			fi
1156			rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1157			if [ -z "$rulename" ]; then
1158				warn "$_me: cannot extract rule name ($line)"
1159				_err=1
1160				break;
1161			fi
1162			eval $rulename=\$rulenum
1163			debug "found ruleset: $rulename=$rulenum"
1164			if ! /sbin/devfs rule -s $rulenum delset; then
1165				_err=1
1166				break
1167			fi
1168			;;
1169		*)
1170			rulecmd="${line%%"\#*"}"
1171			# evaluate the command incase it includes
1172			# other rules
1173			if [ -n "$rulecmd" ]; then
1174				debug "adding rule ($rulecmd)"
1175				if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1176				then
1177					_err=1
1178					break
1179				fi
1180			fi
1181			;;
1182		esac
1183		if [ $_err -ne 0 ]; then
1184			debug "error in $_me"
1185			break
1186		fi
1187	done } < $file
1188	return $_err
1189}
1190
1191# devfs_init_rulesets
1192#	Initializes rulesets from configuration files. Returns
1193#	non-zero if there was an error.
1194#
1195devfs_init_rulesets()
1196{
1197	local file _me
1198	_me="devfs_init_rulesets"
1199
1200	# Go through this only once
1201	if [ -n "$devfs_rulesets_init" ]; then
1202		debug "$_me: devfs rulesets already initialized"
1203		return
1204	fi
1205	for file in $devfs_rulesets; do
1206		devfs_rulesets_from_file $file || return 1
1207	done
1208	devfs_rulesets_init=1
1209	debug "$_me: devfs rulesets initialized"
1210	return 0
1211}
1212
1213# devfs_set_ruleset ruleset [dir]
1214#	Sets the default ruleset of dir to ruleset. The ruleset argument
1215#	must be a ruleset name as specified in devfs.rules(5) file.
1216#	Returns non-zero if it could not set it successfully.
1217#
1218devfs_set_ruleset()
1219{
1220	local devdir rs _me
1221	[ -n "$1" ] && eval rs=\$$1 || rs=
1222	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1223	_me="devfs_set_ruleset"
1224
1225	if [ -z "$rs" ]; then
1226		warn "$_me: you must specify a ruleset number"
1227		return 1
1228	fi
1229	debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1230	if ! /sbin/devfs $devdir ruleset $rs; then
1231		warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1232		return 1
1233	fi
1234	return 0
1235}
1236
1237# devfs_apply_ruleset ruleset [dir]
1238#	Apply ruleset number $ruleset to the devfs mountpoint $dir.
1239#	The ruleset argument must be a ruleset name as specified
1240#	in a devfs.rules(5) file.  Returns 0 on success or non-zero
1241#	if it could not apply the ruleset.
1242#
1243devfs_apply_ruleset()
1244{
1245	local devdir rs _me
1246	[ -n "$1" ] && eval rs=\$$1 || rs=
1247	[ -n "$2" ] && devdir="-m "$2"" || devdir=
1248	_me="devfs_apply_ruleset"
1249
1250	if [ -z "$rs" ]; then
1251		warn "$_me: you must specify a ruleset"
1252		return 1
1253	fi
1254	debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1255	if ! /sbin/devfs $devdir rule -s $rs applyset; then
1256		warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1257		return 1
1258	fi
1259	return 0
1260}
1261
1262# devfs_domount dir [ruleset]
1263#	Mount devfs on dir. If ruleset is specified it is set
1264#	on the mount-point. It must also be a ruleset name as specified
1265#	in a devfs.rules(5) file. Returns 0 on success.
1266#
1267devfs_domount()
1268{
1269	local devdir rs _me
1270	devdir="$1"
1271	[ -n "$2" ] && rs=$2 || rs=
1272	_me="devfs_domount()"
1273
1274	if [ -z "$devdir" ]; then
1275		warn "$_me: you must specify a mount-point"
1276		return 1
1277	fi
1278	debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1279	if ! mount -t devfs dev "$devdir"; then
1280		warn "$_me: Unable to mount devfs on $devdir"
1281		return 1
1282	fi
1283	if [ -n "$rs" ]; then
1284		devfs_init_rulesets
1285		devfs_set_ruleset $rs $devdir
1286		devfs -m $devdir rule applyset
1287	fi
1288	return 0
1289}
1290
1291# devfs_mount_jail dir [ruleset]
1292#	Mounts a devfs file system appropriate for jails
1293#	on the directory dir. If ruleset is specified, the ruleset
1294#	it names will be used instead.  If present, ruleset must
1295#	be the name of a ruleset as defined in a devfs.rules(5) file.
1296#	This function returns non-zero if an error occurs.
1297#
1298devfs_mount_jail()
1299{
1300	local jdev rs _me
1301	jdev="$1"
1302	[ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1303	_me="devfs_mount_jail"
1304
1305	devfs_init_rulesets
1306	if ! devfs_domount "$jdev" $rs; then
1307		warn "$_me: devfs was not mounted on $jdev"
1308		return 1
1309	fi
1310	return 0
1311}
1312
1313# Provide a function for normalizing the mounting of memory
1314# filesystems.  This should allow the rest of the code here to remain
1315# as close as possible between 5-current and 4-stable.
1316#   $1 = size
1317#   $2 = mount point
1318#   $3 = (optional) extra mdmfs flags
1319mount_md()
1320{
1321	if [ -n "$3" ]; then
1322		flags="$3"
1323	fi
1324	/sbin/mdmfs $flags -s $1 md $2
1325}
1326
1327# Code common to scripts that need to load a kernel module
1328# if it isn't in the kernel yet. Syntax:
1329#   load_kld [-e regex] [-m module] file
1330# where -e or -m chooses the way to check if the module
1331# is already loaded:
1332#   regex is egrep'd in the output from `kldstat -v',
1333#   module is passed to `kldstat -m'.
1334# The default way is as though `-m file' were specified.
1335load_kld()
1336{
1337	local _loaded _mod _opt _re
1338
1339	while getopts "e:m:" _opt; do
1340		case "$_opt" in
1341		e) _re="$OPTARG" ;;
1342		m) _mod="$OPTARG" ;;
1343		*) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1344		esac
1345	done
1346	shift $(($OPTIND - 1))
1347	if [ $# -ne 1 ]; then
1348		err 3 'USAGE: load_kld [-e regex] [-m module] file'
1349	fi
1350	_mod=${_mod:-$1}
1351	_loaded=false
1352	if [ -n "$_re" ]; then
1353		if kldstat -v | egrep -q -e "$_re"; then
1354			_loaded=true
1355		fi
1356	else
1357		if kldstat -q -m "$_mod"; then
1358			_loaded=true
1359		fi
1360	fi
1361	if ! $_loaded; then
1362		if ! kldload "$1"; then
1363			warn "Unable to load kernel module $1"
1364			return 1
1365		else
1366			info "$1 kernel module loaded."
1367		fi
1368	else
1369		debug "load_kld: $1 kernel module already loaded."
1370	fi
1371	return 0
1372}
1373
1374# ltr str src dst
1375#	Change every $src in $str to $dst.
1376#	Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1377#	awk(1).
1378ltr()
1379{
1380	local _str _src _dst _out _com
1381	_str=$1
1382	_src=$2
1383	_dst=$3
1384	_out=""
1385
1386	IFS=${_src}
1387	for _com in ${_str}; do
1388		if [ -z "${_out}" ]; then
1389			_out="${_com}"
1390		else
1391			_out="${_out}${_dst}${_com}"
1392		fi
1393	done
1394	echo "${_out}"
1395}
1396
1397# Creates a list of providers for GELI encryption.
1398geli_make_list()
1399{
1400	local devices devices2
1401	local provider mountpoint type options rest
1402
1403	# Create list of GELI providers from fstab.
1404	while read provider mountpoint type options rest ; do
1405		case ":${options}" in
1406		:*noauto*)
1407			noauto=yes
1408			;;
1409		*)
1410			noauto=no
1411			;;
1412		esac
1413
1414		case ":${provider}" in
1415		:#*)
1416			continue
1417			;;
1418		*.eli)
1419			# Skip swap devices.
1420			if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1421				continue
1422			fi
1423			devices="${devices} ${provider}"
1424			;;
1425		esac
1426	done < /etc/fstab
1427
1428	# Append providers from geli_devices.
1429	devices="${devices} ${geli_devices}"
1430
1431	for provider in ${devices}; do
1432		provider=${provider%.eli}
1433		provider=${provider#/dev/}
1434		devices2="${devices2} ${provider}"
1435	done
1436
1437	echo ${devices2}
1438}
1439
1440# Find scripts in local_startup directories that use the old syntax
1441#
1442find_local_scripts_old () {
1443	zlist=''
1444	slist=''
1445	for dir in ${local_startup}; do
1446		if [ -d "${dir}" ]; then
1447			for file in ${dir}/[0-9]*.sh; do
1448				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1449				    continue
1450				zlist="$zlist $file"
1451			done
1452			for file in ${dir}/[^0-9]*.sh; do
1453				grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1454				    continue
1455				slist="$slist $file"
1456			done
1457		fi
1458	done
1459}
1460
1461find_local_scripts_new () {
1462	local_rc=''
1463	for dir in ${local_startup}; do
1464		if [ -d "${dir}" ]; then
1465			for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1466				case "$file" in
1467				*.sample) ;;
1468				*)	if [ -x "$file" ]; then
1469						local_rc="${local_rc} ${file}"
1470					fi
1471					;;
1472				esac
1473			done
1474		fi
1475	done
1476}
1477
1478# check_required_{before|after} command
1479#	Check for things required by the command before and after its precmd,
1480#	respectively.  The two separate functions are needed because some
1481#	conditions should prevent precmd from being run while other things
1482#	depend on precmd having already been run.
1483#
1484check_required_before()
1485{
1486	local _f
1487
1488	case "$1" in
1489	start)
1490		for _f in $required_vars; do
1491			if ! checkyesno $_f; then
1492				warn "\$${_f} is not enabled."
1493				if [ -z "$rc_force" ]; then
1494					return 1
1495				fi
1496			fi
1497		done
1498
1499		for _f in $required_dirs; do
1500			if [ ! -d "${_f}/." ]; then
1501				warn "${_f} is not a directory."
1502				if [ -z "$rc_force" ]; then
1503					return 1
1504				fi
1505			fi
1506		done
1507
1508		for _f in $required_files; do
1509			if [ ! -r "${_f}" ]; then
1510				warn "${_f} is not readable."
1511				if [ -z "$rc_force" ]; then
1512					return 1
1513				fi
1514			fi
1515		done
1516		;;
1517	esac
1518
1519	return 0
1520}
1521
1522check_required_after()
1523{
1524	local _f _args
1525
1526	case "$1" in
1527	start)
1528		for _f in $required_modules; do
1529			case "${_f}" in
1530				*~*)	_args="-e ${_f#*~} ${_f%%~*}" ;;
1531				*:*)	_args="-m ${_f#*:} ${_f%%:*}" ;;
1532				*)	_args="${_f}" ;;
1533			esac
1534			if ! load_kld ${_args}; then
1535				if [ -z "$rc_force" ]; then
1536					return 1
1537				fi
1538			fi
1539		done
1540		;;
1541	esac
1542
1543	return 0
1544}
1545
1546fi
1547
1548_rc_subr_loaded=:
1549