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=`
57 # set_rcvar_obsolete oldvar [newvar] [msg]
58 # Define obsolete variable.
59 # Global variable $rcvars_obsolete is used.
65 debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
67 rcvars_obsolete="${rcvars_obsolete# } $1"
68 eval ${1}_newvar=\"$2\"
70 eval ${_var}_obsolete_msg=\"$*\"
75 # Force a service to start. Intended for use by services
76 # to resolve dependency issues. It is assumed the caller
77 # has check to make sure this call is necessary
78 # $1 - filename of script, in /etc/rc.d, to run
84 info "${name} depends on ${_depend}, which will be forced to start."
85 if ! /etc/rc.d/${_depend} forcestart; then
86 warn "Unable to force ${_depend}. It may already be running."
94 # Test $1 variable, and warn if not set to YES or NO.
95 # Return 0 if it's "yes" (et al), nonzero otherwise.
100 debug "checkyesno: $1 is set to $_value."
103 # "yes", "true", "on", or "1"
104 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
108 # "no", "false", "off", or "0"
109 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
113 warn "\$${1} is not set properly - see rc.conf(5)."
121 # print the list in reverse order
127 _revlist="$_revfile $_revlist"
133 # If booting directly to multiuser or $always is enabled,
134 # send SIGTERM to the parent (/etc/rc) to abort the boot.
135 # Otherwise just exit.
142 # "yes", "true", "on", or "1"
143 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
150 if [ "$autoboot" = yes -o "$always" = true ]; then
151 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
158 # mount_critical_filesystems type
159 # Go through the list of critical filesystems as provided in
160 # the rc.conf(5) variable $critical_filesystems_${type}, checking
161 # each one to see if it is mounted, and if it is not, mounting it.
163 mount_critical_filesystems()
165 eval _fslist=\$critical_filesystems_${1}
166 for _fs in $_fslist; do
169 while read what _on on _type type; do
170 if [ $on = $_fs ]; then
177 mount $_fs >/dev/null 2>&1
184 # check_pidfile pidfile procname [interpreter]
185 # Parses the first line of pidfile for a PID, and ensures
186 # that the process is running and matches procname.
187 # Prints the matching PID upon success, nothing otherwise.
188 # interpreter is optional; see _find_processes() for details.
195 if [ -z "$_pidfile" -o -z "$_procname" ]; then
196 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
198 if [ ! -f $_pidfile ]; then
199 debug "pid file ($_pidfile): not readable."
202 read _pid _junk < $_pidfile
203 if [ -z "$_pid" ]; then
204 debug "pid file ($_pidfile): no pid in file."
207 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
211 # check_process procname [interpreter]
212 # Ensures that a process (or processes) named procname is running.
213 # Prints a list of matching PIDs.
214 # interpreter is optional; see _find_processes() for details.
220 if [ -z "$_procname" ]; then
221 err 3 'USAGE: check_process procname [interpreter]'
223 _find_processes $_procname ${_interpreter:-.} '-ax'
227 # _find_processes procname interpreter psargs
228 # Search for procname in the output of ps generated by psargs.
229 # Prints the PIDs of any matching processes, space separated.
231 # If interpreter == ".", check the following variations of procname
232 # against the first word of each command:
234 # `basename procname`
235 # `basename procname` + ":"
236 # "(" + `basename procname` + ")"
237 # "[" + `basename procname` + "]"
239 # If interpreter != ".", read the first line of procname, remove the
240 # leading #!, normalise whitespace, append procname, and attempt to
241 # match that against each command, either as is, or with extra words
242 # at the end. As an alternative, to deal with interpreted daemons
243 # using perl, the basename of the interpreter plus a colon is also
244 # tried as the prefix to procname.
248 if [ $# -ne 3 ]; then
249 err 3 'USAGE: _find_processes procname interpreter psargs'
256 if [ $_interpreter != "." ]; then # an interpreted script
257 _script=${_chroot}${_chroot:+"/"}$_procname
258 if [ -r $_script ]; then
259 read _interp < $_script # read interpreter name
262 _interp=${_interp#\#!} # strip #!
266 shift # drop env to get real name
269 if [ $_interpreter != $1 ]; then
270 warn "\$command_interpreter $_interpreter != $1"
274 warn "no shebang line in $_script"
279 warn "cannot read shebang line from $_script"
282 _interp="$* $_procname" # cleanup spaces, add _procname
285 _fp_match='case "$_argv" in
286 ${_interp}|"${_interp} "*|"${_interpbn}: ${_procname}"*)'
287 else # a normal daemon
288 _procnamebn=${_procname##*/}
289 _fp_args='_arg0 _argv'
290 _fp_match='case "$_arg0" in
291 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
295 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
296 while read _npid _jid '"$_fp_args"'; do
298 if [ "$JID" -eq "$_jid" ];
299 then echo -n "$_pref$_npid";
306 # debug "in _find_processes: proccheck is ($_proccheck)."
311 # wait_for_pids pid [pid ...]
312 # spins until none of the pids exist
316 local _list _prefix _nlist _j
319 if [ -z "$_list" ]; then
326 if kill -0 $_j 2>/dev/null; then
327 _nlist="${_nlist}${_nlist:+ }$_j"
328 [ -n "$_prefix" ] && sleep 1
331 if [ -z "$_nlist" ]; then
335 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
337 pwait $_list 2>/dev/null
339 if [ -n "$_prefix" ]; then
345 # get_pidfile_from_conf string file
347 # Takes a string to search for in the specified file.
348 # Ignores lines with traditional comment characters.
352 # if get_pidfile_from_conf string file; then
353 # pidfile="$_pidfile_from_conf"
355 # pidfile='appropriate default'
358 get_pidfile_from_conf()
360 if [ -z "$1" -o -z "$2" ]; then
361 err 3 "USAGE: get_pidfile_from_conf string file ($name)"
364 local string file line
366 string="$1" ; file="$2"
368 if [ ! -s "$file" ]; then
369 err 3 "get_pidfile_from_conf: $file does not exist ($name)"
374 *[#\;]*${string}*) continue ;;
375 *${string}*) break ;;
379 if [ -n "$line" ]; then
381 _pidfile_from_conf="/${line%%[\"\;]*}"
389 # If rc_quiet is set (usually as a result of using faststart at
390 # boot time) check if rc_startmsgs is enabled.
394 if [ -n "$rc_quiet" ]; then
395 checkyesno rc_startmsgs
402 # run_rc_command argument
403 # Search for argument in the list of supported commands, which is:
404 # "start stop restart rcvar status poll ${extra_commands}"
405 # If there's a match, run ${argument}_cmd or the default method
408 # If argument has a given prefix, then change the operation as follows:
411 # fast Skip the pid check, and set rc_fast=yes, rc_quiet=yes
412 # force Set ${rcvar} to YES, and set rc_force=yes
413 # one Set ${rcvar} to YES
414 # quiet Don't output some diagnostics, and set rc_quiet=yes
416 # The following globals are used:
418 # Name Needed Purpose
419 # ---- ------ -------
420 # name y Name of script.
422 # command n Full path to command.
423 # Not needed if ${rc_arg}_cmd is set for
426 # command_args n Optional args/shell directives for command.
428 # command_interpreter n If not empty, command is interpreted, so
429 # call check_{pidfile,process}() appropriately.
431 # desc n Description of script.
433 # extra_commands n List of extra commands supported.
435 # pidfile n If set, use check_pidfile $pidfile $command,
436 # otherwise use check_process $command.
437 # In either case, only check if $command is set.
439 # procname n Process name to check for instead of $command.
441 # rcvar n This is checked with checkyesno to determine
442 # if the action should be run.
444 # ${name}_program n Full path to command.
445 # Meant to be used in /etc/rc.conf to override
448 # ${name}_chroot n Directory to chroot to before running ${command}
449 # Requires /usr to be mounted.
451 # ${name}_chdir n Directory to cd to before running ${command}
452 # (if not using ${name}_chroot).
454 # ${name}_flags n Arguments to call ${command} with.
455 # NOTE: $flags from the parent environment
456 # can be used to override this.
458 # ${name}_nice n Nice level to run ${command} at.
460 # ${name}_user n User to run ${command} as, using su(1) if not
461 # using ${name}_chroot.
462 # Requires /usr to be mounted.
464 # ${name}_group n Group to run chrooted ${command} as.
465 # Requires /usr to be mounted.
467 # ${name}_groups n Comma separated list of supplementary groups
468 # to run the chrooted ${command} with.
469 # Requires /usr to be mounted.
471 # ${rc_arg}_cmd n If set, use this as the method when invoked;
472 # Otherwise, use default command (see below)
474 # ${rc_arg}_precmd n If set, run just before performing the
475 # ${rc_arg}_cmd method in the default
476 # operation (i.e, after checking for required
477 # bits and process (non)existence).
478 # If this completes with a non-zero exit code,
479 # don't run ${rc_arg}_cmd.
481 # ${rc_arg}_postcmd n If set, run just after performing the
482 # ${rc_arg}_cmd method, if that method
483 # returned a zero exit code.
485 # required_dirs n If set, check for the existence of the given
486 # directories before running a (re)start command.
488 # required_files n If set, check for the readability of the given
489 # files before running a (re)start command.
491 # required_modules n If set, ensure the given kernel modules are
492 # loaded before running a (re)start command.
493 # The check and possible loads are actually
494 # done after start_precmd so that the modules
495 # aren't loaded in vain, should the precmd
496 # return a non-zero status to indicate a error.
497 # If a word in the list looks like "foo:bar",
498 # "foo" is the KLD file name and "bar" is the
499 # module name. If a word looks like "foo~bar",
500 # "foo" is the KLD file name and "bar" is a
501 # egrep(1) pattern matching the module name.
502 # Otherwise the module name is assumed to be
503 # the same as the KLD file name, which is most
504 # common. See load_kld().
506 # required_vars n If set, perform checkyesno on each of the
507 # listed variables before running the default
510 # Default behaviour for a given argument, if no override method is
513 # Argument Default behaviour
514 # -------- -----------------
515 # start if !running && checkyesno ${rcvar}
519 # rc_pid=$(check_pidfile $pidfile $command)
521 # rc_pid=$(check_process $command)
522 # kill $sig_stop $rc_pid
523 # wait_for_pids $rc_pid
524 # ($sig_stop defaults to TERM.)
526 # reload Similar to stop, except use $sig_reload instead,
527 # and doesn't wait_for_pids.
528 # $sig_reload defaults to HUP.
529 # Note that `reload' isn't provided by default,
530 # it should be enabled via $extra_commands.
532 # restart Run `stop' then `start'.
534 # status Show if ${command} is running, etc.
536 # poll Wait for ${command} to exit.
538 # rcvar Display what rc.conf variable is used (if any).
540 # Variables available to methods, and after run_rc_command() has
545 # rc_arg Argument to command, after fast/force/one processing
548 # rc_flags Flags to start the default command with.
549 # Defaults to ${name}_flags, unless overridden
550 # by $flags from the environment.
551 # This variable may be changed by the precmd method.
553 # rc_pid PID of command (if appropriate)
555 # rc_fast Not empty if "fast" was provided (q.v.)
557 # rc_force Not empty if "force" was provided (q.v.)
559 # rc_quiet Not empty if "quiet" was provided
566 if [ -z "$name" ]; then
567 err 3 'run_rc_command: $name is not set.'
570 # Don't repeat the first argument when passing additional command-
571 # line arguments to the command subroutines.
578 fast*) # "fast" prefix; don't check pid
579 rc_arg=${rc_arg#fast}
583 force*) # "force" prefix; always run
586 rc_arg=${rc_arg#${_rc_prefix}}
587 if [ -n "${rcvar}" ]; then
591 one*) # "one" prefix; set ${rcvar}=yes
593 rc_arg=${rc_arg#${_rc_prefix}}
594 if [ -n "${rcvar}" ]; then
598 quiet*) # "quiet" prefix; omit some messages
600 rc_arg=${rc_arg#${_rc_prefix}}
605 eval _override_command=\$${name}_program
606 command=${_override_command:-$command}
608 _keywords="start stop restart rcvar $extra_commands"
611 _procname=${procname:-${command}}
613 # setup pid check command
614 if [ -n "$_procname" ]; then
615 if [ -n "$pidfile" ]; then
616 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
618 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
620 if [ -n "$_pidcmd" ]; then
621 _keywords="${_keywords} status poll"
625 if [ -z "$rc_arg" ]; then
629 if [ -n "$flags" ]; then # allow override from environment
632 eval rc_flags=\$${name}_flags
634 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
635 _nice=\$${name}_nice _user=\$${name}_user \
636 _group=\$${name}_group _groups=\$${name}_groups
638 if [ -n "$_user" ]; then # unset $_user if running as that user
639 if [ "$_user" = "$(eval $IDCMD)" ]; then
644 [ -z "$autoboot" ] && eval $_pidcmd # determine the pid if necessary
646 for _elem in $_keywords; do
647 if [ "$_elem" != "$rc_arg" ]; then
650 # if ${rcvar} is set, $1 is not "rcvar"
651 # and ${rc_pid} is not set, then run
652 # checkyesno ${rcvar}
653 # and return if that failed
655 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
656 [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
657 if ! checkyesno ${rcvar}; then
658 if [ -n "${rc_quiet}" ]; then
661 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
662 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
663 echo "instead of '${rc_arg}'."
668 # if there's a custom ${XXX_cmd},
669 # run that instead of the default
671 eval _cmd=\$${rc_arg}_cmd \
672 _precmd=\$${rc_arg}_precmd \
673 _postcmd=\$${rc_arg}_postcmd
675 if [ -n "$_cmd" ]; then
676 _run_rc_precmd || return 1
677 _run_rc_doit "$_cmd $rc_extra_args" || return 1
682 case "$rc_arg" in # default operations...
685 _run_rc_precmd || return 1
686 if [ -n "$rc_pid" ]; then
687 echo "${name} is running as pid $rc_pid."
689 echo "${name} is not running."
696 if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
697 echo 1>&2 "${name} already running? (pid=$rc_pid)."
701 if [ ! -x ${_chroot}${_chroot:+"/"}${command} ]; then
702 warn "run_rc_command: cannot run $command"
706 if ! _run_rc_precmd; then
707 warn "failed precmd routine for ${name}"
711 # setup the full command to run
713 check_startmsgs && echo "Starting ${name}."
714 if [ -n "$_chroot" ]; then
716 ${_nice:+nice -n $_nice }\
717 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
718 $_chroot $command $rc_flags $command_args"
721 ${_chdir:+cd $_chdir && }\
722 $command $rc_flags $command_args"
723 if [ -n "$_user" ]; then
724 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
726 if [ -n "$_nice" ]; then
727 if [ -z "$_user" ]; then
728 _doit="sh -c \"$_doit\""
730 _doit="nice -n $_nice $_doit"
734 # run the full command
736 if ! _run_rc_doit "$_doit"; then
737 warn "failed to start ${name}"
741 # finally, run postcmd
747 if [ -z "$rc_pid" ]; then
748 [ -n "$rc_fast" ] && return 0
753 _run_rc_precmd || return 1
755 # send the signal to stop
757 echo "Stopping ${name}."
758 _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
759 _run_rc_doit "$_doit" || return 1
761 # wait for the command to exit,
763 wait_for_pids $rc_pid
769 if [ -z "$rc_pid" ]; then
774 _run_rc_precmd || return 1
776 _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
777 _run_rc_doit "$_doit" || return 1
783 # prevent restart being called more
784 # than once by any given script
786 if ${_rc_restart_done:-false}; then
789 _rc_restart_done=true
791 _run_rc_precmd || return 1
793 # run those in a subshell to keep global variables
794 ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
795 ( run_rc_command ${_rc_prefix}start $rc_extra_args )
797 [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
803 _run_rc_precmd || return 1
804 if [ -n "$rc_pid" ]; then
805 wait_for_pids $rc_pid
812 if [ -n "$desc" ]; then
818 # Get unique vars in $rcvar
821 $_v\ *|\ *$_v|*\ $_v\ *) ;;
828 if [ -z "$_v" ]; then
832 eval _desc=\$${_v}_desc
833 eval _defval=\$${_v}_defval
836 eval echo \"$_v=\\\"\$$_v\\\"\"
837 # decode multiple lines of _desc
838 while [ -n "$_desc" ]; do
841 echo "# $_h ${_desc%%^^*}"
846 echo "# $_h ${_desc}"
851 echo "# (default: \"$_defval\")"
864 echo 1>&2 "$0: unknown directive '$rc_arg'."
870 # Helper functions for run_rc_command: common code.
871 # They use such global variables besides the exported rc_* ones:
881 check_required_before "$rc_arg" || return 1
883 if [ -n "$_precmd" ]; then
884 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
885 eval "$_precmd $rc_extra_args"
888 # If precmd failed and force isn't set, request exit.
889 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
894 check_required_after "$rc_arg" || return 1
901 if [ -n "$_postcmd" ]; then
902 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
903 eval "$_postcmd $rc_extra_args"
911 debug "run_rc_command: doit: $*"
915 # If command failed and force isn't set, request exit.
916 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
927 if [ -n "$pidfile" ]; then
928 _pidmsg=" (check $pidfile)."
932 echo 1>&2 "${name} not running?${_pidmsg}"
939 _cmd="kill -$1 $rc_pid"
940 if [ -n "$_user" ]; then
941 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
947 # run_rc_script file arg
948 # Start the script `file' with `arg', and correctly handle the
949 # return value from the script.
950 # If `file' ends with `.sh', it's sourced into the current environment
951 # when $rc_fast_and_loose is set, otherwise it is run as a child process.
952 # If `file' appears to be a backup or scratch file, ignore it.
953 # Otherwise if it is executable run as a child process.
959 if [ -z "$_file" -o -z "$_arg" ]; then
960 err 3 'USAGE: run_rc_script file arg'
963 unset name command command_args command_interpreter \
964 extra_commands pidfile procname \
965 rcvar rcvars_obsolete required_dirs required_files \
967 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
970 /etc/rc.d/*.sh) # no longer allowed in the base
971 warn "Ignoring old-style startup script $_file"
973 *[~#]|*.OLD|*.bak|*.orig|*,v) # scratch file; skip
974 warn "Ignoring scratch file $_file"
977 if [ -x $_file ]; then
978 if [ -n "$rc_fast_and_loose" ]; then
981 ( trap "echo Script $_file interrupted; kill -QUIT $$" 3
982 trap "echo Script $_file interrupted; exit 1" 2
983 trap "echo Script $_file running" 29
984 set $_arg; . $_file )
992 # load_rc_config name
993 # Source in the configuration file for a given name.
997 local _name _rcvar_val _var _defval _v _msg _new
999 if [ -z "$_name" ]; then
1000 err 3 'USAGE: load_rc_config name'
1003 if ${_rc_conf_loaded:-false}; then
1006 if [ -r /etc/defaults/rc.conf ]; then
1007 debug "Sourcing /etc/defaults/rc.conf"
1008 . /etc/defaults/rc.conf
1010 elif [ -r /etc/rc.conf ]; then
1011 debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1014 _rc_conf_loaded=true
1016 if [ -f /etc/rc.conf.d/"$_name" ]; then
1017 debug "Sourcing /etc/rc.conf.d/${_name}"
1018 . /etc/rc.conf.d/"$_name"
1021 # Set defaults if defined.
1022 for _var in $rcvar; do
1023 eval _defval=\$${_var}_defval
1024 if [ -n "$_defval" ]; then
1025 eval : \${$_var:=\$${_var}_defval}
1029 # check obsolete rc.conf variables
1030 for _var in $rcvars_obsolete; do
1032 eval _msg=\$${_var}_obsolete_msg
1033 eval _new=\$${_var}_newvar
1038 if [ -z "$_new" ]; then
1041 eval $_new=\"\$$_var\"
1042 if [ -z "$_msg" ]; then
1043 _msg="Use \$$_new instead."
1046 warn "\$$_var is obsolete. $_msg"
1053 # load_rc_config_var name var
1054 # Read the rc.conf(5) var for name and set in the
1055 # current shell, using load_rc_config in a subshell to prevent
1056 # unwanted side effects from other variable assignments.
1058 load_rc_config_var()
1060 if [ $# -ne 2 ]; then
1061 err 3 'USAGE: load_rc_config_var name var'
1064 load_rc_config '$1' >/dev/null;
1065 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1066 echo '$2'=\'\''${'$2'}\'\'';
1073 # Print a usage string for $0, with `commands' being a list of
1078 echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1082 echo -n 1>&2 "$_sep$_elem"
1090 # err exitval message
1091 # Display message to stderr and log to the syslog, and exit with exitval.
1098 if [ -x /usr/bin/logger ]; then
1099 logger "$0: ERROR: $*"
1101 echo 1>&2 "$0: ERROR: $*"
1107 # Display message to stderr and log to the syslog.
1111 if [ -x /usr/bin/logger ]; then
1112 logger "$0: WARNING: $*"
1114 echo 1>&2 "$0: WARNING: $*"
1119 # Display informational message to stdout and log to syslog.
1124 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1125 if [ -x /usr/bin/logger ]; then
1126 logger "$0: INFO: $*"
1135 # If debugging is enabled in rc.conf output message to stderr.
1136 # BEWARE that you don't call any subroutine that itself calls this
1142 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1143 if [ -x /usr/bin/logger ]; then
1144 logger "$0: DEBUG: $*"
1146 echo 1>&2 "$0: DEBUG: $*"
1152 # backup_file action file cur backup
1153 # Make a backup copy of `file' into `cur', and save the previous
1154 # version of `cur' as `backup' or use rcs for archiving.
1156 # This routine checks the value of the backup_uses_rcs variable,
1157 # which can be either YES or NO.
1159 # The `action' keyword can be one of the following:
1161 # add `file' is now being backed up (and is possibly
1162 # being reentered into the backups system). `cur'
1163 # is created and RCS files, if necessary, are
1166 # update `file' has changed and needs to be backed up.
1167 # If `cur' exists, it is copied to to `back' or
1168 # checked into RCS (if the repository file is old),
1169 # and then `file' is copied to `cur'. Another RCS
1170 # check in done here if RCS is being used.
1172 # remove `file' is no longer being tracked by the backups
1173 # system. If RCS is not being used, `cur' is moved
1174 # to `back', otherwise an empty file is checked in,
1175 # and then `cur' is removed.
1185 if checkyesno backup_uses_rcs; then
1186 _msg0="backup archive"
1189 # ensure that history file is not locked
1190 if [ -f $_cur,v ]; then
1191 rcs -q -u -U -M $_cur
1194 # ensure after switching to rcs that the
1195 # current backup is not lost
1196 if [ -f $_cur ]; then
1197 # no archive, or current newer than archive
1198 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1199 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1208 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1211 chown root:wheel $_cur $_cur,v
1215 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1217 chown root:wheel $_cur $_cur,v
1224 if [ -f $_cur ]; then
1228 chown root:wheel $_cur
1237 # make_symlink src link
1238 # Make a symbolic link 'link' to src from basedir. If the
1239 # directory in which link is to be created does not exist
1240 # a warning will be displayed and an error will be returned.
1241 # Returns 0 on success, 1 otherwise.
1245 local src link linkdir _me
1248 linkdir="`dirname $link`"
1249 _me="make_symlink()"
1251 if [ -z "$src" -o -z "$link" ]; then
1252 warn "$_me: requires two arguments."
1255 if [ ! -d "$linkdir" ]; then
1256 warn "$_me: the directory $linkdir does not exist."
1259 if ! ln -sf $src $link; then
1260 warn "$_me: unable to make a symbolic link from $link to $src"
1266 # devfs_rulesets_from_file file
1267 # Reads a set of devfs commands from file, and creates
1268 # the specified rulesets with their rules. Returns non-zero
1269 # if there was an error.
1271 devfs_rulesets_from_file()
1275 _me="devfs_rulesets_from_file"
1278 if [ -z "$file" ]; then
1279 warn "$_me: you must specify a file"
1282 if [ ! -e "$file" ]; then
1283 debug "$_me: no such file ($file)"
1286 debug "reading rulesets from file ($file)"
1294 rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1295 if [ -z "$rulenum" ]; then
1296 warn "$_me: cannot extract rule number ($line)"
1300 rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1301 if [ -z "$rulename" ]; then
1302 warn "$_me: cannot extract rule name ($line)"
1306 eval $rulename=\$rulenum
1307 debug "found ruleset: $rulename=$rulenum"
1308 if ! /sbin/devfs rule -s $rulenum delset; then
1314 rulecmd="${line%%"\#*"}"
1315 # evaluate the command incase it includes
1317 if [ -n "$rulecmd" ]; then
1318 debug "adding rule ($rulecmd)"
1319 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1327 if [ $_err -ne 0 ]; then
1328 debug "error in $_me"
1335 # devfs_init_rulesets
1336 # Initializes rulesets from configuration files. Returns
1337 # non-zero if there was an error.
1339 devfs_init_rulesets()
1342 _me="devfs_init_rulesets"
1344 # Go through this only once
1345 if [ -n "$devfs_rulesets_init" ]; then
1346 debug "$_me: devfs rulesets already initialized"
1349 for file in $devfs_rulesets; do
1350 if ! devfs_rulesets_from_file $file; then
1351 warn "$_me: could not read rules from $file"
1355 devfs_rulesets_init=1
1356 debug "$_me: devfs rulesets initialized"
1360 # devfs_set_ruleset ruleset [dir]
1361 # Sets the default ruleset of dir to ruleset. The ruleset argument
1362 # must be a ruleset name as specified in devfs.rules(5) file.
1363 # Returns non-zero if it could not set it successfully.
1368 [ -n "$1" ] && eval rs=\$$1 || rs=
1369 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1370 _me="devfs_set_ruleset"
1372 if [ -z "$rs" ]; then
1373 warn "$_me: you must specify a ruleset number"
1376 debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1377 if ! /sbin/devfs $devdir ruleset $rs; then
1378 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1384 # devfs_apply_ruleset ruleset [dir]
1385 # Apply ruleset number $ruleset to the devfs mountpoint $dir.
1386 # The ruleset argument must be a ruleset name as specified
1387 # in a devfs.rules(5) file. Returns 0 on success or non-zero
1388 # if it could not apply the ruleset.
1390 devfs_apply_ruleset()
1393 [ -n "$1" ] && eval rs=\$$1 || rs=
1394 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1395 _me="devfs_apply_ruleset"
1397 if [ -z "$rs" ]; then
1398 warn "$_me: you must specify a ruleset"
1401 debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1402 if ! /sbin/devfs $devdir rule -s $rs applyset; then
1403 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1409 # devfs_domount dir [ruleset]
1410 # Mount devfs on dir. If ruleset is specified it is set
1411 # on the mount-point. It must also be a ruleset name as specified
1412 # in a devfs.rules(5) file. Returns 0 on success.
1418 [ -n "$2" ] && rs=$2 || rs=
1419 _me="devfs_domount()"
1421 if [ -z "$devdir" ]; then
1422 warn "$_me: you must specify a mount-point"
1425 debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1426 if ! mount -t devfs dev "$devdir"; then
1427 warn "$_me: Unable to mount devfs on $devdir"
1430 if [ -n "$rs" ]; then
1432 devfs_set_ruleset $rs $devdir
1433 devfs -m $devdir rule applyset
1438 # devfs_mount_jail dir [ruleset]
1439 # Mounts a devfs file system appropriate for jails
1440 # on the directory dir. If ruleset is specified, the ruleset
1441 # it names will be used instead. If present, ruleset must
1442 # be the name of a ruleset as defined in a devfs.rules(5) file.
1443 # This function returns non-zero if an error occurs.
1449 [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1450 _me="devfs_mount_jail"
1453 if ! devfs_domount "$jdev" $rs; then
1454 warn "$_me: devfs was not mounted on $jdev"
1460 # Provide a function for normalizing the mounting of memory
1461 # filesystems. This should allow the rest of the code here to remain
1462 # as close as possible between 5-current and 4-stable.
1465 # $3 = (optional) extra mdmfs flags
1468 if [ -n "$3" ]; then
1471 /sbin/mdmfs $flags -s $1 md $2
1474 # Code common to scripts that need to load a kernel module
1475 # if it isn't in the kernel yet. Syntax:
1476 # load_kld [-e regex] [-m module] file
1477 # where -e or -m chooses the way to check if the module
1478 # is already loaded:
1479 # regex is egrep'd in the output from `kldstat -v',
1480 # module is passed to `kldstat -m'.
1481 # The default way is as though `-m file' were specified.
1484 local _loaded _mod _opt _re
1486 while getopts "e:m:" _opt; do
1489 m) _mod="$OPTARG" ;;
1490 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1493 shift $(($OPTIND - 1))
1494 if [ $# -ne 1 ]; then
1495 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1499 if [ -n "$_re" ]; then
1500 if kldstat -v | egrep -q -e "$_re"; then
1504 if kldstat -q -m "$_mod"; then
1509 if ! kldload "$1"; then
1510 warn "Unable to load kernel module $1"
1513 info "$1 kernel module loaded."
1516 debug "load_kld: $1 kernel module already loaded."
1522 # Change every $src in $str to $dst.
1523 # Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1527 local _str _src _dst _out _com
1534 for _com in ${_str}; do
1535 if [ -z "${_out}" ]; then
1538 _out="${_out}${_dst}${_com}"
1544 # Creates a list of providers for GELI encryption.
1547 local devices devices2
1548 local provider mountpoint type options rest
1550 # Create list of GELI providers from fstab.
1551 while read provider mountpoint type options rest ; do
1552 case ":${options}" in
1561 case ":${provider}" in
1566 # Skip swap devices.
1567 if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1570 devices="${devices} ${provider}"
1575 # Append providers from geli_devices.
1576 devices="${devices} ${geli_devices}"
1578 for provider in ${devices}; do
1579 provider=${provider%.eli}
1580 provider=${provider#/dev/}
1581 devices2="${devices2} ${provider}"
1587 # Find scripts in local_startup directories that use the old syntax
1589 find_local_scripts_old () {
1592 for dir in ${local_startup}; do
1593 if [ -d "${dir}" ]; then
1594 for file in ${dir}/[0-9]*.sh; do
1595 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1597 zlist="$zlist $file"
1599 for file in ${dir}/[!0-9]*.sh; do
1600 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1602 slist="$slist $file"
1608 find_local_scripts_new () {
1610 for dir in ${local_startup}; do
1611 if [ -d "${dir}" ]; then
1612 for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1615 *) if [ -x "$file" ]; then
1616 local_rc="${local_rc} ${file}"
1625 # check_required_{before|after} command
1626 # Check for things required by the command before and after its precmd,
1627 # respectively. The two separate functions are needed because some
1628 # conditions should prevent precmd from being run while other things
1629 # depend on precmd having already been run.
1631 check_required_before()
1637 for _f in $required_vars; do
1638 if ! checkyesno $_f; then
1639 warn "\$${_f} is not enabled."
1640 if [ -z "$rc_force" ]; then
1646 for _f in $required_dirs; do
1647 if [ ! -d "${_f}/." ]; then
1648 warn "${_f} is not a directory."
1649 if [ -z "$rc_force" ]; then
1655 for _f in $required_files; do
1656 if [ ! -r "${_f}" ]; then
1657 warn "${_f} is not readable."
1658 if [ -z "$rc_force" ]; then
1669 check_required_after()
1675 for _f in $required_modules; do
1677 *~*) _args="-e ${_f#*~} ${_f%%~*}" ;;
1678 *:*) _args="-m ${_f#*:} ${_f%%:*}" ;;
1681 if ! load_kld ${_args}; then
1682 if [ -z "$rc_force" ]; then
1693 # check_kern_features mib
1694 # Return existence of kern.features.* sysctl MIB as true or
1695 # false. The result will be cached in $_rc_cache_kern_features_
1696 # namespace. "0" means the kern.features.X exists.
1698 check_kern_features()
1702 [ -n "$1" ] || return 1;
1703 eval _v=\$_rc_cache_kern_features_$1
1704 [ -n "$_v" ] && return "$_v";
1706 if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1707 eval _rc_cache_kern_features_$1=0
1710 eval _rc_cache_kern_features_$1=1
1715 # _echoonce var msg mode
1716 # mode=0: Echo $msg if ${$var} is empty.
1717 # After doing echo, a string is set to ${$var}.
1719 # mode=1: Echo $msg if ${$var} is a string with non-zero length.
1723 local _var _msg _mode
1729 1) [ -n "$_var" ] && echo "$_msg" ;;
1730 *) [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1734 fi # [ -z "${_rc_subr_loaded}" ]