]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - libexec/rc/rc.subr
MFC r351863:
[FreeBSD/FreeBSD.git] / libexec / rc / 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}_env_file n      File to source variables to run ${command} with.
766 #
767 #       ${name}_fib     n       Routing table number to run ${command} with.
768 #
769 #       ${name}_nice    n       Nice level to run ${command} at.
770 #
771 #       ${name}_oomprotect n    Don't kill ${command} when swap space is exhausted.
772 #
773 #       ${name}_user    n       User to run ${command} as, using su(1) if not
774 #                               using ${name}_chroot.
775 #                               Requires /usr to be mounted.
776 #
777 #       ${name}_group   n       Group to run chrooted ${command} as.
778 #                               Requires /usr to be mounted.
779 #
780 #       ${name}_groups  n       Comma separated list of supplementary groups
781 #                               to run the chrooted ${command} with.
782 #                               Requires /usr to be mounted.
783 #
784 #       ${name}_prepend n       Command added before ${command}.
785 #
786 #       ${name}_login_class n   Login class to use, else "daemon".
787 #
788 #       ${name}_limits  n       limits(1) to apply to ${command}.
789 #
790 #       ${rc_arg}_cmd   n       If set, use this as the method when invoked;
791 #                               Otherwise, use default command (see below)
792 #
793 #       ${rc_arg}_precmd n      If set, run just before performing the
794 #                               ${rc_arg}_cmd method in the default
795 #                               operation (i.e, after checking for required
796 #                               bits and process (non)existence).
797 #                               If this completes with a non-zero exit code,
798 #                               don't run ${rc_arg}_cmd.
799 #
800 #       ${rc_arg}_postcmd n     If set, run just after performing the
801 #                               ${rc_arg}_cmd method, if that method
802 #                               returned a zero exit code.
803 #
804 #       required_dirs   n       If set, check for the existence of the given
805 #                               directories before running a (re)start command.
806 #
807 #       required_files  n       If set, check for the readability of the given
808 #                               files before running a (re)start command.
809 #
810 #       required_modules n      If set, ensure the given kernel modules are
811 #                               loaded before running a (re)start command.
812 #                               The check and possible loads are actually
813 #                               done after start_precmd so that the modules
814 #                               aren't loaded in vain, should the precmd
815 #                               return a non-zero status to indicate a error.
816 #                               If a word in the list looks like "foo:bar",
817 #                               "foo" is the KLD file name and "bar" is the
818 #                               module name.  If a word looks like "foo~bar",
819 #                               "foo" is the KLD file name and "bar" is a
820 #                               egrep(1) pattern matching the module name.
821 #                               Otherwise the module name is assumed to be
822 #                               the same as the KLD file name, which is most
823 #                               common.  See load_kld().
824 #
825 #       required_vars   n       If set, perform checkyesno on each of the
826 #                               listed variables before running the default
827 #                               (re)start command.
828 #
829 #       Default behaviour for a given argument, if no override method is
830 #       provided:
831 #
832 #       Argument        Default behaviour
833 #       --------        -----------------
834 #       start           if !running && checkyesno ${rcvar}
835 #                               ${command}
836 #
837 #       stop            if ${pidfile}
838 #                               rc_pid=$(check_pidfile $pidfile $command)
839 #                       else
840 #                               rc_pid=$(check_process $command)
841 #                       kill $sig_stop $rc_pid
842 #                       wait_for_pids $rc_pid
843 #                       ($sig_stop defaults to TERM.)
844 #
845 #       reload          Similar to stop, except use $sig_reload instead,
846 #                       and doesn't wait_for_pids.
847 #                       $sig_reload defaults to HUP.
848 #                       Note that `reload' isn't provided by default,
849 #                       it should be enabled via $extra_commands.
850 #
851 #       restart         Run `stop' then `start'.
852 #
853 #       status          Show if ${command} is running, etc.
854 #
855 #       poll            Wait for ${command} to exit.
856 #
857 #       rcvar           Display what rc.conf variable is used (if any).
858 #
859 #       enabled         Return true if the service is enabled.
860 #
861 #       describe        Show the service's description
862 #
863 #       extracommands   Show the service's extra commands
864 #
865 #       Variables available to methods, and after run_rc_command() has
866 #       completed:
867 #
868 #       Variable        Purpose
869 #       --------        -------
870 #       rc_arg          Argument to command, after fast/force/one processing
871 #                       performed
872 #
873 #       rc_flags        Flags to start the default command with.
874 #                       Defaults to ${name}_flags, unless overridden
875 #                       by $flags from the environment.
876 #                       This variable may be changed by the precmd method.
877 #
878 #       rc_service      Path to the service being executed, in case the service
879 #                       needs to re-invoke itself.
880 #
881 #       rc_pid          PID of command (if appropriate)
882 #
883 #       rc_fast         Not empty if "fast" was provided (q.v.)
884 #
885 #       rc_force        Not empty if "force" was provided (q.v.)
886 #
887 #       rc_quiet        Not empty if "quiet" was provided
888 #
889 #
890 run_rc_command()
891 {
892         _return=0
893         rc_arg=$1
894         if [ -z "$name" ]; then
895                 err 3 'run_rc_command: $name is not set.'
896         fi
897
898         # Don't repeat the first argument when passing additional command-
899         # line arguments to the command subroutines.
900         #
901         shift 1
902         rc_extra_args="$*"
903
904         _rc_prefix=
905         case "$rc_arg" in
906         fast*)                          # "fast" prefix; don't check pid
907                 rc_arg=${rc_arg#fast}
908                 rc_fast=yes
909                 rc_quiet=yes
910                 ;;
911         force*)                         # "force" prefix; always run
912                 rc_force=yes
913                 _rc_prefix=force
914                 rc_arg=${rc_arg#${_rc_prefix}}
915                 if [ -n "${rcvar}" ]; then
916                         eval ${rcvar}=YES
917                 fi
918                 ;;
919         one*)                           # "one" prefix; set ${rcvar}=yes
920                 _rc_prefix=one
921                 rc_arg=${rc_arg#${_rc_prefix}}
922                 if [ -n "${rcvar}" ]; then
923                         eval ${rcvar}=YES
924                 fi
925                 ;;
926         quiet*)                         # "quiet" prefix; omit some messages
927                 _rc_prefix=quiet
928                 rc_arg=${rc_arg#${_rc_prefix}}
929                 rc_quiet=yes
930                 ;;
931         esac
932
933         eval _override_command=\$${name}_program
934         command=${_override_command:-$command}
935
936         _keywords="start stop restart rcvar enable disable delete enabled describe extracommands $extra_commands"
937         rc_pid=
938         _pidcmd=
939         _procname=${procname:-${command}}
940
941                                         # setup pid check command
942         if [ -n "$_procname" ]; then
943                 if [ -n "$pidfile" ]; then
944                         _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
945                 else
946                         _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
947                 fi
948                 _keywords="${_keywords} status poll"
949         fi
950
951         if [ -z "$rc_arg" ]; then
952                 rc_usage $_keywords
953         fi
954
955         if [ "$rc_arg" = "enabled" ] ; then
956                 checkyesno ${rcvar}
957                 return $?
958         fi
959
960         if [ -n "$flags" ]; then        # allow override from environment
961                 rc_flags=$flags
962         else
963                 eval rc_flags=\$${name}_flags
964         fi
965         eval _chdir=\$${name}_chdir     _chroot=\$${name}_chroot \
966             _nice=\$${name}_nice        _user=\$${name}_user \
967             _group=\$${name}_group      _groups=\$${name}_groups \
968             _fib=\$${name}_fib          _env=\$${name}_env \
969             _prepend=\$${name}_prepend  _login_class=\${${name}_login_class:-daemon} \
970             _limits=\$${name}_limits    _oomprotect=\$${name}_oomprotect \
971             _env_file=\$${name}_env_file
972
973         if [ -n "$_env_file" ] && [ -r "${_env_file}" ]; then   # load env from file
974                 set -a
975                 . $_env_file
976                 set +a
977         fi
978
979         if [ -n "$_user" ]; then        # unset $_user if running as that user
980                 if [ "$_user" = "$(eval $IDCMD)" ]; then
981                         unset _user
982                 fi
983         fi
984
985         [ -z "$autoboot" ] && eval $_pidcmd     # determine the pid if necessary
986
987         for _elem in $_keywords; do
988                 if [ "$_elem" != "$rc_arg" ]; then
989                         continue
990                 fi
991                                         # if ${rcvar} is set, $1 is not "rcvar", "describe",
992                                         # "enable" or "delete", and ${rc_pid} is not set, run:
993                                         #       checkyesno ${rcvar}
994                                         # and return if that failed
995                                         #
996                 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a "$rc_arg" != "stop" \
997                     -a "$rc_arg" != "delete" -a "$rc_arg" != "enable" \
998                     -a "$rc_arg" != "describe" ] ||
999                     [ -n "${rcvar}" -a "$rc_arg" = "stop" -a -z "${rc_pid}" ]; then
1000                         if ! checkyesno ${rcvar}; then
1001                                 if [ -n "${rc_quiet}" ]; then
1002                                         return 0
1003                                 fi
1004                                 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
1005                                 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
1006                                 echo "instead of '${rc_arg}'."
1007                                 return 0
1008                         fi
1009                 fi
1010
1011                 if [ $rc_arg = "start" -a -z "$rc_fast" -a -n "$rc_pid" ]; then
1012                         if [ -z "$rc_quiet" ]; then
1013                                 echo 1>&2 "${name} already running? " \
1014                                     "(pid=$rc_pid)."
1015                         fi
1016                         return 1
1017                 fi
1018
1019                                         # if there's a custom ${XXX_cmd},
1020                                         # run that instead of the default
1021                                         #
1022                 eval _cmd=\$${rc_arg}_cmd \
1023                      _precmd=\$${rc_arg}_precmd \
1024                      _postcmd=\$${rc_arg}_postcmd
1025
1026                 if [ -n "$_cmd" ]; then
1027                         if [ -n "$_env" ]; then
1028                                 eval "export -- $_env"
1029                         fi
1030                         _run_rc_precmd || return 1
1031                         _run_rc_doit "$_cmd $rc_extra_args" || return 1
1032                         _run_rc_postcmd
1033                         return $_return
1034                 fi
1035
1036                 case "$rc_arg" in       # default operations...
1037
1038                 describe)
1039                         if [ -n "$desc" ]; then
1040                                 echo "$desc"
1041                         fi
1042                         ;;
1043         
1044                 extracommands)
1045                         echo "$extra_commands"
1046                         ;;
1047
1048                 enable)
1049                         _out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=YES") &&
1050                                 echo "$name enabled in ${_out%%:*}"     
1051                         ;;
1052
1053                 disable)
1054                         _out=$(/usr/sbin/sysrc -vs "$name" "$rcvar=NO") &&
1055                                 echo "$name disabled in ${_out%%:*}"    
1056                         ;;
1057
1058                 delete)
1059                         _files=
1060                         for _file in $(sysrc -lEs "$name"); do
1061                                 _out=$(sysrc -Fif $_file "$rcvar") && _files="$_files $_file"
1062                         done
1063                         /usr/sbin/sysrc -x "$rcvar" && echo "$rcvar deleted in ${_files# }"
1064                                 # delete file in rc.conf.d if desired and empty.
1065                         checkyesno service_delete_empty || _files=
1066                         for _file in $_files; do
1067                                 [ "$_file" = "${_file#*/rc.conf.d/}" ] && continue
1068                                 [ $(/usr/bin/stat -f%z $_file) -gt 0 ] && continue
1069                                 /bin/rm "$_file" && echo "Empty file $_file removed"
1070                         done
1071                         ;;
1072
1073                 status)
1074                         _run_rc_precmd || return 1
1075                         if [ -n "$rc_pid" ]; then
1076                                 echo "${name} is running as pid $rc_pid."
1077                         else
1078                                 echo "${name} is not running."
1079                                 return 1
1080                         fi
1081                         _run_rc_postcmd
1082                         ;;
1083
1084                 start)
1085                         if [ ! -x "${_chroot}${_chroot:+/}${command}" ]; then
1086                                 warn "run_rc_command: cannot run $command"
1087                                 return 1
1088                         fi
1089
1090                         if ! _run_rc_precmd; then
1091                                 warn "failed precmd routine for ${name}"
1092                                 return 1
1093                         fi
1094
1095                                         # setup the full command to run
1096                                         #
1097                         check_startmsgs && echo "Starting ${name}."
1098                         if [ -n "$_chroot" ]; then
1099                                 _cd=
1100                                 _doit="\
1101 ${_nice:+nice -n $_nice }\
1102 ${_fib:+setfib -F $_fib }\
1103 ${_env:+env $_env }\
1104 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
1105 $_chroot $command $rc_flags $command_args"
1106                         else
1107                                 _cd="${_chdir:+cd $_chdir && }"
1108                                 _doit="\
1109 ${_fib:+setfib -F $_fib }\
1110 ${_env:+env $_env }\
1111 $command $rc_flags $command_args"
1112                                 if [ -n "$_user" ]; then
1113                                     _doit="su -m $_user -c 'sh -c \"$_doit\"'"
1114                                 fi
1115                                 if [ -n "$_nice" ]; then
1116                                         if [ -z "$_user" ]; then
1117                                                 _doit="sh -c \"$_doit\""
1118                                         fi
1119                                         _doit="nice -n $_nice $_doit"
1120                                 fi
1121                                 if [ -n "$_prepend" ]; then
1122                                         _doit="$_prepend $_doit"
1123                                 fi
1124                         fi
1125
1126                                         # Prepend default limits
1127                         _doit="$_cd limits -C $_login_class $_limits $_doit"
1128
1129                                         # run the full command
1130                                         #
1131                         if ! _run_rc_doit "$_doit"; then
1132                                 warn "failed to start ${name}"
1133                                 return 1
1134                         fi
1135
1136                                         # finally, run postcmd
1137                                         #
1138                         _run_rc_postcmd
1139                         ;;
1140
1141                 stop)
1142                         if [ -z "$rc_pid" ]; then
1143                                 [ -n "$rc_fast" ] && return 0
1144                                 _run_rc_notrunning
1145                                 return 1
1146                         fi
1147
1148                         _run_rc_precmd || return 1
1149
1150                                         # send the signal to stop
1151                                         #
1152                         echo "Stopping ${name}."
1153                         _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
1154                         _run_rc_doit "$_doit" || return 1
1155
1156                                         # wait for the command to exit,
1157                                         # and run postcmd.
1158                         wait_for_pids $rc_pid
1159
1160                         _run_rc_postcmd
1161                         ;;
1162
1163                 reload)
1164                         if [ -z "$rc_pid" ]; then
1165                                 _run_rc_notrunning
1166                                 return 1
1167                         fi
1168
1169                         _run_rc_precmd || return 1
1170
1171                         _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
1172                         _run_rc_doit "$_doit" || return 1
1173
1174                         _run_rc_postcmd
1175                         ;;
1176
1177                 restart)
1178                                         # prevent restart being called more
1179                                         # than once by any given script
1180                                         #
1181                         if ${_rc_restart_done:-false}; then
1182                                 return 0
1183                         fi
1184                         _rc_restart_done=true
1185
1186                         _run_rc_precmd || return 1
1187
1188                         # run those in a subshell to keep global variables
1189                         ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
1190                         ( run_rc_command ${_rc_prefix}start $rc_extra_args )
1191                         _return=$?
1192                         [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
1193
1194                         _run_rc_postcmd
1195                         ;;
1196
1197                 poll)
1198                         _run_rc_precmd || return 1
1199                         if [ -n "$rc_pid" ]; then
1200                                 wait_for_pids $rc_pid
1201                         fi
1202                         _run_rc_postcmd
1203                         ;;
1204
1205                 rcvar)
1206                         echo -n "# $name"
1207                         if [ -n "$desc" ]; then
1208                                 echo " : $desc"
1209                         else
1210                                 echo ""
1211                         fi
1212                         echo "#"
1213                         # Get unique vars in $rcvar $rcvars
1214                         for _v in $rcvar $rcvars; do
1215                                 case $v in
1216                                 $_v\ *|\ *$_v|*\ $_v\ *) ;;
1217                                 *)      v="${v# } $_v" ;;
1218                                 esac
1219                         done
1220
1221                         # Display variables.
1222                         for _v in $v; do
1223                                 if [ -z "$_v" ]; then
1224                                         continue
1225                                 fi
1226
1227                                 eval _desc=\$${_v}_desc
1228                                 eval _defval=\$${_v}_defval
1229                                 _h="-"
1230
1231                                 eval echo \"$_v=\\\"\$$_v\\\"\"
1232                                 # decode multiple lines of _desc
1233                                 while [ -n "$_desc" ]; do
1234                                         case $_desc in
1235                                         *^^*)
1236                                                 echo "# $_h ${_desc%%^^*}"
1237                                                 _desc=${_desc#*^^}
1238                                                 _h=" "
1239                                                 ;;
1240                                         *)
1241                                                 echo "# $_h ${_desc}"
1242                                                 break
1243                                                 ;;
1244                                         esac
1245                                 done
1246                                 echo "#   (default: \"$_defval\")"
1247                         done
1248                         echo ""
1249                         ;;
1250
1251                 *)
1252                         rc_usage $_keywords
1253                         ;;
1254
1255                 esac
1256
1257                 # Apply protect(1) to the PID if ${name}_oomprotect is set.
1258                 case "$rc_arg" in
1259                 start)
1260                         # We cannot use protect(1) inside jails.
1261                         if [ -n "$_oomprotect" ] && [ -f "${PROTECT}" ] &&
1262                             [ "$(sysctl -n security.jail.jailed)" -eq 0 ]; then
1263                                 pid=$(check_process $command)
1264                                 case $_oomprotect in
1265                                 [Aa][Ll][Ll])
1266                                         ${PROTECT} -i -p ${pid}
1267                                         ;;
1268                                 [Yy][Ee][Ss])
1269                                         ${PROTECT} -p ${pid}
1270                                         ;;
1271                                 esac
1272                         fi
1273                 ;;
1274                 esac
1275
1276                 return $_return
1277         done
1278
1279         echo 1>&2 "$0: unknown directive '$rc_arg'."
1280         rc_usage $_keywords
1281         # not reached
1282 }
1283
1284 #
1285 # Helper functions for run_rc_command: common code.
1286 # They use such global variables besides the exported rc_* ones:
1287 #
1288 #       name           R/W
1289 #       ------------------
1290 #       _precmd         R
1291 #       _postcmd        R
1292 #       _return         W
1293 #
1294 _run_rc_precmd()
1295 {
1296         check_required_before "$rc_arg" || return 1
1297
1298         if [ -n "$_precmd" ]; then
1299                 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
1300                 eval "$_precmd $rc_extra_args"
1301                 _return=$?
1302
1303                 # If precmd failed and force isn't set, request exit.
1304                 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1305                         return 1
1306                 fi
1307         fi
1308
1309         check_required_after "$rc_arg" || return 1
1310
1311         return 0
1312 }
1313
1314 _run_rc_postcmd()
1315 {
1316         if [ -n "$_postcmd" ]; then
1317                 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
1318                 eval "$_postcmd $rc_extra_args"
1319                 _return=$?
1320         fi
1321         return 0
1322 }
1323
1324 _run_rc_doit()
1325 {
1326         debug "run_rc_command: doit: $*"
1327         eval "$@"
1328         _return=$?
1329
1330         # If command failed and force isn't set, request exit.
1331         if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
1332                 return 1
1333         fi
1334
1335         return 0
1336 }
1337
1338 _run_rc_notrunning()
1339 {
1340         local _pidmsg
1341
1342         if [ -n "$pidfile" ]; then
1343                 _pidmsg=" (check $pidfile)."
1344         else
1345                 _pidmsg=
1346         fi
1347         echo 1>&2 "${name} not running?${_pidmsg}"
1348 }
1349
1350 _run_rc_killcmd()
1351 {
1352         local _cmd
1353
1354         _cmd="kill -$1 $rc_pid"
1355         if [ -n "$_user" ]; then
1356                 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
1357         fi
1358         echo "$_cmd"
1359 }
1360
1361 #
1362 # run_rc_script file arg
1363 #       Start the script `file' with `arg', and correctly handle the
1364 #       return value from the script.
1365 #       If `file' ends with `.sh' and lives in /etc/rc.d, ignore it as it's
1366 #       an old-style startup file.
1367 #       If `file' ends with `.sh' and does not live in /etc/rc.d, it's sourced
1368 #       into the current environment if $rc_fast_and_loose is set; otherwise
1369 #       it is run as a child process.
1370 #       If `file' appears to be a backup or scratch file, ignore it.
1371 #       Otherwise if it is executable run as a child process.
1372 #
1373 run_rc_script()
1374 {
1375         _file=$1
1376         _arg=$2
1377         if [ -z "$_file" -o -z "$_arg" ]; then
1378                 err 3 'USAGE: run_rc_script file arg'
1379         fi
1380
1381         unset   name command command_args command_interpreter \
1382                 extra_commands pidfile procname \
1383                 rcvar rcvars rcvars_obsolete required_dirs required_files \
1384                 required_vars
1385         eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
1386
1387         rc_service="$_file"
1388         case "$_file" in
1389         /etc/rc.d/*.sh)                 # no longer allowed in the base
1390                 warn "Ignoring old-style startup script $_file"
1391                 ;;
1392         *[~#]|*.OLD|*.bak|*.orig|*,v)   # scratch file; skip
1393                 warn "Ignoring scratch file $_file"
1394                 ;;
1395         *)                              # run in subshell
1396                 if [ -x $_file ]; then
1397                         if [ -n "$rc_fast_and_loose" ]; then
1398                                 set $_arg; . $_file
1399                         else
1400                                 ( trap "echo Script $_file interrupted >&2 ; kill -QUIT $$" 3
1401                                   trap "echo Script $_file interrupted >&2 ; exit 1" 2
1402                                   trap "echo Script $_file running >&2" 29
1403                                   set $_arg; . $_file )
1404                         fi
1405                 fi
1406                 ;;
1407         esac
1408 }
1409
1410 #
1411 # load_rc_config [service]
1412 #       Source in the configuration file(s) for a given service.
1413 #       If no service is specified, only the global configuration
1414 #       file(s) will be loaded.
1415 #
1416 load_rc_config()
1417 {
1418         local _name _rcvar_val _var _defval _v _msg _new _d
1419         _name=$1
1420
1421         if ${_rc_conf_loaded:-false}; then
1422                 :
1423         else
1424                 if [ -r /etc/defaults/rc.conf ]; then
1425                         debug "Sourcing /etc/defaults/rc.conf"
1426                         . /etc/defaults/rc.conf
1427                         source_rc_confs
1428                 elif [ -r /etc/rc.conf ]; then
1429                         debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1430                         . /etc/rc.conf
1431                 fi
1432                 _rc_conf_loaded=true
1433         fi
1434
1435         # If a service name was specified, attempt to load
1436         # service-specific configuration
1437         if [ -n "$_name" ] ; then
1438                 for _d in /etc ${local_startup}; do
1439                         _d=${_d%/rc.d}
1440                         if [ -f ${_d}/rc.conf.d/"$_name" ]; then
1441                                 debug "Sourcing ${_d}/rc.conf.d/$_name"
1442                                 . ${_d}/rc.conf.d/"$_name"
1443                         elif [ -d ${_d}/rc.conf.d/"$_name" ] ; then
1444                                 local _rc
1445                                 for _rc in ${_d}/rc.conf.d/"$_name"/* ; do
1446                                         if [ -f "$_rc" ] ; then
1447                                                 debug "Sourcing $_rc"
1448                                                 . "$_rc"
1449                                         fi
1450                                 done
1451                         fi
1452                 done
1453         fi
1454
1455         # Set defaults if defined.
1456         for _var in $rcvar $rcvars; do
1457                 eval _defval=\$${_var}_defval
1458                 if [ -n "$_defval" ]; then
1459                         eval : \${$_var:=\$${_var}_defval}
1460                 fi
1461         done
1462
1463         # check obsolete rc.conf variables
1464         for _var in $rcvars_obsolete; do
1465                 eval _v=\$$_var
1466                 eval _msg=\$${_var}_obsolete_msg
1467                 eval _new=\$${_var}_newvar
1468                 case $_v in
1469                 "")
1470                         ;;
1471                 *)
1472                         if [ -z "$_new" ]; then
1473                                 _msg="Ignored."
1474                         else
1475                                 eval $_new=\"\$$_var\"
1476                                 if [ -z "$_msg" ]; then
1477                                         _msg="Use \$$_new instead."
1478                                 fi
1479                         fi
1480                         warn "\$$_var is obsolete.  $_msg"
1481                         ;;
1482                 esac
1483         done
1484 }
1485
1486 #
1487 # load_rc_config_var name var
1488 #       Read the rc.conf(5) var for name and set in the
1489 #       current shell, using load_rc_config in a subshell to prevent
1490 #       unwanted side effects from other variable assignments.
1491 #
1492 load_rc_config_var()
1493 {
1494         if [ $# -ne 2 ]; then
1495                 err 3 'USAGE: load_rc_config_var name var'
1496         fi
1497         eval $(eval '(
1498                 load_rc_config '$1' >/dev/null;
1499                 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1500                         echo '$2'=\'\''${'$2'}\'\'';
1501                 fi
1502         )' )
1503 }
1504
1505 #
1506 # rc_usage commands
1507 #       Print a usage string for $0, with `commands' being a list of
1508 #       valid commands.
1509 #
1510 rc_usage()
1511 {
1512         echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1513
1514         _sep=
1515         for _elem; do
1516                 echo -n 1>&2 "$_sep$_elem"
1517                 _sep="|"
1518         done
1519         echo 1>&2 ")"
1520         exit 1
1521 }
1522
1523 #
1524 # err exitval message
1525 #       Display message to stderr and log to the syslog, and exit with exitval.
1526 #
1527 err()
1528 {
1529         exitval=$1
1530         shift
1531
1532         if [ -x /usr/bin/logger ]; then
1533                 logger "$0: ERROR: $*"
1534         fi
1535         echo 1>&2 "$0: ERROR: $*"
1536         exit $exitval
1537 }
1538
1539 #
1540 # warn message
1541 #       Display message to stderr and log to the syslog.
1542 #
1543 warn()
1544 {
1545         if [ -x /usr/bin/logger ]; then
1546                 logger "$0: WARNING: $*"
1547         fi
1548         echo 1>&2 "$0: WARNING: $*"
1549 }
1550
1551 #
1552 # info message
1553 #       Display informational message to stdout and log to syslog.
1554 #
1555 info()
1556 {
1557         case ${rc_info} in
1558         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1559                 if [ -x /usr/bin/logger ]; then
1560                         logger "$0: INFO: $*"
1561                 fi
1562                 echo "$0: INFO: $*"
1563                 ;;
1564         esac
1565 }
1566
1567 #
1568 # debug message
1569 #       If debugging is enabled in rc.conf output message to stderr.
1570 #       BEWARE that you don't call any subroutine that itself calls this
1571 #       function.
1572 #
1573 debug()
1574 {
1575         case ${rc_debug} in
1576         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1577                 if [ -x /usr/bin/logger ]; then
1578                         logger "$0: DEBUG: $*"
1579                 fi
1580                 echo 1>&2 "$0: DEBUG: $*"
1581                 ;;
1582         esac
1583 }
1584
1585 #
1586 # backup_file action file cur backup
1587 #       Make a backup copy of `file' into `cur', and save the previous
1588 #       version of `cur' as `backup'.
1589 #
1590 #       The `action' keyword can be one of the following:
1591 #
1592 #       add             `file' is now being backed up (and is possibly
1593 #                       being reentered into the backups system).  `cur'
1594 #                       is created.
1595 #
1596 #       update          `file' has changed and needs to be backed up.
1597 #                       If `cur' exists, it is copied to `back'
1598 #                       and then `file' is copied to `cur'.
1599 #
1600 #       remove          `file' is no longer being tracked by the backups
1601 #                       system.  `cur' is moved `back'.
1602 #
1603 #
1604 backup_file()
1605 {
1606         _action=$1
1607         _file=$2
1608         _cur=$3
1609         _back=$4
1610
1611         case $_action in
1612         add|update)
1613                 if [ -f $_cur ]; then
1614                         cp -p $_cur $_back
1615                 fi
1616                 cp -p $_file $_cur
1617                 chown root:wheel $_cur
1618                 ;;
1619         remove)
1620                 mv -f $_cur $_back
1621                 ;;
1622         esac
1623 }
1624
1625 # make_symlink src link
1626 #       Make a symbolic link 'link' to src from basedir. If the
1627 #       directory in which link is to be created does not exist
1628 #       a warning will be displayed and an error will be returned.
1629 #       Returns 0 on success, 1 otherwise.
1630 #
1631 make_symlink()
1632 {
1633         local src link linkdir _me
1634         src="$1"
1635         link="$2"
1636         linkdir="`dirname $link`"
1637         _me="make_symlink()"
1638
1639         if [ -z "$src" -o -z "$link" ]; then
1640                 warn "$_me: requires two arguments."
1641                 return 1
1642         fi
1643         if [ ! -d "$linkdir" ]; then
1644                 warn "$_me: the directory $linkdir does not exist."
1645                 return 1
1646         fi
1647         if ! ln -sf $src $link; then
1648                 warn "$_me: unable to make a symbolic link from $link to $src"
1649                 return 1
1650         fi
1651         return 0
1652 }
1653
1654 # devfs_rulesets_from_file file
1655 #       Reads a set of devfs commands from file, and creates
1656 #       the specified rulesets with their rules. Returns non-zero
1657 #       if there was an error.
1658 #
1659 devfs_rulesets_from_file()
1660 {
1661         local file _err _me _opts
1662         file="$1"
1663         _me="devfs_rulesets_from_file"
1664         _err=0
1665
1666         if [ -z "$file" ]; then
1667                 warn "$_me: you must specify a file"
1668                 return 1
1669         fi
1670         if [ ! -e "$file" ]; then
1671                 debug "$_me: no such file ($file)"
1672                 return 0
1673         fi
1674
1675         # Disable globbing so that the rule patterns are not expanded
1676         # by accident with matching filesystem entries.
1677         _opts=$-; set -f
1678
1679         debug "reading rulesets from file ($file)"
1680         { while read line
1681         do
1682                 case $line in
1683                 \#*)
1684                         continue
1685                         ;;
1686                 \[*\]*)
1687                         rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1688                         if [ -z "$rulenum" ]; then
1689                                 warn "$_me: cannot extract rule number ($line)"
1690                                 _err=1
1691                                 break
1692                         fi
1693                         rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1694                         if [ -z "$rulename" ]; then
1695                                 warn "$_me: cannot extract rule name ($line)"
1696                                 _err=1
1697                                 break;
1698                         fi
1699                         eval $rulename=\$rulenum
1700                         debug "found ruleset: $rulename=$rulenum"
1701                         if ! /sbin/devfs rule -s $rulenum delset; then
1702                                 _err=1
1703                                 break
1704                         fi
1705                         ;;
1706                 *)
1707                         rulecmd="${line%%"\#*"}"
1708                         # evaluate the command incase it includes
1709                         # other rules
1710                         if [ -n "$rulecmd" ]; then
1711                                 debug "adding rule ($rulecmd)"
1712                                 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1713                                 then
1714                                         _err=1
1715                                         break
1716                                 fi
1717                         fi
1718                         ;;
1719                 esac
1720                 if [ $_err -ne 0 ]; then
1721                         debug "error in $_me"
1722                         break
1723                 fi
1724         done } < $file
1725         case $_opts in *f*) ;; *) set +f ;; esac
1726         return $_err
1727 }
1728
1729 # devfs_init_rulesets
1730 #       Initializes rulesets from configuration files. Returns
1731 #       non-zero if there was an error.
1732 #
1733 devfs_init_rulesets()
1734 {
1735         local file _me
1736         _me="devfs_init_rulesets"
1737
1738         # Go through this only once
1739         if [ -n "$devfs_rulesets_init" ]; then
1740                 debug "$_me: devfs rulesets already initialized"
1741                 return
1742         fi
1743         for file in $devfs_rulesets; do
1744                 if ! devfs_rulesets_from_file $file; then
1745                         warn "$_me: could not read rules from $file"
1746                         return 1
1747                 fi
1748         done
1749         devfs_rulesets_init=1
1750         debug "$_me: devfs rulesets initialized"
1751         return 0
1752 }
1753
1754 # devfs_set_ruleset ruleset [dir]
1755 #       Sets the default ruleset of dir to ruleset. The ruleset argument
1756 #       must be a ruleset name as specified in devfs.rules(5) file.
1757 #       Returns non-zero if it could not set it successfully.
1758 #
1759 devfs_set_ruleset()
1760 {
1761         local devdir rs _me
1762         [ -n "$1" ] && eval rs=\$$1 || rs=
1763         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1764         _me="devfs_set_ruleset"
1765
1766         if [ -z "$rs" ]; then
1767                 warn "$_me: you must specify a ruleset number"
1768                 return 1
1769         fi
1770         debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1771         if ! /sbin/devfs $devdir ruleset $rs; then
1772                 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1773                 return 1
1774         fi
1775         return 0
1776 }
1777
1778 # devfs_apply_ruleset ruleset [dir]
1779 #       Apply ruleset number $ruleset to the devfs mountpoint $dir.
1780 #       The ruleset argument must be a ruleset name as specified
1781 #       in a devfs.rules(5) file.  Returns 0 on success or non-zero
1782 #       if it could not apply the ruleset.
1783 #
1784 devfs_apply_ruleset()
1785 {
1786         local devdir rs _me
1787         [ -n "$1" ] && eval rs=\$$1 || rs=
1788         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1789         _me="devfs_apply_ruleset"
1790
1791         if [ -z "$rs" ]; then
1792                 warn "$_me: you must specify a ruleset"
1793                 return 1
1794         fi
1795         debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1796         if ! /sbin/devfs $devdir rule -s $rs applyset; then
1797                 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1798                 return 1
1799         fi
1800         return 0
1801 }
1802
1803 # devfs_domount dir [ruleset]
1804 #       Mount devfs on dir. If ruleset is specified it is set
1805 #       on the mount-point. It must also be a ruleset name as specified
1806 #       in a devfs.rules(5) file. Returns 0 on success.
1807 #
1808 devfs_domount()
1809 {
1810         local devdir rs _me
1811         devdir="$1"
1812         [ -n "$2" ] && rs=$2 || rs=
1813         _me="devfs_domount()"
1814
1815         if [ -z "$devdir" ]; then
1816                 warn "$_me: you must specify a mount-point"
1817                 return 1
1818         fi
1819         debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1820         if ! mount -t devfs dev "$devdir"; then
1821                 warn "$_me: Unable to mount devfs on $devdir"
1822                 return 1
1823         fi
1824         if [ -n "$rs" ]; then
1825                 devfs_init_rulesets
1826                 devfs_set_ruleset $rs $devdir
1827                 devfs -m $devdir rule applyset
1828         fi
1829         return 0
1830 }
1831
1832 # Provide a function for normalizing the mounting of memory
1833 # filesystems.  This should allow the rest of the code here to remain
1834 # as close as possible between 5-current and 4-stable.
1835 #   $1 = size
1836 #   $2 = mount point
1837 #   $3 = (optional) extra mdmfs flags
1838 mount_md()
1839 {
1840         if [ -n "$3" ]; then
1841                 flags="$3"
1842         fi
1843         /sbin/mdmfs $flags -s $1 ${mfs_type} $2
1844 }
1845
1846 # Code common to scripts that need to load a kernel module
1847 # if it isn't in the kernel yet. Syntax:
1848 #   load_kld [-e regex] [-m module] file
1849 # where -e or -m chooses the way to check if the module
1850 # is already loaded:
1851 #   regex is egrep'd in the output from `kldstat -v',
1852 #   module is passed to `kldstat -m'.
1853 # The default way is as though `-m file' were specified.
1854 load_kld()
1855 {
1856         local _loaded _mod _opt _re
1857
1858         while getopts "e:m:" _opt; do
1859                 case "$_opt" in
1860                 e) _re="$OPTARG" ;;
1861                 m) _mod="$OPTARG" ;;
1862                 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1863                 esac
1864         done
1865         shift $(($OPTIND - 1))
1866         if [ $# -ne 1 ]; then
1867                 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1868         fi
1869         _mod=${_mod:-$1}
1870         _loaded=false
1871         if [ -n "$_re" ]; then
1872                 if kldstat -v | egrep -q -e "$_re"; then
1873                         _loaded=true
1874                 fi
1875         else
1876                 if kldstat -q -m "$_mod"; then
1877                         _loaded=true
1878                 fi
1879         fi
1880         if ! $_loaded; then
1881                 if ! kldload "$1"; then
1882                         warn "Unable to load kernel module $1"
1883                         return 1
1884                 else
1885                         info "$1 kernel module loaded."
1886                 fi
1887         else
1888                 debug "load_kld: $1 kernel module already loaded."
1889         fi
1890         return 0
1891 }
1892
1893 # ltr str src dst [var]
1894 #       Change every $src in $str to $dst.
1895 #       Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1896 #       awk(1). If var is non-NULL, set it to the result.
1897 ltr()
1898 {
1899         local _str _src _dst _out _com _var
1900         _str="$1"
1901         _src="$2"
1902         _dst="$3"
1903         _var="$4"
1904         _out=""
1905
1906         local IFS="${_src}"
1907         for _com in ${_str}; do
1908                 if [ -z "${_out}" ]; then
1909                         _out="${_com}"
1910                 else
1911                         _out="${_out}${_dst}${_com}"
1912                 fi
1913         done
1914         if [ -n "${_var}" ]; then
1915                 setvar "${_var}" "${_out}"
1916         else
1917                 echo "${_out}"
1918         fi
1919 }
1920
1921 # Creates a list of providers for GELI encryption.
1922 geli_make_list()
1923 {
1924         local devices devices2
1925         local provider mountpoint type options rest
1926
1927         # Create list of GELI providers from fstab.
1928         while read provider mountpoint type options rest ; do
1929                 case ":${options}" in
1930                 :*noauto*)
1931                         noauto=yes
1932                         ;;
1933                 *)
1934                         noauto=no
1935                         ;;
1936                 esac
1937
1938                 case ":${provider}" in
1939                 :#*)
1940                         continue
1941                         ;;
1942                 *.eli)
1943                         # Skip swap devices.
1944                         if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1945                                 continue
1946                         fi
1947                         devices="${devices} ${provider}"
1948                         ;;
1949                 esac
1950         done < /etc/fstab
1951
1952         # Append providers from geli_devices.
1953         devices="${devices} ${geli_devices}"
1954
1955         for provider in ${devices}; do
1956                 provider=${provider%.eli}
1957                 provider=${provider#/dev/}
1958                 devices2="${devices2} ${provider}"
1959         done
1960
1961         echo ${devices2}
1962 }
1963
1964 # Originally, root mount hold had to be released before mounting
1965 # the root filesystem.  This delayed the boot, so it was changed
1966 # to only wait if the root device isn't readily available.  This
1967 # can result in rc scripts executing before all the devices - such
1968 # as graid(8), or USB disks - can be accessed.  This function can
1969 # be used to explicitly wait for root mount holds to be released.
1970 root_hold_wait()
1971 {
1972         local wait waited holders
1973
1974         waited=0
1975         while true; do
1976                 holders="$(sysctl -n vfs.root_mount_hold)"
1977                 if [ -z "${holders}" ]; then
1978                         break;
1979                 fi
1980                 if [ ${waited} -eq 0 ]; then
1981                         echo -n "Waiting ${root_hold_delay}s" \
1982                         "for the root mount holders: ${holders}"
1983                 else
1984                         echo -n .
1985                 fi
1986                 if [ ${waited} -ge ${root_hold_delay} ]; then
1987                         echo
1988                         break
1989                 fi
1990                 sleep 1
1991                 waited=$(($waited + 1))
1992         done
1993 }
1994
1995 # Find scripts in local_startup directories that use the old syntax
1996 #
1997 find_local_scripts_old() {
1998         zlist=''
1999         slist=''
2000         for dir in ${local_startup}; do
2001                 if [ -d "${dir}" ]; then
2002                         for file in ${dir}/[0-9]*.sh; do
2003                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2004                                     continue
2005                                 zlist="$zlist $file"
2006                         done
2007                         for file in ${dir}/[!0-9]*.sh; do
2008                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
2009                                     continue
2010                                 slist="$slist $file"
2011                         done
2012                 fi
2013         done
2014 }
2015
2016 find_local_scripts_new() {
2017         local_rc=''
2018         for dir in ${local_startup}; do
2019                 if [ -d "${dir}" ]; then
2020                         for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
2021                                 case "$file" in
2022                                 *.sample) ;;
2023                                 *)      if [ -x "$file" ]; then
2024                                                 local_rc="${local_rc} ${file}"
2025                                         fi
2026                                         ;;
2027                                 esac
2028                         done
2029                 fi
2030         done
2031 }
2032
2033 # check_required_{before|after} command
2034 #       Check for things required by the command before and after its precmd,
2035 #       respectively.  The two separate functions are needed because some
2036 #       conditions should prevent precmd from being run while other things
2037 #       depend on precmd having already been run.
2038 #
2039 check_required_before()
2040 {
2041         local _f
2042
2043         case "$1" in
2044         start)
2045                 for _f in $required_vars; do
2046                         if ! checkyesno $_f; then
2047                                 warn "\$${_f} is not enabled."
2048                                 if [ -z "$rc_force" ]; then
2049                                         return 1
2050                                 fi
2051                         fi
2052                 done
2053
2054                 for _f in $required_dirs; do
2055                         if [ ! -d "${_f}/." ]; then
2056                                 warn "${_f} is not a directory."
2057                                 if [ -z "$rc_force" ]; then
2058                                         return 1
2059                                 fi
2060                         fi
2061                 done
2062
2063                 for _f in $required_files; do
2064                         if [ ! -r "${_f}" ]; then
2065                                 warn "${_f} is not readable."
2066                                 if [ -z "$rc_force" ]; then
2067                                         return 1
2068                                 fi
2069                         fi
2070                 done
2071                 ;;
2072         esac
2073
2074         return 0
2075 }
2076
2077 check_required_after()
2078 {
2079         local _f _args
2080
2081         case "$1" in
2082         start)
2083                 for _f in $required_modules; do
2084                         case "${_f}" in
2085                                 *~*)    _args="-e ${_f#*~} ${_f%%~*}" ;;
2086                                 *:*)    _args="-m ${_f#*:} ${_f%%:*}" ;;
2087                                 *)      _args="${_f}" ;;
2088                         esac
2089                         if ! load_kld ${_args}; then
2090                                 if [ -z "$rc_force" ]; then
2091                                         return 1
2092                                 fi
2093                         fi
2094                 done
2095                 ;;
2096         esac
2097
2098         return 0
2099 }
2100
2101 # check_jail mib
2102 #       Return true if security.jail.$mib exists and set to 1.
2103
2104 check_jail()
2105 {
2106         local _mib _v
2107
2108         _mib=$1
2109         if _v=$(${SYSCTL_N} "security.jail.$_mib" 2> /dev/null); then
2110                 case $_v in
2111                 1)      return 0;;
2112                 esac
2113         fi
2114         return 1
2115 }
2116
2117 # check_kern_features mib
2118 #       Return existence of kern.features.* sysctl MIB as true or
2119 #       false.  The result will be cached in $_rc_cache_kern_features_
2120 #       namespace.  "0" means the kern.features.X exists.
2121
2122 check_kern_features()
2123 {
2124         local _v
2125
2126         [ -n "$1" ] || return 1;
2127         eval _v=\$_rc_cache_kern_features_$1
2128         [ -n "$_v" ] && return "$_v";
2129
2130         if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
2131                 eval _rc_cache_kern_features_$1=0
2132                 return 0
2133         else
2134                 eval _rc_cache_kern_features_$1=1
2135                 return 1
2136         fi
2137 }
2138
2139 # check_namevarlist var
2140 #       Return "0" if ${name}_var is reserved in rc.subr.
2141
2142 _rc_namevarlist="program chroot chdir env flags fib nice user group groups prepend"
2143 check_namevarlist()
2144 {
2145         local _v
2146
2147         for _v in $_rc_namevarlist; do
2148         case $1 in
2149         $_v)    return 0 ;;
2150         esac
2151         done
2152
2153         return 1
2154 }
2155
2156 # _echoonce var msg mode
2157 #       mode=0: Echo $msg if ${$var} is empty.
2158 #               After doing echo, a string is set to ${$var}.
2159 #
2160 #       mode=1: Echo $msg if ${$var} is a string with non-zero length.
2161 #
2162 _echoonce()
2163 {
2164         local _var _msg _mode
2165         eval _var=\$$1
2166         _msg=$2
2167         _mode=$3
2168
2169         case $_mode in
2170         1)      [ -n "$_var" ] && echo "$_msg" ;;
2171         *)      [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
2172         esac
2173 }
2174
2175 # If the loader env variable rc.debug is set, turn on debugging. rc.conf will
2176 # still override this, but /etc/defaults/rc.conf can't unconditionally set this
2177 # since it would undo what we've done here.
2178 if kenv -q rc.debug > /dev/null ; then
2179         rc_debug=YES
2180 fi