]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - etc/rc.subr
Merge branch 'releng/11.3' into releng-CDN/11.3
[FreeBSD/FreeBSD.git] / etc / rc.subr
1 # $NetBSD: rc.subr,v 1.67 2006/10/07 11:25:15 elad Exp $
2 # $FreeBSD$
3 #
4 # Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
5 # All rights reserved.
6 #
7 # This code is derived from software contributed to The NetBSD Foundation
8 # by Luke Mewburn.
9 #
10 # Redistribution and use in source and binary forms, with or without
11 # modification, are permitted provided that the following conditions
12 # are met:
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.
18 #
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.
30 #
31 # rc.subr
32 #       functions used by various rc scripts
33 #
34
35 : ${RC_PID:=$$}; export RC_PID
36
37 #
38 #       Operating System dependent/independent variables
39 #
40
41 if [ -n "${_rc_subr_loaded}" ]; then
42         return
43 fi
44
45 _rc_subr_loaded="YES"
46
47 SYSCTL="/sbin/sysctl"
48 SYSCTL_N="${SYSCTL} -n"
49 SYSCTL_W="${SYSCTL}"
50 PROTECT="/usr/bin/protect"
51 ID="/usr/bin/id"
52 IDCMD="if [ -x $ID ]; then $ID -un; fi"
53 PS="/bin/ps -ww"
54 JID=0
55 # rc_service provides the path to the service script that we are executing.
56 # This is not being set here in an execution context, necessarily, so it's
57 # really just a reasonable guess, and it will get overwritten later if
58 # we are executing from some other means than direct execution by service(8)
59 # or manual invocation of the service script.  The prime example of this is
60 # during system startup, all rc scripts will be invoked via /etc/rc, so
61 # run_rc_script will overwrite rc_service with the file being sourced.
62 rc_service="$0"
63
64 #
65 #       functions
66 #       ---------
67
68 # list_vars pattern
69 #       List vars matching pattern.
70
71 list_vars()
72 {
73         set | { while read LINE; do
74                 var="${LINE%%=*}"
75                 case "$var" in
76                 "$LINE"|*[!a-zA-Z0-9_]*) continue ;;
77                 $1) echo $var
78                 esac
79         done; }
80 }
81
82 # set_rcvar [var] [defval] [desc]
83 #
84 #       Echo or define a rc.conf(5) variable name.  Global variable
85 #       $rcvars is used.
86 #
87 #       If no argument is specified, echo "${name}_enable".
88 #
89 #       If only a var is specified, echo "${var}_enable".
90 #
91 #       If var and defval are specified, the ${var} is defined as
92 #       rc.conf(5) variable and the default value is ${defvar}.  An
93 #       optional argument $desc can also be specified to add a
94 #       description for that.
95 #
96 set_rcvar()
97 {
98         local _var
99
100         case $# in
101         0)      echo ${name}_enable ;;
102         1)      echo ${1}_enable ;;
103         *)
104                 debug "set_rcvar: \$$1=$2 is added" \
105                     " as a rc.conf(5) variable."
106                 _var=$1
107                 rcvars="${rcvars# } $_var"
108                 eval ${_var}_defval=\"$2\"
109                 shift 2
110                 eval ${_var}_desc=\"$*\"
111         ;;
112         esac
113 }
114
115 # set_rcvar_obsolete oldvar [newvar] [msg]
116 #       Define obsolete variable.
117 #       Global variable $rcvars_obsolete is used.
118 #
119 set_rcvar_obsolete()
120 {
121         local _var
122         _var=$1
123         debug "set_rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
124
125         rcvars_obsolete="${rcvars_obsolete# } $1"
126         eval ${1}_newvar=\"$2\"
127         shift 2
128         eval ${_var}_obsolete_msg=\"$*\"
129 }
130
131 #
132 # force_depend script [rcvar]
133 #       Force a service to start. Intended for use by services
134 #       to resolve dependency issues.
135 #       $1 - filename of script, in /etc/rc.d, to run
136 #       $2 - name of the script's rcvar (minus the _enable)
137 #
138 force_depend()
139 {
140         local _depend _dep_rcvar
141
142         _depend="$1"
143         _dep_rcvar="${2:-$1}_enable"
144
145         [ -n "$rc_fast" ] && ! checkyesno always_force_depends &&
146             checkyesno $_dep_rcvar && return 0
147
148         /etc/rc.d/${_depend} forcestatus >/dev/null 2>&1 && return 0
149
150         info "${name} depends on ${_depend}, which will be forced to start."
151         if ! /etc/rc.d/${_depend} forcestart; then
152                 warn "Unable to force ${_depend}. It may already be running."
153                 return 1
154         fi
155 }
156
157 #
158 # checkyesno var
159 #       Test $1 variable, and warn if not set to YES or NO.
160 #       Return 0 if it's "yes" (et al), nonzero otherwise.
161 #
162 checkyesno()
163 {
164         eval _value=\$${1}
165         debug "checkyesno: $1 is set to $_value."
166         case $_value in
167
168                 #       "yes", "true", "on", or "1"
169         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
170                 return 0
171                 ;;
172
173                 #       "no", "false", "off", or "0"
174         [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
175                 return 1
176                 ;;
177         *)
178                 warn "\$${1} is not set properly - see rc.conf(5)."
179                 return 1
180                 ;;
181         esac
182 }
183
184 #
185 # reverse_list list
186 #       print the list in reverse order
187 #
188 reverse_list()
189 {
190         _revlist=
191         for _revfile; do
192                 _revlist="$_revfile $_revlist"
193         done
194         echo $_revlist
195 }
196
197 # stop_boot always
198 #       If booting directly to multiuser or $always is enabled,
199 #       send SIGTERM to the parent (/etc/rc) to abort the boot.
200 #       Otherwise just exit.
201 #
202 stop_boot()
203 {
204         local always
205
206         case $1 in
207                 #       "yes", "true", "on", or "1"
208         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
209                 always=true
210                 ;;
211         *)
212                 always=false
213                 ;;
214         esac
215         if [ "$autoboot" = yes -o "$always" = true ]; then
216                 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
217                 kill -TERM ${RC_PID}
218         fi
219         exit 1
220 }
221
222 #
223 # mount_critical_filesystems type
224 #       Go through the list of critical filesystems as provided in
225 #       the rc.conf(5) variable $critical_filesystems_${type}, checking
226 #       each one to see if it is mounted, and if it is not, mounting it.
227 #
228 mount_critical_filesystems()
229 {
230         eval _fslist=\$critical_filesystems_${1}
231         for _fs in $_fslist; do
232                 mount | (
233                         _ismounted=false
234                         while read what _on on _type type; do
235                                 if [ $on = $_fs ]; then
236                                         _ismounted=true
237                                 fi
238                         done
239                         if $_ismounted; then
240                                 :
241                         else
242                                 mount $_fs >/dev/null 2>&1
243                         fi
244                 )
245         done
246 }
247
248 #
249 # check_pidfile pidfile procname [interpreter]
250 #       Parses the first line of pidfile for a PID, and ensures
251 #       that the process is running and matches procname.
252 #       Prints the matching PID upon success, nothing otherwise.
253 #       interpreter is optional; see _find_processes() for details.
254 #
255 check_pidfile()
256 {
257         _pidfile=$1
258         _procname=$2
259         _interpreter=$3
260         if [ -z "$_pidfile" -o -z "$_procname" ]; then
261                 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
262         fi
263         if [ ! -f $_pidfile ]; then
264                 debug "pid file ($_pidfile): not readable."
265                 return
266         fi
267         read _pid _junk < $_pidfile
268         if [ -z "$_pid" ]; then
269                 debug "pid file ($_pidfile): no pid in file."
270                 return
271         fi
272         _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
273 }
274
275 #
276 # check_process procname [interpreter]
277 #       Ensures that a process (or processes) named procname is running.
278 #       Prints a list of matching PIDs.
279 #       interpreter is optional; see _find_processes() for details.
280 #
281 check_process()
282 {
283         _procname=$1
284         _interpreter=$2
285         if [ -z "$_procname" ]; then
286                 err 3 'USAGE: check_process procname [interpreter]'
287         fi
288         _find_processes $_procname ${_interpreter:-.} '-ax'
289 }
290
291 #
292 # _find_processes procname interpreter psargs
293 #       Search for procname in the output of ps generated by psargs.
294 #       Prints the PIDs of any matching processes, space separated.
295 #
296 #       If interpreter == ".", check the following variations of procname
297 #       against the first word of each command:
298 #               procname
299 #               `basename procname`
300 #               `basename procname` + ":"
301 #               "(" + `basename procname` + ")"
302 #               "[" + `basename procname` + "]"
303 #
304 #       If interpreter != ".", read the first line of procname, remove the
305 #       leading #!, normalise whitespace, append procname, and attempt to
306 #       match that against each command, either as is, or with extra words
307 #       at the end.  As an alternative, to deal with interpreted daemons
308 #       using perl, the basename of the interpreter plus a colon is also
309 #       tried as the prefix to procname.
310 #
311 _find_processes()
312 {
313         if [ $# -ne 3 ]; then
314                 err 3 'USAGE: _find_processes procname interpreter psargs'
315         fi
316         _procname=$1
317         _interpreter=$2
318         _psargs=$3
319
320         _pref=
321         if [ $_interpreter != "." ]; then       # an interpreted script
322                 _script="${_chroot}${_chroot:+/}$_procname"
323                 if [ -r "$_script" ]; then
324                         read _interp < $_script # read interpreter name
325                         case "$_interp" in
326                         \#!*)
327                                 _interp=${_interp#\#!}  # strip #!
328                                 set -- $_interp
329                                 case $1 in
330                                 */bin/env)
331                                         shift   # drop env to get real name
332                                         ;;
333                                 esac
334                                 if [ $_interpreter != $1 ]; then
335                                         warn "\$command_interpreter $_interpreter != $1"
336                                 fi
337                                 ;;
338                         *)
339                                 warn "no shebang line in $_script"
340                                 set -- $_interpreter
341                                 ;;
342                         esac
343                 else
344                         warn "cannot read shebang line from $_script"
345                         set -- $_interpreter
346                 fi
347                 _interp="$* $_procname"         # cleanup spaces, add _procname
348                 _interpbn=${1##*/}
349                 _fp_args='_argv'
350                 _fp_match='case "$_argv" in
351                     ${_interp}|"${_interp} "*|"[${_interpbn}]"|"${_interpbn}: ${_procname}"*)'
352         else                                    # a normal daemon
353                 _procnamebn=${_procname##*/}
354                 _fp_args='_arg0 _argv'
355                 _fp_match='case "$_arg0" in
356                     $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
357         fi
358
359         _proccheck="\
360                 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
361                 while read _npid _jid '"$_fp_args"'; do
362                         '"$_fp_match"'
363                                 if [ "$JID" -eq "$_jid" ];
364                                 then echo -n "$_pref$_npid";
365                                 _pref=" ";
366                                 fi
367                                 ;;
368                         esac
369                 done'
370
371 #       debug "in _find_processes: proccheck is ($_proccheck)."
372         eval $_proccheck
373 }
374
375 # sort_lite [-b] [-n] [-k POS] [-t SEP]
376 #       A lite version of sort(1) (supporting a few options) that can be used
377 #       before the real sort(1) is available (e.g., in scripts that run prior
378 #       to mountcritremote). Requires only shell built-in functionality.
379 #
380 sort_lite()
381 {
382         local funcname=sort_lite
383         local sort_sep="$IFS" sort_ignore_leading_space=
384         local sort_field=0 sort_strict_fields= sort_numeric=
385         local nitems=0 skip_leading=0 trim=
386
387         local OPTIND flag
388         while getopts bnk:t: flag; do
389                 case "$flag" in
390                 b) sort_ignore_leading_space=1 ;;
391                 n) sort_numeric=1 sort_ignore_leading_space=1 ;;
392                 k) sort_field="${OPTARG%%,*}" ;; # only up to first comma
393                         # NB: Unlike sort(1) only one POS allowed
394                 t) sort_sep="$OPTARG"
395                    if [ ${#sort_sep} -gt 1 ]; then
396                         echo "$funcname: multi-character tab \`$sort_sep'" >&2
397                         return 1
398                    fi
399                    sort_strict_fields=1
400                    ;;
401                 \?) return 1 ;;
402                 esac
403         done
404         shift $(( $OPTIND - 1 ))
405
406         # Create transformation pattern to trim leading text if desired
407         case "$sort_field" in
408         ""|[!0-9]*|*[!0-9.]*)
409                 echo "$funcname: invalid sort field \`$sort_field'" >&2
410                 return 1
411                 ;;
412         *.*)
413                 skip_leading=${sort_field#*.} sort_field=${sort_field%%.*}
414                 while [ ${skip_leading:-0} -gt 1 ] 2> /dev/null; do
415                         trim="$trim?" skip_leading=$(( $skip_leading - 1 ))
416                 done
417         esac
418
419         # Copy input to series of local numbered variables
420         # NB: IFS of NULL preserves leading whitespace
421         local LINE
422         while IFS= read -r LINE || [ "$LINE" ]; do
423                 nitems=$(( $nitems + 1 ))
424                 local src_$nitems="$LINE"
425         done
426
427         #
428         # Sort numbered locals using insertion sort
429         #
430         local curitem curitem_orig curitem_mod curitem_haskey
431         local dest dest_orig dest_mod dest_haskey
432         local d gt n
433         local i=1 
434         while [ $i -le $nitems ]; do
435                 curitem_haskey=1 # Assume sort field (-k POS) exists
436                 eval curitem=\"\$src_$i\"
437                 curitem_mod="$curitem" # for modified comparison
438                 curitem_orig="$curitem" # for original comparison
439
440                 # Trim leading whitespace if desired
441                 if [ "$sort_ignore_leading_space" ]; then
442                         while case "$curitem_orig" in
443                                 [$IFS]*) : ;; *) false; esac
444                         do
445                                 curitem_orig="${curitem_orig#?}"
446                         done
447                         curitem_mod="$curitem_orig"
448                 fi
449
450                 # Shift modified comparison value if sort field (-k POS) is > 1
451                 n=$sort_field
452                 while [ $n -gt 1 ]; do
453                         case "$curitem_mod" in
454                         *[$sort_sep]*)
455                                 # Cut text up-to (and incl.) first separator
456                                 curitem_mod="${curitem_mod#*[$sort_sep]}"
457
458                                 # Skip NULLs unless strict field splitting
459                                 [ "$sort_strict_fields" ] ||
460                                         [ "${curitem_mod%%[$sort_sep]*}" ] ||
461                                         [ $n -eq 2 ] ||
462                                         continue
463                                 ;;
464                         *)
465                                 # Asked for a field that doesn't exist
466                                 curitem_haskey= break
467                         esac
468                         n=$(( $n - 1 ))
469                 done
470
471                 # Trim trailing words if sort field >= 1
472                 [ $sort_field -ge 1 -a "$sort_numeric" ] &&
473                         curitem_mod="${curitem_mod%%[$sort_sep]*}"
474
475                 # Apply optional trim (-k POS.TRIM) to cut leading characters
476                 curitem_mod="${curitem_mod#$trim}"
477
478                 # Determine the type of modified comparison to use initially
479                 # NB: Prefer numerical if requested but fallback to standard
480                 case "$curitem_mod" in
481                 ""|[!0-9]*) # NULL or begins with non-number
482                         gt=">"
483                         [ "$sort_numeric" ] && curitem_mod=0
484                         ;;
485                 *)
486                         if [ "$sort_numeric" ]; then
487                                 gt="-gt"
488                                 curitem_mod="${curitem_mod%%[!0-9]*}"
489                                         # NB: trailing non-digits removed
490                                         # otherwise numeric comparison fails
491                         else
492                                 gt=">"
493                         fi
494                 esac
495
496                 # If first time through, short-circuit below position-search
497                 if [ $i -le 1 ]; then
498                         d=0
499                 else
500                         d=1
501                 fi
502
503                 #
504                 # Find appropriate element position
505                 #
506                 while [ $d -gt 0 ]
507                 do
508                         dest_haskey=$curitem_haskey
509                         eval dest=\"\$dest_$d\"
510                         dest_mod="$dest" # for modified comparison
511                         dest_orig="$dest" # for original comparison
512
513                         # Trim leading whitespace if desired
514                         if [ "$sort_ignore_leading_space" ]; then
515                                 while case "$dest_orig" in
516                                         [$IFS]*) : ;; *) false; esac
517                                 do
518                                         dest_orig="${dest_orig#?}"
519                                 done
520                                 dest_mod="$dest_orig"
521                         fi
522
523                         # Shift modified value if sort field (-k POS) is > 1
524                         n=$sort_field
525                         while [ $n -gt 1 ]; do
526                                 case "$dest_mod" in
527                                 *[$sort_sep]*)
528                                         # Cut text up-to (and incl.) 1st sep
529                                         dest_mod="${dest_mod#*[$sort_sep]}"
530
531                                         # Skip NULLs unless strict fields
532                                         [ "$sort_strict_fields" ] ||
533                                             [ "${dest_mod%%[$sort_sep]*}" ] ||
534                                             [ $n -eq 2 ] ||
535                                             continue
536                                         ;;
537                                 *)
538                                         # Asked for a field that doesn't exist
539                                         dest_haskey= break
540                                 esac
541                                 n=$(( $n - 1 ))
542                         done
543
544                         # Trim trailing words if sort field >= 1
545                         [ $sort_field -ge 1 -a "$sort_numeric" ] &&
546                                 dest_mod="${dest_mod%%[$sort_sep]*}"
547
548                         # Apply optional trim (-k POS.TRIM), cut leading chars
549                         dest_mod="${dest_mod#$trim}"
550
551                         # Determine type of modified comparison to use
552                         # NB: Prefer numerical if requested, fallback to std
553                         case "$dest_mod" in
554                         ""|[!0-9]*) # NULL or begins with non-number
555                                 gt=">"
556                                 [ "$sort_numeric" ] && dest_mod=0
557                                 ;;
558                         *)
559                                 if [ "$sort_numeric" ]; then
560                                         gt="-gt"
561                                         dest_mod="${dest_mod%%[!0-9]*}"
562                                                 # NB: kill trailing non-digits
563                                                 # for numeric comparison safety
564                                 else
565                                         gt=">"
566                                 fi
567                         esac
568
569                         # Break if we've found the proper element position
570                         if [ "$curitem_haskey" -a "$dest_haskey" ]; then
571                                 if [ "$dest_mod" = "$curitem_mod" ]; then
572                                         [ "$dest_orig" ">" "$curitem_orig" ] &&
573                                                 break
574                                 elif [ "$dest_mod" $gt "$curitem_mod" ] \
575                                         2> /dev/null
576                                 then
577                                         break
578                                 fi
579                         else
580                                 [ "$dest_orig" ">" "$curitem_orig" ] && break
581                         fi
582
583                         # Break if we've hit the end
584                         [ $d -ge $i ] && break
585
586                         d=$(( $d + 1 ))
587                 done
588
589                 # Shift remaining positions forward, making room for new item
590                 n=$i
591                 while [ $n -ge $d ]; do
592                         # Shift destination item forward one placement
593                         eval dest_$(( $n + 1 ))=\"\$dest_$n\"
594                         n=$(( $n - 1 ))
595                 done
596
597                 # Place the element
598                 if [ $i -eq 1 ]; then
599                         local dest_1="$curitem"
600                 else
601                         local dest_$d="$curitem"
602                 fi
603
604                 i=$(( $i + 1 ))
605         done
606
607         # Print sorted results
608         d=1
609         while [ $d -le $nitems ]; do
610                 eval echo \"\$dest_$d\"
611                 d=$(( $d + 1 ))
612         done
613 }
614
615 #
616 # wait_for_pids pid [pid ...]
617 #       spins until none of the pids exist
618 #
619 wait_for_pids()
620 {
621         local _list _prefix _nlist _j
622
623         _list="$@"
624         if [ -z "$_list" ]; then
625                 return
626         fi
627         _prefix=
628         while true; do
629                 _nlist="";
630                 for _j in $_list; do
631                         if kill -0 $_j 2>/dev/null; then
632                                 _nlist="${_nlist}${_nlist:+ }$_j"
633                                 [ -n "$_prefix" ] && sleep 1
634                         fi
635                 done
636                 if [ -z "$_nlist" ]; then
637                         break
638                 fi
639                 _list=$_nlist
640                 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
641                 _prefix=", "
642                 pwait $_list 2>/dev/null
643         done
644         if [ -n "$_prefix" ]; then
645                 echo "."
646         fi
647 }
648
649 #
650 # get_pidfile_from_conf string file
651 #
652 #       Takes a string to search for in the specified file.
653 #       Ignores lines with traditional comment characters.
654 #
655 # Example:
656 #
657 # if get_pidfile_from_conf string file; then
658 #       pidfile="$_pidfile_from_conf"
659 # else
660 #       pidfile='appropriate default'
661 # fi
662 #
663 get_pidfile_from_conf()
664 {
665         if [ -z "$1" -o -z "$2" ]; then
666                 err 3 "USAGE: get_pidfile_from_conf string file ($name)"
667         fi
668
669         local string file line
670
671         string="$1" ; file="$2"
672
673         if [ ! -s "$file" ]; then
674                 err 3 "get_pidfile_from_conf: $file does not exist ($name)"
675         fi
676
677         while read line; do
678                 case "$line" in
679                 *[#\;]*${string}*)      continue ;;
680                 *${string}*)            break ;;
681                 esac
682         done < $file
683
684         if [ -n "$line" ]; then
685                 line=${line#*/}
686                 _pidfile_from_conf="/${line%%[\"\;]*}"
687         else
688                 return 1
689         fi
690 }
691
692 #
693 # check_startmsgs
694 #       If rc_quiet is set (usually as a result of using faststart at
695 #       boot time) check if rc_startmsgs is enabled.
696 #
697 check_startmsgs()
698 {
699         if [ -n "$rc_quiet" ]; then
700                 checkyesno rc_startmsgs
701         else
702                 return 0
703         fi
704 }
705
706 #
707 # run_rc_command argument
708 #       Search for argument in the list of supported commands, which is:
709 #               "start stop restart rcvar status poll ${extra_commands}"
710 #       If there's a match, run ${argument}_cmd or the default method
711 #       (see below).
712 #
713 #       If argument has a given prefix, then change the operation as follows:
714 #               Prefix  Operation
715 #               ------  ---------
716 #               fast    Skip the pid check, and set rc_fast=yes, rc_quiet=yes
717 #               force   Set ${rcvar} to YES, and set rc_force=yes
718 #               one     Set ${rcvar} to YES
719 #               quiet   Don't output some diagnostics, and set rc_quiet=yes
720 #
721 #       The following globals are used:
722 #
723 #       Name            Needed  Purpose
724 #       ----            ------  -------
725 #       name            y       Name of script.
726 #
727 #       command         n       Full path to command.
728 #                               Not needed if ${rc_arg}_cmd is set for
729 #                               each keyword.
730 #
731 #       command_args    n       Optional args/shell directives for command.
732 #
733 #       command_interpreter n   If not empty, command is interpreted, so
734 #                               call check_{pidfile,process}() appropriately.
735 #
736 #       desc            n       Description of script.
737 #
738 #       extra_commands  n       List of extra commands supported.
739 #
740 #       pidfile         n       If set, use check_pidfile $pidfile $command,
741 #                               otherwise use check_process $command.
742 #                               In either case, only check if $command is set.
743 #
744 #       procname        n       Process name to check for instead of $command.
745 #
746 #       rcvar           n       This is checked with checkyesno to determine
747 #                               if the action should be run.
748 #
749 #       ${name}_program n       Full path to command.
750 #                               Meant to be used in /etc/rc.conf to override
751 #                               ${command}.
752 #
753 #       ${name}_chroot  n       Directory to chroot to before running ${command}
754 #                               Requires /usr to be mounted.
755 #
756 #       ${name}_chdir   n       Directory to cd to before running ${command}
757 #                               (if not using ${name}_chroot).
758 #
759 #       ${name}_flags   n       Arguments to call ${command} with.
760 #                               NOTE:   $flags from the parent environment
761 #                                       can be used to override this.
762 #
763 #       ${name}_env     n       Environment variables to run ${command} with.
764 #
765 #       ${name}_fib     n       Routing table number to run ${command} with.
766 #
767 #       ${name}_nice    n       Nice level to run ${command} at.
768 #
769 #       ${name}_oomprotect n    Don't kill ${command} when swap space is exhausted.
770 #
771 #       ${name}_user    n       User to run ${command} as, using su(1) if not
772 #                               using ${name}_chroot.
773 #                               Requires /usr to be mounted.
774 #
775 #       ${name}_group   n       Group to run chrooted ${command} as.
776 #                               Requires /usr to be mounted.
777 #
778 #       ${name}_groups  n       Comma separated list of supplementary groups
779 #                               to run the chrooted ${command} with.
780 #                               Requires /usr to be mounted.
781 #
782 #       ${name}_prepend n       Command added before ${command}.
783 #
784 #       ${name}_login_class n   Login class to use, else "daemon".
785 #
786 #       ${rc_arg}_cmd   n       If set, use this as the method when invoked;
787 #                               Otherwise, use default command (see below)
788 #
789 #       ${rc_arg}_precmd n      If set, run just before performing the
790 #                               ${rc_arg}_cmd method in the default
791 #                               operation (i.e, after checking for required
792 #                               bits and process (non)existence).
793 #                               If this completes with a non-zero exit code,
794 #                               don't run ${rc_arg}_cmd.
795 #
796 #       ${rc_arg}_postcmd n     If set, run just after performing the
797 #                               ${rc_arg}_cmd method, if that method
798 #                               returned a zero exit code.
799 #
800 #       required_dirs   n       If set, check for the existence of the given
801 #                               directories before running a (re)start command.
802 #
803 #       required_files  n       If set, check for the readability of the given
804 #                               files before running a (re)start command.
805 #
806 #       required_modules n      If set, ensure the given kernel modules are
807 #                               loaded before running a (re)start command.
808 #                               The check and possible loads are actually
809 #                               done after start_precmd so that the modules
810 #                               aren't loaded in vain, should the precmd
811 #                               return a non-zero status to indicate a error.
812 #                               If a word in the list looks like "foo:bar",
813 #                               "foo" is the KLD file name and "bar" is the
814 #                               module name.  If a word looks like "foo~bar",
815 #                               "foo" is the KLD file name and "bar" is a
816 #                               egrep(1) pattern matching the module name.
817 #                               Otherwise the module name is assumed to be
818 #                               the same as the KLD file name, which is most
819 #                               common.  See load_kld().
820 #
821 #       required_vars   n       If set, perform checkyesno on each of the
822 #                               listed variables before running the default
823 #                               (re)start command.
824 #
825 #       Default behaviour for a given argument, if no override method is
826 #       provided:
827 #
828 #       Argument        Default behaviour
829 #       --------        -----------------
830 #       start           if !running && checkyesno ${rcvar}
831 #                               ${command}
832 #
833 #       stop            if ${pidfile}
834 #                               rc_pid=$(check_pidfile $pidfile $command)
835 #                       else
836 #                               rc_pid=$(check_process $command)
837 #                       kill $sig_stop $rc_pid
838 #                       wait_for_pids $rc_pid
839 #                       ($sig_stop defaults to TERM.)
840 #
841 #       reload          Similar to stop, except use $sig_reload instead,
842 #                       and doesn't wait_for_pids.
843 #                       $sig_reload defaults to HUP.
844 #                       Note that `reload' isn't provided by default,
845 #                       it should be enabled via $extra_commands.
846 #
847 #       restart         Run `stop' then `start'.
848 #
849 #       status          Show if ${command} is running, etc.
850 #
851 #       poll            Wait for ${command} to exit.
852 #
853 #       rcvar           Display what rc.conf variable is used (if any).
854 #
855 #       enabled         Return true if the service is enabled.
856 #
857 #       describe        Show the service's description
858 #
859 #       extracommands   Show the service's extra commands
860 #
861 #       Variables available to methods, and after run_rc_command() has
862 #       completed:
863 #
864 #       Variable        Purpose
865 #       --------        -------
866 #       rc_arg          Argument to command, after fast/force/one processing
867 #                       performed
868 #
869 #       rc_flags        Flags to start the default command with.
870 #                       Defaults to ${name}_flags, unless overridden
871 #                       by $flags from the environment.
872 #                       This variable may be changed by the precmd method.
873 #
874 #       rc_service      Path to the service being executed, in case the service
875 #                       needs to re-invoke itself.
876 #
877 #       rc_pid          PID of command (if appropriate)
878 #
879 #       rc_fast         Not empty if "fast" was provided (q.v.)
880 #
881 #       rc_force        Not empty if "force" was provided (q.v.)
882 #
883 #       rc_quiet        Not empty if "quiet" was provided
884 #
885 #
886 run_rc_command()
887 {
888         _return=0
889         rc_arg=$1
890         if [ -z "$name" ]; then
891                 err 3 'run_rc_command: $name is not set.'
892         fi
893
894         # Don't repeat the first argument when passing additional command-
895         # line arguments to the command subroutines.
896         #
897         shift 1
898         rc_extra_args="$*"
899
900         _rc_prefix=
901         case "$rc_arg" in
902         fast*)                          # "fast" prefix; don't check pid
903                 rc_arg=${rc_arg#fast}
904                 rc_fast=yes
905                 rc_quiet=yes
906                 ;;
907         force*)                         # "force" prefix; always run
908                 rc_force=yes
909                 _rc_prefix=force
910                 rc_arg=${rc_arg#${_rc_prefix}}
911                 if [ -n "${rcvar}" ]; then
912                         eval ${rcvar}=YES
913                 fi
914                 ;;
915         one*)                           # "one" prefix; set ${rcvar}=yes
916                 _rc_prefix=one
917                 rc_arg=${rc_arg#${_rc_prefix}}
918                 if [ -n "${rcvar}" ]; then
919                         eval ${rcvar}=YES
920                 fi
921                 ;;
922         quiet*)                         # "quiet" prefix; omit some messages
923                 _rc_prefix=quiet
924                 rc_arg=${rc_arg#${_rc_prefix}}
925                 rc_quiet=yes
926                 ;;
927         esac
928
929         eval _override_command=\$${name}_program
930         command=${_override_command:-$command}
931
932         _keywords="start stop restart rcvar enabled describe extracommands $extra_commands"
933         rc_pid=
934         _pidcmd=
935         _procname=${procname:-${command}}
936
937                                         # setup pid check command
938         if [ -n "$_procname" ]; then
939                 if [ -n "$pidfile" ]; then
940                         _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
941                 else
942                         _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
943                 fi
944                 _keywords="${_keywords} status poll"
945         fi
946
947         if [ -z "$rc_arg" ]; then
948                 rc_usage $_keywords
949         fi
950
951         if [ "$rc_arg" = "enabled" ] ; then
952                 checkyesno ${rcvar}
953                 return $?
954         fi
955
956         if [ -n "$flags" ]; then        # allow override from environment
957                 rc_flags=$flags
958         else
959                 eval rc_flags=\$${name}_flags
960         fi
961         eval _chdir=\$${name}_chdir     _chroot=\$${name}_chroot \
962             _nice=\$${name}_nice        _user=\$${name}_user \
963             _group=\$${name}_group      _groups=\$${name}_groups \
964             _fib=\$${name}_fib          _env=\$${name}_env \
965             _prepend=\$${name}_prepend  _login_class=\${${name}_login_class:-daemon} \
966             _oomprotect=\$${name}_oomprotect
967
968         if [ -n "$_user" ]; then        # unset $_user if running as that user
969                 if [ "$_user" = "$(eval $IDCMD)" ]; then
970                         unset _user
971                 fi
972         fi
973
974         [ -z "$autoboot" ] && eval $_pidcmd     # determine the pid if necessary
975
976         for _elem in $_keywords; do
977                 if [ "$_elem" != "$rc_arg" ]; then
978                         continue
979                 fi
980                                         # if ${rcvar} is set, $1 is not "rcvar" and not "describe"
981                                         # and ${rc_pid} is not set, then run
982                                         #       checkyesno ${rcvar}
983                                         # and return if that failed
984                                         #
985                 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
986                     -a "$rc_arg" != "describe" ] ||
987                     [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
988                         if ! checkyesno ${rcvar}; then
989                                 if [ -n "${rc_quiet}" ]; then
990                                         return 0
991                                 fi
992                                 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
993                                 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
994                                 echo "instead of '${rc_arg}'."
995                                 return 0
996                         fi
997                 fi
998
999                 if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1000                         if [ -z "$rc_quiet" ]; then
1001                                 echo 1>&2 "${name} already running? " \
1002                                     "(pid=$rc_pid)."
1003                         fi
1004                         return 1
1005                 fi
1006
1007                                         # if there's a custom ${XXX_cmd},
1008                                         # run that instead of the default
1009                                         #
1010                 eval _cmd=\$${rc_arg}_cmd \
1011                      _precmd=\$${rc_arg}_precmd \
1012                      _postcmd=\$${rc_arg}_postcmd
1013
1014                 if [ -n "$_cmd" ]; then
1015                         _run_rc_precmd || return 1
1016                         _run_rc_doit "$_cmd $rc_extra_args" || return 1
1017                         _run_rc_postcmd
1018                         return $_return
1019                 fi
1020
1021                 case "$rc_arg" in       # default operations...
1022
1023                 describe)
1024                         if [ -n "$desc" ]; then
1025                                 echo "$desc"
1026                         fi
1027                         ;;
1028         
1029                 extracommands)
1030                         echo "$extra_commands"
1031                         ;;
1032
1033                 status)
1034                         _run_rc_precmd || return 1
1035                         if [ -n "$rc_pid" ]; then
1036                                 echo "${name} is running as pid $rc_pid."
1037                         else
1038                                 echo "${name} is not running."
1039                                 return 1
1040                         fi
1041                         _run_rc_postcmd
1042                         ;;
1043
1044                 start)
1045                         if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1046                                 warn "run_rc_command: cannot run $command"
1047                                 return 1
1048                         fi
1049
1050                         if ! _run_rc_precmd; then
1051                                 warn "failed precmd routine for ${name}"
1052                                 return 1
1053                         fi
1054
1055                                         # setup the full command to run
1056                                         #
1057                         check_startmsgs && echo "Starting ${name}."
1058                         if [ -n "$_chroot" ]; then
1059                                 _cd=
1060                                 _doit="\
1061 ${_nice:+nice -n $_nice }\
1062 ${_fib:+setfib -F $_fib }\
1063 ${_env:+env $_env }\
1064 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1065 $_chroot $command $rc_flags $command_args"
1066                         else
1067                                 _cd="${_chdir:+cd $_chdir && }"
1068                                 _doit="\
1069 ${_fib:+setfib -F $_fib }\
1070 ${_env:+env $_env }\
1071 $command $rc_flags $command_args"
1072                                 if [ -n "$_user" ]; then
1073                                     _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1074                                 fi
1075                                 if [ -n "$_nice" ]; then
1076                                         if [ -z "$_user" ]; then
1077                                                 _doit="sh -c \"$_doit\""
1078                                         fi
1079                                         _doit="nice -n $_nice $_doit"
1080                                 fi
1081                                 if [ -n "$_prepend" ]; then
1082                                         _doit="$_prepend $_doit"
1083                                 fi
1084                         fi
1085
1086                                         # Prepend default limits
1087                         _doit="$_cd limits -C $_login_class $_doit"
1088
1089                                         # run the full command
1090                                         #
1091                         if ! _run_rc_doit "$_doit"; then
1092                                 warn "failed to start ${name}"
1093                                 return 1
1094                         fi
1095
1096                                         # finally, run postcmd
1097                                         #
1098                         _run_rc_postcmd
1099                         ;;
1100
1101                 stop)
1102                         if [ -z "$rc_pid" ]; then
1103                                 [ -n "$rc_fast" ] && return 0
1104                                 _run_rc_notrunning
1105                                 return 1
1106                         fi
1107
1108                         _run_rc_precmd || return 1
1109
1110                                         # send the signal to stop
1111                                         #
1112                         echo "Stopping ${name}."
1113                         _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1114                         _run_rc_doit "$_doit" || return 1
1115
1116                                         # wait for the command to exit,
1117                                         # and run postcmd.
1118                         wait_for_pids $rc_pid
1119
1120                         _run_rc_postcmd
1121                         ;;
1122
1123                 reload)
1124                         if [ -z "$rc_pid" ]; then
1125                                 _run_rc_notrunning
1126                                 return 1
1127                         fi
1128
1129                         _run_rc_precmd || return 1
1130
1131                         _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1132                         _run_rc_doit "$_doit" || return 1
1133
1134                         _run_rc_postcmd
1135                         ;;
1136
1137                 restart)
1138                                         # prevent restart being called more
1139                                         # than once by any given script
1140                                         #
1141                         if ${_rc_restart_done:-false}; then
1142                                 return 0
1143                         fi
1144                         _rc_restart_done=true
1145
1146                         _run_rc_precmd || return 1
1147
1148                         # run those in a subshell to keep global variables
1149                         ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1150                         ( run_rc_command ${_rc_prefix}start $rc_extra_args )
1151                         _return=$?
1152                         [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1153
1154                         _run_rc_postcmd
1155                         ;;
1156
1157                 poll)
1158                         _run_rc_precmd || return 1
1159                         if [ -n "$rc_pid" ]; then
1160                                 wait_for_pids $rc_pid
1161                         fi
1162                         _run_rc_postcmd
1163                         ;;
1164
1165                 rcvar)
1166                         echo -n "# $name"
1167                         if [ -n "$desc" ]; then
1168                                 echo " : $desc"
1169                         else
1170                                 echo ""
1171                         fi
1172                         echo "#"
1173                         # Get unique vars in $rcvar $rcvars
1174                         for _v in $rcvar $rcvars; do
1175                                 case $v in
1176                                 $_v\ *|\ *$_v|*\ $_v\ *) ;;
1177                                 *)      v="${v# } $_v" ;;
1178                                 esac
1179                         done
1180
1181                         # Display variables.
1182                         for _v in $v; do
1183                                 if [ -z "$_v" ]; then
1184                                         continue
1185                                 fi
1186
1187                                 eval _desc=\$${_v}_desc
1188                                 eval _defval=\$${_v}_defval
1189                                 _h="-"
1190
1191                                 eval echo \"$_v=\\\"\$$_v\\\"\"
1192                                 # decode multiple lines of _desc
1193                                 while [ -n "$_desc" ]; do
1194                                         case $_desc in
1195                                         *^^*)
1196                                                 echo "# $_h ${_desc%%^^*}"
1197                                                 _desc=${_desc#*^^}
1198                                                 _h=" "
1199                                                 ;;
1200                                         *)
1201                                                 echo "# $_h ${_desc}"
1202                                                 break
1203                                                 ;;
1204                                         esac
1205                                 done
1206                                 echo "#   (default: \"$_defval\")"
1207                         done
1208                         echo ""
1209                         ;;
1210
1211                 *)
1212                         rc_usage $_keywords
1213                         ;;
1214
1215                 esac
1216
1217                 # Apply protect(1) to the PID if ${name}_oomprotect is set.
1218                 case "$rc_arg" in
1219                 start)
1220                         # We cannot use protect(1) inside jails.
1221                         if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1222                             [ "$(sysctl -n security.jail.jailed)" -eq 0 ]; then
1223                                 pid=$(check_process $command)
1224                                 case $_oomprotect in
1225                                 [Aa][Ll][Ll])
1226                                         ${PROTECT} -i -p ${pid}
1227                                         ;;
1228                                 [Yy][Ee][Ss])
1229                                         ${PROTECT} -p ${pid}
1230                                         ;;
1231                                 esac
1232                         fi      
1233                 ;;
1234                 esac
1235
1236                 return $_return
1237         done
1238
1239         echo 1>&2 "$0: unknown directive '$rc_arg'."
1240         rc_usage $_keywords
1241         # not reached
1242 }
1243
1244 #
1245 # Helper functions for run_rc_command: common code.
1246 # They use such global variables besides the exported rc_* ones:
1247 #
1248 #       name           R/W
1249 #       ------------------
1250 #       _precmd         R
1251 #       _postcmd        R
1252 #       _return         W
1253 #
1254 _run_rc_precmd()
1255 {
1256         check_required_before "$rc_arg" || return 1
1257
1258         if [ -n "$_precmd" ]; then
1259                 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1260                 eval "$_precmd $rc_extra_args"
1261                 _return=$?
1262
1263                 # If precmd failed and force isn't set, request exit.
1264                 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1265                         return 1
1266                 fi
1267         fi
1268
1269         check_required_after "$rc_arg" || return 1
1270
1271         return 0
1272 }
1273
1274 _run_rc_postcmd()
1275 {
1276         if [ -n "$_postcmd" ]; then
1277                 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1278                 eval "$_postcmd $rc_extra_args"
1279                 _return=$?
1280         fi
1281         return 0
1282 }
1283
1284 _run_rc_doit()
1285 {
1286         debug "run_rc_command: doit: $*"
1287         eval "$@"
1288         _return=$?
1289
1290         # If command failed and force isn't set, request exit.
1291         if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1292                 return 1
1293         fi
1294
1295         return 0
1296 }
1297
1298 _run_rc_notrunning()
1299 {
1300         local _pidmsg
1301
1302         if [ -n "$pidfile" ]; then
1303                 _pidmsg=" (check $pidfile)."
1304         else
1305                 _pidmsg=
1306         fi
1307         echo 1>&2 "${name} not running?${_pidmsg}"
1308 }
1309
1310 _run_rc_killcmd()
1311 {
1312         local _cmd
1313
1314         _cmd="kill -$1 $rc_pid"
1315         if [ -n "$_user" ]; then
1316                 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1317         fi
1318         echo "$_cmd"
1319 }
1320
1321 #
1322 # run_rc_script file arg
1323 #       Start the script `file' with `arg', and correctly handle the
1324 #       return value from the script.
1325 #       If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1326 #       an old-style startup file.
1327 #       If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1328 #       into the current environment if $rc_fast_and_loose is set; otherwise
1329 #       it is run as a child process.
1330 #       If `file' appears to be a backup or scratch file, ignore it.
1331 #       Otherwise if it is executable run as a child process.
1332 #
1333 run_rc_script()
1334 {
1335         _file=$1
1336         _arg=$2
1337         if [ -z "$_file" -o -z "$_arg" ]; then
1338                 err 3 'USAGE: run_rc_script file arg'
1339         fi
1340
1341         unset   name command command_args command_interpreter \
1342                 extra_commands pidfile procname \
1343                 rcvar rcvars rcvars_obsolete required_dirs required_files \
1344                 required_vars
1345         eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1346
1347         rc_service="$_file"
1348         case "$_file" in
1349         /etc/rc.d/*.sh)                 # no longer allowed in the base
1350                 warn "Ignoring old-style startup script $_file"
1351                 ;;
1352         *[~#]|*.OLD|*.bak|*.orig|*,v)   # scratch file; skip
1353                 warn "Ignoring scratch file $_file"
1354                 ;;
1355         *)                              # run in subshell
1356                 if [ -x $_file ]; then
1357                         if [ -n "$rc_fast_and_loose" ]; then
1358                                 set $_arg; . $_file
1359                         else
1360                                 ( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1361                                   trap "echo Script $_file interrupted >&2 ; exit 1" 2
1362                                   trap "echo Script $_file running >&2" 29
1363                                   set $_arg; . $_file )
1364                         fi
1365                 fi
1366                 ;;
1367         esac
1368 }
1369
1370 #
1371 # load_rc_config [service]
1372 #       Source in the configuration file(s) for a given service.
1373 #       If no service is specified, only the global configuration
1374 #       file(s) will be loaded.
1375 #
1376 load_rc_config()
1377 {
1378         local _name _rcvar_val _var _defval _v _msg _new _d
1379         _name=$1
1380
1381         if ${_rc_conf_loaded:-false}; then
1382                 :
1383         else
1384                 if [ -r /etc/defaults/rc.conf ]; then
1385                         debug "Sourcing /etc/defaults/rc.conf"
1386                         . /etc/defaults/rc.conf
1387                         source_rc_confs
1388                 elif [ -r /etc/rc.conf ]; then
1389                         debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1390                         . /etc/rc.conf
1391                 fi
1392                 _rc_conf_loaded=true
1393         fi
1394
1395         # If a service name was specified, attempt to load
1396         # service-specific configuration
1397         if [ -n "$_name" ] ; then
1398                 for _d in /etc ${local_startup}; do
1399                         _d=${_d%/rc.d}
1400                         if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1401                                 debug "Sourcing ${_d}/rc.conf.d/$_name"
1402                                 . ${_d}/rc.conf.d/"$_name"
1403                         elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
1404                                 local _rc
1405                                 for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
1406                                         if [ -f "$_rc" ] ; then
1407                                                 debug "Sourcing $_rc"
1408                                                 . "$_rc"
1409                                         fi
1410                                 done
1411                         fi
1412                 done
1413         fi
1414
1415         # Set defaults if defined.
1416         for _var in $rcvar $rcvars; do
1417                 eval _defval=\$${_var}_defval
1418                 if [ -n "$_defval" ]; then
1419                         eval : \${$_var:=\$${_var}_defval}
1420                 fi
1421         done
1422
1423         # check obsolete rc.conf variables
1424         for _var in $rcvars_obsolete; do
1425                 eval _v=\$$_var
1426                 eval _msg=\$${_var}_obsolete_msg
1427                 eval _new=\$${_var}_newvar
1428                 case $_v in
1429                 "")
1430                         ;;
1431                 *)
1432                         if [ -z "$_new" ]; then
1433                                 _msg="Ignored."
1434                         else
1435                                 eval $_new=\"\$$_var\"
1436                                 if [ -z "$_msg" ]; then
1437                                         _msg="Use \$$_new instead."
1438                                 fi
1439                         fi
1440                         warn "\$$_var is obsolete.  $_msg"
1441                         ;;
1442                 esac
1443         done
1444 }
1445
1446 #
1447 # load_rc_config_var name var
1448 #       Read the rc.conf(5) var for name and set in the
1449 #       current shell, using load_rc_config in a subshell to prevent
1450 #       unwanted side effects from other variable assignments.
1451 #
1452 load_rc_config_var()
1453 {
1454         if [ $# -ne 2 ]; then
1455                 err 3 'USAGE: load_rc_config_var name var'
1456         fi
1457         eval $(eval '(
1458                 load_rc_config '$1' >/dev/null;
1459                 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1460                         echo '$2'=\'\''${'$2'}\'\'';
1461                 fi
1462         )' )
1463 }
1464
1465 #
1466 # rc_usage commands
1467 #       Print a usage string for $0, with `commands' being a list of
1468 #       valid commands.
1469 #
1470 rc_usage()
1471 {
1472         echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1473
1474         _sep=
1475         for _elem; do
1476                 echo -n 1>&2 "$_sep$_elem"
1477                 _sep="|"
1478         done
1479         echo 1>&2 ")"
1480         exit 1
1481 }
1482
1483 #
1484 # err exitval message
1485 #       Display message to stderr and log to the syslog, and exit with exitval.
1486 #
1487 err()
1488 {
1489         exitval=$1
1490         shift
1491
1492         if [ -x /usr/bin/logger ]; then
1493                 logger "$0: ERROR: $*"
1494         fi
1495         echo 1>&2 "$0: ERROR: $*"
1496         exit $exitval
1497 }
1498
1499 #
1500 # warn message
1501 #       Display message to stderr and log to the syslog.
1502 #
1503 warn()
1504 {
1505         if [ -x /usr/bin/logger ]; then
1506                 logger "$0: WARNING: $*"
1507         fi
1508         echo 1>&2 "$0: WARNING: $*"
1509 }
1510
1511 #
1512 # info message
1513 #       Display informational message to stdout and log to syslog.
1514 #
1515 info()
1516 {
1517         case ${rc_info} in
1518         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1519                 if [ -x /usr/bin/logger ]; then
1520                         logger "$0: INFO: $*"
1521                 fi
1522                 echo "$0: INFO: $*"
1523                 ;;
1524         esac
1525 }
1526
1527 #
1528 # debug message
1529 #       If debugging is enabled in rc.conf output message to stderr.
1530 #       BEWARE that you don't call any subroutine that itself calls this
1531 #       function.
1532 #
1533 debug()
1534 {
1535         case ${rc_debug} in
1536         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1537                 if [ -x /usr/bin/logger ]; then
1538                         logger "$0: DEBUG: $*"
1539                 fi
1540                 echo 1>&2 "$0: DEBUG: $*"
1541                 ;;
1542         esac
1543 }
1544
1545 #
1546 # backup_file action file cur backup
1547 #       Make a backup copy of `file' into `cur', and save the previous
1548 #       version of `cur' as `backup' or use rcs for archiving.
1549 #
1550 #       This routine checks the value of the backup_uses_rcs variable,
1551 #       which can be either YES or NO.
1552 #
1553 #       The `action' keyword can be one of the following:
1554 #
1555 #       add             `file' is now being backed up (and is possibly
1556 #                       being reentered into the backups system).  `cur'
1557 #                       is created and RCS files, if necessary, are
1558 #                       created as well.
1559 #
1560 #       update          `file' has changed and needs to be backed up.
1561 #                       If `cur' exists, it is copied to to `back' or
1562 #                       checked into RCS (if the repository file is old),
1563 #                       and then `file' is copied to `cur'.  Another RCS
1564 #                       check in done here if RCS is being used.
1565 #
1566 #       remove          `file' is no longer being tracked by the backups
1567 #                       system.  If RCS is not being used, `cur' is moved
1568 #                       to `back', otherwise an empty file is checked in,
1569 #                       and then `cur' is removed.
1570 #
1571 #
1572 backup_file()
1573 {
1574         _action=$1
1575         _file=$2
1576         _cur=$3
1577         _back=$4
1578
1579         if checkyesno backup_uses_rcs; then
1580                 _msg0="backup archive"
1581                 _msg1="update"
1582
1583                 # ensure that history file is not locked
1584                 if [ -f $_cur,v ]; then
1585                         rcs -q -u -U -M $_cur
1586                 fi
1587
1588                 # ensure after switching to rcs that the
1589                 # current backup is not lost
1590                 if [ -f $_cur ]; then
1591                         # no archive, or current newer than archive
1592                         if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1593                                 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1594                                 rcs -q -kb -U $_cur
1595                                 co -q -f -u $_cur
1596                         fi
1597                 fi
1598
1599                 case $_action in
1600                 add|update)
1601                         cp -p $_file $_cur
1602                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1603                         rcs -q -kb -U $_cur
1604                         co -q -f -u $_cur
1605                         chown root:wheel $_cur $_cur,v
1606                         ;;
1607                 remove)
1608                         cp /dev/null $_cur
1609                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1610                         rcs -q -kb -U $_cur
1611                         chown root:wheel $_cur $_cur,v
1612                         rm $_cur
1613                         ;;
1614                 esac
1615         else
1616                 case $_action in
1617                 add|update)
1618                         if [ -f $_cur ]; then
1619                                 cp -p $_cur $_back
1620                         fi
1621                         cp -p $_file $_cur
1622                         chown root:wheel $_cur
1623                         ;;
1624                 remove)
1625                         mv -f $_cur $_back
1626                         ;;
1627                 esac
1628         fi
1629 }
1630
1631 # make_symlink src link
1632 #       Make a symbolic link 'link' to src from basedir. If the
1633 #       directory in which link is to be created does not exist
1634 #       a warning will be displayed and an error will be returned.
1635 #       Returns 0 on success, 1 otherwise.
1636 #
1637 make_symlink()
1638 {
1639         local src link linkdir _me
1640         src="$1"
1641         link="$2"
1642         linkdir="`dirname $link`"
1643         _me="make_symlink()"
1644
1645         if [ -z "$src" -o -z "$link" ]; then
1646                 warn "$_me: requires two arguments."
1647                 return 1
1648         fi
1649         if [ ! -d "$linkdir" ]; then
1650                 warn "$_me: the directory $linkdir does not exist."
1651                 return 1
1652         fi
1653         if ! ln -sf $src $link; then
1654                 warn "$_me: unable to make a symbolic link from $link to $src"
1655                 return 1
1656         fi
1657         return 0
1658 }
1659
1660 # devfs_rulesets_from_file file
1661 #       Reads a set of devfs commands from file, and creates
1662 #       the specified rulesets with their rules. Returns non-zero
1663 #       if there was an error.
1664 #
1665 devfs_rulesets_from_file()
1666 {
1667         local file _err _me _opts
1668         file="$1"
1669         _me="devfs_rulesets_from_file"
1670         _err=0
1671
1672         if [ -z "$file" ]; then
1673                 warn "$_me: you must specify a file"
1674                 return 1
1675         fi
1676         if [ ! -e "$file" ]; then
1677                 debug "$_me: no such file ($file)"
1678                 return 0
1679         fi
1680
1681         # Disable globbing so that the rule patterns are not expanded
1682         # by accident with matching filesystem entries.
1683         _opts=$-; set -f
1684
1685         debug "reading rulesets from file ($file)"
1686         { while read line
1687         do
1688                 case $line in
1689                 \#*)
1690                         continue
1691                         ;;
1692                 \[*\]*)
1693                         rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1694                         if [ -z "$rulenum" ]; then
1695                                 warn "$_me: cannot extract rule number ($line)"
1696                                 _err=1
1697                                 break
1698                         fi
1699                         rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1700                         if [ -z "$rulename" ]; then
1701                                 warn "$_me: cannot extract rule name ($line)"
1702                                 _err=1
1703                                 break;
1704                         fi
1705                         eval $rulename=\$rulenum
1706                         debug "found ruleset: $rulename=$rulenum"
1707                         if ! /sbin/devfs rule -s $rulenum delset; then
1708                                 _err=1
1709                                 break
1710                         fi
1711                         ;;
1712                 *)
1713                         rulecmd="${line%%"\#*"}"
1714                         # evaluate the command incase it includes
1715                         # other rules
1716                         if [ -n "$rulecmd" ]; then
1717                                 debug "adding rule ($rulecmd)"
1718                                 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1719                                 then
1720                                         _err=1
1721                                         break
1722                                 fi
1723                         fi
1724                         ;;
1725                 esac
1726                 if [ $_err -ne 0 ]; then
1727                         debug "error in $_me"
1728                         break
1729                 fi
1730         done } < $file
1731         case $_opts in *f*) ;; *) set +f ;; esac
1732         return $_err
1733 }
1734
1735 # devfs_init_rulesets
1736 #       Initializes rulesets from configuration files. Returns
1737 #       non-zero if there was an error.
1738 #
1739 devfs_init_rulesets()
1740 {
1741         local file _me
1742         _me="devfs_init_rulesets"
1743
1744         # Go through this only once
1745         if [ -n "$devfs_rulesets_init" ]; then
1746                 debug "$_me: devfs rulesets already initialized"
1747                 return
1748         fi
1749         for file in $devfs_rulesets; do
1750                 if ! devfs_rulesets_from_file $file; then
1751                         warn "$_me: could not read rules from $file"
1752                         return 1
1753                 fi
1754         done
1755         devfs_rulesets_init=1
1756         debug "$_me: devfs rulesets initialized"
1757         return 0
1758 }
1759
1760 # devfs_set_ruleset ruleset [dir]
1761 #       Sets the default ruleset of dir to ruleset. The ruleset argument
1762 #       must be a ruleset name as specified in devfs.rules(5) file.
1763 #       Returns non-zero if it could not set it successfully.
1764 #
1765 devfs_set_ruleset()
1766 {
1767         local devdir rs _me
1768         [ -n "$1" ] && eval rs=\$$1 || rs=
1769         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1770         _me="devfs_set_ruleset"
1771
1772         if [ -z "$rs" ]; then
1773                 warn "$_me: you must specify a ruleset number"
1774                 return 1
1775         fi
1776         debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1777         if ! /sbin/devfs $devdir ruleset $rs; then
1778                 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1779                 return 1
1780         fi
1781         return 0
1782 }
1783
1784 # devfs_apply_ruleset ruleset [dir]
1785 #       Apply ruleset number $ruleset to the devfs mountpoint $dir.
1786 #       The ruleset argument must be a ruleset name as specified
1787 #       in a devfs.rules(5) file.  Returns 0 on success or non-zero
1788 #       if it could not apply the ruleset.
1789 #
1790 devfs_apply_ruleset()
1791 {
1792         local devdir rs _me
1793         [ -n "$1" ] && eval rs=\$$1 || rs=
1794         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1795         _me="devfs_apply_ruleset"
1796
1797         if [ -z "$rs" ]; then
1798                 warn "$_me: you must specify a ruleset"
1799                 return 1
1800         fi
1801         debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1802         if ! /sbin/devfs $devdir rule -s $rs applyset; then
1803                 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1804                 return 1
1805         fi
1806         return 0
1807 }
1808
1809 # devfs_domount dir [ruleset]
1810 #       Mount devfs on dir. If ruleset is specified it is set
1811 #       on the mount-point. It must also be a ruleset name as specified
1812 #       in a devfs.rules(5) file. Returns 0 on success.
1813 #
1814 devfs_domount()
1815 {
1816         local devdir rs _me
1817         devdir="$1"
1818         [ -n "$2" ] && rs=$2 || rs=
1819         _me="devfs_domount()"
1820
1821         if [ -z "$devdir" ]; then
1822                 warn "$_me: you must specify a mount-point"
1823                 return 1
1824         fi
1825         debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1826         if ! mount -t devfs dev "$devdir"; then
1827                 warn "$_me: Unable to mount devfs on $devdir"
1828                 return 1
1829         fi
1830         if [ -n "$rs" ]; then
1831                 devfs_init_rulesets
1832                 devfs_set_ruleset $rs $devdir
1833                 devfs -m $devdir rule applyset
1834         fi
1835         return 0
1836 }
1837
1838 # Provide a function for normalizing the mounting of memory
1839 # filesystems.  This should allow the rest of the code here to remain
1840 # as close as possible between 5-current and 4-stable.
1841 #   $1 = size
1842 #   $2 = mount point
1843 #   $3 = (optional) extra mdmfs flags
1844 mount_md()
1845 {
1846         if [ -n "$3" ]; then
1847                 flags="$3"
1848         fi
1849         /sbin/mdmfs $flags -s $1 ${mfs_type} $2
1850 }
1851
1852 # Code common to scripts that need to load a kernel module
1853 # if it isn't in the kernel yet. Syntax:
1854 #   load_kld [-e regex] [-m module] file
1855 # where -e or -m chooses the way to check if the module
1856 # is already loaded:
1857 #   regex is egrep'd in the output from `kldstat -v',
1858 #   module is passed to `kldstat -m'.
1859 # The default way is as though `-m file' were specified.
1860 load_kld()
1861 {
1862         local _loaded _mod _opt _re
1863
1864         while getopts "e:m:" _opt; do
1865                 case "$_opt" in
1866                 e) _re="$OPTARG" ;;
1867                 m) _mod="$OPTARG" ;;
1868                 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1869                 esac
1870         done
1871         shift $(($OPTIND - 1))
1872         if [ $# -ne 1 ]; then
1873                 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1874         fi
1875         _mod=${_mod:-$1}
1876         _loaded=false
1877         if [ -n "$_re" ]; then
1878                 if kldstat -v | egrep -q -e "$_re"; then
1879                         _loaded=true
1880                 fi
1881         else
1882                 if kldstat -q -m "$_mod"; then
1883                         _loaded=true
1884                 fi
1885         fi
1886         if ! $_loaded; then
1887                 if ! kldload "$1"; then
1888                         warn "Unable to load kernel module $1"
1889                         return 1
1890                 else
1891                         info "$1 kernel module loaded."
1892                 fi
1893         else
1894                 debug "load_kld: $1 kernel module already loaded."
1895         fi
1896         return 0
1897 }
1898
1899 # ltr str src dst [var]
1900 #       Change every $src in $str to $dst.
1901 #       Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1902 #       awk(1). If var is non-NULL, set it to the result.
1903 ltr()
1904 {
1905         local _str _src _dst _out _com _var
1906         _str="$1"
1907         _src="$2"
1908         _dst="$3"
1909         _var="$4"
1910         _out=""
1911
1912         local IFS="${_src}"
1913         for _com in ${_str}; do
1914                 if [ -z "${_out}" ]; then
1915                         _out="${_com}"
1916                 else
1917                         _out="${_out}${_dst}${_com}"
1918                 fi
1919         done
1920         if [ -n "${_var}" ]; then
1921                 setvar "${_var}" "${_out}"
1922         else
1923                 echo "${_out}"
1924         fi
1925 }
1926
1927 # Creates a list of providers for GELI encryption.
1928 geli_make_list()
1929 {
1930         local devices devices2
1931         local provider mountpoint type options rest
1932
1933         # Create list of GELI providers from fstab.
1934         while read provider mountpoint type options rest ; do
1935                 case ":${options}" in
1936                 :*noauto*)
1937                         noauto=yes
1938                         ;;
1939                 *)
1940                         noauto=no
1941                         ;;
1942                 esac
1943
1944                 case ":${provider}" in
1945                 :#*)
1946                         continue
1947                         ;;
1948                 *.eli)
1949                         # Skip swap devices.
1950                         if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1951                                 continue
1952                         fi
1953                         devices="${devices} ${provider}"
1954                         ;;
1955                 esac
1956         done < /etc/fstab
1957
1958         # Append providers from geli_devices.
1959         devices="${devices} ${geli_devices}"
1960
1961         for provider in ${devices}; do
1962                 provider=${provider%.eli}
1963                 provider=${provider#/dev/}
1964                 devices2="${devices2} ${provider}"
1965         done
1966
1967         echo ${devices2}
1968 }
1969
1970 # Originally, root mount hold had to be released before mounting
1971 # the root filesystem.  This delayed the boot, so it was changed
1972 # to only wait if the root device isn't readily available.  This
1973 # can result in rc scripts executing before all the devices - such
1974 # as graid(8), or USB disks - can be accessed.  This function can
1975 # be used to explicitly wait for root mount holds to be released.
1976 root_hold_wait()
1977 {
1978         local wait waited holders
1979
1980         waited=0
1981         while true; do
1982                 holders="$(sysctl -n vfs.root_mount_hold)"
1983                 if [ -z "${holders}" ]; then
1984                         break;
1985                 fi
1986                 if [ ${waited} -eq 0 ]; then
1987                         echo -n "Waiting ${root_hold_delay}s" \
1988                         "for the root mount holders: ${holders}"
1989                 else
1990                         echo -n .
1991                 fi
1992                 if [ ${waited} -ge ${root_hold_delay} ]; then
1993                         echo
1994                         break
1995                 fi
1996                 sleep 1
1997                 waited=$(($waited + 1))
1998         done
1999 }
2000
2001 # Find scripts in local_startup directories that use the old syntax
2002 #
2003 find_local_scripts_old() {
2004         zlist=''
2005         slist=''
2006         for dir in ${local_startup}; do
2007                 if [ -d "${dir}" ]; then
2008                         for file in ${dir}/[0-9]*.sh; do
2009                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2010                                     continue
2011                                 zlist="$zlist $file"
2012                         done
2013                         for file in ${dir}/[!0-9]*.sh; do
2014                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2015                                     continue
2016                                 slist="$slist $file"
2017                         done
2018                 fi
2019         done
2020 }
2021
2022 find_local_scripts_new() {
2023         local_rc=''
2024         for dir in ${local_startup}; do
2025                 if [ -d "${dir}" ]; then
2026                         for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
2027                                 case "$file" in
2028                                 *.sample) ;;
2029                                 *)      if [ -x "$file" ]; then
2030                                                 local_rc="${local_rc} ${file}"
2031                                         fi
2032                                         ;;
2033                                 esac
2034                         done
2035                 fi
2036         done
2037 }
2038
2039 # check_required_{before|after} command
2040 #       Check for things required by the command before and after its precmd,
2041 #       respectively.  The two separate functions are needed because some
2042 #       conditions should prevent precmd from being run while other things
2043 #       depend on precmd having already been run.
2044 #
2045 check_required_before()
2046 {
2047         local _f
2048
2049         case "$1" in
2050         start)
2051                 for _f in $required_vars; do
2052                         if ! checkyesno $_f; then
2053                                 warn "\$${_f} is not enabled."
2054                                 if [ -z "$rc_force" ]; then
2055                                         return 1
2056                                 fi
2057                         fi
2058                 done
2059
2060                 for _f in $required_dirs; do
2061                         if [ ! -d "${_f}/." ]; then
2062                                 warn "${_f} is not a directory."
2063                                 if [ -z "$rc_force" ]; then
2064                                         return 1
2065                                 fi
2066                         fi
2067                 done
2068
2069                 for _f in $required_files; do
2070                         if [ ! -r "${_f}" ]; then
2071                                 warn "${_f} is not readable."
2072                                 if [ -z "$rc_force" ]; then
2073                                         return 1
2074                                 fi
2075                         fi
2076                 done
2077                 ;;
2078         esac
2079
2080         return 0
2081 }
2082
2083 check_required_after()
2084 {
2085         local _f _args
2086
2087         case "$1" in
2088         start)
2089                 for _f in $required_modules; do
2090                         case "${_f}" in
2091                                 *~*)    _args="-e ${_f#*~} ${_f%%~*}" ;;
2092                                 *:*)    _args="-m ${_f#*:} ${_f%%:*}" ;;
2093                                 *)      _args="${_f}" ;;
2094                         esac
2095                         if ! load_kld ${_args}; then
2096                                 if [ -z "$rc_force" ]; then
2097                                         return 1
2098                                 fi
2099                         fi
2100                 done
2101                 ;;
2102         esac
2103
2104         return 0
2105 }
2106
2107 # check_jail mib
2108 #       Return true if security.jail.$mib exists and set to 1.
2109
2110 check_jail()
2111 {
2112         local _mib _v
2113
2114         _mib=$1
2115         if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2116                 case $_v in
2117                 1)      return 0;;
2118                 esac
2119         fi
2120         return 1
2121 }
2122
2123 # check_kern_features mib
2124 #       Return existence of kern.features.* sysctl MIB as true or
2125 #       false.  The result will be cached in $_rc_cache_kern_features_
2126 #       namespace.  "0" means the kern.features.X exists.
2127
2128 check_kern_features()
2129 {
2130         local _v
2131
2132         [ -n "$1" ] || return 1;
2133         eval _v=\$_rc_cache_kern_features_$1
2134         [ -n "$_v" ] && return "$_v";
2135
2136         if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2137                 eval _rc_cache_kern_features_$1=0
2138                 return 0
2139         else
2140                 eval _rc_cache_kern_features_$1=1
2141                 return 1
2142         fi
2143 }
2144
2145 # check_namevarlist var
2146 #       Return "0" if ${name}_var is reserved in rc.subr.
2147
2148 _rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend"
2149 check_namevarlist()
2150 {
2151         local _v
2152
2153         for _v in $_rc_namevarlist; do
2154         case $1 in
2155         $_v)    return 0 ;;
2156         esac
2157         done
2158
2159         return 1
2160 }
2161
2162 # _echoonce var msg mode
2163 #       mode=0: Echo $msg if ${$var} is empty.
2164 #               After doing echo, a string is set to ${$var}.
2165 #
2166 #       mode=1: Echo $msg if ${$var} is a string with non-zero length.
2167 #
2168 _echoonce()
2169 {
2170         local _var _msg _mode
2171         eval _var=\$$1
2172         _msg=$2
2173         _mode=$3
2174
2175         case $_mode in
2176         1)      [ -n "$_var" ] && echo "$_msg" ;;
2177         *)      [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2178         esac
2179 }
2180
2181 # If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2182 # still override this, but /etc/defaults/rc.conf can't unconditionally set this
2183 # since it would undo what we've done here.
2184 if kenv -q rc.debug > /dev/null ; then
2185         rc_debug=YES
2186 fi