1 # $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
4 # Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
7 # This code is derived from software contributed to The NetBSD Foundation
10 # Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in the
17 # documentation and/or other materials provided with the distribution.
19 # THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
32 # functions used by various rc scripts
35 : ${RC_PID:=$$}; export RC_PID
38 # Operating System dependent/independent variables
41 if [ -z "${_rc_subr_loaded}" ]; then
46 SYSCTL_N="${SYSCTL} -n"
49 IDCMD="if [ -x $ID ]; then $ID -un; fi"
51 JID=`$PS -p $$ -o jid=`
58 # List vars matching pattern.
62 set | { while read LINE; do
65 "$LINE"|*[!a-zA-Z0-9_]*) continue ;;
71 # set_rcvar_obsolete oldvar [newvar] [msg]
72 # Define obsolete variable.
73 # Global variable $rcvars_obsolete is used.
79 debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
81 rcvars_obsolete="${rcvars_obsolete# } $1"
82 eval ${1}_newvar=\"$2\"
84 eval ${_var}_obsolete_msg=\"$*\"
88 # force_depend script [rcvar]
89 # Force a service to start. Intended for use by services
90 # to resolve dependency issues.
91 # $1 - filename of script, in /etc/rc.d, to run
92 # $2 - name of the script's rcvar (minus the _enable)
96 local _depend _dep_rcvar
99 _dep_rcvar="${2:-$1}_enable"
101 [ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
102 checkyesno $_dep_rcvar && return 0
104 /etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
106 info "${name} depends on ${_depend}, which will be forced to start."
107 if ! /etc/rc.d/${_depend} forcestart; then
108 warn "Unable to force ${_depend}. It may already be running."
115 # Test $1 variable, and warn if not set to YES or NO.
116 # Return 0 if it's "yes" (et al), nonzero otherwise.
121 debug "checkyesno: $1 is set to $_value."
124 # "yes", "true", "on", or "1"
125 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
129 # "no", "false", "off", or "0"
130 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
134 warn "\$${1} is not set properly - see rc.conf(5)."
142 # print the list in reverse order
148 _revlist="$_revfile $_revlist"
154 # If booting directly to multiuser or $always is enabled,
155 # send SIGTERM to the parent (/etc/rc) to abort the boot.
156 # Otherwise just exit.
163 # "yes", "true", "on", or "1"
164 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
171 if [ "$autoboot" = yes -o "$always" = true ]; then
172 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
179 # mount_critical_filesystems type
180 # Go through the list of critical filesystems as provided in
181 # the rc.conf(5) variable $critical_filesystems_${type}, checking
182 # each one to see if it is mounted, and if it is not, mounting it.
184 mount_critical_filesystems()
186 eval _fslist=\$critical_filesystems_${1}
187 for _fs in $_fslist; do
190 while read what _on on _type type; do
191 if [ $on = $_fs ]; then
198 mount $_fs >/dev/null 2>&1
205 # check_pidfile pidfile procname [interpreter]
206 # Parses the first line of pidfile for a PID, and ensures
207 # that the process is running and matches procname.
208 # Prints the matching PID upon success, nothing otherwise.
209 # interpreter is optional; see _find_processes() for details.
216 if [ -z "$_pidfile" -o -z "$_procname" ]; then
217 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
219 if [ ! -f $_pidfile ]; then
220 debug "pid file ($_pidfile): not readable."
223 read _pid _junk < $_pidfile
224 if [ -z "$_pid" ]; then
225 debug "pid file ($_pidfile): no pid in file."
228 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
232 # check_process procname [interpreter]
233 # Ensures that a process (or processes) named procname is running.
234 # Prints a list of matching PIDs.
235 # interpreter is optional; see _find_processes() for details.
241 if [ -z "$_procname" ]; then
242 err 3 'USAGE: check_process procname [interpreter]'
244 _find_processes $_procname ${_interpreter:-.} '-ax'
248 # _find_processes procname interpreter psargs
249 # Search for procname in the output of ps generated by psargs.
250 # Prints the PIDs of any matching processes, space separated.
252 # If interpreter == ".", check the following variations of procname
253 # against the first word of each command:
255 # `basename procname`
256 # `basename procname` + ":"
257 # "(" + `basename procname` + ")"
258 # "[" + `basename procname` + "]"
260 # If interpreter != ".", read the first line of procname, remove the
261 # leading #!, normalise whitespace, append procname, and attempt to
262 # match that against each command, either as is, or with extra words
263 # at the end. As an alternative, to deal with interpreted daemons
264 # using perl, the basename of the interpreter plus a colon is also
265 # tried as the prefix to procname.
269 if [ $# -ne 3 ]; then
270 err 3 'USAGE: _find_processes procname interpreter psargs'
277 if [ $_interpreter != "." ]; then # an interpreted script
278 _script="${_chroot}${_chroot:+/}$_procname"
279 if [ -r "$_script" ]; then
280 read _interp < $_script # read interpreter name
283 _interp=${_interp#\#!} # strip #!
287 shift # drop env to get real name
290 if [ $_interpreter != $1 ]; then
291 warn "\$command_interpreter $_interpreter != $1"
295 warn "no shebang line in $_script"
300 warn "cannot read shebang line from $_script"
303 _interp="$* $_procname" # cleanup spaces, add _procname
306 _fp_match='case "$_argv" in
307 ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
308 else # a normal daemon
309 _procnamebn=${_procname##*/}
310 _fp_args='_arg0 _argv'
311 _fp_match='case "$_arg0" in
312 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
316 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
317 while read _npid _jid '"$_fp_args"'; do
319 if [ "$JID" -eq "$_jid" ];
320 then echo -n "$_pref$_npid";
327 # debug "in _find_processes: proccheck is ($_proccheck)."
331 # sort_lite [-b] [-n] [-k POS] [-t SEP]
332 # A lite version of sort(1) (supporting a few options) that can be used
333 # before the real sort(1) is available (e.g., in scripts that run prior
334 # to mountcritremote). Requires only shell built-in functionality.
338 local funcname=sort_lite
339 local sort_sep="$IFS" sort_ignore_leading_space=
340 local sort_field=0 sort_strict_fields= sort_numeric=
341 local nitems=0 skip_leading=0 trim=
344 while getopts bnk:t: flag; do
346 b) sort_ignore_leading_space=1 ;;
347 n) sort_numeric=1 sort_ignore_leading_space=1 ;;
348 k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
349 # NB: Unlike sort(1) only one POS allowed
350 t) sort_sep="$OPTARG"
351 if [ ${#sort_sep} -gt 1 ]; then
352 echo "$funcname: multi-character tab \`$sort_sep'" >&2
360 shift $(( $OPTIND - 1 ))
362 # Create transformation pattern to trim leading text if desired
363 case "$sort_field" in
364 ""|[!0-9]*|*[!0-9.]*)
365 echo "$funcname: invalid sort field \`$sort_field'" >&2
369 skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
370 while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
371 trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
375 # Copy input to series of local numbered variables
376 # NB: IFS of NULL preserves leading whitespace
378 while IFS= read -r LINE || [ "$LINE" ]; do
379 nitems=$(( $nitems + 1 ))
380 local src_$nitems="$LINE"
384 # Sort numbered locals using insertion sort
386 local curitem curitem_orig curitem_mod curitem_haskey
387 local dest dest_orig dest_mod dest_haskey
390 while [ $i -le $nitems ]; do
391 curitem_haskey=1 # Assume sort field (-k POS) exists
392 eval curitem=\"\$src_$i\"
393 curitem_mod="$curitem" # for modified comparison
394 curitem_orig="$curitem" # for original comparison
396 # Trim leading whitespace if desired
397 if [ "$sort_ignore_leading_space" ]; then
398 while case "$curitem_orig" in
399 [$IFS]*) : ;; *) false; esac
401 curitem_orig="${curitem_orig#?}"
403 curitem_mod="$curitem_orig"
406 # Shift modified comparison value if sort field (-k POS) is > 1
408 while [ $n -gt 1 ]; do
409 case "$curitem_mod" in
411 # Cut text up-to (and incl.) first separator
412 curitem_mod="${curitem_mod#*[$sort_sep]}"
414 # Skip NULLs unless strict field splitting
415 [ "$sort_strict_fields" ] ||
416 [ "${curitem_mod%%[$sort_sep]*}" ] ||
421 # Asked for a field that doesn't exist
422 curitem_haskey= break
427 # Trim trailing words if sort field >= 1
428 [ $sort_field -ge 1 -a "$sort_numeric" ] &&
429 curitem_mod="${curitem_mod%%[$sort_sep]*}"
431 # Apply optional trim (-k POS.TRIM) to cut leading characters
432 curitem_mod="${curitem_mod#$trim}"
434 # Determine the type of modified comparison to use initially
435 # NB: Prefer numerical if requested but fallback to standard
436 case "$curitem_mod" in
437 ""|[!0-9]*) # NULL or begins with non-number
439 [ "$sort_numeric" ] && curitem_mod=0
442 if [ "$sort_numeric" ]; then
444 curitem_mod="${curitem_mod%%[!0-9]*}"
445 # NB: trailing non-digits removed
446 # otherwise numeric comparison fails
452 # If first time through, short-circuit below position-search
453 if [ $i -le 1 ]; then
460 # Find appropriate element position
464 dest_haskey=$curitem_haskey
465 eval dest=\"\$dest_$d\"
466 dest_mod="$dest" # for modified comparison
467 dest_orig="$dest" # for original comparison
469 # Trim leading whitespace if desired
470 if [ "$sort_ignore_leading_space" ]; then
471 while case "$dest_orig" in
472 [$IFS]*) : ;; *) false; esac
474 dest_orig="${dest_orig#?}"
476 dest_mod="$dest_orig"
479 # Shift modified value if sort field (-k POS) is > 1
481 while [ $n -gt 1 ]; do
484 # Cut text up-to (and incl.) 1st sep
485 dest_mod="${dest_mod#*[$sort_sep]}"
487 # Skip NULLs unless strict fields
488 [ "$sort_strict_fields" ] ||
489 [ "${dest_mod%%[$sort_sep]*}" ] ||
494 # Asked for a field that doesn't exist
500 # Trim trailing words if sort field >= 1
501 [ $sort_field -ge 1 -a "$sort_numeric" ] &&
502 dest_mod="${dest_mod%%[$sort_sep]*}"
504 # Apply optional trim (-k POS.TRIM), cut leading chars
505 dest_mod="${dest_mod#$trim}"
507 # Determine type of modified comparison to use
508 # NB: Prefer numerical if requested, fallback to std
510 ""|[!0-9]*) # NULL or begins with non-number
512 [ "$sort_numeric" ] && dest_mod=0
515 if [ "$sort_numeric" ]; then
517 dest_mod="${dest_mod%%[!0-9]*}"
518 # NB: kill trailing non-digits
519 # for numeric comparison safety
525 # Break if we've found the proper element position
526 if [ "$curitem_haskey" -a "$dest_haskey" ]; then
527 if [ "$dest_mod" = "$curitem_mod" ]; then
528 [ "$dest_orig" ">" "$curitem_orig" ] &&
530 elif [ "$dest_mod" $gt "$curitem_mod" ] \
536 [ "$dest_orig" ">" "$curitem_orig" ] && break
539 # Break if we've hit the end
540 [ $d -ge $i ] && break
545 # Shift remaining positions forward, making room for new item
547 while [ $n -ge $d ]; do
548 # Shift destination item forward one placement
549 eval dest_$(( $n + 1 ))=\"\$dest_$n\"
554 if [ $i -eq 1 ]; then
555 local dest_1="$curitem"
557 local dest_$d="$curitem"
563 # Print sorted results
565 while [ $d -le $nitems ]; do
566 eval echo \"\$dest_$d\"
572 # wait_for_pids pid [pid ...]
573 # spins until none of the pids exist
577 local _list _prefix _nlist _j
580 if [ -z "$_list" ]; then
587 if kill -0 $_j 2>/dev/null; then
588 _nlist="${_nlist}${_nlist:+ }$_j"
589 [ -n "$_prefix" ] && sleep 1
592 if [ -z "$_nlist" ]; then
596 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
598 pwait $_list 2>/dev/null
600 if [ -n "$_prefix" ]; then
606 # get_pidfile_from_conf string file
608 # Takes a string to search for in the specified file.
609 # Ignores lines with traditional comment characters.
613 # if get_pidfile_from_conf string file; then
614 # pidfile="$_pidfile_from_conf"
616 # pidfile='appropriate default'
619 get_pidfile_from_conf()
621 if [ -z "$1" -o -z "$2" ]; then
622 err 3 "USAGE: get_pidfile_from_conf string file ($name)"
625 local string file line
627 string="$1" ; file="$2"
629 if [ ! -s "$file" ]; then
630 err 3 "get_pidfile_from_conf: $file does not exist ($name)"
635 *[#\;]*${string}*) continue ;;
636 *${string}*) break ;;
640 if [ -n "$line" ]; then
642 _pidfile_from_conf="/${line%%[\"\;]*}"
650 # If rc_quiet is set (usually as a result of using faststart at
651 # boot time) check if rc_startmsgs is enabled.
655 if [ -n "$rc_quiet" ]; then
656 checkyesno rc_startmsgs
663 # run_rc_command argument
664 # Search for argument in the list of supported commands, which is:
665 # "start stop restart rcvar status poll ${extra_commands}"
666 # If there's a match, run ${argument}_cmd or the default method
669 # If argument has a given prefix, then change the operation as follows:
672 # fast Skip the pid check, and set rc_fast=yes, rc_quiet=yes
673 # force Set ${rcvar} to YES, and set rc_force=yes
674 # one Set ${rcvar} to YES
675 # quiet Don't output some diagnostics, and set rc_quiet=yes
677 # The following globals are used:
679 # Name Needed Purpose
680 # ---- ------ -------
681 # name y Name of script.
683 # command n Full path to command.
684 # Not needed if ${rc_arg}_cmd is set for
687 # command_args n Optional args/shell directives for command.
689 # command_interpreter n If not empty, command is interpreted, so
690 # call check_{pidfile,process}() appropriately.
692 # desc n Description of script.
694 # extra_commands n List of extra commands supported.
696 # pidfile n If set, use check_pidfile $pidfile $command,
697 # otherwise use check_process $command.
698 # In either case, only check if $command is set.
700 # procname n Process name to check for instead of $command.
702 # rcvar n This is checked with checkyesno to determine
703 # if the action should be run.
705 # ${name}_program n Full path to command.
706 # Meant to be used in /etc/rc.conf to override
709 # ${name}_chroot n Directory to chroot to before running ${command}
710 # Requires /usr to be mounted.
712 # ${name}_chdir n Directory to cd to before running ${command}
713 # (if not using ${name}_chroot).
715 # ${name}_flags n Arguments to call ${command} with.
716 # NOTE: $flags from the parent environment
717 # can be used to override this.
719 # ${name}_fib n Routing table number to run ${command} with.
721 # ${name}_nice n Nice level to run ${command} at.
723 # ${name}_user n User to run ${command} as, using su(1) if not
724 # using ${name}_chroot.
725 # Requires /usr to be mounted.
727 # ${name}_group n Group to run chrooted ${command} as.
728 # Requires /usr to be mounted.
730 # ${name}_groups n Comma separated list of supplementary groups
731 # to run the chrooted ${command} with.
732 # Requires /usr to be mounted.
734 # ${rc_arg}_cmd n If set, use this as the method when invoked;
735 # Otherwise, use default command (see below)
737 # ${rc_arg}_precmd n If set, run just before performing the
738 # ${rc_arg}_cmd method in the default
739 # operation (i.e, after checking for required
740 # bits and process (non)existence).
741 # If this completes with a non-zero exit code,
742 # don't run ${rc_arg}_cmd.
744 # ${rc_arg}_postcmd n If set, run just after performing the
745 # ${rc_arg}_cmd method, if that method
746 # returned a zero exit code.
748 # required_dirs n If set, check for the existence of the given
749 # directories before running a (re)start command.
751 # required_files n If set, check for the readability of the given
752 # files before running a (re)start command.
754 # required_modules n If set, ensure the given kernel modules are
755 # loaded before running a (re)start command.
756 # The check and possible loads are actually
757 # done after start_precmd so that the modules
758 # aren't loaded in vain, should the precmd
759 # return a non-zero status to indicate a error.
760 # If a word in the list looks like "foo:bar",
761 # "foo" is the KLD file name and "bar" is the
762 # module name. If a word looks like "foo~bar",
763 # "foo" is the KLD file name and "bar" is a
764 # egrep(1) pattern matching the module name.
765 # Otherwise the module name is assumed to be
766 # the same as the KLD file name, which is most
767 # common. See load_kld().
769 # required_vars n If set, perform checkyesno on each of the
770 # listed variables before running the default
773 # Default behaviour for a given argument, if no override method is
776 # Argument Default behaviour
777 # -------- -----------------
778 # start if !running && checkyesno ${rcvar}
782 # rc_pid=$(check_pidfile $pidfile $command)
784 # rc_pid=$(check_process $command)
785 # kill $sig_stop $rc_pid
786 # wait_for_pids $rc_pid
787 # ($sig_stop defaults to TERM.)
789 # reload Similar to stop, except use $sig_reload instead,
790 # and doesn't wait_for_pids.
791 # $sig_reload defaults to HUP.
792 # Note that `reload' isn't provided by default,
793 # it should be enabled via $extra_commands.
795 # restart Run `stop' then `start'.
797 # status Show if ${command} is running, etc.
799 # poll Wait for ${command} to exit.
801 # rcvar Display what rc.conf variable is used (if any).
803 # enabled Return true if the service is enabled.
805 # Variables available to methods, and after run_rc_command() has
810 # rc_arg Argument to command, after fast/force/one processing
813 # rc_flags Flags to start the default command with.
814 # Defaults to ${name}_flags, unless overridden
815 # by $flags from the environment.
816 # This variable may be changed by the precmd method.
818 # rc_pid PID of command (if appropriate)
820 # rc_fast Not empty if "fast" was provided (q.v.)
822 # rc_force Not empty if "force" was provided (q.v.)
824 # rc_quiet Not empty if "quiet" was provided
831 if [ -z "$name" ]; then
832 err 3 'run_rc_command: $name is not set.'
835 # Don't repeat the first argument when passing additional command-
836 # line arguments to the command subroutines.
843 fast*) # "fast" prefix; don't check pid
844 rc_arg=${rc_arg#fast}
848 force*) # "force" prefix; always run
851 rc_arg=${rc_arg#${_rc_prefix}}
852 if [ -n "${rcvar}" ]; then
856 one*) # "one" prefix; set ${rcvar}=yes
858 rc_arg=${rc_arg#${_rc_prefix}}
859 if [ -n "${rcvar}" ]; then
863 quiet*) # "quiet" prefix; omit some messages
865 rc_arg=${rc_arg#${_rc_prefix}}
870 eval _override_command=\$${name}_program
871 command=${_override_command:-$command}
873 _keywords="start stop restart rcvar enabled $extra_commands"
876 _procname=${procname:-${command}}
878 # setup pid check command
879 if [ -n "$_procname" ]; then
880 if [ -n "$pidfile" ]; then
881 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
883 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
885 if [ -n "$_pidcmd" ]; then
886 _keywords="${_keywords} status poll"
890 if [ -z "$rc_arg" ]; then
894 if [ "$rc_arg" = "enabled" ] ; then
899 if [ -n "$flags" ]; then # allow override from environment
902 eval rc_flags=\$${name}_flags
904 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
905 _nice=\$${name}_nice _user=\$${name}_user \
906 _group=\$${name}_group _groups=\$${name}_groups \
909 if [ -n "$_user" ]; then # unset $_user if running as that user
910 if [ "$_user" = "$(eval $IDCMD)" ]; then
915 [ -z "$autoboot" ] && eval $_pidcmd # determine the pid if necessary
917 for _elem in $_keywords; do
918 if [ "$_elem" != "$rc_arg" ]; then
921 # if ${rcvar} is set, $1 is not "rcvar"
922 # and ${rc_pid} is not set, then run
923 # checkyesno ${rcvar}
924 # and return if that failed
926 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
927 [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
928 if ! checkyesno ${rcvar}; then
929 if [ -n "${rc_quiet}" ]; then
932 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
933 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
934 echo "instead of '${rc_arg}'."
939 # if there's a custom ${XXX_cmd},
940 # run that instead of the default
942 eval _cmd=\$${rc_arg}_cmd \
943 _precmd=\$${rc_arg}_precmd \
944 _postcmd=\$${rc_arg}_postcmd
946 if [ -n "$_cmd" ]; then
947 _run_rc_precmd || return 1
948 _run_rc_doit "$_cmd $rc_extra_args" || return 1
953 case "$rc_arg" in # default operations...
956 _run_rc_precmd || return 1
957 if [ -n "$rc_pid" ]; then
958 echo "${name} is running as pid $rc_pid."
960 echo "${name} is not running."
967 if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
968 if [ -z "$rc_quiet" ]; then
969 echo 1>&2 "${name} already running? " \
975 if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
976 warn "run_rc_command: cannot run $command"
980 if ! _run_rc_precmd; then
981 warn "failed precmd routine for ${name}"
985 # setup the full command to run
987 check_startmsgs && echo "Starting ${name}."
988 if [ -n "$_chroot" ]; then
990 ${_nice:+nice -n $_nice }\
991 ${_fib:+setfib -F $_fib }\
992 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
993 $_chroot $command $rc_flags $command_args"
996 ${_chdir:+cd $_chdir && }\
997 ${_fib:+setfib -F $_fib }\
998 $command $rc_flags $command_args"
999 if [ -n "$_user" ]; then
1000 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1002 if [ -n "$_nice" ]; then
1003 if [ -z "$_user" ]; then
1004 _doit="sh -c \"$_doit\""
1006 _doit="nice -n $_nice $_doit"
1010 # run the full command
1012 if ! _run_rc_doit "$_doit"; then
1013 warn "failed to start ${name}"
1017 # finally, run postcmd
1023 if [ -z "$rc_pid" ]; then
1024 [ -n "$rc_fast" ] && return 0
1029 _run_rc_precmd || return 1
1031 # send the signal to stop
1033 echo "Stopping ${name}."
1034 _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1035 _run_rc_doit "$_doit" || return 1
1037 # wait for the command to exit,
1039 wait_for_pids $rc_pid
1045 if [ -z "$rc_pid" ]; then
1050 _run_rc_precmd || return 1
1052 _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1053 _run_rc_doit "$_doit" || return 1
1059 # prevent restart being called more
1060 # than once by any given script
1062 if ${_rc_restart_done:-false}; then
1065 _rc_restart_done=true
1067 _run_rc_precmd || return 1
1069 # run those in a subshell to keep global variables
1070 ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1071 ( run_rc_command ${_rc_prefix}start $rc_extra_args )
1073 [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1079 _run_rc_precmd || return 1
1080 if [ -n "$rc_pid" ]; then
1081 wait_for_pids $rc_pid
1088 if [ -n "$desc" ]; then
1094 # Get unique vars in $rcvar
1095 for _v in $rcvar; do
1097 $_v\ *|\ *$_v|*\ $_v\ *) ;;
1098 *) v="${v# } $_v" ;;
1102 # Display variables.
1104 if [ -z "$_v" ]; then
1108 eval _desc=\$${_v}_desc
1109 eval _defval=\$${_v}_defval
1112 eval echo \"$_v=\\\"\$$_v\\\"\"
1113 # decode multiple lines of _desc
1114 while [ -n "$_desc" ]; do
1117 echo "# $_h ${_desc%%^^*}"
1122 echo "# $_h ${_desc}"
1127 echo "# (default: \"$_defval\")"
1140 echo 1>&2 "$0: unknown directive '$rc_arg'."
1146 # Helper functions for run_rc_command: common code.
1147 # They use such global variables besides the exported rc_* ones:
1150 # ------------------
1157 check_required_before "$rc_arg" || return 1
1159 if [ -n "$_precmd" ]; then
1160 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1161 eval "$_precmd $rc_extra_args"
1164 # If precmd failed and force isn't set, request exit.
1165 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1170 check_required_after "$rc_arg" || return 1
1177 if [ -n "$_postcmd" ]; then
1178 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1179 eval "$_postcmd $rc_extra_args"
1187 debug "run_rc_command: doit: $*"
1191 # If command failed and force isn't set, request exit.
1192 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1199 _run_rc_notrunning()
1203 if [ -n "$pidfile" ]; then
1204 _pidmsg=" (check $pidfile)."
1208 echo 1>&2 "${name} not running?${_pidmsg}"
1215 _cmd="kill -$1 $rc_pid"
1216 if [ -n "$_user" ]; then
1217 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1223 # run_rc_script file arg
1224 # Start the script `file' with `arg', and correctly handle the
1225 # return value from the script.
1226 # If `file' ends with `.sh', it's sourced into the current environment
1227 # when $rc_fast_and_loose is set, otherwise it is run as a child process.
1228 # If `file' appears to be a backup or scratch file, ignore it.
1229 # Otherwise if it is executable run as a child process.
1235 if [ -z "$_file" -o -z "$_arg" ]; then
1236 err 3 'USAGE: run_rc_script file arg'
1239 unset name command command_args command_interpreter \
1240 extra_commands pidfile procname \
1241 rcvar rcvars_obsolete required_dirs required_files \
1243 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1246 /etc/rc.d/*.sh) # no longer allowed in the base
1247 warn "Ignoring old-style startup script $_file"
1249 *[~#]|*.OLD|*.bak|*.orig|*,v) # scratch file; skip
1250 warn "Ignoring scratch file $_file"
1252 *) # run in subshell
1253 if [ -x $_file ]; then
1254 if [ -n "$rc_fast_and_loose" ]; then
1257 ( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1258 trap "echo Script $_file interrupted >&2 ; exit 1" 2
1259 trap "echo Script $_file running >&2" 29
1260 set $_arg; . $_file )
1268 # load_rc_config name
1269 # Source in the configuration file for a given name.
1273 local _name _rcvar_val _var _defval _v _msg _new
1275 if [ -z "$_name" ]; then
1276 err 3 'USAGE: load_rc_config name'
1279 if ${_rc_conf_loaded:-false}; then
1282 if [ -r /etc/defaults/rc.conf ]; then
1283 debug "Sourcing /etc/defaults/rc.conf"
1284 . /etc/defaults/rc.conf
1286 elif [ -r /etc/rc.conf ]; then
1287 debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1290 _rc_conf_loaded=true
1292 if [ -f /etc/rc.conf.d/"$_name" ]; then
1293 debug "Sourcing /etc/rc.conf.d/${_name}"
1294 . /etc/rc.conf.d/"$_name"
1297 # Set defaults if defined.
1298 for _var in $rcvar; do
1299 eval _defval=\$${_var}_defval
1300 if [ -n "$_defval" ]; then
1301 eval : \${$_var:=\$${_var}_defval}
1305 # check obsolete rc.conf variables
1306 for _var in $rcvars_obsolete; do
1308 eval _msg=\$${_var}_obsolete_msg
1309 eval _new=\$${_var}_newvar
1314 if [ -z "$_new" ]; then
1317 eval $_new=\"\$$_var\"
1318 if [ -z "$_msg" ]; then
1319 _msg="Use \$$_new instead."
1322 warn "\$$_var is obsolete. $_msg"
1329 # load_rc_config_var name var
1330 # Read the rc.conf(5) var for name and set in the
1331 # current shell, using load_rc_config in a subshell to prevent
1332 # unwanted side effects from other variable assignments.
1334 load_rc_config_var()
1336 if [ $# -ne 2 ]; then
1337 err 3 'USAGE: load_rc_config_var name var'
1340 load_rc_config '$1' >/dev/null;
1341 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1342 echo '$2'=\'\''${'$2'}\'\'';
1349 # Print a usage string for $0, with `commands' being a list of
1354 echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1358 echo -n 1>&2 "$_sep$_elem"
1366 # err exitval message
1367 # Display message to stderr and log to the syslog, and exit with exitval.
1374 if [ -x /usr/bin/logger ]; then
1375 logger "$0: ERROR: $*"
1377 echo 1>&2 "$0: ERROR: $*"
1383 # Display message to stderr and log to the syslog.
1387 if [ -x /usr/bin/logger ]; then
1388 logger "$0: WARNING: $*"
1390 echo 1>&2 "$0: WARNING: $*"
1395 # Display informational message to stdout and log to syslog.
1400 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1401 if [ -x /usr/bin/logger ]; then
1402 logger "$0: INFO: $*"
1411 # If debugging is enabled in rc.conf output message to stderr.
1412 # BEWARE that you don't call any subroutine that itself calls this
1418 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1419 if [ -x /usr/bin/logger ]; then
1420 logger "$0: DEBUG: $*"
1422 echo 1>&2 "$0: DEBUG: $*"
1428 # backup_file action file cur backup
1429 # Make a backup copy of `file' into `cur', and save the previous
1430 # version of `cur' as `backup' or use rcs for archiving.
1432 # This routine checks the value of the backup_uses_rcs variable,
1433 # which can be either YES or NO.
1435 # The `action' keyword can be one of the following:
1437 # add `file' is now being backed up (and is possibly
1438 # being reentered into the backups system). `cur'
1439 # is created and RCS files, if necessary, are
1442 # update `file' has changed and needs to be backed up.
1443 # If `cur' exists, it is copied to to `back' or
1444 # checked into RCS (if the repository file is old),
1445 # and then `file' is copied to `cur'. Another RCS
1446 # check in done here if RCS is being used.
1448 # remove `file' is no longer being tracked by the backups
1449 # system. If RCS is not being used, `cur' is moved
1450 # to `back', otherwise an empty file is checked in,
1451 # and then `cur' is removed.
1461 if checkyesno backup_uses_rcs; then
1462 _msg0="backup archive"
1465 # ensure that history file is not locked
1466 if [ -f $_cur,v ]; then
1467 rcs -q -u -U -M $_cur
1470 # ensure after switching to rcs that the
1471 # current backup is not lost
1472 if [ -f $_cur ]; then
1473 # no archive, or current newer than archive
1474 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1475 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1484 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1487 chown root:wheel $_cur $_cur,v
1491 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1493 chown root:wheel $_cur $_cur,v
1500 if [ -f $_cur ]; then
1504 chown root:wheel $_cur
1513 # make_symlink src link
1514 # Make a symbolic link 'link' to src from basedir. If the
1515 # directory in which link is to be created does not exist
1516 # a warning will be displayed and an error will be returned.
1517 # Returns 0 on success, 1 otherwise.
1521 local src link linkdir _me
1524 linkdir="`dirname $link`"
1525 _me="make_symlink()"
1527 if [ -z "$src" -o -z "$link" ]; then
1528 warn "$_me: requires two arguments."
1531 if [ ! -d "$linkdir" ]; then
1532 warn "$_me: the directory $linkdir does not exist."
1535 if ! ln -sf $src $link; then
1536 warn "$_me: unable to make a symbolic link from $link to $src"
1542 # devfs_rulesets_from_file file
1543 # Reads a set of devfs commands from file, and creates
1544 # the specified rulesets with their rules. Returns non-zero
1545 # if there was an error.
1547 devfs_rulesets_from_file()
1549 local file _err _me _opts
1551 _me="devfs_rulesets_from_file"
1554 if [ -z "$file" ]; then
1555 warn "$_me: you must specify a file"
1558 if [ ! -e "$file" ]; then
1559 debug "$_me: no such file ($file)"
1563 # Disable globbing so that the rule patterns are not expanded
1564 # by accident with matching filesystem entries.
1567 debug "reading rulesets from file ($file)"
1575 rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1576 if [ -z "$rulenum" ]; then
1577 warn "$_me: cannot extract rule number ($line)"
1581 rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1582 if [ -z "$rulename" ]; then
1583 warn "$_me: cannot extract rule name ($line)"
1587 eval $rulename=\$rulenum
1588 debug "found ruleset: $rulename=$rulenum"
1589 if ! /sbin/devfs rule -s $rulenum delset; then
1595 rulecmd="${line%%"\#*"}"
1596 # evaluate the command incase it includes
1598 if [ -n "$rulecmd" ]; then
1599 debug "adding rule ($rulecmd)"
1600 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1608 if [ $_err -ne 0 ]; then
1609 debug "error in $_me"
1613 case $_opts in *f*) ;; *) set +f ;; esac
1617 # devfs_init_rulesets
1618 # Initializes rulesets from configuration files. Returns
1619 # non-zero if there was an error.
1621 devfs_init_rulesets()
1624 _me="devfs_init_rulesets"
1626 # Go through this only once
1627 if [ -n "$devfs_rulesets_init" ]; then
1628 debug "$_me: devfs rulesets already initialized"
1631 for file in $devfs_rulesets; do
1632 if ! devfs_rulesets_from_file $file; then
1633 warn "$_me: could not read rules from $file"
1637 devfs_rulesets_init=1
1638 debug "$_me: devfs rulesets initialized"
1642 # devfs_set_ruleset ruleset [dir]
1643 # Sets the default ruleset of dir to ruleset. The ruleset argument
1644 # must be a ruleset name as specified in devfs.rules(5) file.
1645 # Returns non-zero if it could not set it successfully.
1650 [ -n "$1" ] && eval rs=\$$1 || rs=
1651 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1652 _me="devfs_set_ruleset"
1654 if [ -z "$rs" ]; then
1655 warn "$_me: you must specify a ruleset number"
1658 debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1659 if ! /sbin/devfs $devdir ruleset $rs; then
1660 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1666 # devfs_apply_ruleset ruleset [dir]
1667 # Apply ruleset number $ruleset to the devfs mountpoint $dir.
1668 # The ruleset argument must be a ruleset name as specified
1669 # in a devfs.rules(5) file. Returns 0 on success or non-zero
1670 # if it could not apply the ruleset.
1672 devfs_apply_ruleset()
1675 [ -n "$1" ] && eval rs=\$$1 || rs=
1676 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1677 _me="devfs_apply_ruleset"
1679 if [ -z "$rs" ]; then
1680 warn "$_me: you must specify a ruleset"
1683 debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1684 if ! /sbin/devfs $devdir rule -s $rs applyset; then
1685 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1691 # devfs_domount dir [ruleset]
1692 # Mount devfs on dir. If ruleset is specified it is set
1693 # on the mount-point. It must also be a ruleset name as specified
1694 # in a devfs.rules(5) file. Returns 0 on success.
1700 [ -n "$2" ] && rs=$2 || rs=
1701 _me="devfs_domount()"
1703 if [ -z "$devdir" ]; then
1704 warn "$_me: you must specify a mount-point"
1707 debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1708 if ! mount -t devfs dev "$devdir"; then
1709 warn "$_me: Unable to mount devfs on $devdir"
1712 if [ -n "$rs" ]; then
1714 devfs_set_ruleset $rs $devdir
1715 devfs -m $devdir rule applyset
1720 # Provide a function for normalizing the mounting of memory
1721 # filesystems. This should allow the rest of the code here to remain
1722 # as close as possible between 5-current and 4-stable.
1725 # $3 = (optional) extra mdmfs flags
1728 if [ -n "$3" ]; then
1731 /sbin/mdmfs $flags -s $1 md $2
1734 # Code common to scripts that need to load a kernel module
1735 # if it isn't in the kernel yet. Syntax:
1736 # load_kld [-e regex] [-m module] file
1737 # where -e or -m chooses the way to check if the module
1738 # is already loaded:
1739 # regex is egrep'd in the output from `kldstat -v',
1740 # module is passed to `kldstat -m'.
1741 # The default way is as though `-m file' were specified.
1744 local _loaded _mod _opt _re
1746 while getopts "e:m:" _opt; do
1749 m) _mod="$OPTARG" ;;
1750 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1753 shift $(($OPTIND - 1))
1754 if [ $# -ne 1 ]; then
1755 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1759 if [ -n "$_re" ]; then
1760 if kldstat -v | egrep -q -e "$_re"; then
1764 if kldstat -q -m "$_mod"; then
1769 if ! kldload "$1"; then
1770 warn "Unable to load kernel module $1"
1773 info "$1 kernel module loaded."
1776 debug "load_kld: $1 kernel module already loaded."
1781 # ltr str src dst [var]
1782 # Change every $src in $str to $dst.
1783 # Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1784 # awk(1). If var is non-NULL, set it to the result.
1787 local _str _src _dst _out _com _var
1795 for _com in ${_str}; do
1796 if [ -z "${_out}" ]; then
1799 _out="${_out}${_dst}${_com}"
1802 if [ -n "${_var}" ]; then
1803 setvar "${_var}" "${_out}"
1809 # Creates a list of providers for GELI encryption.
1812 local devices devices2
1813 local provider mountpoint type options rest
1815 # Create list of GELI providers from fstab.
1816 while read provider mountpoint type options rest ; do
1817 case ":${options}" in
1826 case ":${provider}" in
1831 # Skip swap devices.
1832 if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1835 devices="${devices} ${provider}"
1840 # Append providers from geli_devices.
1841 devices="${devices} ${geli_devices}"
1843 for provider in ${devices}; do
1844 provider=${provider%.eli}
1845 provider=${provider#/dev/}
1846 devices2="${devices2} ${provider}"
1852 # Find scripts in local_startup directories that use the old syntax
1854 find_local_scripts_old() {
1857 for dir in ${local_startup}; do
1858 if [ -d "${dir}" ]; then
1859 for file in ${dir}/[0-9]*.sh; do
1860 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1862 zlist="$zlist $file"
1864 for file in ${dir}/[!0-9]*.sh; do
1865 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1867 slist="$slist $file"
1873 find_local_scripts_new() {
1875 for dir in ${local_startup}; do
1876 if [ -d "${dir}" ]; then
1877 for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1880 *) if [ -x "$file" ]; then
1881 local_rc="${local_rc} ${file}"
1890 # check_required_{before|after} command
1891 # Check for things required by the command before and after its precmd,
1892 # respectively. The two separate functions are needed because some
1893 # conditions should prevent precmd from being run while other things
1894 # depend on precmd having already been run.
1896 check_required_before()
1902 for _f in $required_vars; do
1903 if ! checkyesno $_f; then
1904 warn "\$${_f} is not enabled."
1905 if [ -z "$rc_force" ]; then
1911 for _f in $required_dirs; do
1912 if [ ! -d "${_f}/." ]; then
1913 warn "${_f} is not a directory."
1914 if [ -z "$rc_force" ]; then
1920 for _f in $required_files; do
1921 if [ ! -r "${_f}" ]; then
1922 warn "${_f} is not readable."
1923 if [ -z "$rc_force" ]; then
1934 check_required_after()
1940 for _f in $required_modules; do
1942 *~*) _args="-e ${_f#*~} ${_f%%~*}" ;;
1943 *:*) _args="-m ${_f#*:} ${_f%%:*}" ;;
1946 if ! load_kld ${_args}; then
1947 if [ -z "$rc_force" ]; then
1958 # check_kern_features mib
1959 # Return existence of kern.features.* sysctl MIB as true or
1960 # false. The result will be cached in $_rc_cache_kern_features_
1961 # namespace. "0" means the kern.features.X exists.
1963 check_kern_features()
1967 [ -n "$1" ] || return 1;
1968 eval _v=\$_rc_cache_kern_features_$1
1969 [ -n "$_v" ] && return "$_v";
1971 if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1972 eval _rc_cache_kern_features_$1=0
1975 eval _rc_cache_kern_features_$1=1
1980 # check_namevarlist var
1981 # Return "0" if ${name}_var is reserved in rc.subr.
1983 _rc_namevarlist="program chroot chdir flags fib nice user group groups"
1988 for _v in $_rc_namevarlist; do
1997 # _echoonce var msg mode
1998 # mode=0: Echo $msg if ${$var} is empty.
1999 # After doing echo, a string is set to ${$var}.
2001 # mode=1: Echo $msg if ${$var} is a string with non-zero length.
2005 local _var _msg _mode
2011 1) [ -n "$_var" ] && echo "$_msg" ;;
2012 *) [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2016 fi # [ -z "${_rc_subr_loaded}" ]