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