rc.subr revision 1.86
1# $NetBSD: rc.subr,v 1.86 2010/09/26 18:37:14 apb Exp $
2#
3# Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
4# All rights reserved.
5#
6# This code is derived from software contributed to The NetBSD Foundation
7# by Luke Mewburn.
8#
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12# 1. Redistributions of source code must retain the above copyright
13#    notice, this list of conditions and the following disclaimer.
14# 2. Redistributions in binary form must reproduce the above copyright
15#    notice, this list of conditions and the following disclaimer in the
16#    documentation and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
22# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28# POSSIBILITY OF SUCH DAMAGE.
29#
30# rc.subr
31#	functions used by various rc scripts
32#
33
34: ${rcvar_manpage:='rc.conf(5)'}
35: ${RC_PID:=$$} ; export RC_PID
36nl='
37' # a literal newline
38
39#
40#	functions
41#	---------
42
43#
44# checkyesno var
45#	Test $1 variable, and warn if not set to YES or NO.
46#	Return 0 if it's "yes" (et al), nonzero otherwise.
47#
48checkyesno()
49{
50	eval _value=\$${1}
51	case $_value in
52
53		#	"yes", "true", "on", or "1"
54	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
55		return 0
56		;;
57
58		#	"no", "false", "off", or "0"
59	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
60		return 1
61		;;
62	*)
63		warn "\$${1} is not set properly - see ${rcvar_manpage}."
64		return 1
65		;;
66	esac
67}
68
69#
70# yesno_to_truefalse var
71#	Convert the value of a variable from any of the values
72#	understood by checkyesno() to "true" or "false".
73#
74yesno_to_truefalse()
75{
76	local var=$1
77	if checkyesno $var; then
78		eval $var=true
79		return 0
80	else
81		eval $var=false
82		return 1
83	fi
84}
85
86#
87# reverse_list list
88#	print the list in reverse order
89#
90reverse_list()
91{
92	_revlist=
93	for _revfile; do
94		_revlist="$_revfile $_revlist"
95	done
96	echo $_revlist
97}
98
99#
100# If booting directly to multiuser, send SIGTERM to
101# the parent (/etc/rc) to abort the boot.
102# Otherwise just exit.
103#
104stop_boot()
105{
106	if [ "$autoboot" = yes ]; then
107		echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
108		kill -TERM ${RC_PID}
109	fi
110	exit 1
111}
112
113#
114# mount_critical_filesystems type
115#	Go through the list of critical filesystems as provided in
116#	the rc.conf(5) variable $critical_filesystems_${type}, checking
117#	each one to see if it is mounted, and if it is not, mounting it.
118#	It's not an error if file systems prefixed with "OPTIONAL:"
119#	are not mentioned in /etc/fstab.
120#
121mount_critical_filesystems()
122{
123	eval _fslist=\$critical_filesystems_${1}
124	_mountcrit_es=0
125	for _fs in $_fslist; do
126		_optional=false
127		case "$_fs" in
128		OPTIONAL:*)
129			_optional=true
130			_fs="${_fs#*:}"
131			;;
132		esac
133		_ismounted=false
134		# look for a line like "${fs} on * type *"
135		# or "* on ${fs} type *" in the output from mount.
136		case "${nl}$( mount )${nl}" in
137		*" on ${_fs} type "*)
138			_ismounted=true
139			;;
140		*"${nl}${_fs} on "*)
141			_ismounted=true
142			;;
143		esac
144		if $_ismounted; then
145			print_rc_metadata \
146			"note:File system ${_fs} was already mounted"
147		else
148			_mount_output=$( mount $_fs 2>&1 )
149			_mount_es=$?
150			case "$_mount_output" in
151			*"${nl}"*)
152				# multiple lines can't be good,
153				# not even if $_optional is true
154				;;
155			*'unknown special file or file system'*)
156				if $_optional; then
157					# ignore this error
158					print_rc_metadata \
159			"note:Optional file system ${_fs} is not present"
160					_mount_es=0
161					_mount_output=""
162				fi
163				;;
164			esac
165			if [ -n "$_mount_output" ]; then
166				printf >&2 "%s\n" "$_mount_output"
167			fi
168			if [ "$_mount_es" != 0 ]; then
169				_mountcrit_es="$_mount_es"
170			fi
171		fi
172	done
173	return $_mountcrit_es
174}
175
176#
177# check_pidfile pidfile procname [interpreter]
178#	Parses the first line of pidfile for a PID, and ensures
179#	that the process is running and matches procname.
180#	Prints the matching PID upon success, nothing otherwise.
181#	interpreter is optional; see _find_processes() for details.
182#
183check_pidfile()
184{
185	_pidfile=$1
186	_procname=$2
187	_interpreter=$3
188	if [ -z "$_pidfile" -o -z "$_procname" ]; then
189		err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
190	fi
191	if [ ! -f $_pidfile ]; then
192		return
193	fi
194	read _pid _junk < $_pidfile
195	if [ -z "$_pid" ]; then
196		return
197	fi
198	_find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
199}
200
201#
202# check_process procname [interpreter]
203#	Ensures that a process (or processes) named procname is running.
204#	Prints a list of matching PIDs.
205#	interpreter is optional; see _find_processes() for details.
206#
207check_process()
208{
209	_procname=$1
210	_interpreter=$2
211	if [ -z "$_procname" ]; then
212		err 3 'USAGE: check_process procname [interpreter]'
213	fi
214	_find_processes $_procname ${_interpreter:-.} '-ax'
215}
216
217#
218# _find_processes procname interpreter psargs
219#	Search for procname in the output of ps generated by psargs.
220#	Prints the PIDs of any matching processes, space separated.
221#
222#	If interpreter == ".", check the following variations of procname
223#	against the first word of each command:
224#		procname
225#		`basename procname`
226#		`basename procname` + ":"
227#		"(" + `basename procname` + ")"
228#
229#	If interpreter != ".", read the first line of procname, remove the
230#	leading #!, normalise whitespace, append procname, and attempt to
231#	match that against each command, either as is, or with extra words
232#	at the end.  As an alternative, to deal with interpreted daemons
233#	using perl, the basename of the interpreter plus a colon is also
234#	tried as the prefix to procname.
235#
236_find_processes()
237{
238	if [ $# -ne 3 ]; then
239		err 3 'USAGE: _find_processes procname interpreter psargs'
240	fi
241	_procname=$1
242	_interpreter=$2
243	_psargs=$3
244
245	_pref=
246	_procnamebn=${_procname##*/}
247	if [ $_interpreter != "." ]; then	# an interpreted script
248		read _interp < ${_chroot:-}/$_procname	# read interpreter name
249		_interp=${_interp#\#!}		# strip #!
250		set -- $_interp
251		if [ $_interpreter != $1 ]; then
252			warn "\$command_interpreter $_interpreter != $1"
253		fi
254		_interp="$* $_procname"		# cleanup spaces, add _procname
255		_interpbn=${1##*/}
256		_fp_args='_argv'
257		_fp_match='case "$_argv" in
258		    ${_interp}|"${_interp} "*|"${_interpbn}: "*${_procnamebn}*)'
259	else					# a normal daemon
260		_fp_args='_arg0 _argv'
261		_fp_match='case "$_arg0" in
262		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")'
263	fi
264
265	_proccheck='
266		ps -o "pid,command" '"$_psargs"' |
267		while read _npid '"$_fp_args"'; do
268			case "$_npid" in
269			    PID)
270				continue ;;
271			esac ; '"$_fp_match"'
272				echo -n "$_pref$_npid" ;
273				_pref=" "
274				;;
275			esac
276		done'
277
278#echo 1>&2 "proccheck is :$_proccheck:"
279	eval $_proccheck
280}
281
282#
283# wait_for_pids pid [pid ...]
284#	spins until none of the pids exist
285#
286wait_for_pids()
287{
288	_list="$@"
289	if [ -z "$_list" ]; then
290		return
291	fi
292	_prefix=
293	while true; do
294		_nlist="";
295		for _j in $_list; do
296			if kill -0 $_j 2>/dev/null; then
297				_nlist="${_nlist}${_nlist:+ }$_j"
298			fi
299		done
300		if [ -z "$_nlist" ]; then
301			break
302		fi
303		_list=$_nlist
304		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
305		_prefix=", "
306		sleep 2
307	done
308	if [ -n "$_prefix" ]; then
309		echo "."
310	fi
311}
312
313#
314# run_rc_command argument [parameters]
315#	Search for argument in the list of supported commands, which is:
316#		"start stop restart rcvar status poll ${extra_commands}"
317#	If there's a match, run ${argument}_cmd or the default method
318#	(see below), and pass the optional list of parameters to it.
319#
320#	If argument has a given prefix, then change the operation as follows:
321#		Prefix	Operation
322#		------	---------
323#		fast	Skip the pid check, and set rc_fast=yes
324#		force	Set ${rcvar} to YES, and set rc_force=yes
325#		one	Set ${rcvar} to YES
326#
327#	The following globals are used:
328#
329#	Name		Needed	Purpose
330#	----		------	-------
331#	name		y	Name of script.
332#
333#	command		n	Full path to command.
334#				Not needed if ${rc_arg}_cmd is set for
335#				each keyword.
336#
337#	command_args	n	Optional args/shell directives for command.
338#
339#	command_interpreter n	If not empty, command is interpreted, so
340#				call check_{pidfile,process}() appropriately.
341#
342#	extra_commands	n	List of extra commands supported.
343#
344#	pidfile		n	If set, use check_pidfile $pidfile $command,
345#				otherwise use check_process $command.
346#				In either case, only check if $command is set.
347#
348#	procname	n	Process name to check for instead of $command.
349#
350#	rcvar		n	This is checked with checkyesno to determine
351#				if the action should be run.
352#
353#	${name}_chroot	n	Directory to chroot to before running ${command}
354#				Requires /usr to be mounted.
355#
356#	${name}_chdir	n	Directory to cd to before running ${command}
357#				(if not using ${name}_chroot).
358#
359#	${name}_flags	n	Arguments to call ${command} with.
360#				NOTE:	$flags from the parent environment
361#					can be used to override this.
362#
363#	${name}_env	n	Additional environment variable settings
364#				for running ${command}
365#
366#	${name}_nice	n	Nice level to run ${command} at.
367#
368#	${name}_user	n	User to run ${command} as, using su(1) if not
369#				using ${name}_chroot.
370#				Requires /usr to be mounted.
371#
372#	${name}_group	n	Group to run chrooted ${command} as.
373#				Requires /usr to be mounted.
374#
375#	${name}_groups	n	Comma separated list of supplementary groups
376#				to run the chrooted ${command} with.
377#				Requires /usr to be mounted.
378#
379#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
380#				Otherwise, use default command (see below)
381#
382#	${rc_arg}_precmd n	If set, run just before performing the
383#				${rc_arg}_cmd method in the default
384#				operation (i.e, after checking for required
385#				bits and process (non)existence).
386#				If this completes with a non-zero exit code,
387#				don't run ${rc_arg}_cmd.
388#
389#	${rc_arg}_postcmd n	If set, run just after performing the
390#				${rc_arg}_cmd method, if that method
391#				returned a zero exit code.
392#
393#	required_dirs	n	If set, check for the existence of the given
394#				directories before running the default
395#				(re)start command.
396#
397#	required_files	n	If set, check for the readability of the given
398#				files before running the default (re)start
399#				command.
400#
401#	required_vars	n	If set, perform checkyesno on each of the
402#				listed variables before running the default
403#				(re)start command.
404#
405#	Default behaviour for a given argument, if no override method is
406#	provided:
407#
408#	Argument	Default behaviour
409#	--------	-----------------
410#	start		if !running && checkyesno ${rcvar}
411#				${command}
412#
413#	stop		if ${pidfile}
414#				rc_pid=$(check_pidfile $pidfile $command)
415#			else
416#				rc_pid=$(check_process $command)
417#			kill $sig_stop $rc_pid
418#			wait_for_pids $rc_pid
419#			($sig_stop defaults to TERM.)
420#
421#	reload		Similar to stop, except use $sig_reload instead,
422#			and doesn't wait_for_pids.
423#			$sig_reload defaults to HUP.
424#
425#	restart		Run `stop' then `start'.
426#
427#	status		Show if ${command} is running, etc.
428#
429#	poll		Wait for ${command} to exit.
430#
431#	rcvar		Display what rc.conf variable is used (if any).
432#
433#	Variables available to methods, and after run_rc_command() has
434#	completed:
435#
436#	Variable	Purpose
437#	--------	-------
438#	rc_arg		Argument to command, after fast/force/one processing
439#			performed
440#
441#	rc_flags	Flags to start the default command with.
442#			Defaults to ${name}_flags, unless overridden
443#			by $flags from the environment.
444#			This variable may be changed by the precmd method.
445#
446#	rc_pid		PID of command (if appropriate)
447#
448#	rc_fast		Not empty if "fast" was provided (q.v.)
449#
450#	rc_force	Not empty if "force" was provided (q.v.)
451#
452#
453run_rc_command()
454{
455	rc_arg=$1
456	if [ -z "$name" ]; then
457		err 3 'run_rc_command: $name is not set.'
458	fi
459
460	_rc_prefix=
461	case "$rc_arg" in
462	fast*)				# "fast" prefix; don't check pid
463		rc_arg=${rc_arg#fast}
464		rc_fast=yes
465		;;
466	force*)				# "force" prefix; always run
467		rc_force=yes
468		_rc_prefix=force
469		rc_arg=${rc_arg#${_rc_prefix}}
470		if [ -n "${rcvar}" ]; then
471			eval ${rcvar}=YES
472		fi
473		;;
474	one*)				# "one" prefix; set ${rcvar}=yes
475		_rc_prefix=one
476		rc_arg=${rc_arg#${_rc_prefix}}
477		if [ -n "${rcvar}" ]; then
478			eval ${rcvar}=YES
479		fi
480		;;
481	esac
482
483	_keywords="start stop restart rcvar"
484	if [ -n "$extra_commands" ]; then
485		_keywords="${_keywords} ${extra_commands}"
486	fi
487	rc_pid=
488	_pidcmd=
489	_procname=${procname:-${command}}
490
491					# setup pid check command if not fast
492	if [ -z "$rc_fast" -a -n "$_procname" ]; then
493		if [ -n "$pidfile" ]; then
494			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
495		else
496			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
497		fi
498		if [ -n "$_pidcmd" ]; then
499			_keywords="${_keywords} status poll"
500		fi
501	fi
502
503	if [ -z "$rc_arg" ]; then
504		rc_usage "$_keywords"
505	fi
506	shift	# remove $rc_arg from the positional parameters
507
508	if [ -n "$flags" ]; then	# allow override from environment
509		rc_flags=$flags
510	else
511		eval rc_flags=\$${name}_flags
512	fi
513	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
514	    _nice=\$${name}_nice	_user=\$${name}_user \
515	    _group=\$${name}_group	_groups=\$${name}_groups \
516	    _env=\"\$${name}_env\"
517
518	if [ -n "$_user" ]; then	# unset $_user if running as that user
519		if [ "$_user" = "$(id -un)" ]; then
520			unset _user
521		fi
522	fi
523
524					# if ${rcvar} is set, and $1 is not
525					# "rcvar", then run
526					#	checkyesno ${rcvar}
527					# and return if that failed or warn
528					# user and exit when interactive
529					#
530	if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
531		if ! checkyesno ${rcvar}; then
532					# check whether interactive or not
533			if [ -n "$_run_rc_script" ]; then
534				return 0
535			fi
536			for _elem in $_keywords; do
537				if [ "$_elem" = "$rc_arg" ]; then
538					echo 1>&2 "\$${rcvar} is not enabled - see ${rcvar_manpage}."
539					echo 1>&2 "Use the following if you wish to perform the operation:"
540					echo 1>&2 "  $0 one${rc_arg}"
541					exit 1
542				fi
543			done
544			echo 1>&2 "$0: unknown directive '$rc_arg'."
545			rc_usage "$_keywords"
546		fi
547	fi
548
549	eval $_pidcmd			# determine the pid if necessary
550
551	for _elem in $_keywords; do
552		if [ "$_elem" != "$rc_arg" ]; then
553			continue
554		fi
555
556					# if there's a custom ${XXX_cmd},
557					# run that instead of the default
558					#
559		eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \
560		    _postcmd=\$${rc_arg}_postcmd
561		if [ -n "$_cmd" ]; then
562					# if the precmd failed and force
563					# isn't set, exit
564					#
565			if ! eval $_precmd && [ -z "$rc_force" ]; then
566				return 1
567			fi
568
569			if ! eval $_cmd \"\${@}\" && [ -z "$rc_force" ]; then
570				return 1
571			fi
572			eval $_postcmd
573			return 0
574		fi
575
576		if [ ${#} -gt 0 ]; then
577			err 1 "the $rc_arg command does not take any parameters"
578		fi
579
580		case "$rc_arg" in	# default operations...
581
582		status)
583			if [ -n "$rc_pid" ]; then
584				echo "${name} is running as pid $rc_pid."
585			else
586				echo "${name} is not running."
587				return 1
588			fi
589			;;
590
591		start)
592			if [ -n "$rc_pid" ]; then
593				echo 1>&2 "${name} already running? (pid=$rc_pid)."
594				exit 1
595			fi
596
597			if [ ! -x ${_chroot}${command} ]; then
598				return 0
599			fi
600
601					# check for required variables,
602					# directories, and files
603					#
604			for _f in $required_vars; do
605				if ! checkyesno $_f; then
606					warn "\$${_f} is not enabled."
607					if [ -z "$rc_force" ]; then
608						return 1
609					fi
610				fi
611			done
612			for _f in $required_dirs; do
613				if [ ! -d "${_f}/." ]; then
614					warn "${_f} is not a directory."
615					if [ -z "$rc_force" ]; then
616						return 1
617					fi
618				fi
619			done
620			for _f in $required_files; do
621				if [ ! -r "${_f}" ]; then
622					warn "${_f} is not readable."
623					if [ -z "$rc_force" ]; then
624						return 1
625					fi
626				fi
627			done
628
629					# if the precmd failed and force
630					# isn't set, exit
631					#
632			if ! eval $_precmd && [ -z "$rc_force" ]; then
633				return 1
634			fi
635
636					# setup the command to run, and run it
637					#
638			echo "Starting ${name}."
639			if [ -n "$_chroot" ]; then
640				_doit="\
641${_env:+env $_env }\
642${_nice:+nice -n $_nice }\
643chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
644$_chroot $command $rc_flags $command_args"
645			else
646				_doit="\
647${_chdir:+cd $_chdir; }\
648${_env:+env $_env }\
649${_nice:+nice -n $_nice }\
650$command $rc_flags $command_args"
651				if [ -n "$_user" ]; then
652				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
653				fi
654			fi
655
656					# if the cmd failed and force
657					# isn't set, exit
658					#
659			if ! eval $_doit && [ -z "$rc_force" ]; then
660				return 1
661			fi
662
663					# finally, run postcmd
664					#
665			eval $_postcmd
666			;;
667
668		stop)
669			if [ -z "$rc_pid" ]; then
670				if [ -n "$pidfile" ]; then
671					echo 1>&2 \
672				    "${name} not running? (check $pidfile)."
673				else
674					echo 1>&2 "${name} not running?"
675				fi
676				exit 1
677			fi
678
679					# if the precmd failed and force
680					# isn't set, exit
681					#
682			if ! eval $_precmd && [ -z "$rc_force" ]; then
683				return 1
684			fi
685
686					# send the signal to stop
687					#
688			echo "Stopping ${name}."
689			_doit="kill -${sig_stop:-TERM} $rc_pid"
690			if [ -n "$_user" ]; then
691				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
692			fi
693
694					# if the stop cmd failed and force
695					# isn't set, exit
696					#
697			if ! eval $_doit && [ -z "$rc_force" ]; then
698				return 1
699			fi
700
701					# wait for the command to exit,
702					# and run postcmd.
703			wait_for_pids $rc_pid
704			eval $_postcmd
705			;;
706
707		reload)
708			if [ -z "$rc_pid" ]; then
709				if [ -n "$pidfile" ]; then
710					echo 1>&2 \
711				    "${name} not running? (check $pidfile)."
712				else
713					echo 1>&2 "${name} not running?"
714				fi
715				exit 1
716			fi
717			echo "Reloading ${name} config files."
718			if ! eval $_precmd && [ -z "$rc_force" ]; then
719				return 1
720			fi
721			_doit="kill -${sig_reload:-HUP} $rc_pid"
722			if [ -n "$_user" ]; then
723				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
724			fi
725			if ! eval $_doit && [ -z "$rc_force" ]; then
726				return 1
727			fi
728			eval $_postcmd
729			;;
730
731		restart)
732			if ! eval $_precmd && [ -z "$rc_force" ]; then
733				return 1
734			fi
735					# prevent restart being called more
736					# than once by any given script
737					#
738			if ${_rc_restart_done:-false}; then
739				return 0
740			fi
741			_rc_restart_done=true
742
743			( $0 ${_rc_prefix}stop )
744			$0 ${_rc_prefix}start
745
746			eval $_postcmd
747			;;
748
749		poll)
750			if [ -n "$rc_pid" ]; then
751				wait_for_pids $rc_pid
752			fi
753			;;
754
755		rcvar)
756			echo "# $name"
757			if [ -n "$rcvar" ]; then
758				if checkyesno ${rcvar}; then
759					echo "\$${rcvar}=YES"
760				else
761					echo "\$${rcvar}=NO"
762				fi
763			fi
764			;;
765
766		*)
767			rc_usage "$_keywords"
768			;;
769
770		esac
771		return 0
772	done
773
774	echo 1>&2 "$0: unknown directive '$rc_arg'."
775	rc_usage "$_keywords"
776	exit 1
777}
778
779#
780# run_rc_script file arg
781#	Start the script `file' with `arg', and correctly handle the
782#	return value from the script.  If `file' ends with `.sh', it's
783#	sourced into the current environment.  If `file' appears to be
784#	a backup or scratch file, ignore it.  Otherwise if it's
785#	executable run as a child process.
786#
787#	If `file' contains "KEYWORD: interactive" and if we are
788#	running inside /etc/rc with postprocessing (as signified by
789#	_rc_postprocessor_fd being defined) then the script's stdout
790#	and stderr are redirected to $_rc_original_stdout_fd and
791#	$_rc_original_stderr_fd, so the output will be displayed on the
792#	console but not intercepted by /etc/rc's postprocessor.
793#
794run_rc_script()
795{
796	_file=$1
797	_arg=$2
798	if [ -z "$_file" -o -z "$_arg" ]; then
799		err 3 'USAGE: run_rc_script file arg'
800	fi
801
802	_run_rc_script=true
803
804	unset	name command command_args command_interpreter \
805		extra_commands pidfile procname \
806		rcvar required_dirs required_files required_vars
807	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
808
809	_must_redirect=false
810	if [ -n "${_rc_postprocessor_fd}" ] \
811	    && _has_rcorder_keyword interactive $_file
812	then
813		_must_redirect=true
814	fi
815
816	case "$_file" in
817	*.sh)				# run in current shell
818		if $_must_redirect; then
819			print_rc_metadata \
820			    "note:Output from ${_file} is not logged"
821			no_rc_postprocess eval \
822			    'set $_arg ; . $_file'
823		else
824			set $_arg ; . $_file
825		fi
826		;;
827	*[~#]|*.OLD|*.orig|*,v)		# scratch file; skip
828		warn "Ignoring scratch file $_file"
829		;;
830	*)				# run in subshell
831		if [ -x $_file ] && $_must_redirect; then
832			print_rc_metadata \
833			    "note:Output from ${_file} is not logged"
834			if [ -n "$rc_fast_and_loose" ]; then
835				no_rc_postprocess eval \
836				    'set $_arg ; . $_file'
837			else
838				no_rc_postprocess eval \
839				    '( set $_arg ; . $_file )'
840			fi
841		elif [ -x $_file ]; then
842			if [ -n "$rc_fast_and_loose" ]; then
843				set $_arg ; . $_file
844			else
845				( set $_arg ; . $_file )
846			fi
847		else
848			warn "Ignoring non-executable file $_file"
849		fi
850		;;
851	esac
852}
853
854#
855# load_rc_config command
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		. /etc/rc.conf
869		_rc_conf_loaded=true
870	fi
871	if [ -f /etc/rc.conf.d/"$_command" ]; then
872		. /etc/rc.conf.d/"$_command"
873	fi
874}
875
876#
877# load_rc_config_var cmd var
878#	Read the rc.conf(5) var for cmd and set in the
879#	current shell, using load_rc_config in a subshell to prevent
880#	unwanted side effects from other variable assignments.
881#
882load_rc_config_var()
883{
884	if [ $# -ne 2 ]; then
885		err 3 'USAGE: load_rc_config_var cmd var'
886	fi
887	eval $(eval '(
888		load_rc_config '$1' >/dev/null;
889		if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
890			echo '$2'=\'\''${'$2'}\'\'';
891		fi
892	)' )
893}
894
895#
896# rc_usage commands
897#	Print a usage string for $0, with `commands' being a list of
898#	valid commands.
899#
900rc_usage()
901{
902	echo -n 1>&2 "Usage: $0 [fast|force|one]("
903
904	_sep=
905	for _elem; do
906		echo -n 1>&2 "$_sep$_elem"
907		_sep="|"
908	done
909	echo 1>&2 ")"
910	exit 1
911}
912
913#
914# err exitval message
915#	Display message to stderr and log to the syslog, and exit with exitval.
916#
917err()
918{
919	exitval=$1
920	shift
921
922	if [ -x /usr/bin/logger ]; then
923		logger "$0: ERROR: $*"
924	fi
925	echo 1>&2 "$0: ERROR: $*"
926	exit $exitval
927}
928
929#
930# warn message
931#	Display message to stderr and log to the syslog.
932#
933warn()
934{
935	if [ -x /usr/bin/logger ]; then
936		logger "$0: WARNING: $*"
937	fi
938	echo 1>&2 "$0: WARNING: $*"
939}
940
941#
942# backup_file action file cur backup
943#	Make a backup copy of `file' into `cur', and save the previous
944#	version of `cur' as `backup' or use rcs for archiving.
945#
946#	This routine checks the value of the backup_uses_rcs variable,
947#	which can be either YES or NO.
948#
949#	The `action' keyword can be one of the following:
950#
951#	add		`file' is now being backed up (and is possibly
952#			being reentered into the backups system).  `cur'
953#			is created and RCS files, if necessary, are
954#			created as well.
955#
956#	update		`file' has changed and needs to be backed up.
957#			If `cur' exists, it is copied to to `back' or
958#			checked into RCS (if the repository file is old),
959#			and then `file' is copied to `cur'.  Another RCS
960#			check in done here if RCS is being used.
961#
962#	remove		`file' is no longer being tracked by the backups
963#			system.  If RCS is not being used, `cur' is moved
964#			to `back', otherwise an empty file is checked in,
965#			and then `cur' is removed.
966#
967#
968backup_file()
969{
970	_action=$1
971	_file=$2
972	_cur=$3
973	_back=$4
974
975	if checkyesno backup_uses_rcs; then
976		_msg0="backup archive"
977		_msg1="update"
978
979		# ensure that history file is not locked
980		if [ -f $_cur,v ]; then
981			rcs -q -u -U -M $_cur
982		fi
983
984		# ensure after switching to rcs that the
985		# current backup is not lost
986		if [ -f $_cur ]; then
987			# no archive, or current newer than archive
988			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
989				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
990				rcs -q -kb -U $_cur
991				co -q -f -u $_cur
992			fi
993		fi
994
995		case $_action in
996		add|update)
997			cp -p $_file $_cur
998			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
999			rcs -q -kb -U $_cur
1000			co -q -f -u $_cur
1001			chown root:wheel $_cur $_cur,v
1002			;;
1003		remove)
1004			cp /dev/null $_cur
1005			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1006			rcs -q -kb -U $_cur
1007			chown root:wheel $_cur $_cur,v
1008			rm $_cur
1009			;;
1010		esac
1011	else
1012		case $_action in
1013		add|update)
1014			if [ -f $_cur ]; then
1015				cp -p $_cur $_back
1016			fi
1017			cp -p $_file $_cur
1018			chown root:wheel $_cur
1019			;;
1020		remove)
1021			mv -f $_cur $_back
1022			;;
1023		esac
1024	fi
1025}
1026
1027#
1028# handle_fsck_error fsck_exit_code
1029#	Take action depending on the return code from fsck.
1030#
1031handle_fsck_error()
1032{
1033	case $1 in
1034	0)	# OK
1035		return
1036		;;
1037	2)	# Needs re-run, still fs errors
1038		echo "File system still has errors; re-run fsck manually!"
1039		;;
1040	4)	# Root modified
1041		echo "Root filesystem was modified, rebooting ..."
1042		reboot -n
1043		echo "Reboot failed; help!"
1044		;;
1045	8)	# Check failed
1046		echo "Automatic file system check failed; help!"
1047		;;
1048	12)	# Got signal
1049		echo "Boot interrupted."
1050		;;
1051	*)
1052		echo "Unknown error $1; help!"
1053		;;
1054	esac
1055	stop_boot
1056}
1057
1058#
1059# _has_rcorder_keyword word file
1060#	Check whether a file contains a "# KEYWORD:" comment with a
1061#	specified keyword in the style used by rcorder(8).
1062#
1063_has_rcorder_keyword()
1064{
1065	local word="$1"
1066	local file="$2"
1067	local line
1068
1069	[ -r "$file" ] || return 1
1070	while read line; do
1071		case "${line} " in
1072		"# KEYWORD:"*[\ \	]"${word}"[\ \	]*)
1073			return 0
1074			;;
1075		"#"*)
1076			continue
1077			;;
1078		*[A-Za-z0-9]*)
1079			# give up at the first non-empty non-comment line
1080			return 1
1081			;;
1082		esac
1083	done <"$file"
1084	return 1
1085}
1086
1087#
1088# print_rc_metadata string
1089#	Print the specified string in such a way that the post-processor
1090#	inside /etc/rc will treat it as meta-data.
1091#
1092#	If we are not running inside /etc/rc, do nothing.
1093#
1094#	For public use by any rc.d script, the string must begin with
1095#	"note:", followed by arbitrary text.  The intent is that the text
1096#	will appear in a log file but not on the console.
1097#
1098#	For private use within /etc/rc, the string must contain a
1099#	keyword recognised by the rc_postprocess_metadata() function
1100#	defined in /etc/rc, followed by a colon, followed by one or more
1101#	colon-separated arguments associated with the keyword.
1102#
1103print_rc_metadata()
1104{
1105	# _rc_postprocessor fd, if defined, is the fd to which we must
1106	# print, prefixing the output with $_rc_metadata_prefix.
1107	#
1108	if [ -n "$_rc_postprocessor_fd" ]; then
1109		printf "%s%s\n" "$rc_metadata_prefix" "$1" \
1110			>&${_rc_postprocessor_fd}
1111	fi
1112}
1113
1114#
1115# print_rc_normal string
1116#	Print the specified string in such way that it is treated as
1117#	normal output, regardless of whether or not we are running
1118#	inside /etc/rc with post-processing.
1119#
1120#	Ths intent is that a script that is run via the
1121#	no_rc_postprocess() function (so its output would ordinarily be
1122#	invisible to the post-processor) can nevertheless arrange for
1123#	the post-processor to see things printed with print_rc_normal().
1124#
1125print_rc_normal()
1126{
1127	# If _rc_postprocessor_fd is defined, then it is the fd
1128	# to shich we must print; otherwise print to stdout.
1129	#
1130	printf "%s\n" "$1" >&${_rc_postprocessor_fd:-1}
1131}
1132
1133#
1134# no_rc_postprocess cmd...
1135#	Execute the specified command in such a way that its output
1136#	bypasses the post-processor that handles the output from
1137#	most commands that are run inside /etc/rc.  If we are not
1138#	inside /etc/rc, then just execute the command without special
1139#	treatment.
1140#
1141#	The intent is that interactive commands can be run via
1142#	no_rc_postprocess(), and their output will apear immediately
1143#	on the console instead of being hidden or delayed by the
1144#	post-processor.	 An unfortunate consequence of the output
1145#	bypassing the post-processor is that the output will not be
1146#	logged.
1147#
1148no_rc_postprocess()
1149{
1150	if [ -n "${_rc_postprocessor_fd}" ]; then
1151		"$@" >&${_rc_original_stdout_fd} 2>&${_rc_original_stderr_fd}
1152	else
1153		"$@"
1154	fi
1155}
1156
1157#
1158# twiddle
1159#	On each call, print a different one of "/", "-", "\\", "|",
1160#	followed by a backspace.  The most recently printed value is
1161#	saved in $_twiddle_state.
1162#
1163#	Output is to /dev/tty, so this function may be useful even inside
1164#	a script whose output is redirected.
1165#
1166twiddle()
1167{
1168	case "$_twiddle_state" in
1169	'/')	_next='-' ;;
1170	'-')	_next='\' ;;
1171	'\')	_next='|' ;;
1172	*)	_next='/' ;;
1173	esac
1174	printf "%s\b" "$_next" >/dev/tty
1175	_twiddle_state="$_next"
1176}
1177
1178#
1179# human_exit_code
1180#	Print the a human version of the exit code.
1181#
1182human_exit_code()
1183{
1184	if [ "$1" -lt 127 ]
1185	then
1186		echo "exited with code $1"
1187	elif [ "$(expr $1 % 256)" -eq 127 ]
1188	then
1189		# This cannot really happen because the shell will not
1190		# pass stopped job status out and the exit code is limited
1191		# to 8 bits. This code is here just for completeness.
1192		echo "stopped with signal $(expr $1 / 256)"
1193	else
1194		echo "terminated with signal $(expr $1 - 128)"
1195	fi
1196}
1197
1198#
1199# collapse_backslash_newline
1200#	Copy input to output, collapsing <backslash><newline>
1201#	to nothing, but leaving other backslashes alone.
1202#
1203collapse_backslash_newline()
1204{
1205	local line
1206	while read -r line ; do
1207		case "$line" in
1208		*\\)
1209			# print it, without the backslash or newline
1210			printf "%s" "${line%?}"
1211			;;
1212		*)
1213			# print it, with a newline
1214			printf "%s\n" "${line}"
1215			;;
1216		esac
1217	done
1218}
1219
1220_rc_subr_loaded=:
1221