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 [var] [defval] [desc]
59 # Echo or define a rc.conf(5) variable name. Global variable
62 # If no argument is specified, echo "${name}_enable".
64 # If only a var is specified, echo "${var}_enable".
66 # If var and defval are specified, the ${var} is defined as
67 # rc.conf(5) variable and the default value is ${defvar}. An
68 # optional argument $desc can also be specified to add a
69 # description for that.
81 debug "rcvar_define: \$$1=$2 is added" \
82 " as a rc.conf(5) variable."
86 rcvars="${rcvars# } $_var"
87 eval ${_var}_defval=\"$2\"
89 # encode multiple lines of _desc
91 eval ${_var}_desc=\"\${${_var}_desc#^^}^^$l\"
93 eval ${_var}_desc=\"\${${_var}_desc#^^}\"
98 # set_rcvar_obsolete oldvar [newvar] [msg]
99 # Define obsolete variable.
100 # Global variable $rcvars_obsolete is used.
106 debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
108 rcvars_obsolete="${rcvars_obsolete# } $1"
109 eval ${1}_newvar=\"$2\"
111 eval ${_var}_obsolete_msg=\"$*\"
115 # force_depend script [rcvar]
116 # Force a service to start. Intended for use by services
117 # to resolve dependency issues.
118 # $1 - filename of script, in /etc/rc.d, to run
119 # $2 - name of the script's rcvar (minus the _enable)
123 local _depend _dep_rcvar
126 _dep_rcvar="${2:-$1}_enable"
128 [ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
129 checkyesno $_dep_rcvar && return 0
131 /etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
133 info "${name} depends on ${_depend}, which will be forced to start."
134 if ! /etc/rc.d/${_depend} forcestart; then
135 warn "Unable to force ${_depend}. It may already be running."
142 # Test $1 variable, and warn if not set to YES or NO.
143 # Return 0 if it's "yes" (et al), nonzero otherwise.
148 debug "checkyesno: $1 is set to $_value."
151 # "yes", "true", "on", or "1"
152 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
156 # "no", "false", "off", or "0"
157 [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
161 warn "\$${1} is not set properly - see rc.conf(5)."
169 # print the list in reverse order
175 _revlist="$_revfile $_revlist"
181 # If booting directly to multiuser or $always is enabled,
182 # send SIGTERM to the parent (/etc/rc) to abort the boot.
183 # Otherwise just exit.
190 # "yes", "true", "on", or "1"
191 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
198 if [ "$autoboot" = yes -o "$always" = true ]; then
199 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
206 # mount_critical_filesystems type
207 # Go through the list of critical filesystems as provided in
208 # the rc.conf(5) variable $critical_filesystems_${type}, checking
209 # each one to see if it is mounted, and if it is not, mounting it.
211 mount_critical_filesystems()
213 eval _fslist=\$critical_filesystems_${1}
214 for _fs in $_fslist; do
217 while read what _on on _type type; do
218 if [ $on = $_fs ]; then
225 mount $_fs >/dev/null 2>&1
232 # check_pidfile pidfile procname [interpreter]
233 # Parses the first line of pidfile for a PID, and ensures
234 # that the process is running and matches procname.
235 # Prints the matching PID upon success, nothing otherwise.
236 # interpreter is optional; see _find_processes() for details.
243 if [ -z "$_pidfile" -o -z "$_procname" ]; then
244 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
246 if [ ! -f $_pidfile ]; then
247 debug "pid file ($_pidfile): not readable."
250 read _pid _junk < $_pidfile
251 if [ -z "$_pid" ]; then
252 debug "pid file ($_pidfile): no pid in file."
255 _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
259 # check_process procname [interpreter]
260 # Ensures that a process (or processes) named procname is running.
261 # Prints a list of matching PIDs.
262 # interpreter is optional; see _find_processes() for details.
268 if [ -z "$_procname" ]; then
269 err 3 'USAGE: check_process procname [interpreter]'
271 _find_processes $_procname ${_interpreter:-.} '-ax'
275 # _find_processes procname interpreter psargs
276 # Search for procname in the output of ps generated by psargs.
277 # Prints the PIDs of any matching processes, space separated.
279 # If interpreter == ".", check the following variations of procname
280 # against the first word of each command:
282 # `basename procname`
283 # `basename procname` + ":"
284 # "(" + `basename procname` + ")"
285 # "[" + `basename procname` + "]"
287 # If interpreter != ".", read the first line of procname, remove the
288 # leading #!, normalise whitespace, append procname, and attempt to
289 # match that against each command, either as is, or with extra words
290 # at the end. As an alternative, to deal with interpreted daemons
291 # using perl, the basename of the interpreter plus a colon is also
292 # tried as the prefix to procname.
296 if [ $# -ne 3 ]; then
297 err 3 'USAGE: _find_processes procname interpreter psargs'
304 if [ $_interpreter != "." ]; then # an interpreted script
305 _script="${_chroot}${_chroot:+/}$_procname"
306 if [ -r "$_script" ]; then
307 read _interp < $_script # read interpreter name
310 _interp=${_interp#\#!} # strip #!
314 shift # drop env to get real name
317 if [ $_interpreter != $1 ]; then
318 warn "\$command_interpreter $_interpreter != $1"
322 warn "no shebang line in $_script"
327 warn "cannot read shebang line from $_script"
330 _interp="$* $_procname" # cleanup spaces, add _procname
333 _fp_match='case "$_argv" in
334 ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
335 else # a normal daemon
336 _procnamebn=${_procname##*/}
337 _fp_args='_arg0 _argv'
338 _fp_match='case "$_arg0" in
339 $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
343 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
344 while read _npid _jid '"$_fp_args"'; do
346 if [ "$JID" -eq "$_jid" ];
347 then echo -n "$_pref$_npid";
354 # debug "in _find_processes: proccheck is ($_proccheck)."
359 # wait_for_pids pid [pid ...]
360 # spins until none of the pids exist
364 local _list _prefix _nlist _j
367 if [ -z "$_list" ]; then
374 if kill -0 $_j 2>/dev/null; then
375 _nlist="${_nlist}${_nlist:+ }$_j"
376 [ -n "$_prefix" ] && sleep 1
379 if [ -z "$_nlist" ]; then
383 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
385 pwait $_list 2>/dev/null
387 if [ -n "$_prefix" ]; then
393 # get_pidfile_from_conf string file
395 # Takes a string to search for in the specified file.
396 # Ignores lines with traditional comment characters.
400 # if get_pidfile_from_conf string file; then
401 # pidfile="$_pidfile_from_conf"
403 # pidfile='appropriate default'
406 get_pidfile_from_conf()
408 if [ -z "$1" -o -z "$2" ]; then
409 err 3 "USAGE: get_pidfile_from_conf string file ($name)"
412 local string file line
414 string="$1" ; file="$2"
416 if [ ! -s "$file" ]; then
417 err 3 "get_pidfile_from_conf: $file does not exist ($name)"
422 *[#\;]*${string}*) continue ;;
423 *${string}*) break ;;
427 if [ -n "$line" ]; then
429 _pidfile_from_conf="/${line%%[\"\;]*}"
437 # If rc_quiet is set (usually as a result of using faststart at
438 # boot time) check if rc_startmsgs is enabled.
442 if [ -n "$rc_quiet" ]; then
443 checkyesno rc_startmsgs
450 # run_rc_command argument
451 # Search for argument in the list of supported commands, which is:
452 # "start stop restart rcvar status poll ${extra_commands}"
453 # If there's a match, run ${argument}_cmd or the default method
456 # If argument has a given prefix, then change the operation as follows:
459 # fast Skip the pid check, and set rc_fast=yes, rc_quiet=yes
460 # force Set ${rcvar} to YES, and set rc_force=yes
461 # one Set ${rcvar} to YES
462 # quiet Don't output some diagnostics, and set rc_quiet=yes
464 # The following globals are used:
466 # Name Needed Purpose
467 # ---- ------ -------
468 # name y Name of script.
470 # command n Full path to command.
471 # Not needed if ${rc_arg}_cmd is set for
474 # command_args n Optional args/shell directives for command.
476 # command_interpreter n If not empty, command is interpreted, so
477 # call check_{pidfile,process}() appropriately.
479 # desc n Description of script.
481 # extra_commands n List of extra commands supported.
483 # pidfile n If set, use check_pidfile $pidfile $command,
484 # otherwise use check_process $command.
485 # In either case, only check if $command is set.
487 # procname n Process name to check for instead of $command.
489 # rcvar n This is checked with checkyesno to determine
490 # if the action should be run.
492 # ${name}_program n Full path to command.
493 # Meant to be used in /etc/rc.conf to override
496 # ${name}_chroot n Directory to chroot to before running ${command}
497 # Requires /usr to be mounted.
499 # ${name}_chdir n Directory to cd to before running ${command}
500 # (if not using ${name}_chroot).
502 # ${name}_flags n Arguments to call ${command} with.
503 # NOTE: $flags from the parent environment
504 # can be used to override this.
506 # ${name}_fib n Routing table number to run ${command} with.
508 # ${name}_nice n Nice level to run ${command} at.
510 # ${name}_user n User to run ${command} as, using su(1) if not
511 # using ${name}_chroot.
512 # Requires /usr to be mounted.
514 # ${name}_group n Group to run chrooted ${command} as.
515 # Requires /usr to be mounted.
517 # ${name}_groups n Comma separated list of supplementary groups
518 # to run the chrooted ${command} with.
519 # Requires /usr to be mounted.
521 # ${rc_arg}_cmd n If set, use this as the method when invoked;
522 # Otherwise, use default command (see below)
524 # ${rc_arg}_precmd n If set, run just before performing the
525 # ${rc_arg}_cmd method in the default
526 # operation (i.e, after checking for required
527 # bits and process (non)existence).
528 # If this completes with a non-zero exit code,
529 # don't run ${rc_arg}_cmd.
531 # ${rc_arg}_postcmd n If set, run just after performing the
532 # ${rc_arg}_cmd method, if that method
533 # returned a zero exit code.
535 # required_dirs n If set, check for the existence of the given
536 # directories before running a (re)start command.
538 # required_files n If set, check for the readability of the given
539 # files before running a (re)start command.
541 # required_modules n If set, ensure the given kernel modules are
542 # loaded before running a (re)start command.
543 # The check and possible loads are actually
544 # done after start_precmd so that the modules
545 # aren't loaded in vain, should the precmd
546 # return a non-zero status to indicate a error.
547 # If a word in the list looks like "foo:bar",
548 # "foo" is the KLD file name and "bar" is the
549 # module name. If a word looks like "foo~bar",
550 # "foo" is the KLD file name and "bar" is a
551 # egrep(1) pattern matching the module name.
552 # Otherwise the module name is assumed to be
553 # the same as the KLD file name, which is most
554 # common. See load_kld().
556 # required_vars n If set, perform checkyesno on each of the
557 # listed variables before running the default
560 # Default behaviour for a given argument, if no override method is
563 # Argument Default behaviour
564 # -------- -----------------
565 # start if !running && checkyesno ${rcvar}
569 # rc_pid=$(check_pidfile $pidfile $command)
571 # rc_pid=$(check_process $command)
572 # kill $sig_stop $rc_pid
573 # wait_for_pids $rc_pid
574 # ($sig_stop defaults to TERM.)
576 # reload Similar to stop, except use $sig_reload instead,
577 # and doesn't wait_for_pids.
578 # $sig_reload defaults to HUP.
579 # Note that `reload' isn't provided by default,
580 # it should be enabled via $extra_commands.
582 # restart Run `stop' then `start'.
584 # status Show if ${command} is running, etc.
586 # poll Wait for ${command} to exit.
588 # rcvar Display what rc.conf variable is used (if any).
590 # Variables available to methods, and after run_rc_command() has
595 # rc_arg Argument to command, after fast/force/one processing
598 # rc_flags Flags to start the default command with.
599 # Defaults to ${name}_flags, unless overridden
600 # by $flags from the environment.
601 # This variable may be changed by the precmd method.
603 # rc_pid PID of command (if appropriate)
605 # rc_fast Not empty if "fast" was provided (q.v.)
607 # rc_force Not empty if "force" was provided (q.v.)
609 # rc_quiet Not empty if "quiet" was provided
616 if [ -z "$name" ]; then
617 err 3 'run_rc_command: $name is not set.'
620 # Don't repeat the first argument when passing additional command-
621 # line arguments to the command subroutines.
628 fast*) # "fast" prefix; don't check pid
629 rc_arg=${rc_arg#fast}
633 force*) # "force" prefix; always run
636 rc_arg=${rc_arg#${_rc_prefix}}
637 if [ -n "${rcvar}" ]; then
641 one*) # "one" prefix; set ${rcvar}=yes
643 rc_arg=${rc_arg#${_rc_prefix}}
644 if [ -n "${rcvar}" ]; then
648 quiet*) # "quiet" prefix; omit some messages
650 rc_arg=${rc_arg#${_rc_prefix}}
655 eval _override_command=\$${name}_program
656 command=${_override_command:-$command}
658 _keywords="start stop restart rcvar $extra_commands"
661 _procname=${procname:-${command}}
663 # setup pid check command
664 if [ -n "$_procname" ]; then
665 if [ -n "$pidfile" ]; then
666 _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
668 _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
670 if [ -n "$_pidcmd" ]; then
671 _keywords="${_keywords} status poll"
675 if [ -z "$rc_arg" ]; then
679 if [ -n "$flags" ]; then # allow override from environment
682 eval rc_flags=\$${name}_flags
684 eval _chdir=\$${name}_chdir _chroot=\$${name}_chroot \
685 _nice=\$${name}_nice _user=\$${name}_user \
686 _group=\$${name}_group _groups=\$${name}_groups \
689 if [ -n "$_user" ]; then # unset $_user if running as that user
690 if [ "$_user" = "$(eval $IDCMD)" ]; then
695 [ -z "$autoboot" ] && eval $_pidcmd # determine the pid if necessary
697 for _elem in $_keywords; do
698 if [ "$_elem" != "$rc_arg" ]; then
701 # if ${rcvar} is set, $1 is not "rcvar"
702 # and ${rc_pid} is not set, then run
703 # checkyesno ${rcvar}
704 # and return if that failed
706 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" ] ||
707 [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
708 if ! checkyesno ${rcvar}; then
709 if [ -n "${rc_quiet}" ]; then
712 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
713 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
714 echo "instead of '${rc_arg}'."
719 # if there's a custom ${XXX_cmd},
720 # run that instead of the default
722 eval _cmd=\$${rc_arg}_cmd \
723 _precmd=\$${rc_arg}_precmd \
724 _postcmd=\$${rc_arg}_postcmd
726 if [ -n "$_cmd" ]; then
727 _run_rc_precmd || return 1
728 _run_rc_doit "$_cmd $rc_extra_args" || return 1
733 case "$rc_arg" in # default operations...
736 _run_rc_precmd || return 1
737 if [ -n "$rc_pid" ]; then
738 echo "${name} is running as pid $rc_pid."
740 echo "${name} is not running."
747 if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
748 if [ -z "$rc_quiet" ]; then
749 echo 1>&2 "${name} already running? " \
755 if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
756 warn "run_rc_command: cannot run $command"
760 if ! _run_rc_precmd; then
761 warn "failed precmd routine for ${name}"
765 # setup the full command to run
767 check_startmsgs && echo "Starting ${name}."
768 if [ -n "$_chroot" ]; then
770 ${_nice:+nice -n $_nice }\
771 ${_fib:+setfib -F $_fib }\
772 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
773 $_chroot $command $rc_flags $command_args"
776 ${_chdir:+cd $_chdir && }\
777 ${_fib:+setfib -F $_fib }\
778 $command $rc_flags $command_args"
779 if [ -n "$_user" ]; then
780 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
782 if [ -n "$_nice" ]; then
783 if [ -z "$_user" ]; then
784 _doit="sh -c \"$_doit\""
786 _doit="nice -n $_nice $_doit"
790 # run the full command
792 if ! _run_rc_doit "$_doit"; then
793 warn "failed to start ${name}"
797 # finally, run postcmd
803 if [ -z "$rc_pid" ]; then
804 [ -n "$rc_fast" ] && return 0
809 _run_rc_precmd || return 1
811 # send the signal to stop
813 echo "Stopping ${name}."
814 _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
815 _run_rc_doit "$_doit" || return 1
817 # wait for the command to exit,
819 wait_for_pids $rc_pid
825 if [ -z "$rc_pid" ]; then
830 _run_rc_precmd || return 1
832 _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
833 _run_rc_doit "$_doit" || return 1
839 # prevent restart being called more
840 # than once by any given script
842 if ${_rc_restart_done:-false}; then
845 _rc_restart_done=true
847 _run_rc_precmd || return 1
849 # run those in a subshell to keep global variables
850 ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
851 ( run_rc_command ${_rc_prefix}start $rc_extra_args )
853 [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
859 _run_rc_precmd || return 1
860 if [ -n "$rc_pid" ]; then
861 wait_for_pids $rc_pid
868 if [ -n "$desc" ]; then
874 # Get unique vars in $rcvar $rcvars
875 for _v in $rcvar $rcvars; do
877 $_v\ *|\ *$_v|*\ $_v\ *) ;;
884 if [ -z "$_v" ]; then
888 eval _desc=\$${_v}_desc
889 eval _defval=\$${_v}_defval
892 eval echo \"$_v=\\\"\$$_v\\\"\"
893 # decode multiple lines of _desc
894 while [ -n "$_desc" ]; do
897 echo "# $_h ${_desc%%^^*}"
902 echo "# $_h ${_desc}"
907 echo "# (default: \"$_defval\")"
920 echo 1>&2 "$0: unknown directive '$rc_arg'."
926 # Helper functions for run_rc_command: common code.
927 # They use such global variables besides the exported rc_* ones:
937 check_required_before "$rc_arg" || return 1
939 if [ -n "$_precmd" ]; then
940 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
941 eval "$_precmd $rc_extra_args"
944 # If precmd failed and force isn't set, request exit.
945 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
950 check_required_after "$rc_arg" || return 1
957 if [ -n "$_postcmd" ]; then
958 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
959 eval "$_postcmd $rc_extra_args"
967 debug "run_rc_command: doit: $*"
971 # If command failed and force isn't set, request exit.
972 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
983 if [ -n "$pidfile" ]; then
984 _pidmsg=" (check $pidfile)."
988 echo 1>&2 "${name} not running?${_pidmsg}"
995 _cmd="kill -$1 $rc_pid"
996 if [ -n "$_user" ]; then
997 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1003 # run_rc_script file arg
1004 # Start the script `file' with `arg', and correctly handle the
1005 # return value from the script.
1006 # If `file' ends with `.sh', it's sourced into the current environment
1007 # when $rc_fast_and_loose is set, otherwise it is run as a child process.
1008 # If `file' appears to be a backup or scratch file, ignore it.
1009 # Otherwise if it is executable run as a child process.
1015 if [ -z "$_file" -o -z "$_arg" ]; then
1016 err 3 'USAGE: run_rc_script file arg'
1019 unset name command command_args command_interpreter \
1020 extra_commands pidfile procname \
1021 rcvar rcvars rcvars_obsolete required_dirs required_files \
1023 eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1026 /etc/rc.d/*.sh) # no longer allowed in the base
1027 warn "Ignoring old-style startup script $_file"
1029 *[~#]|*.OLD|*.bak|*.orig|*,v) # scratch file; skip
1030 warn "Ignoring scratch file $_file"
1032 *) # run in subshell
1033 if [ -x $_file ]; then
1034 if [ -n "$rc_fast_and_loose" ]; then
1037 ( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1038 trap "echo Script $_file interrupted >&2 ; exit 1" 2
1039 trap "echo Script $_file running >&2" 29
1040 set $_arg; . $_file )
1048 # load_rc_config name
1049 # Source in the configuration file for a given name.
1053 local _name _var _defval _v _msg _new
1055 if [ -z "$_name" ]; then
1056 err 3 'USAGE: load_rc_config name'
1059 if ${_rc_conf_loaded:-false}; then
1062 if [ -r /etc/defaults/rc.conf ]; then
1063 debug "Sourcing /etc/defaults/rc.conf"
1064 . /etc/defaults/rc.conf
1066 elif [ -r /etc/rc.conf ]; then
1067 debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1070 _rc_conf_loaded=true
1072 if [ -f /etc/rc.conf.d/"$_name" ]; then
1073 debug "Sourcing /etc/rc.conf.d/${_name}"
1074 . /etc/rc.conf.d/"$_name"
1077 # Set defaults if defined.
1078 for _var in $rcvar $rcvars; do
1079 eval _defval=\$${_var}_defval
1080 if [ -n "$_defval" ]; then
1081 eval : \${$_var:=\$${_var}_defval}
1085 # check obsolete rc.conf variables
1086 for _var in $rcvars_obsolete; do
1088 eval _msg=\$${_var}_obsolete_msg
1089 eval _new=\$${_var}_newvar
1094 if [ -z "$_new" ]; then
1097 eval $_new=\"\$$_var\"
1098 if [ -z "$_msg" ]; then
1099 _msg="Use \$$_new instead."
1102 warn "\$$_var is obsolete. $_msg"
1109 # load_rc_config_var name var
1110 # Read the rc.conf(5) var for name and set in the
1111 # current shell, using load_rc_config in a subshell to prevent
1112 # unwanted side effects from other variable assignments.
1114 load_rc_config_var()
1116 if [ $# -ne 2 ]; then
1117 err 3 'USAGE: load_rc_config_var name var'
1120 load_rc_config '$1' >/dev/null;
1121 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1122 echo '$2'=\'\''${'$2'}\'\'';
1129 # Print a usage string for $0, with `commands' being a list of
1134 echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1138 echo -n 1>&2 "$_sep$_elem"
1146 # err exitval message
1147 # Display message to stderr and log to the syslog, and exit with exitval.
1154 if [ -x /usr/bin/logger ]; then
1155 logger "$0: ERROR: $*"
1157 echo 1>&2 "$0: ERROR: $*"
1163 # Display message to stderr and log to the syslog.
1167 if [ -x /usr/bin/logger ]; then
1168 logger "$0: WARNING: $*"
1170 echo 1>&2 "$0: WARNING: $*"
1175 # Display informational message to stdout and log to syslog.
1180 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1181 if [ -x /usr/bin/logger ]; then
1182 logger "$0: INFO: $*"
1191 # If debugging is enabled in rc.conf output message to stderr.
1192 # BEWARE that you don't call any subroutine that itself calls this
1198 [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1199 if [ -x /usr/bin/logger ]; then
1200 logger "$0: DEBUG: $*"
1202 echo 1>&2 "$0: DEBUG: $*"
1208 # backup_file action file cur backup
1209 # Make a backup copy of `file' into `cur', and save the previous
1210 # version of `cur' as `backup' or use rcs for archiving.
1212 # This routine checks the value of the backup_uses_rcs variable,
1213 # which can be either YES or NO.
1215 # The `action' keyword can be one of the following:
1217 # add `file' is now being backed up (and is possibly
1218 # being reentered into the backups system). `cur'
1219 # is created and RCS files, if necessary, are
1222 # update `file' has changed and needs to be backed up.
1223 # If `cur' exists, it is copied to to `back' or
1224 # checked into RCS (if the repository file is old),
1225 # and then `file' is copied to `cur'. Another RCS
1226 # check in done here if RCS is being used.
1228 # remove `file' is no longer being tracked by the backups
1229 # system. If RCS is not being used, `cur' is moved
1230 # to `back', otherwise an empty file is checked in,
1231 # and then `cur' is removed.
1241 if checkyesno backup_uses_rcs; then
1242 _msg0="backup archive"
1245 # ensure that history file is not locked
1246 if [ -f $_cur,v ]; then
1247 rcs -q -u -U -M $_cur
1250 # ensure after switching to rcs that the
1251 # current backup is not lost
1252 if [ -f $_cur ]; then
1253 # no archive, or current newer than archive
1254 if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1255 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1264 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1267 chown root:wheel $_cur $_cur,v
1271 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1273 chown root:wheel $_cur $_cur,v
1280 if [ -f $_cur ]; then
1284 chown root:wheel $_cur
1293 # make_symlink src link
1294 # Make a symbolic link 'link' to src from basedir. If the
1295 # directory in which link is to be created does not exist
1296 # a warning will be displayed and an error will be returned.
1297 # Returns 0 on sucess, 1 otherwise.
1301 local src link linkdir _me
1304 linkdir="`dirname $link`"
1305 _me="make_symlink()"
1307 if [ -z "$src" -o -z "$link" ]; then
1308 warn "$_me: requires two arguments."
1311 if [ ! -d "$linkdir" ]; then
1312 warn "$_me: the directory $linkdir does not exist."
1315 if ! ln -sf $src $link; then
1316 warn "$_me: unable to make a symbolic link from $link to $src"
1322 # devfs_rulesets_from_file file
1323 # Reads a set of devfs commands from file, and creates
1324 # the specified rulesets with their rules. Returns non-zero
1325 # if there was an error.
1327 devfs_rulesets_from_file()
1329 local file _err _me _opts
1331 _me="devfs_rulesets_from_file"
1334 if [ -z "$file" ]; then
1335 warn "$_me: you must specify a file"
1338 if [ ! -e "$file" ]; then
1339 debug "$_me: no such file ($file)"
1343 # Disable globbing so that the rule patterns are not expanded
1344 # by accident with matching filesystem entries.
1347 debug "reading rulesets from file ($file)"
1355 rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1356 if [ -z "$rulenum" ]; then
1357 warn "$_me: cannot extract rule number ($line)"
1361 rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1362 if [ -z "$rulename" ]; then
1363 warn "$_me: cannot extract rule name ($line)"
1367 eval $rulename=\$rulenum
1368 debug "found ruleset: $rulename=$rulenum"
1369 if ! /sbin/devfs rule -s $rulenum delset; then
1375 rulecmd="${line%%"\#*"}"
1376 # evaluate the command incase it includes
1378 if [ -n "$rulecmd" ]; then
1379 debug "adding rule ($rulecmd)"
1380 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1388 if [ $_err -ne 0 ]; then
1389 debug "error in $_me"
1393 case $_opts in *f*) ;; *) set +f ;; esac
1397 # devfs_init_rulesets
1398 # Initializes rulesets from configuration files. Returns
1399 # non-zero if there was an error.
1401 devfs_init_rulesets()
1404 _me="devfs_init_rulesets"
1406 # Go through this only once
1407 if [ -n "$devfs_rulesets_init" ]; then
1408 debug "$_me: devfs rulesets already initialized"
1411 for file in $devfs_rulesets; do
1412 if ! devfs_rulesets_from_file $file; then
1413 warn "$_me: could not read rules from $file"
1417 devfs_rulesets_init=1
1418 debug "$_me: devfs rulesets initialized"
1422 # devfs_set_ruleset ruleset [dir]
1423 # Sets the default ruleset of dir to ruleset. The ruleset argument
1424 # must be a ruleset name as specified in devfs.rules(5) file.
1425 # Returns non-zero if it could not set it successfully.
1430 [ -n "$1" ] && eval rs=\$$1 || rs=
1431 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1432 _me="devfs_set_ruleset"
1434 if [ -z "$rs" ]; then
1435 warn "$_me: you must specify a ruleset number"
1438 debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1439 if ! /sbin/devfs $devdir ruleset $rs; then
1440 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1446 # devfs_apply_ruleset ruleset [dir]
1447 # Apply ruleset number $ruleset to the devfs mountpoint $dir.
1448 # The ruleset argument must be a ruleset name as specified
1449 # in a devfs.rules(5) file. Returns 0 on success or non-zero
1450 # if it could not apply the ruleset.
1452 devfs_apply_ruleset()
1455 [ -n "$1" ] && eval rs=\$$1 || rs=
1456 [ -n "$2" ] && devdir="-m "$2"" || devdir=
1457 _me="devfs_apply_ruleset"
1459 if [ -z "$rs" ]; then
1460 warn "$_me: you must specify a ruleset"
1463 debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1464 if ! /sbin/devfs $devdir rule -s $rs applyset; then
1465 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1471 # devfs_domount dir [ruleset]
1472 # Mount devfs on dir. If ruleset is specified it is set
1473 # on the mount-point. It must also be a ruleset name as specified
1474 # in a devfs.rules(5) file. Returns 0 on success.
1480 [ -n "$2" ] && rs=$2 || rs=
1481 _me="devfs_domount()"
1483 if [ -z "$devdir" ]; then
1484 warn "$_me: you must specify a mount-point"
1487 debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1488 if ! mount -t devfs dev "$devdir"; then
1489 warn "$_me: Unable to mount devfs on $devdir"
1492 if [ -n "$rs" ]; then
1494 devfs_set_ruleset $rs $devdir
1495 devfs -m $devdir rule applyset
1500 # devfs_mount_jail dir [ruleset]
1501 # Mounts a devfs file system appropriate for jails
1502 # on the directory dir. If ruleset is specified, the ruleset
1503 # it names will be used instead. If present, ruleset must
1504 # be the name of a ruleset as defined in a devfs.rules(5) file.
1505 # This function returns non-zero if an error occurs.
1511 [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1512 _me="devfs_mount_jail"
1515 if ! devfs_domount "$jdev" $rs; then
1516 warn "$_me: devfs was not mounted on $jdev"
1522 # Provide a function for normalizing the mounting of memory
1523 # filesystems. This should allow the rest of the code here to remain
1524 # as close as possible between 5-current and 4-stable.
1527 # $3 = (optional) extra mdmfs flags
1530 if [ -n "$3" ]; then
1533 /sbin/mdmfs $flags -s $1 md $2
1536 # Code common to scripts that need to load a kernel module
1537 # if it isn't in the kernel yet. Syntax:
1538 # load_kld [-e regex] [-m module] file
1539 # where -e or -m chooses the way to check if the module
1540 # is already loaded:
1541 # regex is egrep'd in the output from `kldstat -v',
1542 # module is passed to `kldstat -m'.
1543 # The default way is as though `-m file' were specified.
1546 local _loaded _mod _opt _re
1548 while getopts "e:m:" _opt; do
1551 m) _mod="$OPTARG" ;;
1552 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1555 shift $(($OPTIND - 1))
1556 if [ $# -ne 1 ]; then
1557 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1561 if [ -n "$_re" ]; then
1562 if kldstat -v | egrep -q -e "$_re"; then
1566 if kldstat -q -m "$_mod"; then
1571 if ! kldload "$1"; then
1572 warn "Unable to load kernel module $1"
1575 info "$1 kernel module loaded."
1578 debug "load_kld: $1 kernel module already loaded."
1584 # Change every $src in $str to $dst.
1585 # Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1589 local _str _src _dst _out _com
1596 for _com in ${_str}; do
1597 if [ -z "${_out}" ]; then
1600 _out="${_out}${_dst}${_com}"
1606 # Creates a list of providers for GELI encryption.
1609 local devices devices2
1610 local provider mountpoint type options rest
1612 # Create list of GELI providers from fstab.
1613 while read provider mountpoint type options rest ; do
1614 case ":${options}" in
1623 case ":${provider}" in
1628 # Skip swap devices.
1629 if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1632 devices="${devices} ${provider}"
1637 # Append providers from geli_devices.
1638 devices="${devices} ${geli_devices}"
1640 for provider in ${devices}; do
1641 provider=${provider%.eli}
1642 provider=${provider#/dev/}
1643 devices2="${devices2} ${provider}"
1649 # Find scripts in local_startup directories that use the old syntax
1651 find_local_scripts_old () {
1654 for dir in ${local_startup}; do
1655 if [ -d "${dir}" ]; then
1656 for file in ${dir}/[0-9]*.sh; do
1657 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1659 zlist="$zlist $file"
1661 for file in ${dir}/[^0-9]*.sh; do
1662 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1664 slist="$slist $file"
1670 find_local_scripts_new () {
1672 for dir in ${local_startup}; do
1673 if [ -d "${dir}" ]; then
1674 for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1677 *) if [ -x "$file" ]; then
1678 local_rc="${local_rc} ${file}"
1687 # check_required_{before|after} command
1688 # Check for things required by the command before and after its precmd,
1689 # respectively. The two separate functions are needed because some
1690 # conditions should prevent precmd from being run while other things
1691 # depend on precmd having already been run.
1693 check_required_before()
1699 for _f in $required_vars; do
1700 if ! checkyesno $_f; then
1701 warn "\$${_f} is not enabled."
1702 if [ -z "$rc_force" ]; then
1708 for _f in $required_dirs; do
1709 if [ ! -d "${_f}/." ]; then
1710 warn "${_f} is not a directory."
1711 if [ -z "$rc_force" ]; then
1717 for _f in $required_files; do
1718 if [ ! -r "${_f}" ]; then
1719 warn "${_f} is not readable."
1720 if [ -z "$rc_force" ]; then
1731 check_required_after()
1737 for _f in $required_modules; do
1739 *~*) _args="-e ${_f#*~} ${_f%%~*}" ;;
1740 *:*) _args="-m ${_f#*:} ${_f%%:*}" ;;
1743 if ! load_kld ${_args}; then
1744 if [ -z "$rc_force" ]; then
1755 # check_kern_features mib
1756 # Return existence of kern.features.* sysctl MIB as true or
1757 # false. The result will be cached in $_rc_cache_kern_features_
1758 # namespace. "0" means the kern.features.X exists.
1760 check_kern_features()
1764 [ -n "$1" ] || return 1;
1765 eval _v=\$_rc_cache_kern_features_$1
1766 [ -n "$_v" ] && return "$_v";
1768 if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1769 eval _rc_cache_kern_features_$1=0
1772 eval _rc_cache_kern_features_$1=1
1777 # check_namevarlist var
1778 # Return "0" if ${name}_var is reserved in rc.subr.
1780 _rc_namevarlist="program chroot chdir flags fib nice user group groups"
1785 for _v in $_rc_namevarlist; do
1794 # _echoonce var msg mode
1795 # mode=0: Echo $msg if ${$var} is empty.
1796 # After doing echo, a string is set to ${$var}.
1798 # mode=1: Echo $msg if ${$var} is a string with non-zero length.
1802 local _var _msg _mode
1808 1) [ -n "$_var" ] && echo "$_msg" ;;
1809 *) [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1813 fi # [ -z "${_rc_subr_loaded}" ]