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 : ${rcvar_manpage:='rc.conf(5)'}
36 : ${RC_PID:=$$}; export RC_PID
39 # Operating System dependent/independent variables
42 if [ -z "${_rc_subr_loaded}" ]; then
47 SYSCTL_N="${SYSCTL} -n"
50 IDCMD="if [ -x $ID ]; then $ID -un; fi"
52 JID=`$PS -p $$ -o jid=`
58 # set_rcvar [var] [defval] [desc]
60 # Echo or define a rc.conf(5) variable name. Global variable
63 # If no argument is specified, echo "${name}_enable".
65 # If only a var is specified, echo "${var}_enable".
67 # If var and defval are specified, the ${var} is defined as
68 # rc.conf(5) variable and the default value is ${defvar}. An
69 # optional argument $desc can also be specified to add a
70 # description for that.
82 debug "rcvar_define: \$$1=$2 is added" \
83 " as a rc.conf(5) variable."
87 rcvars="${rcvars# } $_var"
88 eval ${_var}_defval=\"$2\"
90 # encode multiple lines of _desc
92 eval ${_var}_desc=\"\${${_var}_desc#^^}^^$l\"
94 eval ${_var}_desc=\"\${${_var}_desc#^^}\"
99 # set_rcvar_obsolete oldvar [newvar] [msg]
100 # Define obsolete variable.
101 # Global variable $rcvars_obsolete is used.
107 debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
109 rcvars_obsolete="${rcvars_obsolete# } $1"
110 eval ${1}_newvar=\"$2\"
112 eval ${_var}_obsolete_msg=\"$*\"
116 # force_depend script [rcvar]
117 # Force a service to start. Intended for use by services
118 # to resolve dependency issues.
119 # $1 - filename of script, in /etc/rc.d, to run
120 # $2 - name of the script's rcvar (minus the _enable)
124 local _depend _dep_rcvar
127 _dep_rcvar="${2:-$1}_enable"
129 [ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
130 checkyesno $_dep_rcvar && return 0
132 /etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
134 info "${name} depends on ${_depend}, which will be forced to start."
135 if ! /etc/rc.d/${_depend} forcestart; then
136 warn "Unable to force ${_depend}. It may already be running."
143 # Test $1 variable, and warn if not set to YES or NO.
144 # Return 0 if it's "yes" (et al), nonzero otherwise.
149 debug "checkyesno: $1 is set to $_value."
152 # "yes", "true", "on", or "1"
153 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
157 # "no", "false", "off", or "0"
158 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
162 warn "\$${1} is not set properly - see ${rcvar_manpage}."
170 # print the list in reverse order
176 _revlist="$_revfile $_revlist"
182 # If booting directly to multiuser or $always is enabled,
183 # send SIGTERM to the parent (/etc/rc) to abort the boot.
184 # Otherwise just exit.
191 # "yes", "true", "on", or "1"
192 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
199 if [ "$autoboot" = yes -o "$always" = true ]; then
200 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
207 # mount_critical_filesystems type
208 # Go through the list of critical filesystems as provided in
209 # the rc.conf(5) variable $critical_filesystems_${type}, checking
210 # each one to see if it is mounted, and if it is not, mounting it.
212 mount_critical_filesystems()
214 eval _fslist=\$critical_filesystems_${1}
215 for _fs in $_fslist; do
218 while read what _on on _type type; do
219 if [ $on = $_fs ]; then
226 mount $_fs >/dev/null 2>&1
233 # check_pidfile pidfile procname [interpreter]
234 # Parses the first line of pidfile for a PID, and ensures
235 # that the process is running and matches procname.
236 # Prints the matching PID upon success, nothing otherwise.
237 # interpreter is optional; see _find_processes() for details.
244 if [ -z "$_pidfile" -o -z "$_procname" ]; then
245 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
247 if [ ! -f $_pidfile ]; then
248 debug "pid file ($_pidfile): not readable."
251 read _pid _junk < $_pidfile
252 if [ -z "$_pid" ]; then
253 debug "pid file ($_pidfile): no pid in file."
256 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
260 # check_process procname [interpreter]
261 # Ensures that a process (or processes) named procname is running.
262 # Prints a list of matching PIDs.
263 # interpreter is optional; see _find_processes() for details.
269 if [ -z "$_procname" ]; then
270 err 3 'USAGE: check_process procname [interpreter]'
272 _find_processes $_procname ${_interpreter:-.} '-ax'
276 # _find_processes procname interpreter psargs
277 # Search for procname in the output of ps generated by psargs.
278 # Prints the PIDs of any matching processes, space separated.
280 # If interpreter == ".", check the following variations of procname
281 # against the first word of each command:
283 # `basename procname`
284 # `basename procname` + ":"
285 # "(" + `basename procname` + ")"
286 # "[" + `basename procname` + "]"
288 # If interpreter != ".", read the first line of procname, remove the
289 # leading #!, normalise whitespace, append procname, and attempt to
290 # match that against each command, either as is, or with extra words
291 # at the end. As an alternative, to deal with interpreted daemons
292 # using perl, the basename of the interpreter plus a colon is also
293 # tried as the prefix to procname.
297 if [ $# -ne 3 ]; then
298 err 3 'USAGE: _find_processes procname interpreter psargs'
305 if [ $_interpreter != "." ]; then # an interpreted script
306 _script=${_chroot}${_chroot:+"/"}$_procname
307 if [ -r $_script ]; then
308 read _interp < $_script # read interpreter name
311 _interp=${_interp#\#!} # strip #!
315 shift # drop env to get real name
318 if [ $_interpreter != $1 ]; then
319 warn "\$command_interpreter $_interpreter != $1"
323 warn "no shebang line in $_script"
328 warn "cannot read shebang line from $_script"
331 _interp="$* $_procname" # cleanup spaces, add _procname
334 _fp_match='case "$_argv" in
335 ${_interp}|"${_interp} "*|"${_interpbn}: ${_procname}"*)'
336 else # a normal daemon
337 _procnamebn=${_procname##*/}
338 _fp_args='_arg0 _argv'
339 _fp_match='case "$_arg0" in
340 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
344 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
345 while read _npid _jid '"$_fp_args"'; do
347 if [ "$JID" -eq "$_jid" ];
348 then echo -n "$_pref$_npid";
355 # debug "in _find_processes: proccheck is ($_proccheck)."
360 # wait_for_pids pid [pid ...]
361 # spins until none of the pids exist
365 local _list _prefix _nlist _j
368 if [ -z "$_list" ]; then
375 if kill -0 $_j 2>/dev/null; then
376 _nlist="${_nlist}${_nlist:+ }$_j"
377 [ -n "$_prefix" ] && sleep 1
380 if [ -z "$_nlist" ]; then
384 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
386 pwait $_list 2>/dev/null
388 if [ -n "$_prefix" ]; then
394 # get_pidfile_from_conf string file
396 # Takes a string to search for in the specified file.
397 # Ignores lines with traditional comment characters.
401 # if get_pidfile_from_conf string file; then
402 # pidfile="$_pidfile_from_conf"
404 # pidfile='appropriate default'
407 get_pidfile_from_conf()
409 if [ -z "$1" -o -z "$2" ]; then
410 err 3 "USAGE: get_pidfile_from_conf string file ($name)"
413 local string file line
415 string="$1" ; file="$2"
417 if [ ! -s "$file" ]; then
418 err 3 "get_pidfile_from_conf: $file does not exist ($name)"
423 *[#\;]*${string}*) continue ;;
424 *${string}*) break ;;
428 if [ -n "$line" ]; then
430 _pidfile_from_conf="/${line%%[\"\;]*}"
438 # If rc_quiet is set (usually as a result of using faststart at
439 # boot time) check if rc_startmsgs is enabled.
443 if [ -n "$rc_quiet" ]; then
444 checkyesno rc_startmsgs
451 # run_rc_command argument
452 # Search for argument in the list of supported commands, which is:
453 # "start stop restart rcvar status poll ${extra_commands}"
454 # If there's a match, run ${argument}_cmd or the default method
457 # If argument has a given prefix, then change the operation as follows:
460 # fast Skip the pid check, and set rc_fast=yes, rc_quiet=yes
461 # force Set ${rcvar} to YES, and set rc_force=yes
462 # one Set ${rcvar} to YES
463 # quiet Don't output some diagnostics, and set rc_quiet=yes
465 # The following globals are used:
467 # Name Needed Purpose
468 # ---- ------ -------
469 # name y Name of script.
471 # command n Full path to command.
472 # Not needed if ${rc_arg}_cmd is set for
475 # command_args n Optional args/shell directives for command.
477 # command_interpreter n If not empty, command is interpreted, so
478 # call check_{pidfile,process}() appropriately.
480 # desc n Description of script.
482 # extra_commands n List of extra commands supported.
484 # pidfile n If set, use check_pidfile $pidfile $command,
485 # otherwise use check_process $command.
486 # In either case, only check if $command is set.
488 # procname n Process name to check for instead of $command.
490 # rcvar n This is checked with checkyesno to determine
491 # if the action should be run.
493 # ${name}_program n Full path to command.
494 # Meant to be used in /etc/rc.conf to override
497 # ${name}_chroot n Directory to chroot to before running ${command}
498 # Requires /usr to be mounted.
500 # ${name}_chdir n Directory to cd to before running ${command}
501 # (if not using ${name}_chroot).
503 # ${name}_flags n Arguments to call ${command} with.
504 # NOTE: $flags from the parent environment
505 # can be used to override this.
507 # ${name}_nice n Nice level to run ${command} at.
509 # ${name}_user n User to run ${command} as, using su(1) if not
510 # using ${name}_chroot.
511 # Requires /usr to be mounted.
513 # ${name}_group n Group to run chrooted ${command} as.
514 # Requires /usr to be mounted.
516 # ${name}_groups n Comma separated list of supplementary groups
517 # to run the chrooted ${command} with.
518 # Requires /usr to be mounted.
520 # ${rc_arg}_cmd n If set, use this as the method when invoked;
521 # Otherwise, use default command (see below)
523 # ${rc_arg}_precmd n If set, run just before performing the
524 # ${rc_arg}_cmd method in the default
525 # operation (i.e, after checking for required
526 # bits and process (non)existence).
527 # If this completes with a non-zero exit code,
528 # don't run ${rc_arg}_cmd.
530 # ${rc_arg}_postcmd n If set, run just after performing the
531 # ${rc_arg}_cmd method, if that method
532 # returned a zero exit code.
534 # required_dirs n If set, check for the existence of the given
535 # directories before running a (re)start command.
537 # required_files n If set, check for the readability of the given
538 # files before running a (re)start command.
540 # required_modules n If set, ensure the given kernel modules are
541 # loaded before running a (re)start command.
542 # The check and possible loads are actually
543 # done after start_precmd so that the modules
544 # aren't loaded in vain, should the precmd
545 # return a non-zero status to indicate a error.
546 # If a word in the list looks like "foo:bar",
547 # "foo" is the KLD file name and "bar" is the
548 # module name. If a word looks like "foo~bar",
549 # "foo" is the KLD file name and "bar" is a
550 # egrep(1) pattern matching the module name.
551 # Otherwise the module name is assumed to be
552 # the same as the KLD file name, which is most
553 # common. See load_kld().
555 # required_vars n If set, perform checkyesno on each of the
556 # listed variables before running the default
559 # Default behaviour for a given argument, if no override method is
562 # Argument Default behaviour
563 # -------- -----------------
564 # start if !running && checkyesno ${rcvar}
568 # rc_pid=$(check_pidfile $pidfile $command)
570 # rc_pid=$(check_process $command)
571 # kill $sig_stop $rc_pid
572 # wait_for_pids $rc_pid
573 # ($sig_stop defaults to TERM.)
575 # reload Similar to stop, except use $sig_reload instead,
576 # and doesn't wait_for_pids.
577 # $sig_reload defaults to HUP.
578 # Note that `reload' isn't provided by default,
579 # it should be enabled via $extra_commands.
581 # restart Run `stop' then `start'.
583 # status Show if ${command} is running, etc.
585 # poll Wait for ${command} to exit.
587 # rcvar Display what rc.conf variable is used (if any).
589 # Variables available to methods, and after run_rc_command() has
594 # rc_arg Argument to command, after fast/force/one processing
597 # rc_flags Flags to start the default command with.
598 # Defaults to ${name}_flags, unless overridden
599 # by $flags from the environment.
600 # This variable may be changed by the precmd method.
602 # rc_pid PID of command (if appropriate)
604 # rc_fast Not empty if "fast" was provided (q.v.)
606 # rc_force Not empty if "force" was provided (q.v.)
608 # rc_quiet Not empty if "quiet" was provided
615 if [ -z "$name" ]; then
616 err 3 'run_rc_command: $name is not set.'
619 # Don't repeat the first argument when passing additional command-
620 # line arguments to the command subroutines.
627 fast*) # "fast" prefix; don't check pid
628 rc_arg=${rc_arg#fast}
632 force*) # "force" prefix; always run
635 rc_arg=${rc_arg#${_rc_prefix}}
636 if [ -n "${rcvar}" ]; then
640 one*) # "one" prefix; set ${rcvar}=yes
642 rc_arg=${rc_arg#${_rc_prefix}}
643 if [ -n "${rcvar}" ]; then
647 quiet*) # "quiet" prefix; omit some messages
649 rc_arg=${rc_arg#${_rc_prefix}}
654 eval _override_command=\$${name}_program
655 command=${_override_command:-$command}
657 _keywords="start stop restart rcvar $extra_commands"
660 _procname=${procname:-${command}}
662 # setup pid check command
663 if [ -n "$_procname" ]; then
664 if [ -n "$pidfile" ]; then
665 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
667 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
669 if [ -n "$_pidcmd" ]; then
670 _keywords="${_keywords} status poll"
674 if [ -z "$rc_arg" ]; then
678 if [ -n "$flags" ]; then # allow override from environment
681 eval rc_flags=\$${name}_flags
683 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
684 _nice=\$${name}_nice _user=\$${name}_user \
685 _group=\$${name}_group _groups=\$${name}_groups
687 if [ -n "$_user" ]; then # unset $_user if running as that user
688 if [ "$_user" = "$(eval $IDCMD)" ]; then
693 [ -z "$autoboot" ] && eval $_pidcmd # determine the pid if necessary
695 for _elem in $_keywords; do
696 if [ "$_elem" != "$rc_arg" ]; then
699 # if ${rcvar} is set, $1 is not "rcvar"
700 # and ${rc_pid} is not set, then run
701 # checkyesno ${rcvar}
702 # and return if that failed
704 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
705 [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
706 if ! checkyesno ${rcvar}; then
707 if [ -n "${rc_quiet}" ]; then
710 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
711 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
712 echo "instead of '${rc_arg}'."
717 # if there's a custom ${XXX_cmd},
718 # run that instead of the default
720 eval _cmd=\$${rc_arg}_cmd \
721 _precmd=\$${rc_arg}_precmd \
722 _postcmd=\$${rc_arg}_postcmd
724 if [ -n "$_cmd" ]; then
725 _run_rc_precmd || return 1
726 _run_rc_doit "$_cmd $rc_extra_args" || return 1
731 case "$rc_arg" in # default operations...
734 _run_rc_precmd || return 1
735 if [ -n "$rc_pid" ]; then
736 echo "${name} is running as pid $rc_pid."
738 echo "${name} is not running."
745 if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
746 echo 1>&2 "${name} already running? (pid=$rc_pid)."
750 if [ ! -x ${_chroot}${_chroot:+"/"}${command} ]; then
751 warn "run_rc_command: cannot run $command"
755 if ! _run_rc_precmd; then
756 warn "failed precmd routine for ${name}"
760 # setup the full command to run
762 check_startmsgs && echo "Starting ${name}."
763 if [ -n "$_chroot" ]; then
765 ${_nice:+nice -n $_nice }\
766 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
767 $_chroot $command $rc_flags $command_args"
770 ${_chdir:+cd $_chdir && }\
771 $command $rc_flags $command_args"
772 if [ -n "$_user" ]; then
773 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
775 if [ -n "$_nice" ]; then
776 if [ -z "$_user" ]; then
777 _doit="sh -c \"$_doit\""
779 _doit="nice -n $_nice $_doit"
783 # run the full command
785 if ! _run_rc_doit "$_doit"; then
786 warn "failed to start ${name}"
790 # finally, run postcmd
796 if [ -z "$rc_pid" ]; then
797 [ -n "$rc_fast" ] && return 0
802 _run_rc_precmd || return 1
804 # send the signal to stop
806 echo "Stopping ${name}."
807 _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
808 _run_rc_doit "$_doit" || return 1
810 # wait for the command to exit,
812 wait_for_pids $rc_pid
818 if [ -z "$rc_pid" ]; then
823 _run_rc_precmd || return 1
825 _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
826 _run_rc_doit "$_doit" || return 1
832 # prevent restart being called more
833 # than once by any given script
835 if ${_rc_restart_done:-false}; then
838 _rc_restart_done=true
840 _run_rc_precmd || return 1
842 # run those in a subshell to keep global variables
843 ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
844 ( run_rc_command ${_rc_prefix}start $rc_extra_args )
846 [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
852 _run_rc_precmd || return 1
853 if [ -n "$rc_pid" ]; then
854 wait_for_pids $rc_pid
861 if [ -n "$desc" ]; then
867 # Get unique vars in $rcvar $rcvars
868 for _v in $rcvar $rcvars; do
870 $_v\ *|\ *$_v|*\ $_v\ *) ;;
877 if [ -z "$_v" ]; then
881 eval _desc=\$${_v}_desc
882 eval _defval=\$${_v}_defval
885 eval echo \"$_v=\\\"\$$_v\\\"\"
886 # decode multiple lines of _desc
887 while [ -n "$_desc" ]; do
890 echo "# $_h ${_desc%%^^*}"
895 echo "# $_h ${_desc}"
900 echo "# (default: \"$_defval\")"
913 echo 1>&2 "$0: unknown directive '$rc_arg'."
919 # Helper functions for run_rc_command: common code.
920 # They use such global variables besides the exported rc_* ones:
930 check_required_before "$rc_arg" || return 1
932 if [ -n "$_precmd" ]; then
933 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
934 eval "$_precmd $rc_extra_args"
937 # If precmd failed and force isn't set, request exit.
938 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
943 check_required_after "$rc_arg" || return 1
950 if [ -n "$_postcmd" ]; then
951 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
952 eval "$_postcmd $rc_extra_args"
960 debug "run_rc_command: doit: $*"
964 # If command failed and force isn't set, request exit.
965 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
976 if [ -n "$pidfile" ]; then
977 _pidmsg=" (check $pidfile)."
981 echo 1>&2 "${name} not running?${_pidmsg}"
988 _cmd="kill -$1 $rc_pid"
989 if [ -n "$_user" ]; then
990 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
996 # run_rc_script file arg
997 # Start the script `file' with `arg', and correctly handle the
998 # return value from the script.
999 # If `file' ends with `.sh', it's sourced into the current environment
1000 # when $rc_fast_and_loose is set, otherwise it is run as a child process.
1001 # If `file' appears to be a backup or scratch file, ignore it.
1002 # Otherwise if it is executable run as a child process.
1008 if [ -z "$_file" -o -z "$_arg" ]; then
1009 err 3 'USAGE: run_rc_script file arg'
1012 unset name command command_args command_interpreter \
1013 extra_commands pidfile procname \
1014 rcvar rcvars rcvars_obsolete required_dirs required_files \
1016 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1019 /etc/rc.d/*.sh) # no longer allowed in the base
1020 warn "Ignoring old-style startup script $_file"
1022 *[~#]|*.OLD|*.bak|*.orig|*,v) # scratch file; skip
1023 warn "Ignoring scratch file $_file"
1025 *) # run in subshell
1026 if [ -x $_file ]; then
1027 if [ -n "$rc_fast_and_loose" ]; then
1030 ( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1031 trap "echo Script $_file interrupted >&2 ; exit 1" 2
1032 trap "echo Script $_file running >&2" 29
1033 set $_arg; . $_file )
1041 # load_rc_config name
1042 # Source in the configuration file for a given name.
1046 local _name _var _defval _v _msg _new
1048 if [ -z "$_name" ]; then
1049 err 3 'USAGE: load_rc_config name'
1052 if ${_rc_conf_loaded:-false}; then
1055 if [ -r /etc/defaults/rc.conf ]; then
1056 debug "Sourcing /etc/defaults/rc.conf"
1057 . /etc/defaults/rc.conf
1059 elif [ -r /etc/rc.conf ]; then
1060 debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1063 _rc_conf_loaded=true
1065 if [ -f /etc/rc.conf.d/"$_name" ]; then
1066 debug "Sourcing /etc/rc.conf.d/${_name}"
1067 . /etc/rc.conf.d/"$_name"
1070 # Set defaults if defined.
1071 for _var in $rcvar $rcvars; do
1072 eval _defval=\$${_var}_defval
1073 if [ -n "$_defval" ]; then
1074 eval : \${$_var:=\$${_var}_defval}
1078 # check obsolete rc.conf variables
1079 for _var in $rcvars_obsolete; do
1081 eval _msg=\$${_var}_obsolete_msg
1082 eval _new=\$${_var}_newvar
1087 if [ -z "$_new" ]; then
1090 eval $_new=\"\$$_var\"
1091 if [ -z "$_msg" ]; then
1092 _msg="Use \$$_new instead."
1095 warn "\$$_var is obsolete. $_msg"
1102 # load_rc_config_var name var
1103 # Read the rc.conf(5) var for name and set in the
1104 # current shell, using load_rc_config in a subshell to prevent
1105 # unwanted side effects from other variable assignments.
1107 load_rc_config_var()
1109 if [ $# -ne 2 ]; then
1110 err 3 'USAGE: load_rc_config_var name var'
1113 load_rc_config '$1' >/dev/null;
1114 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1115 echo '$2'=\'\''${'$2'}\'\'';
1122 # Print a usage string for $0, with `commands' being a list of
1127 echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1131 echo -n 1>&2 "$_sep$_elem"
1139 # err exitval message
1140 # Display message to stderr and log to the syslog, and exit with exitval.
1147 if [ -x /usr/bin/logger ]; then
1148 logger "$0: ERROR: $*"
1150 echo 1>&2 "$0: ERROR: $*"
1156 # Display message to stderr and log to the syslog.
1160 if [ -x /usr/bin/logger ]; then
1161 logger "$0: WARNING: $*"
1163 echo 1>&2 "$0: WARNING: $*"
1168 # Display informational message to stdout and log to syslog.
1173 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1174 if [ -x /usr/bin/logger ]; then
1175 logger "$0: INFO: $*"
1184 # If debugging is enabled in rc.conf output message to stderr.
1185 # BEWARE that you don't call any subroutine that itself calls this
1191 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1192 if [ -x /usr/bin/logger ]; then
1193 logger "$0: DEBUG: $*"
1195 echo 1>&2 "$0: DEBUG: $*"
1201 # backup_file action file cur backup
1202 # Make a backup copy of `file' into `cur', and save the previous
1203 # version of `cur' as `backup' or use rcs for archiving.
1205 # This routine checks the value of the backup_uses_rcs variable,
1206 # which can be either YES or NO.
1208 # The `action' keyword can be one of the following:
1210 # add `file' is now being backed up (and is possibly
1211 # being reentered into the backups system). `cur'
1212 # is created and RCS files, if necessary, are
1215 # update `file' has changed and needs to be backed up.
1216 # If `cur' exists, it is copied to to `back' or
1217 # checked into RCS (if the repository file is old),
1218 # and then `file' is copied to `cur'. Another RCS
1219 # check in done here if RCS is being used.
1221 # remove `file' is no longer being tracked by the backups
1222 # system. If RCS is not being used, `cur' is moved
1223 # to `back', otherwise an empty file is checked in,
1224 # and then `cur' is removed.
1234 if checkyesno backup_uses_rcs; then
1235 _msg0="backup archive"
1238 # ensure that history file is not locked
1239 if [ -f $_cur,v ]; then
1240 rcs -q -u -U -M $_cur
1243 # ensure after switching to rcs that the
1244 # current backup is not lost
1245 if [ -f $_cur ]; then
1246 # no archive, or current newer than archive
1247 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1248 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1257 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1260 chown root:wheel $_cur $_cur,v
1264 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1266 chown root:wheel $_cur $_cur,v
1273 if [ -f $_cur ]; then
1277 chown root:wheel $_cur
1286 # make_symlink src link
1287 # Make a symbolic link 'link' to src from basedir. If the
1288 # directory in which link is to be created does not exist
1289 # a warning will be displayed and an error will be returned.
1290 # Returns 0 on sucess, 1 otherwise.
1294 local src link linkdir _me
1297 linkdir="`dirname $link`"
1298 _me="make_symlink()"
1300 if [ -z "$src" -o -z "$link" ]; then
1301 warn "$_me: requires two arguments."
1304 if [ ! -d "$linkdir" ]; then
1305 warn "$_me: the directory $linkdir does not exist."
1308 if ! ln -sf $src $link; then
1309 warn "$_me: unable to make a symbolic link from $link to $src"
1315 # devfs_rulesets_from_file file
1316 # Reads a set of devfs commands from file, and creates
1317 # the specified rulesets with their rules. Returns non-zero
1318 # if there was an error.
1320 devfs_rulesets_from_file()
1324 _me="devfs_rulesets_from_file"
1327 if [ -z "$file" ]; then
1328 warn "$_me: you must specify a file"
1331 if [ ! -e "$file" ]; then
1332 debug "$_me: no such file ($file)"
1335 debug "reading rulesets from file ($file)"
1343 rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1344 if [ -z "$rulenum" ]; then
1345 warn "$_me: cannot extract rule number ($line)"
1349 rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1350 if [ -z "$rulename" ]; then
1351 warn "$_me: cannot extract rule name ($line)"
1355 eval $rulename=\$rulenum
1356 debug "found ruleset: $rulename=$rulenum"
1357 if ! /sbin/devfs rule -s $rulenum delset; then
1363 rulecmd="${line%%"\#*"}"
1364 # evaluate the command incase it includes
1366 if [ -n "$rulecmd" ]; then
1367 debug "adding rule ($rulecmd)"
1368 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1376 if [ $_err -ne 0 ]; then
1377 debug "error in $_me"
1384 # devfs_init_rulesets
1385 # Initializes rulesets from configuration files. Returns
1386 # non-zero if there was an error.
1388 devfs_init_rulesets()
1391 _me="devfs_init_rulesets"
1393 # Go through this only once
1394 if [ -n "$devfs_rulesets_init" ]; then
1395 debug "$_me: devfs rulesets already initialized"
1398 for file in $devfs_rulesets; do
1399 if ! devfs_rulesets_from_file $file; then
1400 warn "$_me: could not read rules from $file"
1404 devfs_rulesets_init=1
1405 debug "$_me: devfs rulesets initialized"
1409 # devfs_set_ruleset ruleset [dir]
1410 # Sets the default ruleset of dir to ruleset. The ruleset argument
1411 # must be a ruleset name as specified in devfs.rules(5) file.
1412 # Returns non-zero if it could not set it successfully.
1417 [ -n "$1" ] && eval rs=\$$1 || rs=
1418 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1419 _me="devfs_set_ruleset"
1421 if [ -z "$rs" ]; then
1422 warn "$_me: you must specify a ruleset number"
1425 debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1426 if ! /sbin/devfs $devdir ruleset $rs; then
1427 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1433 # devfs_apply_ruleset ruleset [dir]
1434 # Apply ruleset number $ruleset to the devfs mountpoint $dir.
1435 # The ruleset argument must be a ruleset name as specified
1436 # in a devfs.rules(5) file. Returns 0 on success or non-zero
1437 # if it could not apply the ruleset.
1439 devfs_apply_ruleset()
1442 [ -n "$1" ] && eval rs=\$$1 || rs=
1443 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1444 _me="devfs_apply_ruleset"
1446 if [ -z "$rs" ]; then
1447 warn "$_me: you must specify a ruleset"
1450 debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1451 if ! /sbin/devfs $devdir rule -s $rs applyset; then
1452 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1458 # devfs_domount dir [ruleset]
1459 # Mount devfs on dir. If ruleset is specified it is set
1460 # on the mount-point. It must also be a ruleset name as specified
1461 # in a devfs.rules(5) file. Returns 0 on success.
1467 [ -n "$2" ] && rs=$2 || rs=
1468 _me="devfs_domount()"
1470 if [ -z "$devdir" ]; then
1471 warn "$_me: you must specify a mount-point"
1474 debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1475 if ! mount -t devfs dev "$devdir"; then
1476 warn "$_me: Unable to mount devfs on $devdir"
1479 if [ -n "$rs" ]; then
1481 devfs_set_ruleset $rs $devdir
1482 devfs -m $devdir rule applyset
1487 # devfs_mount_jail dir [ruleset]
1488 # Mounts a devfs file system appropriate for jails
1489 # on the directory dir. If ruleset is specified, the ruleset
1490 # it names will be used instead. If present, ruleset must
1491 # be the name of a ruleset as defined in a devfs.rules(5) file.
1492 # This function returns non-zero if an error occurs.
1498 [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1499 _me="devfs_mount_jail"
1502 if ! devfs_domount "$jdev" $rs; then
1503 warn "$_me: devfs was not mounted on $jdev"
1509 # Provide a function for normalizing the mounting of memory
1510 # filesystems. This should allow the rest of the code here to remain
1511 # as close as possible between 5-current and 4-stable.
1514 # $3 = (optional) extra mdmfs flags
1517 if [ -n "$3" ]; then
1520 /sbin/mdmfs $flags -s $1 md $2
1523 # Code common to scripts that need to load a kernel module
1524 # if it isn't in the kernel yet. Syntax:
1525 # load_kld [-e regex] [-m module] file
1526 # where -e or -m chooses the way to check if the module
1527 # is already loaded:
1528 # regex is egrep'd in the output from `kldstat -v',
1529 # module is passed to `kldstat -m'.
1530 # The default way is as though `-m file' were specified.
1533 local _loaded _mod _opt _re
1535 while getopts "e:m:" _opt; do
1538 m) _mod="$OPTARG" ;;
1539 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1542 shift $(($OPTIND - 1))
1543 if [ $# -ne 1 ]; then
1544 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1548 if [ -n "$_re" ]; then
1549 if kldstat -v | egrep -q -e "$_re"; then
1553 if kldstat -q -m "$_mod"; then
1558 if ! kldload "$1"; then
1559 warn "Unable to load kernel module $1"
1562 info "$1 kernel module loaded."
1565 debug "load_kld: $1 kernel module already loaded."
1571 # Change every $src in $str to $dst.
1572 # Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1576 local _str _src _dst _out _com
1583 for _com in ${_str}; do
1584 if [ -z "${_out}" ]; then
1587 _out="${_out}${_dst}${_com}"
1593 # Creates a list of providers for GELI encryption.
1596 local devices devices2
1597 local provider mountpoint type options rest
1599 # Create list of GELI providers from fstab.
1600 while read provider mountpoint type options rest ; do
1601 case ":${options}" in
1610 case ":${provider}" in
1615 # Skip swap devices.
1616 if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1619 devices="${devices} ${provider}"
1624 # Append providers from geli_devices.
1625 devices="${devices} ${geli_devices}"
1627 for provider in ${devices}; do
1628 provider=${provider%.eli}
1629 provider=${provider#/dev/}
1630 devices2="${devices2} ${provider}"
1636 # Find scripts in local_startup directories that use the old syntax
1638 find_local_scripts_old () {
1641 for dir in ${local_startup}; do
1642 if [ -d "${dir}" ]; then
1643 for file in ${dir}/[0-9]*.sh; do
1644 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1646 zlist="$zlist $file"
1648 for file in ${dir}/[^0-9]*.sh; do
1649 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1651 slist="$slist $file"
1657 find_local_scripts_new () {
1659 for dir in ${local_startup}; do
1660 if [ -d "${dir}" ]; then
1661 for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1664 *) if [ -x "$file" ]; then
1665 local_rc="${local_rc} ${file}"
1674 # check_required_{before|after} command
1675 # Check for things required by the command before and after its precmd,
1676 # respectively. The two separate functions are needed because some
1677 # conditions should prevent precmd from being run while other things
1678 # depend on precmd having already been run.
1680 check_required_before()
1686 for _f in $required_vars; do
1687 if ! checkyesno $_f; then
1688 warn "\$${_f} is not enabled."
1689 if [ -z "$rc_force" ]; then
1695 for _f in $required_dirs; do
1696 if [ ! -d "${_f}/." ]; then
1697 warn "${_f} is not a directory."
1698 if [ -z "$rc_force" ]; then
1704 for _f in $required_files; do
1705 if [ ! -r "${_f}" ]; then
1706 warn "${_f} is not readable."
1707 if [ -z "$rc_force" ]; then
1718 check_required_after()
1724 for _f in $required_modules; do
1726 *~*) _args="-e ${_f#*~} ${_f%%~*}" ;;
1727 *:*) _args="-m ${_f#*:} ${_f%%:*}" ;;
1730 if ! load_kld ${_args}; then
1731 if [ -z "$rc_force" ]; then
1742 # check_kern_features mib
1743 # Return existence of kern.features.* sysctl MIB as true or
1744 # false. The result will be cached in $_rc_cache_kern_features_
1745 # namespace. "0" means the kern.features.X exists.
1747 check_kern_features()
1751 [ -n "$1" ] || return 1;
1752 eval _v=\$_rc_cache_kern_features_$1
1753 [ -n "$_v" ] && return "$_v";
1755 if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1756 eval _rc_cache_kern_features_$1=0
1759 eval _rc_cache_kern_features_$1=1
1764 # _echoonce var msg mode
1765 # mode=0: Echo $msg if ${$var} is empty.
1766 # After doing echo, a string is set to ${$var}.
1768 # mode=1: Echo $msg if ${$var} is a string with non-zero length.
1772 local _var _msg _mode
1778 1) [ -n "$_var" ] && echo "$_msg" ;;
1779 *) [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1783 fi # [ -z "${_rc_subr_loaded}" ]