rc.subr revision 1.98
1# $NetBSD: rc.subr,v 1.98 2016/03/06 18:49:42 christos 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_pid}" ] || { unset _rc_pid; return 1; }
818	[ -n "${_rc_postprocessor_fd}" ] || { unset _rc_pid; return 1; }
819	eval ": >&${_rc_postprocessor_fd}" 2>/dev/null \
820	|| { unset _rc_pid; return 1; }
821
822	return 0
823}
824
825#
826# run_rc_script file arg
827#	Start the script `file' with `arg', and correctly handle the
828#	return value from the script.  If `file' ends with `.sh', it's
829#	sourced into the current environment.  If `file' appears to be
830#	a backup or scratch file, ignore it.  Otherwise if it's
831#	executable run as a child process.
832#
833#	If `file' contains "KEYWORD: interactive" and if we are
834#	running inside /etc/rc with postprocessing, then the script's
835#	stdout and stderr are redirected to $_rc_original_stdout_fd and
836#	$_rc_original_stderr_fd, so the output will be displayed on the
837#	console but not intercepted by /etc/rc's postprocessor.
838#
839run_rc_script()
840{
841	_file=$1
842	_arg=$2
843	if [ -z "$_file" -o -z "$_arg" ]; then
844		err 3 'USAGE: run_rc_script file arg'
845	fi
846
847	_run_rc_script=true
848
849	unset	name command command_args command_interpreter \
850		extra_commands pidfile procname \
851		rcvar required_dirs required_files required_vars
852	eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
853
854	_must_redirect=false
855	if _have_rc_postprocessor \
856	    && _has_rcorder_keyword interactive $_file
857	then
858		_must_redirect=true
859	fi
860
861	case "$_file" in
862	*.sh)				# run in current shell
863		if $_must_redirect; then
864			print_rc_metadata \
865			    "note:Output from ${_file} is not logged"
866			no_rc_postprocess eval \
867			    'set $_arg ; . $_file'
868		else
869			set $_arg ; . $_file
870		fi
871		;;
872	*[~#]|*.OLD|*.orig|*,v)		# scratch file; skip
873		warn "Ignoring scratch file $_file"
874		;;
875	*)				# run in subshell
876		if [ -x $_file ] && $_must_redirect; then
877			print_rc_metadata \
878			    "note:Output from ${_file} is not logged"
879			if [ -n "$rc_fast_and_loose" ]; then
880				no_rc_postprocess eval \
881				    'set $_arg ; . $_file'
882			else
883				no_rc_postprocess eval \
884				    '( set $_arg ; . $_file )'
885			fi
886		elif [ -x $_file ]; then
887			if [ -n "$rc_fast_and_loose" ]; then
888				set $_arg ; . $_file
889			else
890				( set $_arg ; . $_file )
891			fi
892		else
893			warn "Ignoring non-executable file $_file"
894		fi
895		;;
896	esac
897}
898
899#
900# load_rc_config command
901#	Source in the configuration file for a given command.
902#
903load_rc_config()
904{
905	_command=$1
906	if [ -z "$_command" ]; then
907		err 3 'USAGE: load_rc_config command'
908	fi
909
910	if ${_rc_conf_loaded:-false}; then
911		:
912	else
913		. /etc/rc.conf
914		_rc_conf_loaded=true
915	fi
916	if [ -f /etc/rc.conf.d/"$_command" ]; then
917		. /etc/rc.conf.d/"$_command"
918	fi
919}
920
921#
922# load_rc_config_var cmd var
923#	Read the rc.conf(5) var for cmd and set in the
924#	current shell, using load_rc_config in a subshell to prevent
925#	unwanted side effects from other variable assignments.
926#
927load_rc_config_var()
928{
929	if [ $# -ne 2 ]; then
930		err 3 'USAGE: load_rc_config_var cmd var'
931	fi
932	eval $(eval '(
933		load_rc_config '$1' >/dev/null;
934		if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
935			echo '$2'=\'\''${'$2'}\'\'';
936		fi
937	)' )
938}
939
940#
941# rc_usage commands
942#	Print a usage string for $0, with `commands' being a list of
943#	valid commands.
944#
945rc_usage()
946{
947	echo -n 1>&2 "Usage: $0 [fast|force|one]("
948
949	_sep=
950	for _elem; do
951		echo -n 1>&2 "$_sep$_elem"
952		_sep="|"
953	done
954	echo 1>&2 ")"
955	exit 1
956}
957
958#
959# err exitval message
960#	Display message to stderr and log to the syslog, and exit with exitval.
961#
962err()
963{
964	exitval=$1
965	shift
966
967	if [ -x /usr/bin/logger ]; then
968		logger "$0: ERROR: $*"
969	fi
970	echo 1>&2 "$0: ERROR: $*"
971	exit $exitval
972}
973
974#
975# warn message
976#	Display message to stderr and log to the syslog.
977#
978warn()
979{
980	if [ -x /usr/bin/logger ]; then
981		logger "$0: WARNING: $*"
982	fi
983	echo 1>&2 "$0: WARNING: $*"
984}
985
986#
987# backup_file action file cur backup
988#	Make a backup copy of `file' into `cur', and save the previous
989#	version of `cur' as `backup' or use rcs for archiving.
990#
991#	This routine checks the value of the backup_uses_rcs variable,
992#	which can be either YES or NO.
993#
994#	The `action' keyword can be one of the following:
995#
996#	add		`file' is now being backed up (and is possibly
997#			being reentered into the backups system).  `cur'
998#			is created and RCS files, if necessary, are
999#			created as well.
1000#
1001#	update		`file' has changed and needs to be backed up.
1002#			If `cur' exists, it is copied to to `back' or
1003#			checked into RCS (if the repository file is old),
1004#			and then `file' is copied to `cur'.  Another RCS
1005#			check in done here if RCS is being used.
1006#
1007#	remove		`file' is no longer being tracked by the backups
1008#			system.  If RCS is not being used, `cur' is moved
1009#			to `back', otherwise an empty file is checked in,
1010#			and then `cur' is removed.
1011#
1012#
1013backup_file()
1014{
1015	_action=$1
1016	_file=$2
1017	_cur=$3
1018	_back=$4
1019
1020	if checkyesno backup_uses_rcs; then
1021		_msg0="backup archive"
1022		_msg1="update"
1023
1024		# ensure that history file is not locked
1025		if [ -f $_cur,v ]; then
1026			rcs -q -u -U -M $_cur
1027		fi
1028
1029		# ensure after switching to rcs that the
1030		# current backup is not lost
1031		if [ -f $_cur ]; then
1032			# no archive, or current newer than archive
1033			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1034				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1035				rcs -q -kb -U $_cur
1036				co -q -f -u $_cur
1037			fi
1038		fi
1039
1040		case $_action in
1041		add|update)
1042			cp -p $_file $_cur
1043			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1044			rcs -q -kb -U $_cur
1045			co -q -f -u $_cur
1046			chown root:wheel $_cur $_cur,v
1047			;;
1048		remove)
1049			cp /dev/null $_cur
1050			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1051			rcs -q -kb -U $_cur
1052			chown root:wheel $_cur $_cur,v
1053			rm $_cur
1054			;;
1055		esac
1056	else
1057		case $_action in
1058		add|update)
1059			if [ -f $_cur ]; then
1060				cp -p $_cur $_back
1061			fi
1062			cp -p $_file $_cur
1063			chown root:wheel $_cur
1064			;;
1065		remove)
1066			mv -f $_cur $_back
1067			;;
1068		esac
1069	fi
1070}
1071
1072#
1073# handle_fsck_error fsck_exit_code
1074#	Take action depending on the return code from fsck.
1075#
1076handle_fsck_error()
1077{
1078	case $1 in
1079	0)	# OK
1080		return
1081		;;
1082	2)	# Needs re-run, still fs errors
1083		echo "File system still has errors; re-run fsck manually!"
1084		;;
1085	4)	# Root modified
1086		echo "Root file system was modified, rebooting ..."
1087		reboot -n
1088		echo "Reboot failed; help!"
1089		;;
1090	8)	# Check failed
1091		echo "Automatic file system check failed; help!"
1092		;;
1093	12)	# Got signal
1094		echo "Boot interrupted."
1095		;;
1096	*)
1097		echo "Unknown error $1; help!"
1098		;;
1099	esac
1100	stop_boot
1101}
1102
1103#
1104# _has_rcorder_keyword word file
1105#	Check whether a file contains a "# KEYWORD:" comment with a
1106#	specified keyword in the style used by rcorder(8).
1107#
1108_has_rcorder_keyword()
1109{
1110	local word="$1"
1111	local file="$2"
1112	local line
1113
1114	[ -r "$file" ] || return 1
1115	while read line; do
1116		case "${line} " in
1117		"# KEYWORD:"*[\ \	]"${word}"[\ \	]*)
1118			return 0
1119			;;
1120		"#"*)
1121			continue
1122			;;
1123		*[A-Za-z0-9]*)
1124			# give up at the first non-empty non-comment line
1125			return 1
1126			;;
1127		esac
1128	done <"$file"
1129	return 1
1130}
1131
1132#
1133# print_rc_metadata string
1134#	Print the specified string in such a way that the post-processor
1135#	inside /etc/rc will treat it as meta-data.
1136#
1137#	If we are not running inside /etc/rc, do nothing.
1138#
1139#	For public use by any rc.d script, the string must begin with
1140#	"note:", followed by arbitrary text.  The intent is that the text
1141#	will appear in a log file but not on the console.
1142#
1143#	For private use within /etc/rc, the string must contain a
1144#	keyword recognised by the rc_postprocess_metadata() function
1145#	defined in /etc/rc, followed by a colon, followed by one or more
1146#	colon-separated arguments associated with the keyword.
1147#
1148print_rc_metadata()
1149{
1150	# _rc_postprocessor fd, if defined, is the fd to which we must
1151	# print, prefixing the output with $_rc_metadata_prefix.
1152	#
1153	if _have_rc_postprocessor; then
1154		command printf "%s%s\n" "$rc_metadata_prefix" "$1" \
1155			>&${_rc_postprocessor_fd}
1156	fi
1157}
1158
1159#
1160# _flush_rc_output
1161#	Arrange for output to be flushed, if we are running
1162#	inside /etc/rc with postprocessing.
1163#
1164_flush_rc_output()
1165{
1166	print_rc_metadata "nop"
1167}
1168
1169#
1170# print_rc_normal [-n] string
1171#	Print the specified string in such way that it is treated as
1172#	normal output, regardless of whether or not we are running
1173#	inside /etc/rc with post-processing.
1174#
1175#	If "-n" is specified in $1, then the string in $2 is printed
1176#	without a newline; otherwise, the string in $1 is printed
1177#	with a newline.
1178#
1179#	Intended use cases include:
1180#
1181#	o   An rc.d script can use ``print_rc_normal -n'' to print a
1182#	    partial line in such a way that it appears immediately
1183#	    instead of being buffered by rc(8)'s post-processor.
1184#
1185#	o   An rc.d script that is run via the no_rc_postprocess
1186#	    function (so most of its output is invisible to rc(8)'s
1187#	    post-processor) can use print_rc_normal to force some of its
1188#	    output to be seen by the post-processor.
1189#
1190#
1191print_rc_normal()
1192{
1193	# print to stdout or _rc_postprocessor_fd, depending on
1194	# whether not we have an rc postprocessor.
1195	#
1196	local fd=1
1197	_have_rc_postprocessor && fd="${_rc_postprocessor_fd}"
1198	case "$1" in
1199	"-n")
1200		command printf "%s" "$2" >&${fd}
1201		_flush_rc_output
1202		;;
1203	*)
1204		command printf "%s\n" "$1" >&${fd}
1205		;;
1206	esac
1207}
1208
1209#
1210# no_rc_postprocess cmd...
1211#	Execute the specified command in such a way that its output
1212#	bypasses the post-processor that handles the output from
1213#	most commands that are run inside /etc/rc.  If we are not
1214#	inside /etc/rc, then just execute the command without special
1215#	treatment.
1216#
1217#	The intent is that interactive commands can be run via
1218#	no_rc_postprocess(), and their output will apear immediately
1219#	on the console instead of being hidden or delayed by the
1220#	post-processor.	 An unfortunate consequence of the output
1221#	bypassing the post-processor is that the output will not be
1222#	logged.
1223#
1224no_rc_postprocess()
1225{
1226	if _have_rc_postprocessor; then
1227		"$@" >&${_rc_original_stdout_fd} 2>&${_rc_original_stderr_fd}
1228	else
1229		"$@"
1230	fi
1231}
1232
1233#
1234# twiddle
1235#	On each call, print a different one of "/", "-", "\\", "|",
1236#	followed by a backspace.  The most recently printed value is
1237#	saved in $_twiddle_state.
1238#
1239#	Output is to /dev/tty, so this function may be useful even inside
1240#	a script whose output is redirected.
1241#
1242twiddle()
1243{
1244	case "$_twiddle_state" in
1245	'/')	_next='-' ;;
1246	'-')	_next='\' ;;
1247	'\')	_next='|' ;;
1248	*)	_next='/' ;;
1249	esac
1250	command printf "%s\b" "$_next" >/dev/tty
1251	_twiddle_state="$_next"
1252}
1253
1254#
1255# human_exit_code
1256#	Print the a human version of the exit code.
1257#
1258human_exit_code()
1259{
1260	if [ "$1" -lt 127 ]
1261	then
1262		echo "exited with code $1"
1263	elif [ "$(expr $1 % 256)" -eq 127 ]
1264	then
1265		# This cannot really happen because the shell will not
1266		# pass stopped job status out and the exit code is limited
1267		# to 8 bits. This code is here just for completeness.
1268		echo "stopped with signal $(expr $1 / 256)"
1269	else
1270		echo "terminated with signal $(expr $1 - 128)"
1271	fi
1272}
1273
1274#
1275# collapse_backslash_newline
1276#	Copy input to output, collapsing <backslash><newline>
1277#	to nothing, but leaving other backslashes alone.
1278#
1279collapse_backslash_newline()
1280{
1281	local line
1282	while read -r line ; do
1283		case "$line" in
1284		*\\)
1285			# print it, without the backslash or newline
1286			command printf "%s" "${line%?}"
1287			;;
1288		*)
1289			# print it, with a newline
1290			command printf "%s\n" "${line}"
1291			;;
1292		esac
1293	done
1294}
1295
1296# Shell implementations of basename and dirname, usable before
1297# the /usr file system is mounted.
1298#
1299basename()
1300{
1301	local file="$1"
1302	local suffix="$2"
1303	local base
1304
1305	base="${file##*/}"		# remove up to and including last '/'
1306	base="${base%${suffix}}"	# remove suffix, if any
1307	command printf "%s\n" "${base}"
1308}
1309
1310dirname()
1311{
1312	local file="$1"
1313	local dir
1314
1315	case "$file" in
1316	/*/*)	dir="${file%/*}" ;;	# common case: absolute path
1317	/*)	dir="/" ;;		# special case: name in root dir
1318	*/*)	dir="${file%/*}" ;;	# common case: relative path with '/'
1319	*)	dir="." ;;		# special case: name without '/'
1320	esac
1321	command printf "%s\n" "${dir}"
1322}
1323
1324# Override the normal "echo" and "printf" commands, so that
1325# partial lines printed by rc.d scripts appear immediately,
1326# instead of being buffered by rc(8)'s post-processor.
1327#
1328# Naive use of the echo or printf commands from rc.d scripts,
1329# elsewhere in rc.subr, or anything else that sources rc.subr,
1330# will call these functions.  To call the real echo and printf
1331# commands, use "command echo" or "command printf".
1332#
1333echo()
1334{
1335	command echo "$@"
1336	case "$1" in
1337	'-n')	_flush_rc_output ;;
1338	esac
1339}
1340printf()
1341{
1342	command printf "$@"
1343	case "$1" in
1344	*'\n')	: ;;
1345	*)	_flush_rc_output ;;
1346	esac
1347}
1348
1349kat() {
1350	local i
1351	local v
1352	for i; do
1353		while read -r v; do
1354			v="${v%%#*}"
1355			if [ -z "$v" ]; then
1356				continue
1357			fi
1358			echo "$v"
1359		done < "$i"
1360	done
1361}
1362
1363_rc_subr_loaded=:
1364