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