1 # $NetBSD: rc.subr,v 1.74 2008/12/06 23:21:32 salo Exp $
3 # Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
6 # This code is derived from software contributed to The NetBSD Foundation
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
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.
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.
31 # functions used by various rc scripts
34 : ${rcvar_manpage:='rc.conf(5)'}
35 : ${RC_PID:=$$} ; export RC_PID
43 # Test $1 variable, and warn if not set to YES or NO.
44 # Return 0 if it's "yes" (et al), nonzero otherwise.
51 # "yes", "true", "on", or "1"
52 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
56 # "no", "false", "off", or "0"
57 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
61 warn "\$${1} is not set properly - see ${rcvar_manpage}."
69 # print the list in reverse order
75 _revlist="$_revfile $_revlist"
81 # If booting directly to multiuser, send SIGTERM to
82 # the parent (/etc/rc) to abort the boot.
83 # Otherwise just exit.
87 if [ "$autoboot" = yes ]; then
88 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
95 # mount_critical_filesystems type
96 # Go through the list of critical filesystems as provided in
97 # the rc.conf(5) variable $critical_filesystems_${type}, checking
98 # each one to see if it is mounted, and if it is not, mounting it.
100 mount_critical_filesystems()
102 eval _fslist=\$critical_filesystems_${1}
103 for _fs in $_fslist; do
106 while read what _on on _type type; do
107 if [ $on = $_fs ]; then
114 mount $_fs >/dev/null 2>&1
121 # check_pidfile pidfile procname [interpreter]
122 # Parses the first line of pidfile for a PID, and ensures
123 # that the process is running and matches procname.
124 # Prints the matching PID upon success, nothing otherwise.
125 # interpreter is optional; see _find_processes() for details.
132 if [ -z "$_pidfile" -o -z "$_procname" ]; then
133 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
135 if [ ! -f $_pidfile ]; then
138 read _pid _junk < $_pidfile
139 if [ -z "$_pid" ]; then
142 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
146 # check_process procname [interpreter]
147 # Ensures that a process (or processes) named procname is running.
148 # Prints a list of matching PIDs.
149 # interpreter is optional; see _find_processes() for details.
155 if [ -z "$_procname" ]; then
156 err 3 'USAGE: check_process procname [interpreter]'
158 _find_processes $_procname ${_interpreter:-.} '-ax'
162 # _find_processes procname interpreter psargs
163 # Search for procname in the output of ps generated by psargs.
164 # Prints the PIDs of any matching processes, space separated.
166 # If interpreter == ".", check the following variations of procname
167 # against the first word of each command:
169 # `basename procname`
170 # `basename procname` + ":"
171 # "(" + `basename procname` + ")"
173 # If interpreter != ".", read the first line of procname, remove the
174 # leading #!, normalise whitespace, append procname, and attempt to
175 # match that against each command, either as is, or with extra words
176 # at the end. As an alternative, to deal with interpreted daemons
177 # using perl, the basename of the interpreter plus a colon is also
178 # tried as the prefix to procname.
182 if [ $# -ne 3 ]; then
183 err 3 'USAGE: _find_processes procname interpreter psargs'
190 _procnamebn=${_procname##*/}
191 if [ $_interpreter != "." ]; then # an interpreted script
192 read _interp < ${_chroot:-}/$_procname # read interpreter name
193 _interp=${_interp#\#!} # strip #!
195 if [ $_interpreter != $1 ]; then
196 warn "\$command_interpreter $_interpreter != $1"
198 _interp="$* $_procname" # cleanup spaces, add _procname
201 _fp_match='case "$_argv" in
202 ${_interp}|"${_interp} "*|"${_interpbn}: "*${_procnamebn}*)'
203 else # a normal daemon
204 _fp_args='_arg0 _argv'
205 _fp_match='case "$_arg0" in
206 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")'
210 ps -o "pid,command" '"$_psargs"' |
211 while read _npid '"$_fp_args"'; do
215 esac ; '"$_fp_match"'
216 echo -n "$_pref$_npid" ;
222 #echo 1>&2 "proccheck is :$_proccheck:"
227 # wait_for_pids pid [pid ...]
228 # spins until none of the pids exist
233 if [ -z "$_list" ]; then
240 if kill -0 $_j 2>/dev/null; then
241 _nlist="${_nlist}${_nlist:+ }$_j"
244 if [ -z "$_nlist" ]; then
248 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
252 if [ -n "$_prefix" ]; then
258 # run_rc_command argument
259 # Search for argument in the list of supported commands, which is:
260 # "start stop restart rcvar status poll ${extra_commands}"
261 # If there's a match, run ${argument}_cmd or the default method
264 # If argument has a given prefix, then change the operation as follows:
267 # fast Skip the pid check, and set rc_fast=yes
268 # force Set ${rcvar} to YES, and set rc_force=yes
269 # one Set ${rcvar} to YES
271 # The following globals are used:
273 # Name Needed Purpose
274 # ---- ------ -------
275 # name y Name of script.
277 # command n Full path to command.
278 # Not needed if ${rc_arg}_cmd is set for
281 # command_args n Optional args/shell directives for command.
283 # command_interpreter n If not empty, command is interpreted, so
284 # call check_{pidfile,process}() appropriately.
286 # extra_commands n List of extra commands supported.
288 # pidfile n If set, use check_pidfile $pidfile $command,
289 # otherwise use check_process $command.
290 # In either case, only check if $command is set.
292 # procname n Process name to check for instead of $command.
294 # rcvar n This is checked with checkyesno to determine
295 # if the action should be run.
297 # ${name}_chroot n Directory to chroot to before running ${command}
298 # Requires /usr to be mounted.
300 # ${name}_chdir n Directory to cd to before running ${command}
301 # (if not using ${name}_chroot).
303 # ${name}_flags n Arguments to call ${command} with.
304 # NOTE: $flags from the parent environment
305 # can be used to override this.
307 # ${name}_env n Additional environment variable settings
308 # for running ${command}
310 # ${name}_nice n Nice level to run ${command} at.
312 # ${name}_user n User to run ${command} as, using su(1) if not
313 # using ${name}_chroot.
314 # Requires /usr to be mounted.
316 # ${name}_group n Group to run chrooted ${command} as.
317 # Requires /usr to be mounted.
319 # ${name}_groups n Comma separated list of supplementary groups
320 # to run the chrooted ${command} with.
321 # Requires /usr to be mounted.
323 # ${rc_arg}_cmd n If set, use this as the method when invoked;
324 # Otherwise, use default command (see below)
326 # ${rc_arg}_precmd n If set, run just before performing the
327 # ${rc_arg}_cmd method in the default
328 # operation (i.e, after checking for required
329 # bits and process (non)existence).
330 # If this completes with a non-zero exit code,
331 # don't run ${rc_arg}_cmd.
333 # ${rc_arg}_postcmd n If set, run just after performing the
334 # ${rc_arg}_cmd method, if that method
335 # returned a zero exit code.
337 # required_dirs n If set, check for the existence of the given
338 # directories before running the default
341 # required_files n If set, check for the readability of the given
342 # files before running the default (re)start
345 # required_vars n If set, perform checkyesno on each of the
346 # listed variables before running the default
349 # Default behaviour for a given argument, if no override method is
352 # Argument Default behaviour
353 # -------- -----------------
354 # start if !running && checkyesno ${rcvar}
358 # rc_pid=$(check_pidfile $pidfile $command)
360 # rc_pid=$(check_process $command)
361 # kill $sig_stop $rc_pid
362 # wait_for_pids $rc_pid
363 # ($sig_stop defaults to TERM.)
365 # reload Similar to stop, except use $sig_reload instead,
366 # and doesn't wait_for_pids.
367 # $sig_reload defaults to HUP.
369 # restart Run `stop' then `start'.
371 # status Show if ${command} is running, etc.
373 # poll Wait for ${command} to exit.
375 # rcvar Display what rc.conf variable is used (if any).
377 # Variables available to methods, and after run_rc_command() has
382 # rc_arg Argument to command, after fast/force/one processing
385 # rc_flags Flags to start the default command with.
386 # Defaults to ${name}_flags, unless overridden
387 # by $flags from the environment.
388 # This variable may be changed by the precmd method.
390 # rc_pid PID of command (if appropriate)
392 # rc_fast Not empty if "fast" was provided (q.v.)
394 # rc_force Not empty if "force" was provided (q.v.)
400 if [ -z "$name" ]; then
401 err 3 'run_rc_command: $name is not set.'
406 fast*) # "fast" prefix; don't check pid
407 rc_arg=${rc_arg#fast}
410 force*) # "force" prefix; always run
413 rc_arg=${rc_arg#${_rc_prefix}}
414 if [ -n "${rcvar}" ]; then
418 one*) # "one" prefix; set ${rcvar}=yes
420 rc_arg=${rc_arg#${_rc_prefix}}
421 if [ -n "${rcvar}" ]; then
427 _keywords="start stop restart rcvar"
428 if [ -n "$extra_commands" ]; then
429 _keywords="${_keywords} ${extra_commands}"
433 _procname=${procname:-${command}}
435 # setup pid check command if not fast
436 if [ -z "$rc_fast" -a -n "$_procname" ]; then
437 if [ -n "$pidfile" ]; then
438 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
440 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
442 if [ -n "$_pidcmd" ]; then
443 _keywords="${_keywords} status poll"
447 if [ -z "$rc_arg" ]; then
448 rc_usage "$_keywords"
451 if [ -n "$flags" ]; then # allow override from environment
454 eval rc_flags=\$${name}_flags
456 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
457 _nice=\$${name}_nice _user=\$${name}_user \
458 _group=\$${name}_group _groups=\$${name}_groups \
459 _env=\"\$${name}_env\"
461 if [ -n "$_user" ]; then # unset $_user if running as that user
462 if [ "$_user" = "$(id -un)" ]; then
467 # if ${rcvar} is set, and $1 is not
469 # checkyesno ${rcvar}
470 # and return if that failed or warn
471 # user and exit when interactive
473 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
474 if ! checkyesno ${rcvar}; then
475 # check whether interactive or not
476 if [ -n "$_run_rc_script" ]; then
479 for _elem in $_keywords; do
480 if [ "$_elem" = "$rc_arg" ]; then
481 echo 1>&2 "\$${rcvar} is not enabled - see ${rcvar_manpage}."
482 echo 1>&2 "Use the following if you wish to perform the operation:"
483 echo 1>&2 " $0 one${rc_arg}"
487 echo 1>&2 "$0: unknown directive '$rc_arg'."
488 rc_usage "$_keywords"
492 eval $_pidcmd # determine the pid if necessary
494 for _elem in $_keywords; do
495 if [ "$_elem" != "$rc_arg" ]; then
499 # if there's a custom ${XXX_cmd},
500 # run that instead of the default
502 eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \
503 _postcmd=\$${rc_arg}_postcmd
504 if [ -n "$_cmd" ]; then
505 # if the precmd failed and force
508 if ! eval $_precmd && [ -z "$rc_force" ]; then
512 if ! eval $_cmd && [ -z "$rc_force" ]; then
519 case "$rc_arg" in # default operations...
522 if [ -n "$rc_pid" ]; then
523 echo "${name} is running as pid $rc_pid."
525 echo "${name} is not running."
531 if [ -n "$rc_pid" ]; then
532 echo 1>&2 "${name} already running? (pid=$rc_pid)."
536 if [ ! -x ${_chroot}${command} ]; then
540 # check for required variables,
541 # directories, and files
543 for _f in $required_vars; do
544 if ! checkyesno $_f; then
545 warn "\$${_f} is not enabled."
546 if [ -z "$rc_force" ]; then
551 for _f in $required_dirs; do
552 if [ ! -d "${_f}/." ]; then
553 warn "${_f} is not a directory."
554 if [ -z "$rc_force" ]; then
559 for _f in $required_files; do
560 if [ ! -r "${_f}" ]; then
561 warn "${_f} is not readable."
562 if [ -z "$rc_force" ]; then
568 # if the precmd failed and force
571 if ! eval $_precmd && [ -z "$rc_force" ]; then
575 # setup the command to run, and run it
577 echo "Starting ${name}."
578 if [ -n "$_chroot" ]; then
581 ${_nice:+nice -n $_nice }\
582 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
583 $_chroot $command $rc_flags $command_args"
586 ${_chdir:+cd $_chdir; }\
588 ${_nice:+nice -n $_nice }\
589 $command $rc_flags $command_args"
590 if [ -n "$_user" ]; then
591 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
595 # if the cmd failed and force
598 if ! eval $_doit && [ -z "$rc_force" ]; then
602 # finally, run postcmd
608 if [ -z "$rc_pid" ]; then
609 if [ -n "$pidfile" ]; then
611 "${name} not running? (check $pidfile)."
613 echo 1>&2 "${name} not running?"
618 # if the precmd failed and force
621 if ! eval $_precmd && [ -z "$rc_force" ]; then
625 # send the signal to stop
627 echo "Stopping ${name}."
628 _doit="kill -${sig_stop:-TERM} $rc_pid"
629 if [ -n "$_user" ]; then
630 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
633 # if the stop cmd failed and force
636 if ! eval $_doit && [ -z "$rc_force" ]; then
640 # wait for the command to exit,
642 wait_for_pids $rc_pid
647 if [ -z "$rc_pid" ]; then
648 if [ -n "$pidfile" ]; then
650 "${name} not running? (check $pidfile)."
652 echo 1>&2 "${name} not running?"
656 echo "Reloading ${name} config files."
657 if ! eval $_precmd && [ -z "$rc_force" ]; then
660 _doit="kill -${sig_reload:-HUP} $rc_pid"
661 if [ -n "$_user" ]; then
662 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
664 if ! eval $_doit && [ -z "$rc_force" ]; then
671 if ! eval $_precmd && [ -z "$rc_force" ]; then
674 # prevent restart being called more
675 # than once by any given script
677 if ${_rc_restart_done:-false}; then
680 _rc_restart_done=true
682 ( $0 ${_rc_prefix}stop )
683 $0 ${_rc_prefix}start
689 if [ -n "$rc_pid" ]; then
690 wait_for_pids $rc_pid
696 if [ -n "$rcvar" ]; then
697 if checkyesno ${rcvar}; then
698 echo "\$${rcvar}=YES"
706 rc_usage "$_keywords"
713 echo 1>&2 "$0: unknown directive '$rc_arg'."
714 rc_usage "$_keywords"
719 # run_rc_script file arg
720 # Start the script `file' with `arg', and correctly handle the
721 # return value from the script. If `file' ends with `.sh', it's
722 # sourced into the current environment. If `file' appears to be
723 # a backup or scratch file, ignore it. Otherwise if it's
724 # executable run as a child process.
730 if [ -z "$_file" -o -z "$_arg" ]; then
731 err 3 'USAGE: run_rc_script file arg'
736 unset name command command_args command_interpreter \
737 extra_commands pidfile procname \
738 rcvar required_dirs required_files required_vars
739 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
742 *.sh) # run in current shell
745 *[~#]|*.OLD|*.orig|*,v) # scratch file; skip
746 warn "Ignoring scratch file $_file"
749 if [ -x $_file ]; then
750 if [ -n "$rc_fast_and_loose" ]; then
753 ( set $_arg ; . $_file )
761 # load_rc_config command
762 # Source in the configuration file for a given command.
767 if [ -z "$_command" ]; then
768 err 3 'USAGE: load_rc_config command'
771 if ${_rc_conf_loaded:-false}; then
777 if [ -f /etc/rc.conf.d/"$_command" ]; then
778 . /etc/rc.conf.d/"$_command"
783 # load_rc_config_var cmd var
784 # Read the rc.conf(5) var for cmd and set in the
785 # current shell, using load_rc_config in a subshell to prevent
786 # unwanted side effects from other variable assignments.
790 if [ $# -ne 2 ]; then
791 err 3 'USAGE: load_rc_config_var cmd var'
794 load_rc_config '$1' >/dev/null;
795 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
796 echo '$2'=\'\''${'$2'}\'\'';
803 # Print a usage string for $0, with `commands' being a list of
808 echo -n 1>&2 "Usage: $0 [fast|force|one]("
812 echo -n 1>&2 "$_sep$_elem"
820 # err exitval message
821 # Display message to stderr and log to the syslog, and exit with exitval.
828 if [ -x /usr/bin/logger ]; then
829 logger "$0: ERROR: $*"
831 echo 1>&2 "$0: ERROR: $*"
837 # Display message to stderr and log to the syslog.
841 if [ -x /usr/bin/logger ]; then
842 logger "$0: WARNING: $*"
844 echo 1>&2 "$0: WARNING: $*"
848 # backup_file action file cur backup
849 # Make a backup copy of `file' into `cur', and save the previous
850 # version of `cur' as `backup' or use rcs for archiving.
852 # This routine checks the value of the backup_uses_rcs variable,
853 # which can be either YES or NO.
855 # The `action' keyword can be one of the following:
857 # add `file' is now being backed up (and is possibly
858 # being reentered into the backups system). `cur'
859 # is created and RCS files, if necessary, are
862 # update `file' has changed and needs to be backed up.
863 # If `cur' exists, it is copied to to `back' or
864 # checked into RCS (if the repository file is old),
865 # and then `file' is copied to `cur'. Another RCS
866 # check in done here if RCS is being used.
868 # remove `file' is no longer being tracked by the backups
869 # system. If RCS is not being used, `cur' is moved
870 # to `back', otherwise an empty file is checked in,
871 # and then `cur' is removed.
881 if checkyesno backup_uses_rcs; then
882 _msg0="backup archive"
885 # ensure that history file is not locked
886 if [ -f $_cur,v ]; then
887 rcs -q -u -U -M $_cur
890 # ensure after switching to rcs that the
891 # current backup is not lost
892 if [ -f $_cur ]; then
893 # no archive, or current newer than archive
894 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
895 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
904 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
907 chown root:wheel $_cur $_cur,v
911 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
913 chown root:wheel $_cur $_cur,v
920 if [ -f $_cur ]; then
924 chown root:wheel $_cur