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 [var] [defval] [desc]
73 # Echo or define a rc.conf(5) variable name. Global variable
76 # If no argument is specified, echo "${name}_enable".
78 # If only a var is specified, echo "${var}_enable".
80 # If var and defval are specified, the ${var} is defined as
81 # rc.conf(5) variable and the default value is ${defvar}. An
82 # optional argument $desc can also be specified to add a
83 # description for that.
90 0) echo ${name}_enable ;;
91 1) echo ${1}_enable ;;
93 debug "set_rcvar: \$$1=$2 is added" \
94 " as a rc.conf(5) variable."
96 rcvars="${rcvars# } $_var"
97 eval ${_var}_defval=\"$2\"
99 eval ${_var}_desc=\"$*\"
104 # set_rcvar_obsolete oldvar [newvar] [msg]
105 # Define obsolete variable.
106 # Global variable $rcvars_obsolete is used.
112 debug "set_rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
114 rcvars_obsolete="${rcvars_obsolete# } $1"
115 eval ${1}_newvar=\"$2\"
117 eval ${_var}_obsolete_msg=\"$*\"
121 # force_depend script [rcvar]
122 # Force a service to start. Intended for use by services
123 # to resolve dependency issues.
124 # $1 - filename of script, in /etc/rc.d, to run
125 # $2 - name of the script's rcvar (minus the _enable)
129 local _depend _dep_rcvar
132 _dep_rcvar="${2:-$1}_enable"
134 [ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
135 checkyesno $_dep_rcvar && return 0
137 /etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
139 info "${name} depends on ${_depend}, which will be forced to start."
140 if ! /etc/rc.d/${_depend} forcestart; then
141 warn "Unable to force ${_depend}. It may already be running."
148 # Test $1 variable, and warn if not set to YES or NO.
149 # Return 0 if it's "yes" (et al), nonzero otherwise.
154 debug "checkyesno: $1 is set to $_value."
157 # "yes", "true", "on", or "1"
158 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
162 # "no", "false", "off", or "0"
163 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
167 warn "\$${1} is not set properly - see rc.conf(5)."
175 # print the list in reverse order
181 _revlist="$_revfile $_revlist"
187 # If booting directly to multiuser or $always is enabled,
188 # send SIGTERM to the parent (/etc/rc) to abort the boot.
189 # Otherwise just exit.
196 # "yes", "true", "on", or "1"
197 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
204 if [ "$autoboot" = yes -o "$always" = true ]; then
205 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
212 # mount_critical_filesystems type
213 # Go through the list of critical filesystems as provided in
214 # the rc.conf(5) variable $critical_filesystems_${type}, checking
215 # each one to see if it is mounted, and if it is not, mounting it.
217 mount_critical_filesystems()
219 eval _fslist=\$critical_filesystems_${1}
220 for _fs in $_fslist; do
223 while read what _on on _type type; do
224 if [ $on = $_fs ]; then
231 mount $_fs >/dev/null 2>&1
238 # check_pidfile pidfile procname [interpreter]
239 # Parses the first line of pidfile for a PID, and ensures
240 # that the process is running and matches procname.
241 # Prints the matching PID upon success, nothing otherwise.
242 # interpreter is optional; see _find_processes() for details.
249 if [ -z "$_pidfile" -o -z "$_procname" ]; then
250 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
252 if [ ! -f $_pidfile ]; then
253 debug "pid file ($_pidfile): not readable."
256 read _pid _junk < $_pidfile
257 if [ -z "$_pid" ]; then
258 debug "pid file ($_pidfile): no pid in file."
261 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
265 # check_process procname [interpreter]
266 # Ensures that a process (or processes) named procname is running.
267 # Prints a list of matching PIDs.
268 # interpreter is optional; see _find_processes() for details.
274 if [ -z "$_procname" ]; then
275 err 3 'USAGE: check_process procname [interpreter]'
277 _find_processes $_procname ${_interpreter:-.} '-ax'
281 # _find_processes procname interpreter psargs
282 # Search for procname in the output of ps generated by psargs.
283 # Prints the PIDs of any matching processes, space separated.
285 # If interpreter == ".", check the following variations of procname
286 # against the first word of each command:
288 # `basename procname`
289 # `basename procname` + ":"
290 # "(" + `basename procname` + ")"
291 # "[" + `basename procname` + "]"
293 # If interpreter != ".", read the first line of procname, remove the
294 # leading #!, normalise whitespace, append procname, and attempt to
295 # match that against each command, either as is, or with extra words
296 # at the end. As an alternative, to deal with interpreted daemons
297 # using perl, the basename of the interpreter plus a colon is also
298 # tried as the prefix to procname.
302 if [ $# -ne 3 ]; then
303 err 3 'USAGE: _find_processes procname interpreter psargs'
310 if [ $_interpreter != "." ]; then # an interpreted script
311 _script="${_chroot}${_chroot:+/}$_procname"
312 if [ -r "$_script" ]; then
313 read _interp < $_script # read interpreter name
316 _interp=${_interp#\#!} # strip #!
320 shift # drop env to get real name
323 if [ $_interpreter != $1 ]; then
324 warn "\$command_interpreter $_interpreter != $1"
328 warn "no shebang line in $_script"
333 warn "cannot read shebang line from $_script"
336 _interp="$* $_procname" # cleanup spaces, add _procname
339 _fp_match='case "$_argv" in
340 ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
341 else # a normal daemon
342 _procnamebn=${_procname##*/}
343 _fp_args='_arg0 _argv'
344 _fp_match='case "$_arg0" in
345 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
349 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
350 while read _npid _jid '"$_fp_args"'; do
352 if [ "$JID" -eq "$_jid" ];
353 then echo -n "$_pref$_npid";
360 # debug "in _find_processes: proccheck is ($_proccheck)."
364 # sort_lite [-b] [-n] [-k POS] [-t SEP]
365 # A lite version of sort(1) (supporting a few options) that can be used
366 # before the real sort(1) is available (e.g., in scripts that run prior
367 # to mountcritremote). Requires only shell built-in functionality.
371 local funcname=sort_lite
372 local sort_sep="$IFS" sort_ignore_leading_space=
373 local sort_field=0 sort_strict_fields= sort_numeric=
374 local nitems=0 skip_leading=0 trim=
377 while getopts bnk:t: flag; do
379 b) sort_ignore_leading_space=1 ;;
380 n) sort_numeric=1 sort_ignore_leading_space=1 ;;
381 k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
382 # NB: Unlike sort(1) only one POS allowed
383 t) sort_sep="$OPTARG"
384 if [ ${#sort_sep} -gt 1 ]; then
385 echo "$funcname: multi-character tab \`$sort_sep'" >&2
393 shift $(( $OPTIND - 1 ))
395 # Create transformation pattern to trim leading text if desired
396 case "$sort_field" in
397 ""|[!0-9]*|*[!0-9.]*)
398 echo "$funcname: invalid sort field \`$sort_field'" >&2
402 skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
403 while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
404 trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
408 # Copy input to series of local numbered variables
409 # NB: IFS of NULL preserves leading whitespace
411 while IFS= read -r LINE || [ "$LINE" ]; do
412 nitems=$(( $nitems + 1 ))
413 local src_$nitems="$LINE"
417 # Sort numbered locals using insertion sort
419 local curitem curitem_orig curitem_mod curitem_haskey
420 local dest dest_orig dest_mod dest_haskey
423 while [ $i -le $nitems ]; do
424 curitem_haskey=1 # Assume sort field (-k POS) exists
425 eval curitem=\"\$src_$i\"
426 curitem_mod="$curitem" # for modified comparison
427 curitem_orig="$curitem" # for original comparison
429 # Trim leading whitespace if desired
430 if [ "$sort_ignore_leading_space" ]; then
431 while case "$curitem_orig" in
432 [$IFS]*) : ;; *) false; esac
434 curitem_orig="${curitem_orig#?}"
436 curitem_mod="$curitem_orig"
439 # Shift modified comparison value if sort field (-k POS) is > 1
441 while [ $n -gt 1 ]; do
442 case "$curitem_mod" in
444 # Cut text up-to (and incl.) first separator
445 curitem_mod="${curitem_mod#*[$sort_sep]}"
447 # Skip NULLs unless strict field splitting
448 [ "$sort_strict_fields" ] ||
449 [ "${curitem_mod%%[$sort_sep]*}" ] ||
454 # Asked for a field that doesn't exist
455 curitem_haskey= break
460 # Trim trailing words if sort field >= 1
461 [ $sort_field -ge 1 -a "$sort_numeric" ] &&
462 curitem_mod="${curitem_mod%%[$sort_sep]*}"
464 # Apply optional trim (-k POS.TRIM) to cut leading characters
465 curitem_mod="${curitem_mod#$trim}"
467 # Determine the type of modified comparison to use initially
468 # NB: Prefer numerical if requested but fallback to standard
469 case "$curitem_mod" in
470 ""|[!0-9]*) # NULL or begins with non-number
472 [ "$sort_numeric" ] && curitem_mod=0
475 if [ "$sort_numeric" ]; then
477 curitem_mod="${curitem_mod%%[!0-9]*}"
478 # NB: trailing non-digits removed
479 # otherwise numeric comparison fails
485 # If first time through, short-circuit below position-search
486 if [ $i -le 1 ]; then
493 # Find appropriate element position
497 dest_haskey=$curitem_haskey
498 eval dest=\"\$dest_$d\"
499 dest_mod="$dest" # for modified comparison
500 dest_orig="$dest" # for original comparison
502 # Trim leading whitespace if desired
503 if [ "$sort_ignore_leading_space" ]; then
504 while case "$dest_orig" in
505 [$IFS]*) : ;; *) false; esac
507 dest_orig="${dest_orig#?}"
509 dest_mod="$dest_orig"
512 # Shift modified value if sort field (-k POS) is > 1
514 while [ $n -gt 1 ]; do
517 # Cut text up-to (and incl.) 1st sep
518 dest_mod="${dest_mod#*[$sort_sep]}"
520 # Skip NULLs unless strict fields
521 [ "$sort_strict_fields" ] ||
522 [ "${dest_mod%%[$sort_sep]*}" ] ||
527 # Asked for a field that doesn't exist
533 # Trim trailing words if sort field >= 1
534 [ $sort_field -ge 1 -a "$sort_numeric" ] &&
535 dest_mod="${dest_mod%%[$sort_sep]*}"
537 # Apply optional trim (-k POS.TRIM), cut leading chars
538 dest_mod="${dest_mod#$trim}"
540 # Determine type of modified comparison to use
541 # NB: Prefer numerical if requested, fallback to std
543 ""|[!0-9]*) # NULL or begins with non-number
545 [ "$sort_numeric" ] && dest_mod=0
548 if [ "$sort_numeric" ]; then
550 dest_mod="${dest_mod%%[!0-9]*}"
551 # NB: kill trailing non-digits
552 # for numeric comparison safety
558 # Break if we've found the proper element position
559 if [ "$curitem_haskey" -a "$dest_haskey" ]; then
560 if [ "$dest_mod" = "$curitem_mod" ]; then
561 [ "$dest_orig" ">" "$curitem_orig" ] &&
563 elif [ "$dest_mod" $gt "$curitem_mod" ] \
569 [ "$dest_orig" ">" "$curitem_orig" ] && break
572 # Break if we've hit the end
573 [ $d -ge $i ] && break
578 # Shift remaining positions forward, making room for new item
580 while [ $n -ge $d ]; do
581 # Shift destination item forward one placement
582 eval dest_$(( $n + 1 ))=\"\$dest_$n\"
587 if [ $i -eq 1 ]; then
588 local dest_1="$curitem"
590 local dest_$d="$curitem"
596 # Print sorted results
598 while [ $d -le $nitems ]; do
599 eval echo \"\$dest_$d\"
605 # wait_for_pids pid [pid ...]
606 # spins until none of the pids exist
610 local _list _prefix _nlist _j
613 if [ -z "$_list" ]; then
620 if kill -0 $_j 2>/dev/null; then
621 _nlist="${_nlist}${_nlist:+ }$_j"
622 [ -n "$_prefix" ] && sleep 1
625 if [ -z "$_nlist" ]; then
629 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
631 pwait $_list 2>/dev/null
633 if [ -n "$_prefix" ]; then
639 # get_pidfile_from_conf string file
641 # Takes a string to search for in the specified file.
642 # Ignores lines with traditional comment characters.
646 # if get_pidfile_from_conf string file; then
647 # pidfile="$_pidfile_from_conf"
649 # pidfile='appropriate default'
652 get_pidfile_from_conf()
654 if [ -z "$1" -o -z "$2" ]; then
655 err 3 "USAGE: get_pidfile_from_conf string file ($name)"
658 local string file line
660 string="$1" ; file="$2"
662 if [ ! -s "$file" ]; then
663 err 3 "get_pidfile_from_conf: $file does not exist ($name)"
668 *[#\;]*${string}*) continue ;;
669 *${string}*) break ;;
673 if [ -n "$line" ]; then
675 _pidfile_from_conf="/${line%%[\"\;]*}"
683 # If rc_quiet is set (usually as a result of using faststart at
684 # boot time) check if rc_startmsgs is enabled.
688 if [ -n "$rc_quiet" ]; then
689 checkyesno rc_startmsgs
696 # run_rc_command argument
697 # Search for argument in the list of supported commands, which is:
698 # "start stop restart rcvar status poll ${extra_commands}"
699 # If there's a match, run ${argument}_cmd or the default method
702 # If argument has a given prefix, then change the operation as follows:
705 # fast Skip the pid check, and set rc_fast=yes, rc_quiet=yes
706 # force Set ${rcvar} to YES, and set rc_force=yes
707 # one Set ${rcvar} to YES
708 # quiet Don't output some diagnostics, and set rc_quiet=yes
710 # The following globals are used:
712 # Name Needed Purpose
713 # ---- ------ -------
714 # name y Name of script.
716 # command n Full path to command.
717 # Not needed if ${rc_arg}_cmd is set for
720 # command_args n Optional args/shell directives for command.
722 # command_interpreter n If not empty, command is interpreted, so
723 # call check_{pidfile,process}() appropriately.
725 # desc n Description of script.
727 # extra_commands n List of extra commands supported.
729 # pidfile n If set, use check_pidfile $pidfile $command,
730 # otherwise use check_process $command.
731 # In either case, only check if $command is set.
733 # procname n Process name to check for instead of $command.
735 # rcvar n This is checked with checkyesno to determine
736 # if the action should be run.
738 # ${name}_program n Full path to command.
739 # Meant to be used in /etc/rc.conf to override
742 # ${name}_chroot n Directory to chroot to before running ${command}
743 # Requires /usr to be mounted.
745 # ${name}_chdir n Directory to cd to before running ${command}
746 # (if not using ${name}_chroot).
748 # ${name}_flags n Arguments to call ${command} with.
749 # NOTE: $flags from the parent environment
750 # can be used to override this.
752 # ${name}_env n Environment variables to run ${command} with.
754 # ${name}_fib n Routing table number to run ${command} with.
756 # ${name}_nice n Nice level to run ${command} at.
758 # ${name}_user n User to run ${command} as, using su(1) if not
759 # using ${name}_chroot.
760 # Requires /usr to be mounted.
762 # ${name}_group n Group to run chrooted ${command} as.
763 # Requires /usr to be mounted.
765 # ${name}_groups n Comma separated list of supplementary groups
766 # to run the chrooted ${command} with.
767 # Requires /usr to be mounted.
769 # ${name}_prepend n Command added before ${command}.
771 # ${name}_login_class n Login class to use, else "daemon".
773 # ${rc_arg}_cmd n If set, use this as the method when invoked;
774 # Otherwise, use default command (see below)
776 # ${rc_arg}_precmd n If set, run just before performing the
777 # ${rc_arg}_cmd method in the default
778 # operation (i.e, after checking for required
779 # bits and process (non)existence).
780 # If this completes with a non-zero exit code,
781 # don't run ${rc_arg}_cmd.
783 # ${rc_arg}_postcmd n If set, run just after performing the
784 # ${rc_arg}_cmd method, if that method
785 # returned a zero exit code.
787 # required_dirs n If set, check for the existence of the given
788 # directories before running a (re)start command.
790 # required_files n If set, check for the readability of the given
791 # files before running a (re)start command.
793 # required_modules n If set, ensure the given kernel modules are
794 # loaded before running a (re)start command.
795 # The check and possible loads are actually
796 # done after start_precmd so that the modules
797 # aren't loaded in vain, should the precmd
798 # return a non-zero status to indicate a error.
799 # If a word in the list looks like "foo:bar",
800 # "foo" is the KLD file name and "bar" is the
801 # module name. If a word looks like "foo~bar",
802 # "foo" is the KLD file name and "bar" is a
803 # egrep(1) pattern matching the module name.
804 # Otherwise the module name is assumed to be
805 # the same as the KLD file name, which is most
806 # common. See load_kld().
808 # required_vars n If set, perform checkyesno on each of the
809 # listed variables before running the default
812 # Default behaviour for a given argument, if no override method is
815 # Argument Default behaviour
816 # -------- -----------------
817 # start if !running && checkyesno ${rcvar}
821 # rc_pid=$(check_pidfile $pidfile $command)
823 # rc_pid=$(check_process $command)
824 # kill $sig_stop $rc_pid
825 # wait_for_pids $rc_pid
826 # ($sig_stop defaults to TERM.)
828 # reload Similar to stop, except use $sig_reload instead,
829 # and doesn't wait_for_pids.
830 # $sig_reload defaults to HUP.
831 # Note that `reload' isn't provided by default,
832 # it should be enabled via $extra_commands.
834 # restart Run `stop' then `start'.
836 # status Show if ${command} is running, etc.
838 # poll Wait for ${command} to exit.
840 # rcvar Display what rc.conf variable is used (if any).
842 # enabled Return true if the service is enabled.
844 # Variables available to methods, and after run_rc_command() has
849 # rc_arg Argument to command, after fast/force/one processing
852 # rc_flags Flags to start the default command with.
853 # Defaults to ${name}_flags, unless overridden
854 # by $flags from the environment.
855 # This variable may be changed by the precmd method.
857 # rc_pid PID of command (if appropriate)
859 # rc_fast Not empty if "fast" was provided (q.v.)
861 # rc_force Not empty if "force" was provided (q.v.)
863 # rc_quiet Not empty if "quiet" was provided
870 if [ -z "$name" ]; then
871 err 3 'run_rc_command: $name is not set.'
874 # Don't repeat the first argument when passing additional command-
875 # line arguments to the command subroutines.
882 fast*) # "fast" prefix; don't check pid
883 rc_arg=${rc_arg#fast}
887 force*) # "force" prefix; always run
890 rc_arg=${rc_arg#${_rc_prefix}}
891 if [ -n "${rcvar}" ]; then
895 one*) # "one" prefix; set ${rcvar}=yes
897 rc_arg=${rc_arg#${_rc_prefix}}
898 if [ -n "${rcvar}" ]; then
902 quiet*) # "quiet" prefix; omit some messages
904 rc_arg=${rc_arg#${_rc_prefix}}
909 eval _override_command=\$${name}_program
910 command=${_override_command:-$command}
912 _keywords="start stop restart rcvar enabled $extra_commands"
915 _procname=${procname:-${command}}
917 # setup pid check command
918 if [ -n "$_procname" ]; then
919 if [ -n "$pidfile" ]; then
920 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
922 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
924 if [ -n "$_pidcmd" ]; then
925 _keywords="${_keywords} status poll"
929 if [ -z "$rc_arg" ]; then
933 if [ "$rc_arg" = "enabled" ] ; then
938 if [ -n "$flags" ]; then # allow override from environment
941 eval rc_flags=\$${name}_flags
943 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
944 _nice=\$${name}_nice _user=\$${name}_user \
945 _group=\$${name}_group _groups=\$${name}_groups \
946 _fib=\$${name}_fib _env=\$${name}_env \
947 _prepend=\$${name}_prepend _login_class=\${${name}_login_class:-daemon}
949 if [ -n "$_user" ]; then # unset $_user if running as that user
950 if [ "$_user" = "$(eval $IDCMD)" ]; then
955 [ -z "$autoboot" ] && eval $_pidcmd # determine the pid if necessary
957 for _elem in $_keywords; do
958 if [ "$_elem" != "$rc_arg" ]; then
961 # if ${rcvar} is set, $1 is not "rcvar"
962 # and ${rc_pid} is not set, then run
963 # checkyesno ${rcvar}
964 # and return if that failed
966 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
967 [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
968 if ! checkyesno ${rcvar}; then
969 if [ -n "${rc_quiet}" ]; then
972 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
973 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
974 echo "instead of '${rc_arg}'."
979 # if there's a custom ${XXX_cmd},
980 # run that instead of the default
982 eval _cmd=\$${rc_arg}_cmd \
983 _precmd=\$${rc_arg}_precmd \
984 _postcmd=\$${rc_arg}_postcmd
986 if [ -n "$_cmd" ]; then
987 _run_rc_precmd || return 1
988 _run_rc_doit "$_cmd $rc_extra_args" || return 1
993 case "$rc_arg" in # default operations...
996 _run_rc_precmd || return 1
997 if [ -n "$rc_pid" ]; then
998 echo "${name} is running as pid $rc_pid."
1000 echo "${name} is not running."
1007 if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
1008 if [ -z "$rc_quiet" ]; then
1009 echo 1>&2 "${name} already running? " \
1015 if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1016 warn "run_rc_command: cannot run $command"
1020 if ! _run_rc_precmd; then
1021 warn "failed precmd routine for ${name}"
1025 # setup the full command to run
1027 check_startmsgs && echo "Starting ${name}."
1028 if [ -n "$_chroot" ]; then
1030 ${_nice:+nice -n $_nice }\
1031 ${_fib:+setfib -F $_fib }\
1032 ${_env:+env $_env }\
1033 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1034 $_chroot $command $rc_flags $command_args"
1037 ${_chdir:+cd $_chdir && }\
1038 ${_fib:+setfib -F $_fib }\
1039 ${_env:+env $_env }\
1040 $command $rc_flags $command_args"
1041 if [ -n "$_user" ]; then
1042 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1044 if [ -n "$_nice" ]; then
1045 if [ -z "$_user" ]; then
1046 _doit="sh -c \"$_doit\""
1048 _doit="nice -n $_nice $_doit"
1050 if [ -n "$_prepend" ]; then
1051 _doit="$_prepend $_doit"
1055 # Prepend default limits
1056 _doit="limits -C $_login_class $_doit"
1058 # run the full command
1060 if ! _run_rc_doit "$_doit"; then
1061 warn "failed to start ${name}"
1065 # finally, run postcmd
1071 if [ -z "$rc_pid" ]; then
1072 [ -n "$rc_fast" ] && return 0
1077 _run_rc_precmd || return 1
1079 # send the signal to stop
1081 echo "Stopping ${name}."
1082 _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1083 _run_rc_doit "$_doit" || return 1
1085 # wait for the command to exit,
1087 wait_for_pids $rc_pid
1093 if [ -z "$rc_pid" ]; then
1098 _run_rc_precmd || return 1
1100 _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1101 _run_rc_doit "$_doit" || return 1
1107 # prevent restart being called more
1108 # than once by any given script
1110 if ${_rc_restart_done:-false}; then
1113 _rc_restart_done=true
1115 _run_rc_precmd || return 1
1117 # run those in a subshell to keep global variables
1118 ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1119 ( run_rc_command ${_rc_prefix}start $rc_extra_args )
1121 [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1127 _run_rc_precmd || return 1
1128 if [ -n "$rc_pid" ]; then
1129 wait_for_pids $rc_pid
1136 if [ -n "$desc" ]; then
1142 # Get unique vars in $rcvar $rcvars
1143 for _v in $rcvar $rcvars; do
1145 $_v\ *|\ *$_v|*\ $_v\ *) ;;
1146 *) v="${v# } $_v" ;;
1150 # Display variables.
1152 if [ -z "$_v" ]; then
1156 eval _desc=\$${_v}_desc
1157 eval _defval=\$${_v}_defval
1160 eval echo \"$_v=\\\"\$$_v\\\"\"
1161 # decode multiple lines of _desc
1162 while [ -n "$_desc" ]; do
1165 echo "# $_h ${_desc%%^^*}"
1170 echo "# $_h ${_desc}"
1175 echo "# (default: \"$_defval\")"
1188 echo 1>&2 "$0: unknown directive '$rc_arg'."
1194 # Helper functions for run_rc_command: common code.
1195 # They use such global variables besides the exported rc_* ones:
1198 # ------------------
1205 check_required_before "$rc_arg" || return 1
1207 if [ -n "$_precmd" ]; then
1208 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1209 eval "$_precmd $rc_extra_args"
1212 # If precmd failed and force isn't set, request exit.
1213 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1218 check_required_after "$rc_arg" || return 1
1225 if [ -n "$_postcmd" ]; then
1226 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1227 eval "$_postcmd $rc_extra_args"
1235 debug "run_rc_command: doit: $*"
1239 # If command failed and force isn't set, request exit.
1240 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1247 _run_rc_notrunning()
1251 if [ -n "$pidfile" ]; then
1252 _pidmsg=" (check $pidfile)."
1256 echo 1>&2 "${name} not running?${_pidmsg}"
1263 _cmd="kill -$1 $rc_pid"
1264 if [ -n "$_user" ]; then
1265 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1271 # run_rc_script file arg
1272 # Start the script `file' with `arg', and correctly handle the
1273 # return value from the script.
1274 # If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1275 # an old-style startup file.
1276 # If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1277 # into the current environment if $rc_fast_and_loose is set; otherwise
1278 # it is run as a child process.
1279 # If `file' appears to be a backup or scratch file, ignore it.
1280 # Otherwise if it is executable run as a child process.
1286 if [ -z "$_file" -o -z "$_arg" ]; then
1287 err 3 'USAGE: run_rc_script file arg'
1290 unset name command command_args command_interpreter \
1291 extra_commands pidfile procname \
1292 rcvar rcvars rcvars_obsolete required_dirs required_files \
1294 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1297 /etc/rc.d/*.sh) # no longer allowed in the base
1298 warn "Ignoring old-style startup script $_file"
1300 *[~#]|*.OLD|*.bak|*.orig|*,v) # scratch file; skip
1301 warn "Ignoring scratch file $_file"
1303 *) # run in subshell
1304 if [ -x $_file ]; then
1305 if [ -n "$rc_fast_and_loose" ]; then
1308 ( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1309 trap "echo Script $_file interrupted >&2 ; exit 1" 2
1310 trap "echo Script $_file running >&2" 29
1311 set $_arg; . $_file )
1319 # load_rc_config name
1320 # Source in the configuration file for a given name.
1324 local _name _rcvar_val _var _defval _v _msg _new _d
1327 if ${_rc_conf_loaded:-false}; then
1330 if [ -r /etc/defaults/rc.conf ]; then
1331 debug "Sourcing /etc/defaults/rc.conf"
1332 . /etc/defaults/rc.conf
1334 elif [ -r /etc/rc.conf ]; then
1335 debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1338 _rc_conf_loaded=true
1341 # If a service name was specified, attempt to load
1342 # service-specific configuration
1343 if [ -n "$_name" ] ; then
1344 for _d in /etc ${local_startup}; do
1346 if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1347 debug "Sourcing ${_d}/rc.conf.d/$_name"
1348 . ${_d}/rc.conf.d/"$_name"
1349 elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
1351 for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
1352 if [ -f "$_rc" ] ; then
1353 debug "Sourcing $_rc"
1361 # Set defaults if defined.
1362 for _var in $rcvar $rcvars; do
1363 eval _defval=\$${_var}_defval
1364 if [ -n "$_defval" ]; then
1365 eval : \${$_var:=\$${_var}_defval}
1369 # check obsolete rc.conf variables
1370 for _var in $rcvars_obsolete; do
1372 eval _msg=\$${_var}_obsolete_msg
1373 eval _new=\$${_var}_newvar
1378 if [ -z "$_new" ]; then
1381 eval $_new=\"\$$_var\"
1382 if [ -z "$_msg" ]; then
1383 _msg="Use \$$_new instead."
1386 warn "\$$_var is obsolete. $_msg"
1393 # load_rc_config_var name var
1394 # Read the rc.conf(5) var for name and set in the
1395 # current shell, using load_rc_config in a subshell to prevent
1396 # unwanted side effects from other variable assignments.
1398 load_rc_config_var()
1400 if [ $# -ne 2 ]; then
1401 err 3 'USAGE: load_rc_config_var name var'
1404 load_rc_config '$1' >/dev/null;
1405 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1406 echo '$2'=\'\''${'$2'}\'\'';
1413 # Print a usage string for $0, with `commands' being a list of
1418 echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1422 echo -n 1>&2 "$_sep$_elem"
1430 # err exitval message
1431 # Display message to stderr and log to the syslog, and exit with exitval.
1438 if [ -x /usr/bin/logger ]; then
1439 logger "$0: ERROR: $*"
1441 echo 1>&2 "$0: ERROR: $*"
1447 # Display message to stderr and log to the syslog.
1451 if [ -x /usr/bin/logger ]; then
1452 logger "$0: WARNING: $*"
1454 echo 1>&2 "$0: WARNING: $*"
1459 # Display informational message to stdout and log to syslog.
1464 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1465 if [ -x /usr/bin/logger ]; then
1466 logger "$0: INFO: $*"
1475 # If debugging is enabled in rc.conf output message to stderr.
1476 # BEWARE that you don't call any subroutine that itself calls this
1482 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1483 if [ -x /usr/bin/logger ]; then
1484 logger "$0: DEBUG: $*"
1486 echo 1>&2 "$0: DEBUG: $*"
1492 # backup_file action file cur backup
1493 # Make a backup copy of `file' into `cur', and save the previous
1494 # version of `cur' as `backup' or use rcs for archiving.
1496 # This routine checks the value of the backup_uses_rcs variable,
1497 # which can be either YES or NO.
1499 # The `action' keyword can be one of the following:
1501 # add `file' is now being backed up (and is possibly
1502 # being reentered into the backups system). `cur'
1503 # is created and RCS files, if necessary, are
1506 # update `file' has changed and needs to be backed up.
1507 # If `cur' exists, it is copied to to `back' or
1508 # checked into RCS (if the repository file is old),
1509 # and then `file' is copied to `cur'. Another RCS
1510 # check in done here if RCS is being used.
1512 # remove `file' is no longer being tracked by the backups
1513 # system. If RCS is not being used, `cur' is moved
1514 # to `back', otherwise an empty file is checked in,
1515 # and then `cur' is removed.
1525 if checkyesno backup_uses_rcs; then
1526 _msg0="backup archive"
1529 # ensure that history file is not locked
1530 if [ -f $_cur,v ]; then
1531 rcs -q -u -U -M $_cur
1534 # ensure after switching to rcs that the
1535 # current backup is not lost
1536 if [ -f $_cur ]; then
1537 # no archive, or current newer than archive
1538 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1539 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1548 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1551 chown root:wheel $_cur $_cur,v
1555 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1557 chown root:wheel $_cur $_cur,v
1564 if [ -f $_cur ]; then
1568 chown root:wheel $_cur
1577 # make_symlink src link
1578 # Make a symbolic link 'link' to src from basedir. If the
1579 # directory in which link is to be created does not exist
1580 # a warning will be displayed and an error will be returned.
1581 # Returns 0 on success, 1 otherwise.
1585 local src link linkdir _me
1588 linkdir="`dirname $link`"
1589 _me="make_symlink()"
1591 if [ -z "$src" -o -z "$link" ]; then
1592 warn "$_me: requires two arguments."
1595 if [ ! -d "$linkdir" ]; then
1596 warn "$_me: the directory $linkdir does not exist."
1599 if ! ln -sf $src $link; then
1600 warn "$_me: unable to make a symbolic link from $link to $src"
1606 # devfs_rulesets_from_file file
1607 # Reads a set of devfs commands from file, and creates
1608 # the specified rulesets with their rules. Returns non-zero
1609 # if there was an error.
1611 devfs_rulesets_from_file()
1613 local file _err _me _opts
1615 _me="devfs_rulesets_from_file"
1618 if [ -z "$file" ]; then
1619 warn "$_me: you must specify a file"
1622 if [ ! -e "$file" ]; then
1623 debug "$_me: no such file ($file)"
1627 # Disable globbing so that the rule patterns are not expanded
1628 # by accident with matching filesystem entries.
1631 debug "reading rulesets from file ($file)"
1639 rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1640 if [ -z "$rulenum" ]; then
1641 warn "$_me: cannot extract rule number ($line)"
1645 rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1646 if [ -z "$rulename" ]; then
1647 warn "$_me: cannot extract rule name ($line)"
1651 eval $rulename=\$rulenum
1652 debug "found ruleset: $rulename=$rulenum"
1653 if ! /sbin/devfs rule -s $rulenum delset; then
1659 rulecmd="${line%%"\#*"}"
1660 # evaluate the command incase it includes
1662 if [ -n "$rulecmd" ]; then
1663 debug "adding rule ($rulecmd)"
1664 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1672 if [ $_err -ne 0 ]; then
1673 debug "error in $_me"
1677 case $_opts in *f*) ;; *) set +f ;; esac
1681 # devfs_init_rulesets
1682 # Initializes rulesets from configuration files. Returns
1683 # non-zero if there was an error.
1685 devfs_init_rulesets()
1688 _me="devfs_init_rulesets"
1690 # Go through this only once
1691 if [ -n "$devfs_rulesets_init" ]; then
1692 debug "$_me: devfs rulesets already initialized"
1695 for file in $devfs_rulesets; do
1696 if ! devfs_rulesets_from_file $file; then
1697 warn "$_me: could not read rules from $file"
1701 devfs_rulesets_init=1
1702 debug "$_me: devfs rulesets initialized"
1706 # devfs_set_ruleset ruleset [dir]
1707 # Sets the default ruleset of dir to ruleset. The ruleset argument
1708 # must be a ruleset name as specified in devfs.rules(5) file.
1709 # Returns non-zero if it could not set it successfully.
1714 [ -n "$1" ] && eval rs=\$$1 || rs=
1715 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1716 _me="devfs_set_ruleset"
1718 if [ -z "$rs" ]; then
1719 warn "$_me: you must specify a ruleset number"
1722 debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1723 if ! /sbin/devfs $devdir ruleset $rs; then
1724 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1730 # devfs_apply_ruleset ruleset [dir]
1731 # Apply ruleset number $ruleset to the devfs mountpoint $dir.
1732 # The ruleset argument must be a ruleset name as specified
1733 # in a devfs.rules(5) file. Returns 0 on success or non-zero
1734 # if it could not apply the ruleset.
1736 devfs_apply_ruleset()
1739 [ -n "$1" ] && eval rs=\$$1 || rs=
1740 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1741 _me="devfs_apply_ruleset"
1743 if [ -z "$rs" ]; then
1744 warn "$_me: you must specify a ruleset"
1747 debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1748 if ! /sbin/devfs $devdir rule -s $rs applyset; then
1749 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1755 # devfs_domount dir [ruleset]
1756 # Mount devfs on dir. If ruleset is specified it is set
1757 # on the mount-point. It must also be a ruleset name as specified
1758 # in a devfs.rules(5) file. Returns 0 on success.
1764 [ -n "$2" ] && rs=$2 || rs=
1765 _me="devfs_domount()"
1767 if [ -z "$devdir" ]; then
1768 warn "$_me: you must specify a mount-point"
1771 debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1772 if ! mount -t devfs dev "$devdir"; then
1773 warn "$_me: Unable to mount devfs on $devdir"
1776 if [ -n "$rs" ]; then
1778 devfs_set_ruleset $rs $devdir
1779 devfs -m $devdir rule applyset
1784 # Provide a function for normalizing the mounting of memory
1785 # filesystems. This should allow the rest of the code here to remain
1786 # as close as possible between 5-current and 4-stable.
1789 # $3 = (optional) extra mdmfs flags
1792 if [ -n "$3" ]; then
1795 /sbin/mdmfs $flags -s $1 md $2
1798 # Code common to scripts that need to load a kernel module
1799 # if it isn't in the kernel yet. Syntax:
1800 # load_kld [-e regex] [-m module] file
1801 # where -e or -m chooses the way to check if the module
1802 # is already loaded:
1803 # regex is egrep'd in the output from `kldstat -v',
1804 # module is passed to `kldstat -m'.
1805 # The default way is as though `-m file' were specified.
1808 local _loaded _mod _opt _re
1810 while getopts "e:m:" _opt; do
1813 m) _mod="$OPTARG" ;;
1814 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1817 shift $(($OPTIND - 1))
1818 if [ $# -ne 1 ]; then
1819 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1823 if [ -n "$_re" ]; then
1824 if kldstat -v | egrep -q -e "$_re"; then
1828 if kldstat -q -m "$_mod"; then
1833 if ! kldload "$1"; then
1834 warn "Unable to load kernel module $1"
1837 info "$1 kernel module loaded."
1840 debug "load_kld: $1 kernel module already loaded."
1845 # ltr str src dst [var]
1846 # Change every $src in $str to $dst.
1847 # Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1848 # awk(1). If var is non-NULL, set it to the result.
1851 local _str _src _dst _out _com _var
1859 for _com in ${_str}; do
1860 if [ -z "${_out}" ]; then
1863 _out="${_out}${_dst}${_com}"
1866 if [ -n "${_var}" ]; then
1867 setvar "${_var}" "${_out}"
1873 # Creates a list of providers for GELI encryption.
1876 local devices devices2
1877 local provider mountpoint type options rest
1879 # Create list of GELI providers from fstab.
1880 while read provider mountpoint type options rest ; do
1881 case ":${options}" in
1890 case ":${provider}" in
1895 # Skip swap devices.
1896 if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1899 devices="${devices} ${provider}"
1904 # Append providers from geli_devices.
1905 devices="${devices} ${geli_devices}"
1907 for provider in ${devices}; do
1908 provider=${provider%.eli}
1909 provider=${provider#/dev/}
1910 devices2="${devices2} ${provider}"
1916 # Find scripts in local_startup directories that use the old syntax
1918 find_local_scripts_old() {
1921 for dir in ${local_startup}; do
1922 if [ -d "${dir}" ]; then
1923 for file in ${dir}/[0-9]*.sh; do
1924 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1926 zlist="$zlist $file"
1928 for file in ${dir}/[!0-9]*.sh; do
1929 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1931 slist="$slist $file"
1937 find_local_scripts_new() {
1939 for dir in ${local_startup}; do
1940 if [ -d "${dir}" ]; then
1941 for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1944 *) if [ -x "$file" ]; then
1945 local_rc="${local_rc} ${file}"
1954 # check_required_{before|after} command
1955 # Check for things required by the command before and after its precmd,
1956 # respectively. The two separate functions are needed because some
1957 # conditions should prevent precmd from being run while other things
1958 # depend on precmd having already been run.
1960 check_required_before()
1966 for _f in $required_vars; do
1967 if ! checkyesno $_f; then
1968 warn "\$${_f} is not enabled."
1969 if [ -z "$rc_force" ]; then
1975 for _f in $required_dirs; do
1976 if [ ! -d "${_f}/." ]; then
1977 warn "${_f} is not a directory."
1978 if [ -z "$rc_force" ]; then
1984 for _f in $required_files; do
1985 if [ ! -r "${_f}" ]; then
1986 warn "${_f} is not readable."
1987 if [ -z "$rc_force" ]; then
1998 check_required_after()
2004 for _f in $required_modules; do
2006 *~*) _args="-e ${_f#*~} ${_f%%~*}" ;;
2007 *:*) _args="-m ${_f#*:} ${_f%%:*}" ;;
2010 if ! load_kld ${_args}; then
2011 if [ -z "$rc_force" ]; then
2023 # Return true if security.jail.$mib exists and set to 1.
2030 if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2038 # check_kern_features mib
2039 # Return existence of kern.features.* sysctl MIB as true or
2040 # false. The result will be cached in $_rc_cache_kern_features_
2041 # namespace. "0" means the kern.features.X exists.
2043 check_kern_features()
2047 [ -n "$1" ] || return 1;
2048 eval _v=\$_rc_cache_kern_features_$1
2049 [ -n "$_v" ] && return "$_v";
2051 if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2052 eval _rc_cache_kern_features_$1=0
2055 eval _rc_cache_kern_features_$1=1
2060 # check_namevarlist var
2061 # Return "0" if ${name}_var is reserved in rc.subr.
2063 _rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend"
2068 for _v in $_rc_namevarlist; do
2077 # _echoonce var msg mode
2078 # mode=0: Echo $msg if ${$var} is empty.
2079 # After doing echo, a string is set to ${$var}.
2081 # mode=1: Echo $msg if ${$var} is a string with non-zero length.
2085 local _var _msg _mode
2091 1) [ -n "$_var" ] && echo "$_msg" ;;
2092 *) [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2096 fi # [ -z "${_rc_subr_loaded}" ]