rc.subr revision 1.92.8.1
1# $NetBSD: rc.subr,v 1.92.8.1 2014/08/10 07:03:06 tls Exp $
2#
3# Copyright (c) 1997-2011 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 file systems 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			*[uU]'nknown 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 [ $1 = "/usr/bin/env" ]; then
252			shift
253			set -- $(type $1)
254			shift $(($# - 1))
255			_interp="${1##*/} $_procname"
256		else
257			_interp="$* $_procname"
258		fi
259		if [ $_interpreter != $1 ]; then
260			warn "\$command_interpreter $_interpreter != $1"
261		fi
262		_interpbn=${1##*/}
263		_fp_args='_argv'
264		_fp_match='case "$_argv" in
265		    ${_interp}|"${_interp} "*|"${_interpbn}: "*${_procnamebn}*)'
266	else					# a normal daemon
267		_fp_args='_arg0 _argv'
268		_fp_match='case "$_arg0" in
269		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")'
270	fi
271
272	_proccheck='
273		ps -o "pid,command" '"$_psargs"' |
274		while read _npid '"$_fp_args"'; do
275			case "$_npid" in
276			    PID)
277				continue ;;
278			esac ; '"$_fp_match"'
279				echo -n "$_pref$_npid" ;
280				_pref=" "
281				;;
282			esac
283		done'
284
285#echo 1>&2 "proccheck is :$_proccheck:"
286	eval $_proccheck
287}
288
289#
290# wait_for_pids pid [pid ...]
291#	spins until none of the pids exist
292#
293wait_for_pids()
294{
295	_list="$@"
296	if [ -z "$_list" ]; then
297		return
298	fi
299	_prefix=
300	while true; do
301		_nlist="";
302		for _j in $_list; do
303			if kill -0 $_j 2>/dev/null; then
304				_nlist="${_nlist}${_nlist:+ }$_j"
305			fi
306		done
307		if [ -z "$_nlist" ]; then
308			break
309		fi
310		_list=$_nlist
311		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
312		_prefix=", "
313		sleep 2
314	done
315	if [ -n "$_prefix" ]; then
316		echo "."
317	fi
318}
319
320#
321# run_rc_command argument [parameters]
322#	Search for argument in the list of supported commands, which is:
323#		"start stop restart rcvar status poll ${extra_commands}"
324#	If there's a match, run ${argument}_cmd or the default method
325#	(see below), and pass the optional list of parameters to it.
326#
327#	If argument has a given prefix, then change the operation as follows:
328#		Prefix	Operation
329#		------	---------
330#		fast	Skip the pid check, and set rc_fast=yes
331#		force	Set ${rcvar} to YES, and set rc_force=yes
332#		one	Set ${rcvar} to YES
333#
334#	The following globals are used:
335#
336#	Name		Needed	Purpose
337#	----		------	-------
338#	name		y	Name of script.
339#
340#	command		n	Full path to command.
341#				Not needed if ${rc_arg}_cmd is set for
342#				each keyword.
343#
344#	command_args	n	Optional args/shell directives for command.
345#
346#	command_interpreter n	If not empty, command is interpreted, so
347#				call check_{pidfile,process}() appropriately.
348#
349#	extra_commands	n	List of extra commands supported.
350#
351#	pidfile		n	If set, use check_pidfile $pidfile $command,
352#				otherwise use check_process $command.
353#				In either case, only check if $command is set.
354#
355#	procname	n	Process name to check for instead of $command.
356#
357#	rcvar		n	This is checked with checkyesno to determine
358#				if the action should be run.
359#
360#	${name}_chroot	n	Directory to chroot to before running ${command}
361#				Requires /usr to be mounted.
362#
363#	${name}_chdir	n	Directory to cd to before running ${command}
364#				(if not using ${name}_chroot).
365#
366#	${name}_flags	n	Arguments to call ${command} with.
367#				NOTE:	$flags from the parent environment
368#					can be used to override this.
369#
370#	${name}_env	n	Additional environment variable settings
371#				for running ${command}
372#
373#	${name}_nice	n	Nice level to run ${command} at.
374#
375#	${name}_user	n	User to run ${command} as, using su(1) if not
376#				using ${name}_chroot.
377#				Requires /usr to be mounted.
378#
379#	${name}_group	n	Group to run chrooted ${command} as.
380#				Requires /usr to be mounted.
381#
382#	${name}_groups	n	Comma separated list of supplementary groups
383#				to run the chrooted ${command} with.
384#				Requires /usr to be mounted.
385#
386#	${rc_arg}_cmd	n	If set, use this as the method when invoked;
387#				Otherwise, use default command (see below)
388#
389#	${rc_arg}_precmd n	If set, run just before performing the
390#				${rc_arg}_cmd method in the default
391#				operation (i.e, after checking for required
392#				bits and process (non)existence).
393#				If this completes with a non-zero exit code,
394#				don't run ${rc_arg}_cmd.
395#
396#	${rc_arg}_postcmd n	If set, run just after performing the
397#				${rc_arg}_cmd method, if that method
398#				returned a zero exit code.
399#
400#	required_dirs	n	If set, check for the existence of the given
401#				directories before running the default
402#				(re)start command.
403#
404#	required_files	n	If set, check for the readability of the given
405#				files before running the default (re)start
406#				command.
407#
408#	required_vars	n	If set, perform checkyesno on each of the
409#				listed variables before running the default
410#				(re)start command.
411#
412#	Default behaviour for a given argument, if no override method is
413#	provided:
414#
415#	Argument	Default behaviour
416#	--------	-----------------
417#	start		if !running && checkyesno ${rcvar}
418#				${command}
419#
420#	stop		if ${pidfile}
421#				rc_pid=$(check_pidfile $pidfile $command)
422#			else
423#				rc_pid=$(check_process $command)
424#			kill $sig_stop $rc_pid
425#			wait_for_pids $rc_pid
426#			($sig_stop defaults to TERM.)
427#
428#	reload		Similar to stop, except use $sig_reload instead,
429#			and doesn't wait_for_pids.
430#			$sig_reload defaults to HUP.
431#
432#	restart		Run `stop' then `start'.
433#
434#	status		Show if ${command} is running, etc.
435#
436#	poll		Wait for ${command} to exit.
437#
438#	rcvar		Display what rc.conf variable is used (if any).
439#
440#	Variables available to methods, and after run_rc_command() has
441#	completed:
442#
443#	Variable	Purpose
444#	--------	-------
445#	rc_arg		Argument to command, after fast/force/one processing
446#			performed
447#
448#	rc_flags	Flags to start the default command with.
449#			Defaults to ${name}_flags, unless overridden
450#			by $flags from the environment.
451#			This variable may be changed by the precmd method.
452#
453#	rc_pid		PID of command (if appropriate)
454#
455#	rc_fast		Not empty if "fast" was provided (q.v.)
456#
457#	rc_force	Not empty if "force" was provided (q.v.)
458#
459#
460run_rc_command()
461{
462	rc_arg=$1
463	if [ -z "$name" ]; then
464		err 3 'run_rc_command: $name is not set.'
465	fi
466
467	_rc_prefix=
468	case "$rc_arg" in
469	fast*)				# "fast" prefix; don't check pid
470		rc_arg=${rc_arg#fast}
471		rc_fast=yes
472		;;
473	force*)				# "force" prefix; always run
474		rc_force=yes
475		_rc_prefix=force
476		rc_arg=${rc_arg#${_rc_prefix}}
477		if [ -n "${rcvar}" ]; then
478			eval ${rcvar}=YES
479		fi
480		;;
481	one*)				# "one" prefix; set ${rcvar}=yes
482		_rc_prefix=one
483		rc_arg=${rc_arg#${_rc_prefix}}
484		if [ -n "${rcvar}" ]; then
485			eval ${rcvar}=YES
486		fi
487		;;
488	esac
489
490	_keywords="start stop restart rcvar"
491	if [ -n "$extra_commands" ]; then
492		_keywords="${_keywords} ${extra_commands}"
493	fi
494	rc_pid=
495	_pidcmd=
496	_procname=${procname:-${command}}
497
498					# setup pid check command if not fast
499	if [ -z "$rc_fast" -a -n "$_procname" ]; then
500		if [ -n "$pidfile" ]; then
501			_pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
502		else
503			_pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
504		fi
505		if [ -n "$_pidcmd" ]; then
506			_keywords="${_keywords} status poll"
507		fi
508	fi
509
510	if [ -z "$rc_arg" ]; then
511		rc_usage "$_keywords"
512	fi
513	shift	# remove $rc_arg from the positional parameters
514
515	if [ -n "$flags" ]; then	# allow override from environment
516		rc_flags=$flags
517	else
518		eval rc_flags=\$${name}_flags
519	fi
520	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
521	    _nice=\$${name}_nice	_user=\$${name}_user \
522	    _group=\$${name}_group	_groups=\$${name}_groups \
523	    _env=\"\$${name}_env\"
524
525	if [ -n "$_user" ]; then	# unset $_user if running as that user
526		if [ "$_user" = "$(id -un)" ]; then
527			unset _user
528		fi
529	fi
530
531					# if ${rcvar} is set, and $1 is not
532					# "rcvar", then run
533					#	checkyesno ${rcvar}
534					# and return if that failed or warn
535					# user and exit when interactive
536					#
537	if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
538		if ! checkyesno ${rcvar}; then
539					# check whether interactive or not
540			if [ -n "$_run_rc_script" ]; then
541				return 0
542			fi
543			for _elem in $_keywords; do
544				if [ "$_elem" = "$rc_arg" ]; then
545					cat 1>&2 <<EOF
546\$${rcvar} is not enabled - see ${rcvar_manpage}.
547Use the following if you wish to perform the operation:
548  $0 one${rc_arg}
549EOF
550					exit 1
551				fi
552			done
553			echo 1>&2 "$0: unknown directive '$rc_arg'."
554			rc_usage "$_keywords"
555		fi
556	fi
557
558	eval $_pidcmd			# determine the pid if necessary
559
560	for _elem in $_keywords; do
561		if [ "$_elem" != "$rc_arg" ]; then
562			continue
563		fi
564
565					# if there's a custom ${XXX_cmd},
566					# run that instead of the default
567					#
568		eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \
569		    _postcmd=\$${rc_arg}_postcmd
570		if [ -n "$_cmd" ]; then
571					# if the precmd failed and force
572					# isn't set, exit
573					#
574			if ! eval $_precmd && [ -z "$rc_force" ]; then
575				return 1
576			fi
577
578			if ! eval $_cmd \"\${@}\" && [ -z "$rc_force" ]; then
579				return 1
580			fi
581			eval $_postcmd
582			return 0
583		fi
584
585		if [ ${#} -gt 0 ]; then
586			err 1 "the $rc_arg command does not take any parameters"
587		fi
588
589		case "$rc_arg" in	# default operations...
590
591		status)
592			if [ -n "$rc_pid" ]; then
593				echo "${name} is running as pid $rc_pid."
594			else
595				echo "${name} is not running."
596				return 1
597			fi
598			;;
599
600		start)
601			if [ -n "$rc_pid" ]; then
602				echo 1>&2 "${name} already running? (pid=$rc_pid)."
603				exit 1
604			fi
605
606			if [ ! -x ${_chroot}${command} ]; then
607				return 0
608			fi
609
610					# check for required variables,
611					# directories, and files
612					#
613			for _f in $required_vars; do
614				if ! checkyesno $_f; then
615					warn "\$${_f} is not enabled."
616					if [ -z "$rc_force" ]; then
617						return 1
618					fi
619				fi
620			done
621			for _f in $required_dirs; do
622				if [ ! -d "${_f}/." ]; then
623					warn "${_f} is not a directory."
624					if [ -z "$rc_force" ]; then
625						return 1
626					fi
627				fi
628			done
629			for _f in $required_files; do
630				if [ ! -r "${_f}" ]; then
631					warn "${_f} is not readable."
632					if [ -z "$rc_force" ]; then
633						return 1
634					fi
635				fi
636			done
637
638					# if the precmd failed and force
639					# isn't set, exit
640					#
641			if ! eval $_precmd && [ -z "$rc_force" ]; then
642				return 1
643			fi
644
645					# setup the command to run, and run it
646					#
647			echo "Starting ${name}."
648			if [ -n "$_chroot" ]; then
649				_doit="\
650${_env:+env $_env }\
651${_nice:+nice -n $_nice }\
652chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
653$_chroot $command $rc_flags $command_args"
654			else
655				_doit="\
656${_chdir:+cd $_chdir; }\
657${_env:+env $_env }\
658${_nice:+nice -n $_nice }\
659$command $rc_flags $command_args"
660				if [ -n "$_user" ]; then
661				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
662				fi
663			fi
664
665					# if the cmd failed and force
666					# isn't set, exit
667					#
668			if ! eval $_doit && [ -z "$rc_force" ]; then
669				return 1
670			fi
671
672					# finally, run postcmd
673					#
674			eval $_postcmd
675			;;
676
677		stop)
678			if [ -z "$rc_pid" ]; then
679				if [ -n "$pidfile" ]; then
680					echo 1>&2 \
681				    "${name} not running? (check $pidfile)."
682				else
683					echo 1>&2 "${name} not running?"
684				fi
685				exit 1
686			fi
687
688					# if the precmd failed and force
689					# isn't set, exit
690					#
691			if ! eval $_precmd && [ -z "$rc_force" ]; then
692				return 1
693			fi
694
695					# send the signal to stop
696					#
697			echo "Stopping ${name}."
698			_doit="kill -${sig_stop:-TERM} $rc_pid"
699			if [ -n "$_user" ]; then
700				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
701			fi
702
703					# if the stop cmd failed and force
704					# isn't set, exit
705					#
706			if ! eval $_doit && [ -z "$rc_force" ]; then
707				return 1
708			fi
709
710					# wait for the command to exit,
711					# and run postcmd.
712			wait_for_pids $rc_pid
713			eval $_postcmd
714			;;
715
716		reload)
717			if [ -z "$rc_pid" ]; then
718				if [ -n "$pidfile" ]; then
719					echo 1>&2 \
720				    "${name} not running? (check $pidfile)."
721				else
722					echo 1>&2 "${name} not running?"
723				fi
724				exit 1
725			fi
726			echo "Reloading ${name} config files."
727			if ! eval $_precmd && [ -z "$rc_force" ]; then
728				return 1
729			fi
730			_doit="kill -${sig_reload:-HUP} $rc_pid"
731			if [ -n "$_user" ]; then
732				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
733			fi
734			if ! eval $_doit && [ -z "$rc_force" ]; then
735				return 1
736			fi
737			eval $_postcmd
738			;;
739
740		restart)
741			if ! eval $_precmd && [ -z "$rc_force" ]; then
742				return 1
743			fi
744					# prevent restart being called more
745					# than once by any given script
746					#
747			if ${_rc_restart_done:-false}; then
748				return 0
749			fi
750			_rc_restart_done=true
751
752			( $0 ${_rc_prefix}stop )
753			$0 ${_rc_prefix}start
754
755			eval $_postcmd
756			;;
757
758		poll)
759			if [ -n "$rc_pid" ]; then
760				wait_for_pids $rc_pid
761			fi
762			;;
763
764		rcvar)
765			echo "# $name"
766			if [ -n "$rcvar" ]; then
767				if checkyesno ${rcvar}; then
768					echo "\$${rcvar}=YES"
769				else
770					echo "\$${rcvar}=NO"
771				fi
772			fi
773			;;
774
775		*)
776			rc_usage "$_keywords"
777			;;
778
779		esac
780		return 0
781	done
782
783	echo 1>&2 "$0: unknown directive '$rc_arg'."
784	rc_usage "$_keywords"
785	exit 1
786}
787
788#
789# _have_rc_postprocessor
790#	Test whether the current script is running in a context that
791#	was invoked from /etc/rc with a postprocessor.
792#
793#	If the test fails, some variables may be unset to make
794#	such tests more efficient in future.
795#
796_have_rc_postprocessor()
797{
798	# Cheap tests that fd and pid are set, fd is writable.
799	[ -n "${_rc_postprocessor_fd}" ] || return 1
800	[ -n "${_rc_pid}" ] || return 1
801	eval ": >&${_rc_postprocessor_fd}" 2>/dev/null || return 1
802
803	# More expensive test that pid is running.
804	# Unset _rc_pid if this fails.
805	kill -0 "${_rc_pid}" 2>/dev/null \
806	|| { unset _rc_pid; return 1; }
807
808	# More expensive test that pid appears to be
809	# a shell running an rc script.
810	# Unset _rc_pid if this fails.
811	expr "$(ps -p "${_rc_pid}" -o command=)" : ".*sh .*/rc.*" >/dev/null \
812	|| { unset _rc_pid; return 1; }
813
814	return 0
815}
816
817#
818# run_rc_script file arg
819#	Start the script `file' with `arg', and correctly handle the
820#	return value from the script.  If `file' ends with `.sh', it's
821#	sourced into the current environment.  If `file' appears to be
822#	a backup or scratch file, ignore it.  Otherwise if it's
823#	executable run as a child process.
824#
825#	If `file' contains "KEYWORD: interactive" and if we are
826#	running inside /etc/rc with postprocessing, then the script's
827#	stdout and stderr are redirected to $_rc_original_stdout_fd and
828#	$_rc_original_stderr_fd, so the output will be displayed on the
829#	console but not intercepted by /etc/rc's postprocessor.
830#
831run_rc_script()
832{
833	_file=$1
834	_arg=$2
835	if [ -z "$_file" -o -z "$_arg" ]; then
836		err 3 'USAGE: run_rc_script file arg'
837	fi
838
839	_run_rc_script=true
840
841	unset	name command command_args command_interpreter \
842		extra_commands pidfile procname \
843		rcvar required_dirs required_files required_vars
844	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
845
846	_must_redirect=false
847	if _have_rc_postprocessor \
848	    && _has_rcorder_keyword interactive $_file
849	then
850		_must_redirect=true
851	fi
852
853	case "$_file" in
854	*.sh)				# run in current shell
855		if $_must_redirect; then
856			print_rc_metadata \
857			    "note:Output from ${_file} is not logged"
858			no_rc_postprocess eval \
859			    'set $_arg ; . $_file'
860		else
861			set $_arg ; . $_file
862		fi
863		;;
864	*[~#]|*.OLD|*.orig|*,v)		# scratch file; skip
865		warn "Ignoring scratch file $_file"
866		;;
867	*)				# run in subshell
868		if [ -x $_file ] && $_must_redirect; then
869			print_rc_metadata \
870			    "note:Output from ${_file} is not logged"
871			if [ -n "$rc_fast_and_loose" ]; then
872				no_rc_postprocess eval \
873				    'set $_arg ; . $_file'
874			else
875				no_rc_postprocess eval \
876				    '( set $_arg ; . $_file )'
877			fi
878		elif [ -x $_file ]; then
879			if [ -n "$rc_fast_and_loose" ]; then
880				set $_arg ; . $_file
881			else
882				( set $_arg ; . $_file )
883			fi
884		else
885			warn "Ignoring non-executable file $_file"
886		fi
887		;;
888	esac
889}
890
891#
892# load_rc_config command
893#	Source in the configuration file for a given command.
894#
895load_rc_config()
896{
897	_command=$1
898	if [ -z "$_command" ]; then
899		err 3 'USAGE: load_rc_config command'
900	fi
901
902	if ${_rc_conf_loaded:-false}; then
903		:
904	else
905		. /etc/rc.conf
906		_rc_conf_loaded=true
907	fi
908	if [ -f /etc/rc.conf.d/"$_command" ]; then
909		. /etc/rc.conf.d/"$_command"
910	fi
911}
912
913#
914# load_rc_config_var cmd var
915#	Read the rc.conf(5) var for cmd and set in the
916#	current shell, using load_rc_config in a subshell to prevent
917#	unwanted side effects from other variable assignments.
918#
919load_rc_config_var()
920{
921	if [ $# -ne 2 ]; then
922		err 3 'USAGE: load_rc_config_var cmd var'
923	fi
924	eval $(eval '(
925		load_rc_config '$1' >/dev/null;
926		if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
927			echo '$2'=\'\''${'$2'}\'\'';
928		fi
929	)' )
930}
931
932#
933# rc_usage commands
934#	Print a usage string for $0, with `commands' being a list of
935#	valid commands.
936#
937rc_usage()
938{
939	echo -n 1>&2 "Usage: $0 [fast|force|one]("
940
941	_sep=
942	for _elem; do
943		echo -n 1>&2 "$_sep$_elem"
944		_sep="|"
945	done
946	echo 1>&2 ")"
947	exit 1
948}
949
950#
951# err exitval message
952#	Display message to stderr and log to the syslog, and exit with exitval.
953#
954err()
955{
956	exitval=$1
957	shift
958
959	if [ -x /usr/bin/logger ]; then
960		logger "$0: ERROR: $*"
961	fi
962	echo 1>&2 "$0: ERROR: $*"
963	exit $exitval
964}
965
966#
967# warn message
968#	Display message to stderr and log to the syslog.
969#
970warn()
971{
972	if [ -x /usr/bin/logger ]; then
973		logger "$0: WARNING: $*"
974	fi
975	echo 1>&2 "$0: WARNING: $*"
976}
977
978#
979# backup_file action file cur backup
980#	Make a backup copy of `file' into `cur', and save the previous
981#	version of `cur' as `backup' or use rcs for archiving.
982#
983#	This routine checks the value of the backup_uses_rcs variable,
984#	which can be either YES or NO.
985#
986#	The `action' keyword can be one of the following:
987#
988#	add		`file' is now being backed up (and is possibly
989#			being reentered into the backups system).  `cur'
990#			is created and RCS files, if necessary, are
991#			created as well.
992#
993#	update		`file' has changed and needs to be backed up.
994#			If `cur' exists, it is copied to to `back' or
995#			checked into RCS (if the repository file is old),
996#			and then `file' is copied to `cur'.  Another RCS
997#			check in done here if RCS is being used.
998#
999#	remove		`file' is no longer being tracked by the backups
1000#			system.  If RCS is not being used, `cur' is moved
1001#			to `back', otherwise an empty file is checked in,
1002#			and then `cur' is removed.
1003#
1004#
1005backup_file()
1006{
1007	_action=$1
1008	_file=$2
1009	_cur=$3
1010	_back=$4
1011
1012	if checkyesno backup_uses_rcs; then
1013		_msg0="backup archive"
1014		_msg1="update"
1015
1016		# ensure that history file is not locked
1017		if [ -f $_cur,v ]; then
1018			rcs -q -u -U -M $_cur
1019		fi
1020
1021		# ensure after switching to rcs that the
1022		# current backup is not lost
1023		if [ -f $_cur ]; then
1024			# no archive, or current newer than archive
1025			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1026				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1027				rcs -q -kb -U $_cur
1028				co -q -f -u $_cur
1029			fi
1030		fi
1031
1032		case $_action in
1033		add|update)
1034			cp -p $_file $_cur
1035			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1036			rcs -q -kb -U $_cur
1037			co -q -f -u $_cur
1038			chown root:wheel $_cur $_cur,v
1039			;;
1040		remove)
1041			cp /dev/null $_cur
1042			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1043			rcs -q -kb -U $_cur
1044			chown root:wheel $_cur $_cur,v
1045			rm $_cur
1046			;;
1047		esac
1048	else
1049		case $_action in
1050		add|update)
1051			if [ -f $_cur ]; then
1052				cp -p $_cur $_back
1053			fi
1054			cp -p $_file $_cur
1055			chown root:wheel $_cur
1056			;;
1057		remove)
1058			mv -f $_cur $_back
1059			;;
1060		esac
1061	fi
1062}
1063
1064#
1065# handle_fsck_error fsck_exit_code
1066#	Take action depending on the return code from fsck.
1067#
1068handle_fsck_error()
1069{
1070	case $1 in
1071	0)	# OK
1072		return
1073		;;
1074	2)	# Needs re-run, still fs errors
1075		echo "File system still has errors; re-run fsck manually!"
1076		;;
1077	4)	# Root modified
1078		echo "Root file system was modified, rebooting ..."
1079		reboot -n
1080		echo "Reboot failed; help!"
1081		;;
1082	8)	# Check failed
1083		echo "Automatic file system check failed; help!"
1084		;;
1085	12)	# Got signal
1086		echo "Boot interrupted."
1087		;;
1088	*)
1089		echo "Unknown error $1; help!"
1090		;;
1091	esac
1092	stop_boot
1093}
1094
1095#
1096# _has_rcorder_keyword word file
1097#	Check whether a file contains a "# KEYWORD:" comment with a
1098#	specified keyword in the style used by rcorder(8).
1099#
1100_has_rcorder_keyword()
1101{
1102	local word="$1"
1103	local file="$2"
1104	local line
1105
1106	[ -r "$file" ] || return 1
1107	while read line; do
1108		case "${line} " in
1109		"# KEYWORD:"*[\ \	]"${word}"[\ \	]*)
1110			return 0
1111			;;
1112		"#"*)
1113			continue
1114			;;
1115		*[A-Za-z0-9]*)
1116			# give up at the first non-empty non-comment line
1117			return 1
1118			;;
1119		esac
1120	done <"$file"
1121	return 1
1122}
1123
1124#
1125# print_rc_metadata string
1126#	Print the specified string in such a way that the post-processor
1127#	inside /etc/rc will treat it as meta-data.
1128#
1129#	If we are not running inside /etc/rc, do nothing.
1130#
1131#	For public use by any rc.d script, the string must begin with
1132#	"note:", followed by arbitrary text.  The intent is that the text
1133#	will appear in a log file but not on the console.
1134#
1135#	For private use within /etc/rc, the string must contain a
1136#	keyword recognised by the rc_postprocess_metadata() function
1137#	defined in /etc/rc, followed by a colon, followed by one or more
1138#	colon-separated arguments associated with the keyword.
1139#
1140print_rc_metadata()
1141{
1142	# _rc_postprocessor fd, if defined, is the fd to which we must
1143	# print, prefixing the output with $_rc_metadata_prefix.
1144	#
1145	if _have_rc_postprocessor; then
1146		command printf "%s%s\n" "$rc_metadata_prefix" "$1" \
1147			>&${_rc_postprocessor_fd}
1148	fi
1149}
1150
1151#
1152# _flush_rc_output
1153#	Arrange for output to be flushed, if we are running
1154#	inside /etc/rc with postprocessing.
1155#
1156_flush_rc_output()
1157{
1158	print_rc_metadata "nop"
1159}
1160
1161#
1162# print_rc_normal [-n] string
1163#	Print the specified string in such way that it is treated as
1164#	normal output, regardless of whether or not we are running
1165#	inside /etc/rc with post-processing.
1166#
1167#	If "-n" is specified in $1, then the string in $2 is printed
1168#	without a newline; otherwise, the string in $1 is printed
1169#	with a newline.
1170#
1171#	Intended use cases include:
1172#
1173#	o   An rc.d script can use ``print_rc_normal -n'' to print a
1174#	    partial line in such a way that it appears immediately
1175#	    instead of being buffered by rc(8)'s post-processor.
1176#
1177#	o   An rc.d script that is run via the no_rc_postprocess
1178#	    function (so most of its output is invisible to rc(8)'s
1179#	    post-processor) can use print_rc_normal to force some of its
1180#	    output to be seen by the post-processor.
1181#
1182#
1183print_rc_normal()
1184{
1185	# print to stdout or _rc_postprocessor_fd, depending on
1186	# whether not we have an rc postprocessor.
1187	#
1188	local fd=1
1189	_have_rc_postprocessor && fd="${_rc_postprocessor_fd}"
1190	case "$1" in
1191	"-n")
1192		command printf "%s" "$2" >&${fd}
1193		_flush_rc_output
1194		;;
1195	*)
1196		command printf "%s\n" "$1" >&${fd}
1197		;;
1198	esac
1199}
1200
1201#
1202# no_rc_postprocess cmd...
1203#	Execute the specified command in such a way that its output
1204#	bypasses the post-processor that handles the output from
1205#	most commands that are run inside /etc/rc.  If we are not
1206#	inside /etc/rc, then just execute the command without special
1207#	treatment.
1208#
1209#	The intent is that interactive commands can be run via
1210#	no_rc_postprocess(), and their output will apear immediately
1211#	on the console instead of being hidden or delayed by the
1212#	post-processor.	 An unfortunate consequence of the output
1213#	bypassing the post-processor is that the output will not be
1214#	logged.
1215#
1216no_rc_postprocess()
1217{
1218	if _have_rc_postprocessor; then
1219		"$@" >&${_rc_original_stdout_fd} 2>&${_rc_original_stderr_fd}
1220	else
1221		"$@"
1222	fi
1223}
1224
1225#
1226# twiddle
1227#	On each call, print a different one of "/", "-", "\\", "|",
1228#	followed by a backspace.  The most recently printed value is
1229#	saved in $_twiddle_state.
1230#
1231#	Output is to /dev/tty, so this function may be useful even inside
1232#	a script whose output is redirected.
1233#
1234twiddle()
1235{
1236	case "$_twiddle_state" in
1237	'/')	_next='-' ;;
1238	'-')	_next='\' ;;
1239	'\')	_next='|' ;;
1240	*)	_next='/' ;;
1241	esac
1242	command printf "%s\b" "$_next" >/dev/tty
1243	_twiddle_state="$_next"
1244}
1245
1246#
1247# human_exit_code
1248#	Print the a human version of the exit code.
1249#
1250human_exit_code()
1251{
1252	if [ "$1" -lt 127 ]
1253	then
1254		echo "exited with code $1"
1255	elif [ "$(expr $1 % 256)" -eq 127 ]
1256	then
1257		# This cannot really happen because the shell will not
1258		# pass stopped job status out and the exit code is limited
1259		# to 8 bits. This code is here just for completeness.
1260		echo "stopped with signal $(expr $1 / 256)"
1261	else
1262		echo "terminated with signal $(expr $1 - 128)"
1263	fi
1264}
1265
1266#
1267# collapse_backslash_newline
1268#	Copy input to output, collapsing <backslash><newline>
1269#	to nothing, but leaving other backslashes alone.
1270#
1271collapse_backslash_newline()
1272{
1273	local line
1274	while read -r line ; do
1275		case "$line" in
1276		*\\)
1277			# print it, without the backslash or newline
1278			command printf "%s" "${line%?}"
1279			;;
1280		*)
1281			# print it, with a newline
1282			command printf "%s\n" "${line}"
1283			;;
1284		esac
1285	done
1286}
1287
1288# Shell implementations of basename and dirname, usable before
1289# the /usr file system is mounted.
1290#
1291basename()
1292{
1293	local file="$1"
1294	local suffix="$2"
1295	local base
1296
1297	base="${file##*/}"		# remove up to and including last '/'
1298	base="${base%${suffix}}"	# remove suffix, if any
1299	command printf "%s\n" "${base}"
1300}
1301
1302dirname()
1303{
1304	local file="$1"
1305	local dir
1306
1307	case "$file" in
1308	/*/*)	dir="${file%/*}" ;;	# common case: absolute path
1309	/*)	dir="/" ;;		# special case: name in root dir
1310	*/*)	dir="${file%/*}" ;;	# common case: relative path with '/'
1311	*)	dir="." ;;		# special case: name without '/'
1312	esac
1313	command printf "%s\n" "${dir}"
1314}
1315
1316# Override the normal "echo" and "printf" commands, so that
1317# partial lines printed by rc.d scripts appear immediately,
1318# instead of being buffered by rc(8)'s post-processor.
1319#
1320# Naive use of the echo or printf commands from rc.d scripts,
1321# elsewhere in rc.subr, or anything else that sources rc.subr,
1322# will call these functions.  To call the real echo and printf
1323# commands, use "command echo" or "command printf".
1324#
1325echo()
1326{
1327	command echo "$@"
1328	case "$1" in
1329	'-n')	_flush_rc_output ;;
1330	esac
1331}
1332printf()
1333{
1334	command printf "$@"
1335	case "$1" in
1336	*'\n')	: ;;
1337	*)	_flush_rc_output ;;
1338	esac
1339}
1340
1341_rc_subr_loaded=:
1342