rc.subr revision 1.42
1# $NetBSD: rc.subr,v 1.42 2002/02/25 12:49:34 lukem Exp $
2#
3# Copyright (c) 1997-2002 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# 3. All advertising materials mentioning features or use of this software
18#    must display the following acknowledgement:
19#        This product includes software developed by the NetBSD
20#        Foundation, Inc. and its contributors.
21# 4. Neither the name of The NetBSD Foundation nor the names of its
22#    contributors may be used to endorse or promote products derived
23#    from this software without specific prior written permission.
24#
25# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
26# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
27# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
29# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35# POSSIBILITY OF SUCH DAMAGE.
36#
37# rc.subr
38#	functions used by various rc scripts
39#
40
41#
42#	functions
43#	---------
44
45#
46# checkyesno var
47#	Test $1 variable, and warn if not set to YES or NO.
48#	Return 0 if it's "yes" (et al), nonzero otherwise.
49#
50checkyesno()
51{
52	eval _value=\$${1}
53	case $_value in
54
55		#	"yes", "true", "on", or "1"
56	[Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
57		return 0
58		;;
59
60		#	"no", "false", "off", or "0"
61	[Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
62		return 1
63		;;
64	*)
65		warn "\$${1} is not set properly."
66		return 1
67		;;
68	esac
69}
70
71# reverse_list list
72#	print the list in reverse order
73#
74reverse_list()
75{
76	_revlist=
77	for _revfile in $*; do
78		_revlist="$_revfile $_revlist"
79	done
80	echo $_revlist
81}
82
83#
84# mount_critical_filesystems
85#	Go through the list of critical filesystems, checking each one
86#	to see if it is mounted, and if it is not, mounting it.
87#
88mount_critical_filesystems()
89{
90	if [ $1 = local ]; then
91		_fslist=$critical_filesystems_beforenet
92	else
93		_fslist=$critical_filesystems
94	fi
95	for _fs in $_fslist; do
96		mount | (
97			_ismounted=no
98			while read what _on on _type type; do
99				if [ $on = $_fs ]; then
100					_ismounted=yes
101				fi
102			done
103			if [ $_ismounted = no ]; then 
104				mount $_fs >/dev/null 2>&1
105			fi
106		)  
107	done
108}
109
110#
111# check_pidfile pidfile procname
112#	Parses the first line of pidfile for a pid, and ensures
113#	that the process is running and matches procname.
114#	Prints the matching pid upon success, nothing otherwise.
115#
116check_pidfile()
117{
118	_pidfile=$1
119	_procname=$2
120	if [ -z "$_pidfile" -o -z "$_procname" ]; then
121		err 3 'USAGE: check_pidfile pidfile procname'
122	fi
123	if [ ! -f $_pidfile ]; then
124		return
125	fi
126	read _pid _junk < $_pidfile
127	if [ -z "$_pid" ]; then
128		return
129	fi
130	_procnamebn=${_procname##*/}
131	ps -p $_pid -o 'pid,command' | while read _npid _arg0 _argv; do
132		case "$_npid" in
133		    PID)
134			continue ;;
135		esac
136		case "$_arg0" in
137		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")
138			echo $_npid
139			return
140			;;
141		esac
142	done
143}
144
145#
146# check_process procname
147#	Ensures that a process (or processes) named procname is running.
148#	Prints a list of matching pids.
149#
150check_process()
151{
152	_procname=$1
153	if [ -z "$_procname" ]; then
154		err 3 'USAGE: check_process procname'
155	fi
156	_procnamebn=${_procname##*/}
157	_pref=
158	ps -ax -o 'pid,command' | while read _npid _arg0 _argv; do
159		case "$_npid" in
160		    PID)
161			continue ;;
162		esac
163		case "$_arg0" in
164		    $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")
165			echo -n "$_pref$_npid"
166			_pref=" "
167			;;
168		esac
169	done
170}
171
172#
173# wait_for_pids pid [pid ...]
174#	spins until none of the pids exist
175#
176wait_for_pids()
177{
178	_list=$*
179	if [ -z "$_list" ]; then
180		return
181	fi
182	_prefix=
183	while true; do
184		_nlist="";
185		for _j in $_list; do
186			if kill -0 $_j 2>/dev/null; then
187				_nlist="${_nlist}${_nlist:+ }$_j"
188			fi
189		done
190		if [ -z "$_nlist" ]; then
191			break
192		fi
193		_list=$_nlist
194		echo -n ${_prefix:-"Waiting for PIDS: "}$_list
195		_prefix=", "
196		sleep 2
197	done
198	if [ -n "$_prefix" ]; then
199		echo "."
200	fi
201}
202
203#
204# run_rc_command arg
205#	Search for arg in the list of supported commands, which is:
206#		"start stop restart rcvar status poll ${extra_commands}"
207#	If there's a match, run ${arg}_cmd or the default command (see below).
208#
209#	If arg has a given prefix, then change the operation as follows:
210#		prefix	operation
211#		------	---------
212#		fast	Skip the pid check.
213#		force	Set ${rcvar} to YES.
214#
215#	The following globals are used:
216#
217#	name		needed	function
218#	----		------	--------
219#	name		y	Name of script.
220#
221#	command		n	Full path to command.
222#				Not needed if ${arg}_cmd is set for
223#				each keyword.
224#
225#	command_args	n	Optional args/shell directives for command.
226#
227#	extra_commands	n	List of extra commands supported.
228#
229#	pidfile		n	If set, use check_pidfile $pidfile $command,
230#				otherwise use check_process $command.
231#				In either case, only check if $command is set.
232#
233#	procname	n	Process name to check for instead of $command.
234#
235#	rcvar		n	This is checked with checkyesno to determine
236#				if the action should be run.
237#
238#	${name}_chroot	n	Directory to chroot to before running ${command}
239#				Requires /usr to be mounted.
240#
241#	${name}_chdir	n	Directory to cd to before running ${command}
242#				(if not using ${name}_chroot).
243#
244#	${name}_flags	n	Arguments to call ${command} with.
245#				NOTE:	$flags from the parent environment
246#					can be used to override this.
247#
248#	${name}_nice	n	Nice level to run ${command} at.
249#
250#	${name}_user	n	User to run ${command} as, using su(1) if not
251#				using ${name}_chroot.
252#				Requires /usr to be mounted.
253#
254#	${name}_group	n	Group to run chrooted ${command} as.
255#				Requires /usr to be mounted.
256#
257#	${name}_groups	n	Comma separated list of supplementary groups
258#				to run the chrooted ${command} with.
259#				Requires /usr to be mounted.
260#
261#	${_arg}_cmd	n	If set, use this as the action when invoked;
262#				$_arg is available to the action to use.
263#				Otherwise, use default command (see below)
264#
265#	${_arg}_precmd	n	If set, run just before performing the main
266#				action in the default command (i.e, after
267#				checking for required bits and process
268#				(non)existence).
269#				If this completes with a non-zero exit code,
270#				don't run ${_arg}_cmd.
271#
272#	required_dirs	n	If set, check for the existence of the given
273#				directories before running the default
274#				(re)start command.
275#
276#	required_files	n	If set, check for the readability of the given
277#				files before running the default (re)start
278#				command.
279#
280#	required_vars	n	If set, perform checkyesno on each of the
281#				listed variables before running the default
282#				(re)start command.
283#
284#	Default commands for a given arg:
285#
286#	arg		default
287#	---		-------
288#	start		if !running && checkyesno ${rcvar}
289#				${command}
290#
291#	stop		if ${pidfile}
292#				_pid=$(check_pidfile $pidfile $command)
293#			else
294#				_pid=$(check_process $command)
295#			kill $sig_stop $_pid
296#			wait_for_pids $_pid
297#			($sig_stop defaults to TERM.)
298#
299#	reload		Similar to stop, except use $sig_reload instead,
300#			and doesn't wait_for_pids.
301#			$sig_reload defaults to HUP.
302#
303#	restart		Run `stop' then `start'.
304#
305#	status		Show if ${command} is running, etc.
306#
307#	poll		Wait for ${command} to exit.
308#
309#	rcvar		Display what rc.conf variable is used (if any).
310#
311#
312#
313run_rc_command()
314{
315	_arg=$1
316	if [ -z "$name" ]; then
317		err 3 'run_rc_command: $name is not set.'
318	fi
319
320	case "$_arg" in
321	fast*)				# "fast" prefix; don't check pid
322		_arg=${_arg#fast}
323		_rc_fast_run=YES
324		;;
325	force*)				# "force prefix; always start
326		_arg=${_arg#force}
327		_rc_force_run=YES
328		if [ -n "${rcvar}" ]; then
329			eval ${rcvar}=YES
330		fi
331		;;
332	esac
333
334	_keywords="start stop restart rcvar $extra_commands"
335	_pid=
336	_pidcmd=
337	_procname=${procname:-${command}}
338
339					# setup pid check command if not fast
340	if [ -z "$_rc_fast_run" -a -n "$_procname" ]; then
341		if [ -n "$pidfile" ]; then
342			_pidcmd='_pid=$(check_pidfile '$pidfile' '$_procname')'
343		else
344			_pidcmd='_pid=$(check_process '$_procname')'
345		fi
346		if [ -n "$_pidcmd" ]; then
347			_keywords="${_keywords} status poll"
348		fi
349	fi
350
351	if [ -z "$_arg" ]; then
352		rc_usage "$_keywords"
353	fi
354
355	if [ -n "$flags" ]; then	# allow override from environment
356		_flags=$flags
357	else
358		eval _flags=\$${name}_flags
359	fi
360	eval _chdir=\$${name}_chdir	_chroot=\$${name}_chroot \
361	    _nice=\$${name}_nice	_user=\$${name}_user \
362	    _group=\$${name}_group	_groups=\$${name}_groups
363
364	if [ -n "$_user" ]; then	# unset $_user if running as that user
365		if [ "$_user" = "$(id -un)" ]; then
366			unset _user
367		fi
368	fi
369
370					# if ${rcvar} is set, and $1 is not
371					# "rcvar", then run
372					#	checkyesno ${rcvar}
373					# and return if that failed
374					#
375	# XXXX use case?
376	if [ -n "${rcvar}" -a "$_arg" != "rcvar" ]; then
377		if ! checkyesno ${rcvar}; then
378			return 0
379		fi
380	fi
381
382	eval $_pidcmd			# determine the pid if necessary
383
384	for _elem in $_keywords; do
385		if [ "$_elem" != "$_arg" ]; then
386			continue
387		fi
388
389					# if there's a custom ${XXX_cmd},
390					# run that instead of the default
391					#
392		eval _cmd=\$${_arg}_cmd _precmd=\$${_arg}_precmd
393		if [ -n "$_cmd" ]; then
394					# if the precmd failed and force
395					# isn't set, exit
396					#
397			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
398				return 1
399			fi
400
401			eval $_cmd
402			return 0
403		fi
404
405		case "$_arg" in		# default operations...
406
407		status)
408			if [ -n "$_pid" ]; then
409				echo "${name} is running as pid $_pid."
410			else
411				echo "${name} is not running."
412				return 1
413			fi
414			;;
415
416		start)
417			if [ -n "$_pid" ]; then
418				echo "${name} already running? (pid=$_pid)."
419				exit 1
420			fi
421
422			if [ ! -x $command ]; then
423				return 0
424			fi
425
426					# check for required variables,
427					# directories, and files
428					#
429			for _f in $required_vars; do
430				if ! checkyesno $_f; then
431					warn "\$${_f} is not set."
432					if [ -z "$_rc_force_run" ]; then
433						return 1
434					fi
435				fi
436			done
437			for _f in $required_dirs; do
438				if [ ! -d "${_f}/." ]; then
439					warn "${_f} is not a directory."
440					if [ -z "$_rc_force_run" ]; then
441						return 1
442					fi
443				fi
444			done
445			for _f in $required_files; do
446				if [ ! -r "${_f}" ]; then
447					warn "${_f} is not readable."
448					if [ -z "$_rc_force_run" ]; then
449						return 1
450					fi
451				fi
452			done
453
454					# if the precmd failed and force
455					# isn't set, exit
456					#
457			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
458				return 1
459			fi
460
461
462					# setup the command to run, and run it
463					#
464			echo "Starting ${name}."
465			if [ -n "$_chroot" ]; then
466				_doit="\
467${_nice:+nice -n $_nice }\
468chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
469$_chroot $command $_flags $command_args"
470			else
471				_doit="\
472${_chdir:+cd $_chdir; }\
473${_nice:+nice -n $_nice }\
474$command $_flags $command_args"
475				if [ -n "$_user" ]; then
476				    _doit="su -m $_user -c 'sh -c \"$_doit\"'"
477				fi
478			fi
479			eval $_doit
480			;;
481
482		stop)
483			if [ -z "$_pid" ]; then
484				if [ -n "$pidfile" ]; then
485					echo \
486				    "${name} not running? (check $pidfile)."
487				else
488					echo "${name} not running?"
489				fi
490				exit 1
491			fi
492
493			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
494				return 1
495			fi
496			echo "Stopping ${name}."
497			_doit="kill -${sig_stop:-TERM} $_pid"
498			if [ -n "$_user" ]; then
499				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
500			fi
501			eval $_doit
502			wait_for_pids $_pid
503			;;
504
505		reload)
506			if [ -z "$_pid" ]; then
507				if [ -n "$pidfile" ]; then
508					echo \
509				    "${name} not running? (check $pidfile)."
510				else
511					echo "${name} not running?"
512				fi
513				exit 1
514			fi
515			echo "Reloading ${name} config files."
516			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
517				return 1
518			fi
519			_doit="kill -${sig_reload:-HUP} $_pid"
520			if [ -n "$_user" ]; then
521				_doit="su -m $_user -c 'sh -c \"$_doit\"'"
522			fi
523			eval $_doit
524			;;
525
526		restart)
527			if ! eval $_precmd && [ -z "$_rc_force_run" ]; then
528				return 1
529			fi
530					# prevent restart being called more
531					# than once by any given script
532					#
533			if [ -n "$_rc_restart_done" ]; then
534				return 0
535			fi
536			_rc_restart_done=YES
537
538			( $0 ${_rc_force_run:+force}stop )
539			$0 ${_rc_force_run:+force}start
540
541			;;
542
543		poll)
544			if [ -n "$_pid" ]; then
545				wait_for_pids $_pid
546			fi
547			;;
548
549		rcvar)
550			echo "# $name"
551			if [ -n "$rcvar" ]; then
552				if checkyesno ${rcvar}; then
553					echo "\$${rcvar}=YES"
554				else
555					echo "\$${rcvar}=NO"
556				fi
557			fi
558			;;
559
560		*)
561			rc_usage "$_keywords"
562			;;
563
564		esac
565		return 0
566	done
567
568	echo 1>&2 "$0: unknown directive '$_arg'."
569	rc_usage "$_keywords"
570	exit 1
571}
572
573#
574# run_rc_script file arg
575#	Start the script `file' with `arg', and correctly handle the
576#	return value from the script.  If `file' ends with `.sh', it's
577#	sourced into the current environment.  If `file' appears to be
578#	a backup or scratch file, ignore it.  Otherwise if it's
579#	executable run as a child process.
580#
581run_rc_script()
582{
583	_file=$1
584	_arg=$2
585	if [ -z "$_file" -o -z "$_arg" ]; then
586		err 3 'USAGE: run_rc_script file arg'
587	fi
588
589	unset	name command command_args extra_commands pidfile procname \
590		rcvar required_dirs required_files required_vars
591	eval unset ${_arg}_cmd ${_arg}_precmd
592
593	case "$_file" in
594	*.sh)				# run in current shell
595		set $_arg ; . $_file
596		;;
597	*[~#]|*.OLD|*.orig)		# scratch file; skip
598		warn "Ignoring scratch file $_file"
599		;;
600	*)				# run in subshell
601		if [ -x $_file ]; then
602			if [ -n "$rc_fast_and_loose" ]; then
603				set $_arg ; . $_file
604			else
605				( set $_arg ; . $_file )
606			fi
607		fi
608		;;
609	esac
610}
611
612#
613# load_rc_config
614#	Source in the configuration file for a given command.
615#
616load_rc_config()
617{
618	_command=$1
619	if [ -z "$_command" ]; then
620		err 3 'USAGE: load_rc_config command'
621	fi
622
623	if [ -z "$_rc_conf_loaded" ]; then
624		. /etc/rc.conf
625		_rc_conf_loaded=YES
626	fi
627	if [ -f /etc/rc.conf.d/"$_command" ]; then
628		. /etc/rc.conf.d/"$_command"
629	fi
630}
631
632
633#
634# rc_usage commands
635#	Print a usage string for $0, with `commands' being a list of
636#	valid commands.
637#
638rc_usage()
639{
640	echo -n 1>&2 "Usage: $0 [fast|force]("
641
642	_sep=
643	for _elem in $*; do
644		echo -n 1>&2 "$_sep$_elem"
645		_sep="|"
646	done
647	echo 1>&2 ")"
648	exit 1
649}
650
651#
652# err exitval message
653#	Display message to stderr and log to the syslog, and exit with exitval.
654#
655err()
656{
657	exitval=$1
658	shift
659
660	logger "$0: ERROR: $*"
661	echo 1>&2 "$0: ERROR: $*"
662	exit $exitval
663}
664
665#
666# warn message
667#	Display message to stderr and log to the syslog.
668#
669warn()
670{
671	logger "$0: WARNING: $*"
672	echo 1>&2 "$0: WARNING: $*"
673}
674
675#
676# backup_file action file cur backup
677#	Make a backup copy of `file' into `cur', and save the previous
678#	version of `cur' as `backup' or use rcs for archiving.
679#
680#	This routine checks the value of the backup_uses_rcs variable,
681#	which can be either YES or NO.
682#
683#	The `action' keyword can be one of the following:
684#
685#	add		`file' is now being backed up (and is possibly
686#			being reentered into the backups system).  `cur'
687#			is created and RCS files, if necessary, are
688#			created as well.
689#
690#	update		`file' has changed and needs to be backed up.
691#			If `cur' exists, it is copied to to `back' or
692#			checked into RCS (if the repository file is old),
693#			and then `file' is copied to `cur'.  Another RCS
694#			check in done here if RCS is being used.
695#
696#	remove		`file' is no longer being tracked by the backups
697#			system.  If RCS is not being used, `cur' is moved
698#			to `back', otherwise an empty file is checked in,
699#			and then `cur' is removed.
700#
701#
702backup_file()
703{
704	_action=$1
705	_file=$2
706	_cur=$3
707	_back=$4
708
709	if checkyesno backup_uses_rcs; then
710		_msg0="backup archive"
711		_msg1="update"
712
713		# ensure that history file is not locked
714		if [ -f $_cur,v ]; then
715			rcs -q -u -U -M $_cur
716		fi
717
718		# ensure after switching to rcs that the
719		# current backup is not lost
720		if [ -f $_cur ]; then
721			# no archive, or current newer than archive
722			if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
723				ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
724				rcs -q -kb -U $_cur
725			fi
726		fi
727
728		case $_action in
729		add|update)
730			cp -p $_file $_cur
731			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
732			rcs -q -kb -U $_cur
733			chown root:wheel $_cur $_cur,v
734			;;
735		remove)
736			cp /dev/null $_cur
737			ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
738			rcs -q -kb -U $_cur
739			chown root:wheel $_cur $_cur,v
740			rm $_cur
741			;;
742		esac
743	else
744		case $_action in
745		add|update)
746			if [ -f $_cur ]; then
747				cp -p $_cur $_back
748			fi
749			cp -p $_file $_cur
750			chown root:wheel $_cur
751			;;
752		remove)
753			mv -f $_cur $_back
754			;;
755		esac
756	fi
757}
758