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
117 # Force a service to start. Intended for use by services
118 # to resolve dependency issues. It is assumed the caller
119 # has check to make sure this call is necessary
120 # $1 - filename of script, in /etc/rc.d, to run
126 info "${name} depends on ${_depend}, which will be forced to start."
127 if ! /etc/rc.d/${_depend} forcestart; then
128 warn "Unable to force ${_depend}. It may already be running."
136 # Test $1 variable, and warn if not set to YES or NO.
137 # Return 0 if it's "yes" (et al), nonzero otherwise.
142 debug "checkyesno: $1 is set to $_value."
145 # "yes", "true", "on", or "1"
146 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
150 # "no", "false", "off", or "0"
151 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
155 warn "\$${1} is not set properly - see ${rcvar_manpage}."
163 # print the list in reverse order
169 _revlist="$_revfile $_revlist"
175 # If booting directly to multiuser or $always is enabled,
176 # send SIGTERM to the parent (/etc/rc) to abort the boot.
177 # Otherwise just exit.
184 # "yes", "true", "on", or "1"
185 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
192 if [ "$autoboot" = yes -o "$always" = true ]; then
193 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
200 # mount_critical_filesystems type
201 # Go through the list of critical filesystems as provided in
202 # the rc.conf(5) variable $critical_filesystems_${type}, checking
203 # each one to see if it is mounted, and if it is not, mounting it.
205 mount_critical_filesystems()
207 eval _fslist=\$critical_filesystems_${1}
208 for _fs in $_fslist; do
211 while read what _on on _type type; do
212 if [ $on = $_fs ]; then
219 mount $_fs >/dev/null 2>&1
226 # check_pidfile pidfile procname [interpreter]
227 # Parses the first line of pidfile for a PID, and ensures
228 # that the process is running and matches procname.
229 # Prints the matching PID upon success, nothing otherwise.
230 # interpreter is optional; see _find_processes() for details.
237 if [ -z "$_pidfile" -o -z "$_procname" ]; then
238 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
240 if [ ! -f $_pidfile ]; then
241 debug "pid file ($_pidfile): not readable."
244 read _pid _junk < $_pidfile
245 if [ -z "$_pid" ]; then
246 debug "pid file ($_pidfile): no pid in file."
249 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
253 # check_process procname [interpreter]
254 # Ensures that a process (or processes) named procname is running.
255 # Prints a list of matching PIDs.
256 # interpreter is optional; see _find_processes() for details.
262 if [ -z "$_procname" ]; then
263 err 3 'USAGE: check_process procname [interpreter]'
265 _find_processes $_procname ${_interpreter:-.} '-ax'
269 # _find_processes procname interpreter psargs
270 # Search for procname in the output of ps generated by psargs.
271 # Prints the PIDs of any matching processes, space separated.
273 # If interpreter == ".", check the following variations of procname
274 # against the first word of each command:
276 # `basename procname`
277 # `basename procname` + ":"
278 # "(" + `basename procname` + ")"
279 # "[" + `basename procname` + "]"
281 # If interpreter != ".", read the first line of procname, remove the
282 # leading #!, normalise whitespace, append procname, and attempt to
283 # match that against each command, either as is, or with extra words
284 # at the end. As an alternative, to deal with interpreted daemons
285 # using perl, the basename of the interpreter plus a colon is also
286 # tried as the prefix to procname.
290 if [ $# -ne 3 ]; then
291 err 3 'USAGE: _find_processes procname interpreter psargs'
298 if [ $_interpreter != "." ]; then # an interpreted script
299 _script=${_chroot}${_chroot:+"/"}$_procname
300 if [ -r $_script ]; then
301 read _interp < $_script # read interpreter name
304 _interp=${_interp#\#!} # strip #!
308 shift # drop env to get real name
311 if [ $_interpreter != $1 ]; then
312 warn "\$command_interpreter $_interpreter != $1"
316 warn "no shebang line in $_script"
321 warn "cannot read shebang line from $_script"
324 _interp="$* $_procname" # cleanup spaces, add _procname
327 _fp_match='case "$_argv" in
328 ${_interp}|"${_interp} "*|"${_interpbn}: ${_procname}"*)'
329 else # a normal daemon
330 _procnamebn=${_procname##*/}
331 _fp_args='_arg0 _argv'
332 _fp_match='case "$_arg0" in
333 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
337 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
338 while read _npid _jid '"$_fp_args"'; do
340 if [ "$JID" -eq "$_jid" ];
341 then echo -n "$_pref$_npid";
348 # debug "in _find_processes: proccheck is ($_proccheck)."
353 # wait_for_pids pid [pid ...]
354 # spins until none of the pids exist
359 if [ -z "$_list" ]; then
366 if kill -0 $_j 2>/dev/null; then
367 _nlist="${_nlist}${_nlist:+ }$_j"
370 if [ -z "$_nlist" ]; then
374 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
376 pwait $_list 2>/dev/null || sleep 2
378 if [ -n "$_prefix" ]; then
385 # If rc_quiet is set (usually as a result of using faststart at
386 # boot time) check if rc_startmsgs is enabled.
390 if [ -n "$rc_quiet" ]; then
391 checkyesno rc_startmsgs
398 # run_rc_command argument
399 # Search for argument in the list of supported commands, which is:
400 # "start stop restart rcvar status poll ${extra_commands}"
401 # If there's a match, run ${argument}_cmd or the default method
404 # If argument has a given prefix, then change the operation as follows:
407 # fast Skip the pid check, and set rc_fast=yes, rc_quiet=yes
408 # force Set ${rcvar} to YES, and set rc_force=yes
409 # one Set ${rcvar} to YES
410 # quiet Don't output some diagnostics, and set rc_quiet=yes
412 # The following globals are used:
414 # Name Needed Purpose
415 # ---- ------ -------
416 # name y Name of script.
418 # command n Full path to command.
419 # Not needed if ${rc_arg}_cmd is set for
422 # command_args n Optional args/shell directives for command.
424 # command_interpreter n If not empty, command is interpreted, so
425 # call check_{pidfile,process}() appropriately.
427 # desc n Description of script.
429 # extra_commands n List of extra commands supported.
431 # pidfile n If set, use check_pidfile $pidfile $command,
432 # otherwise use check_process $command.
433 # In either case, only check if $command is set.
435 # procname n Process name to check for instead of $command.
437 # rcvar n This is checked with checkyesno to determine
438 # if the action should be run.
440 # ${name}_program n Full path to command.
441 # Meant to be used in /etc/rc.conf to override
444 # ${name}_chroot n Directory to chroot to before running ${command}
445 # Requires /usr to be mounted.
447 # ${name}_chdir n Directory to cd to before running ${command}
448 # (if not using ${name}_chroot).
450 # ${name}_flags n Arguments to call ${command} with.
451 # NOTE: $flags from the parent environment
452 # can be used to override this.
454 # ${name}_nice n Nice level to run ${command} at.
456 # ${name}_user n User to run ${command} as, using su(1) if not
457 # using ${name}_chroot.
458 # Requires /usr to be mounted.
460 # ${name}_group n Group to run chrooted ${command} as.
461 # Requires /usr to be mounted.
463 # ${name}_groups n Comma separated list of supplementary groups
464 # to run the chrooted ${command} with.
465 # Requires /usr to be mounted.
467 # ${rc_arg}_cmd n If set, use this as the method when invoked;
468 # Otherwise, use default command (see below)
470 # ${rc_arg}_precmd n If set, run just before performing the
471 # ${rc_arg}_cmd method in the default
472 # operation (i.e, after checking for required
473 # bits and process (non)existence).
474 # If this completes with a non-zero exit code,
475 # don't run ${rc_arg}_cmd.
477 # ${rc_arg}_postcmd n If set, run just after performing the
478 # ${rc_arg}_cmd method, if that method
479 # returned a zero exit code.
481 # required_dirs n If set, check for the existence of the given
482 # directories before running a (re)start command.
484 # required_files n If set, check for the readability of the given
485 # files before running a (re)start command.
487 # required_modules n If set, ensure the given kernel modules are
488 # loaded before running a (re)start command.
489 # The check and possible loads are actually
490 # done after start_precmd so that the modules
491 # aren't loaded in vain, should the precmd
492 # return a non-zero status to indicate a error.
493 # If a word in the list looks like "foo:bar",
494 # "foo" is the KLD file name and "bar" is the
495 # module name. If a word looks like "foo~bar",
496 # "foo" is the KLD file name and "bar" is a
497 # egrep(1) pattern matching the module name.
498 # Otherwise the module name is assumed to be
499 # the same as the KLD file name, which is most
500 # common. See load_kld().
502 # required_vars n If set, perform checkyesno on each of the
503 # listed variables before running the default
506 # Default behaviour for a given argument, if no override method is
509 # Argument Default behaviour
510 # -------- -----------------
511 # start if !running && checkyesno ${rcvar}
515 # rc_pid=$(check_pidfile $pidfile $command)
517 # rc_pid=$(check_process $command)
518 # kill $sig_stop $rc_pid
519 # wait_for_pids $rc_pid
520 # ($sig_stop defaults to TERM.)
522 # reload Similar to stop, except use $sig_reload instead,
523 # and doesn't wait_for_pids.
524 # $sig_reload defaults to HUP.
525 # Note that `reload' isn't provided by default,
526 # it should be enabled via $extra_commands.
528 # restart Run `stop' then `start'.
530 # status Show if ${command} is running, etc.
532 # poll Wait for ${command} to exit.
534 # rcvar Display what rc.conf variable is used (if any).
536 # Variables available to methods, and after run_rc_command() has
541 # rc_arg Argument to command, after fast/force/one processing
544 # rc_flags Flags to start the default command with.
545 # Defaults to ${name}_flags, unless overridden
546 # by $flags from the environment.
547 # This variable may be changed by the precmd method.
549 # rc_pid PID of command (if appropriate)
551 # rc_fast Not empty if "fast" was provided (q.v.)
553 # rc_force Not empty if "force" was provided (q.v.)
555 # rc_quiet Not empty if "quiet" was provided
562 if [ -z "$name" ]; then
563 err 3 'run_rc_command: $name is not set.'
566 # Don't repeat the first argument when passing additional command-
567 # line arguments to the command subroutines.
574 fast*) # "fast" prefix; don't check pid
575 rc_arg=${rc_arg#fast}
579 force*) # "force" prefix; always run
582 rc_arg=${rc_arg#${_rc_prefix}}
583 if [ -n "${rcvar}" ]; then
587 one*) # "one" prefix; set ${rcvar}=yes
589 rc_arg=${rc_arg#${_rc_prefix}}
590 if [ -n "${rcvar}" ]; then
594 quiet*) # "quiet" prefix; omit some messages
596 rc_arg=${rc_arg#${_rc_prefix}}
601 eval _override_command=\$${name}_program
602 command=${_override_command:-$command}
604 _keywords="start stop restart rcvar $extra_commands"
607 _procname=${procname:-${command}}
609 # setup pid check command
610 if [ -n "$_procname" ]; then
611 if [ -n "$pidfile" ]; then
612 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
614 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
616 if [ -n "$_pidcmd" ]; then
617 _keywords="${_keywords} status poll"
621 if [ -z "$rc_arg" ]; then
625 if [ -n "$flags" ]; then # allow override from environment
628 eval rc_flags=\$${name}_flags
630 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
631 _nice=\$${name}_nice _user=\$${name}_user \
632 _group=\$${name}_group _groups=\$${name}_groups
634 if [ -n "$_user" ]; then # unset $_user if running as that user
635 if [ "$_user" = "$(eval $IDCMD)" ]; then
640 eval $_pidcmd # determine the pid if necessary
642 for _elem in $_keywords; do
643 if [ "$_elem" != "$rc_arg" ]; then
646 # if ${rcvar} is set, and $1 is not
648 # checkyesno ${rcvar}
649 # and return if that failed
651 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
652 if ! checkyesno ${rcvar}; then
653 if [ -n "${rc_quiet}" ]; then
656 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
657 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
658 echo "instead of '${rc_arg}'."
663 # if there's a custom ${XXX_cmd},
664 # run that instead of the default
666 eval _cmd=\$${rc_arg}_cmd \
667 _precmd=\$${rc_arg}_precmd \
668 _postcmd=\$${rc_arg}_postcmd
670 if [ -n "$_cmd" ]; then
671 _run_rc_precmd || return 1
672 _run_rc_doit "$_cmd $rc_extra_args" || return 1
677 case "$rc_arg" in # default operations...
680 _run_rc_precmd || return 1
681 if [ -n "$rc_pid" ]; then
682 echo "${name} is running as pid $rc_pid."
684 echo "${name} is not running."
691 if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
692 echo 1>&2 "${name} already running? (pid=$rc_pid)."
696 if [ ! -x ${_chroot}${_chroot:+"/"}${command} ]; then
697 warn "run_rc_command: cannot run $command"
701 if ! _run_rc_precmd; then
702 warn "failed precmd routine for ${name}"
706 # setup the full command to run
708 check_startmsgs && echo "Starting ${name}."
709 if [ -n "$_chroot" ]; then
711 ${_nice:+nice -n $_nice }\
712 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
713 $_chroot $command $rc_flags $command_args"
716 ${_chdir:+cd $_chdir && }\
717 $command $rc_flags $command_args"
718 if [ -n "$_user" ]; then
719 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
721 if [ -n "$_nice" ]; then
722 if [ -z "$_user" ]; then
723 _doit="sh -c \"$_doit\""
725 _doit="nice -n $_nice $_doit"
729 # run the full command
731 if ! _run_rc_doit "$_doit"; then
732 warn "failed to start ${name}"
736 # finally, run postcmd
742 if [ -z "$rc_pid" ]; then
743 [ -n "$rc_fast" ] && return 0
748 _run_rc_precmd || return 1
750 # send the signal to stop
752 echo "Stopping ${name}."
753 _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
754 _run_rc_doit "$_doit" || return 1
756 # wait for the command to exit,
758 wait_for_pids $rc_pid
764 if [ -z "$rc_pid" ]; then
769 _run_rc_precmd || return 1
771 _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
772 _run_rc_doit "$_doit" || return 1
778 # prevent restart being called more
779 # than once by any given script
781 if ${_rc_restart_done:-false}; then
784 _rc_restart_done=true
786 _run_rc_precmd || return 1
788 # run those in a subshell to keep global variables
789 ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
790 ( run_rc_command ${_rc_prefix}start $rc_extra_args )
792 [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
798 _run_rc_precmd || return 1
799 if [ -n "$rc_pid" ]; then
800 wait_for_pids $rc_pid
807 if [ -n "$desc" ]; then
813 # Get unique vars in $rcvar $rcvars
814 for _v in $rcvar $rcvars; do
816 $_v\ *|\ *$_v|*\ $_v\ *) ;;
823 if [ -z "$_v" ]; then
827 eval _desc=\$${_v}_desc
828 eval _defval=\$${_v}_defval
831 eval echo \"$_v=\\\"\$$_v\\\"\"
832 # decode multiple lines of _desc
833 while [ -n "$_desc" ]; do
836 echo "# $_h ${_desc%%^^*}"
841 echo "# $_h ${_desc}"
846 echo "# (default: \"$_defval\")"
859 echo 1>&2 "$0: unknown directive '$rc_arg'."
865 # Helper functions for run_rc_command: common code.
866 # They use such global variables besides the exported rc_* ones:
876 check_required_before "$rc_arg" || return 1
878 if [ -n "$_precmd" ]; then
879 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
880 eval "$_precmd $rc_extra_args"
883 # If precmd failed and force isn't set, request exit.
884 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
889 check_required_after "$rc_arg" || return 1
896 if [ -n "$_postcmd" ]; then
897 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
898 eval "$_postcmd $rc_extra_args"
906 debug "run_rc_command: doit: $*"
910 # If command failed and force isn't set, request exit.
911 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
922 if [ -n "$pidfile" ]; then
923 _pidmsg=" (check $pidfile)."
927 echo 1>&2 "${name} not running?${_pidmsg}"
934 _cmd="kill -$1 $rc_pid"
935 if [ -n "$_user" ]; then
936 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
942 # run_rc_script file arg
943 # Start the script `file' with `arg', and correctly handle the
944 # return value from the script.
945 # If `file' ends with `.sh', it's sourced into the current environment
946 # when $rc_fast_and_loose is set, otherwise it is run as a child process.
947 # If `file' appears to be a backup or scratch file, ignore it.
948 # Otherwise if it is executable run as a child process.
954 if [ -z "$_file" -o -z "$_arg" ]; then
955 err 3 'USAGE: run_rc_script file arg'
958 unset name command command_args command_interpreter \
959 extra_commands pidfile procname \
960 rcvar rcvars rcvars_obsolete required_dirs required_files \
962 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
965 /etc/rc.d/*.sh) # no longer allowed in the base
966 warn "Ignoring old-style startup script $_file"
968 *[~#]|*.OLD|*.bak|*.orig|*,v) # scratch file; skip
969 warn "Ignoring scratch file $_file"
972 if [ -x $_file ]; then
973 if [ -n "$rc_fast_and_loose" ]; then
976 ( trap "echo Script $_file interrupted; kill -QUIT $$" 3
977 trap "echo Script $_file interrupted; exit 1" 2
978 trap "echo Script $_file running" 29
979 set $_arg; . $_file )
987 # load_rc_config name
988 # Source in the configuration file for a given name.
992 local _name _var _defval _v _msg _new
994 if [ -z "$_name" ]; then
995 err 3 'USAGE: load_rc_config name'
998 if ${_rc_conf_loaded:-false}; then
1001 if [ -r /etc/defaults/rc.conf ]; then
1002 debug "Sourcing /etc/defaults/rc.conf"
1003 . /etc/defaults/rc.conf
1005 elif [ -r /etc/rc.conf ]; then
1006 debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1009 _rc_conf_loaded=true
1011 if [ -f /etc/rc.conf.d/"$_name" ]; then
1012 debug "Sourcing /etc/rc.conf.d/${_name}"
1013 . /etc/rc.conf.d/"$_name"
1016 # Old variable names support
1018 [ -n "$enable_quotas" ] && quota_enable="$enable_quotas"
1020 # Set defaults if defined.
1021 for _var in $rcvar $rcvars; do
1022 _defval=`eval echo "\\\$${_var}_defval"`
1023 if [ -n "$_defval" ]; then
1024 eval : \${$_var:=\$${_var}_defval}
1028 # check obsolete rc.conf variables
1029 for _var in $rcvars_obsolete; do
1030 _v=`eval echo \\$$_var`
1031 _msg=`eval echo \\$${_var}_obsolete_msg`
1032 _new=`eval echo \\$${_var}_newvar`
1037 if [ -z "$_new" ]; then
1040 eval $_new=\"\$$_var\"
1041 if [ -z "$_msg" ]; then
1042 _msg="Use \$$_new instead."
1045 warn "\$$_var is obsolete. $_msg"
1052 # load_rc_config_var name var
1053 # Read the rc.conf(5) var for name and set in the
1054 # current shell, using load_rc_config in a subshell to prevent
1055 # unwanted side effects from other variable assignments.
1057 load_rc_config_var()
1059 if [ $# -ne 2 ]; then
1060 err 3 'USAGE: load_rc_config_var name var'
1063 load_rc_config '$1' >/dev/null;
1064 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1065 echo '$2'=\'\''${'$2'}\'\'';
1072 # Print a usage string for $0, with `commands' being a list of
1077 echo -n 1>&2 "Usage: $0 [fast|force|one]("
1081 echo -n 1>&2 "$_sep$_elem"
1089 # err exitval message
1090 # Display message to stderr and log to the syslog, and exit with exitval.
1097 if [ -x /usr/bin/logger ]; then
1098 logger "$0: ERROR: $*"
1100 echo 1>&2 "$0: ERROR: $*"
1106 # Display message to stderr and log to the syslog.
1110 if [ -x /usr/bin/logger ]; then
1111 logger "$0: WARNING: $*"
1113 echo 1>&2 "$0: WARNING: $*"
1118 # Display informational message to stdout and log to syslog.
1123 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1124 if [ -x /usr/bin/logger ]; then
1125 logger "$0: INFO: $*"
1134 # If debugging is enabled in rc.conf output message to stderr.
1135 # BEWARE that you don't call any subroutine that itself calls this
1141 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1142 if [ -x /usr/bin/logger ]; then
1143 logger "$0: DEBUG: $*"
1145 echo 1>&2 "$0: DEBUG: $*"
1151 # backup_file action file cur backup
1152 # Make a backup copy of `file' into `cur', and save the previous
1153 # version of `cur' as `backup' or use rcs for archiving.
1155 # This routine checks the value of the backup_uses_rcs variable,
1156 # which can be either YES or NO.
1158 # The `action' keyword can be one of the following:
1160 # add `file' is now being backed up (and is possibly
1161 # being reentered into the backups system). `cur'
1162 # is created and RCS files, if necessary, are
1165 # update `file' has changed and needs to be backed up.
1166 # If `cur' exists, it is copied to to `back' or
1167 # checked into RCS (if the repository file is old),
1168 # and then `file' is copied to `cur'. Another RCS
1169 # check in done here if RCS is being used.
1171 # remove `file' is no longer being tracked by the backups
1172 # system. If RCS is not being used, `cur' is moved
1173 # to `back', otherwise an empty file is checked in,
1174 # and then `cur' is removed.
1184 if checkyesno backup_uses_rcs; then
1185 _msg0="backup archive"
1188 # ensure that history file is not locked
1189 if [ -f $_cur,v ]; then
1190 rcs -q -u -U -M $_cur
1193 # ensure after switching to rcs that the
1194 # current backup is not lost
1195 if [ -f $_cur ]; then
1196 # no archive, or current newer than archive
1197 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1198 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1207 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1210 chown root:wheel $_cur $_cur,v
1214 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1216 chown root:wheel $_cur $_cur,v
1223 if [ -f $_cur ]; then
1227 chown root:wheel $_cur
1236 # make_symlink src link
1237 # Make a symbolic link 'link' to src from basedir. If the
1238 # directory in which link is to be created does not exist
1239 # a warning will be displayed and an error will be returned.
1240 # Returns 0 on sucess, 1 otherwise.
1244 local src link linkdir _me
1247 linkdir="`dirname $link`"
1248 _me="make_symlink()"
1250 if [ -z "$src" -o -z "$link" ]; then
1251 warn "$_me: requires two arguments."
1254 if [ ! -d "$linkdir" ]; then
1255 warn "$_me: the directory $linkdir does not exist."
1258 if ! ln -sf $src $link; then
1259 warn "$_me: unable to make a symbolic link from $link to $src"
1265 # devfs_rulesets_from_file file
1266 # Reads a set of devfs commands from file, and creates
1267 # the specified rulesets with their rules. Returns non-zero
1268 # if there was an error.
1270 devfs_rulesets_from_file()
1274 _me="devfs_rulesets_from_file"
1277 if [ -z "$file" ]; then
1278 warn "$_me: you must specify a file"
1281 if [ ! -e "$file" ]; then
1282 debug "$_me: no such file ($file)"
1285 debug "reading rulesets from file ($file)"
1293 rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1294 if [ -z "$rulenum" ]; then
1295 warn "$_me: cannot extract rule number ($line)"
1299 rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1300 if [ -z "$rulename" ]; then
1301 warn "$_me: cannot extract rule name ($line)"
1305 eval $rulename=\$rulenum
1306 debug "found ruleset: $rulename=$rulenum"
1307 if ! /sbin/devfs rule -s $rulenum delset; then
1313 rulecmd="${line%%"\#*"}"
1314 # evaluate the command incase it includes
1316 if [ -n "$rulecmd" ]; then
1317 debug "adding rule ($rulecmd)"
1318 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1326 if [ $_err -ne 0 ]; then
1327 debug "error in $_me"
1334 # devfs_init_rulesets
1335 # Initializes rulesets from configuration files. Returns
1336 # non-zero if there was an error.
1338 devfs_init_rulesets()
1341 _me="devfs_init_rulesets"
1343 # Go through this only once
1344 if [ -n "$devfs_rulesets_init" ]; then
1345 debug "$_me: devfs rulesets already initialized"
1348 for file in $devfs_rulesets; do
1349 devfs_rulesets_from_file $file || return 1
1351 devfs_rulesets_init=1
1352 debug "$_me: devfs rulesets initialized"
1356 # devfs_set_ruleset ruleset [dir]
1357 # Sets the default ruleset of dir to ruleset. The ruleset argument
1358 # must be a ruleset name as specified in devfs.rules(5) file.
1359 # Returns non-zero if it could not set it successfully.
1364 [ -n "$1" ] && eval rs=\$$1 || rs=
1365 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1366 _me="devfs_set_ruleset"
1368 if [ -z "$rs" ]; then
1369 warn "$_me: you must specify a ruleset number"
1372 debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1373 if ! /sbin/devfs $devdir ruleset $rs; then
1374 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1380 # devfs_apply_ruleset ruleset [dir]
1381 # Apply ruleset number $ruleset to the devfs mountpoint $dir.
1382 # The ruleset argument must be a ruleset name as specified
1383 # in a devfs.rules(5) file. Returns 0 on success or non-zero
1384 # if it could not apply the ruleset.
1386 devfs_apply_ruleset()
1389 [ -n "$1" ] && eval rs=\$$1 || rs=
1390 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1391 _me="devfs_apply_ruleset"
1393 if [ -z "$rs" ]; then
1394 warn "$_me: you must specify a ruleset"
1397 debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1398 if ! /sbin/devfs $devdir rule -s $rs applyset; then
1399 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1405 # devfs_domount dir [ruleset]
1406 # Mount devfs on dir. If ruleset is specified it is set
1407 # on the mount-point. It must also be a ruleset name as specified
1408 # in a devfs.rules(5) file. Returns 0 on success.
1414 [ -n "$2" ] && rs=$2 || rs=
1415 _me="devfs_domount()"
1417 if [ -z "$devdir" ]; then
1418 warn "$_me: you must specify a mount-point"
1421 debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1422 if ! mount -t devfs dev "$devdir"; then
1423 warn "$_me: Unable to mount devfs on $devdir"
1426 if [ -n "$rs" ]; then
1428 devfs_set_ruleset $rs $devdir
1429 devfs -m $devdir rule applyset
1434 # devfs_mount_jail dir [ruleset]
1435 # Mounts a devfs file system appropriate for jails
1436 # on the directory dir. If ruleset is specified, the ruleset
1437 # it names will be used instead. If present, ruleset must
1438 # be the name of a ruleset as defined in a devfs.rules(5) file.
1439 # This function returns non-zero if an error occurs.
1445 [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1446 _me="devfs_mount_jail"
1449 if ! devfs_domount "$jdev" $rs; then
1450 warn "$_me: devfs was not mounted on $jdev"
1456 # Provide a function for normalizing the mounting of memory
1457 # filesystems. This should allow the rest of the code here to remain
1458 # as close as possible between 5-current and 4-stable.
1461 # $3 = (optional) extra mdmfs flags
1464 if [ -n "$3" ]; then
1467 /sbin/mdmfs $flags -s $1 md $2
1470 # Code common to scripts that need to load a kernel module
1471 # if it isn't in the kernel yet. Syntax:
1472 # load_kld [-e regex] [-m module] file
1473 # where -e or -m chooses the way to check if the module
1474 # is already loaded:
1475 # regex is egrep'd in the output from `kldstat -v',
1476 # module is passed to `kldstat -m'.
1477 # The default way is as though `-m file' were specified.
1480 local _loaded _mod _opt _re
1482 while getopts "e:m:" _opt; do
1485 m) _mod="$OPTARG" ;;
1486 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1489 shift $(($OPTIND - 1))
1490 if [ $# -ne 1 ]; then
1491 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1495 if [ -n "$_re" ]; then
1496 if kldstat -v | egrep -q -e "$_re"; then
1500 if kldstat -q -m "$_mod"; then
1505 if ! kldload "$1"; then
1506 warn "Unable to load kernel module $1"
1509 info "$1 kernel module loaded."
1512 debug "load_kld: $1 kernel module already loaded."
1518 # Change every $src in $str to $dst.
1519 # Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1523 local _str _src _dst _out _com
1530 for _com in ${_str}; do
1531 if [ -z "${_out}" ]; then
1534 _out="${_out}${_dst}${_com}"
1540 # Creates a list of providers for GELI encryption.
1543 local devices devices2
1544 local provider mountpoint type options rest
1546 # Create list of GELI providers from fstab.
1547 while read provider mountpoint type options rest ; do
1548 case ":${options}" in
1557 case ":${provider}" in
1562 # Skip swap devices.
1563 if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1566 devices="${devices} ${provider}"
1571 # Append providers from geli_devices.
1572 devices="${devices} ${geli_devices}"
1574 for provider in ${devices}; do
1575 provider=${provider%.eli}
1576 provider=${provider#/dev/}
1577 devices2="${devices2} ${provider}"
1583 # Find scripts in local_startup directories that use the old syntax
1585 find_local_scripts_old () {
1588 for dir in ${local_startup}; do
1589 if [ -d "${dir}" ]; then
1590 for file in ${dir}/[0-9]*.sh; do
1591 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1593 zlist="$zlist $file"
1595 for file in ${dir}/[^0-9]*.sh; do
1596 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1598 slist="$slist $file"
1604 find_local_scripts_new () {
1606 for dir in ${local_startup}; do
1607 if [ -d "${dir}" ]; then
1608 for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1611 *) if [ -x "$file" ]; then
1612 local_rc="${local_rc} ${file}"
1621 # check_required_{before|after} command
1622 # Check for things required by the command before and after its precmd,
1623 # respectively. The two separate functions are needed because some
1624 # conditions should prevent precmd from being run while other things
1625 # depend on precmd having already been run.
1627 check_required_before()
1633 for _f in $required_vars; do
1634 if ! checkyesno $_f; then
1635 warn "\$${_f} is not enabled."
1636 if [ -z "$rc_force" ]; then
1642 for _f in $required_dirs; do
1643 if [ ! -d "${_f}/." ]; then
1644 warn "${_f} is not a directory."
1645 if [ -z "$rc_force" ]; then
1651 for _f in $required_files; do
1652 if [ ! -r "${_f}" ]; then
1653 warn "${_f} is not readable."
1654 if [ -z "$rc_force" ]; then
1665 check_required_after()
1671 for _f in $required_modules; do
1673 *~*) _args="-e ${_f#*~} ${_f%%~*}" ;;
1674 *:*) _args="-m ${_f#*:} ${_f%%:*}" ;;
1677 if ! load_kld ${_args}; then
1678 if [ -z "$rc_force" ]; then
1691 # _echoonce var msg mode
1692 # mode=0: Echo $msg if ${$var} is empty.
1693 # After doing echo, a string is set to ${$var}.
1695 # mode=1: Echo $msg if ${$var} is a string with non-zero length.
1699 local _var _msg _mode
1700 _var=`eval echo \\$$1`
1705 1) [ -n "$_var" ] && echo "$_msg" ;;
1706 *) [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;