]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - etc/rc.subr
Fix named(8) DNSSEC validation Denial of Service.
[FreeBSD/releng/8.2.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 : ${rcvar_manpage:='rc.conf(5)'}
36 : ${RC_PID:=$$}; export RC_PID
37
38 #
39 #       Operating System dependent/independent variables
40 #
41
42 if [ -z "${_rc_subr_loaded}" ]; then
43
44 _rc_subr_loaded="YES"
45
46 SYSCTL="/sbin/sysctl"
47 SYSCTL_N="${SYSCTL} -n"
48 SYSCTL_W="${SYSCTL}"
49 ID="/usr/bin/id"
50 IDCMD="if [ -x $ID ]; then $ID -un; fi"
51 PS="/bin/ps -ww"
52 JID=`$PS -p $$ -o jid=`
53
54 #
55 #       functions
56 #       ---------
57
58 # set_rcvar [var] [defval] [desc]
59 #
60 #       Echo or define a rc.conf(5) variable name.  Global variable
61 #       $rcvars is used.
62 #
63 #       If no argument is specified, echo "${name}_enable".
64 #
65 #       If only a var is specified, echo "${var}_enable".
66 #
67 #       If var and defval are specified, the ${var} is defined as
68 #       rc.conf(5) variable and the default value is ${defvar}.  An
69 #       optional argument $desc can also be specified to add a
70 #       description for that.
71 #
72 set_rcvar()
73 {
74         case $# in
75         0)
76                 echo ${name}_enable
77                 ;;
78         1)
79                 echo ${1}_enable
80                 ;;
81         *)
82                 debug "rcvar_define: \$$1=$2 is added" \
83                     " as a rc.conf(5) variable."
84
85                 local _var
86                 _var=$1
87                 rcvars="${rcvars# } $_var"
88                 eval ${_var}_defval=\"$2\"
89                 shift 2
90                 # encode multiple lines of _desc
91                 for l in "$@"; do
92                         eval ${_var}_desc=\"\${${_var}_desc#^^}^^$l\"
93                 done
94                 eval ${_var}_desc=\"\${${_var}_desc#^^}\"
95                 ;;
96         esac
97 }
98
99 # set_rcvar_obsolete oldvar [newvar] [msg]
100 #       Define obsolete variable.
101 #       Global variable $rcvars_obsolete is used.
102 #
103 set_rcvar_obsolete()
104 {
105         local _var
106         _var=$1
107         debug "rcvar_obsolete: \$$1(old) -> \$$2(new) is defined"
108
109         rcvars_obsolete="${rcvars_obsolete# } $1"
110         eval ${1}_newvar=\"$2\"
111         shift 2
112         eval ${_var}_obsolete_msg=\"$*\"
113 }
114
115 #
116 # force_depend script
117 #       Force a service to start. Intended for use by services
118 #       to resolve dependency issues. It is assumed the caller
119 #       has check to make sure this call is necessary
120 #       $1 - filename of script, in /etc/rc.d, to run
121 #
122 force_depend()
123 {
124         _depend="$1"
125
126         info "${name} depends on ${_depend}, which will be forced to start."
127         if ! /etc/rc.d/${_depend} forcestart; then
128                 warn "Unable to force ${_depend}. It may already be running."
129                 return 1
130         fi
131         return 0
132 }
133
134 #
135 # checkyesno var
136 #       Test $1 variable, and warn if not set to YES or NO.
137 #       Return 0 if it's "yes" (et al), nonzero otherwise.
138 #
139 checkyesno()
140 {
141         eval _value=\$${1}
142         debug "checkyesno: $1 is set to $_value."
143         case $_value in
144
145                 #       "yes", "true", "on", or "1"
146         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
147                 return 0
148                 ;;
149
150                 #       "no", "false", "off", or "0"
151         [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
152                 return 1
153                 ;;
154         *)
155                 warn "\$${1} is not set properly - see ${rcvar_manpage}."
156                 return 1
157                 ;;
158         esac
159 }
160
161 #
162 # reverse_list list
163 #       print the list in reverse order
164 #
165 reverse_list()
166 {
167         _revlist=
168         for _revfile; do
169                 _revlist="$_revfile $_revlist"
170         done
171         echo $_revlist
172 }
173
174 # stop_boot always
175 #       If booting directly to multiuser or $always is enabled,
176 #       send SIGTERM to the parent (/etc/rc) to abort the boot.
177 #       Otherwise just exit.
178 #
179 stop_boot()
180 {
181         local always
182
183         case $1 in
184                 #       "yes", "true", "on", or "1"
185         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
186                 always=true
187                 ;;
188         *)
189                 always=false
190                 ;;
191         esac
192         if [ "$autoboot" = yes -o "$always" = true ]; then
193                 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
194                 kill -TERM ${RC_PID}
195         fi
196         exit 1
197 }
198
199 #
200 # mount_critical_filesystems type
201 #       Go through the list of critical filesystems as provided in
202 #       the rc.conf(5) variable $critical_filesystems_${type}, checking
203 #       each one to see if it is mounted, and if it is not, mounting it.
204 #
205 mount_critical_filesystems()
206 {
207         eval _fslist=\$critical_filesystems_${1}
208         for _fs in $_fslist; do
209                 mount | (
210                         _ismounted=false
211                         while read what _on on _type type; do
212                                 if [ $on = $_fs ]; then
213                                         _ismounted=true
214                                 fi
215                         done
216                         if $_ismounted; then
217                                 :
218                         else
219                                 mount $_fs >/dev/null 2>&1
220                         fi
221                 )
222         done
223 }
224
225 #
226 # check_pidfile pidfile procname [interpreter]
227 #       Parses the first line of pidfile for a PID, and ensures
228 #       that the process is running and matches procname.
229 #       Prints the matching PID upon success, nothing otherwise.
230 #       interpreter is optional; see _find_processes() for details.
231 #
232 check_pidfile()
233 {
234         _pidfile=$1
235         _procname=$2
236         _interpreter=$3
237         if [ -z "$_pidfile" -o -z "$_procname" ]; then
238                 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
239         fi
240         if [ ! -f $_pidfile ]; then
241                 debug "pid file ($_pidfile): not readable."
242                 return
243         fi
244         read _pid _junk < $_pidfile
245         if [ -z "$_pid" ]; then
246                 debug "pid file ($_pidfile): no pid in file."
247                 return
248         fi
249         _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
250 }
251
252 #
253 # check_process procname [interpreter]
254 #       Ensures that a process (or processes) named procname is running.
255 #       Prints a list of matching PIDs.
256 #       interpreter is optional; see _find_processes() for details.
257 #
258 check_process()
259 {
260         _procname=$1
261         _interpreter=$2
262         if [ -z "$_procname" ]; then
263                 err 3 'USAGE: check_process procname [interpreter]'
264         fi
265         _find_processes $_procname ${_interpreter:-.} '-ax'
266 }
267
268 #
269 # _find_processes procname interpreter psargs
270 #       Search for procname in the output of ps generated by psargs.
271 #       Prints the PIDs of any matching processes, space separated.
272 #
273 #       If interpreter == ".", check the following variations of procname
274 #       against the first word of each command:
275 #               procname
276 #               `basename procname`
277 #               `basename procname` + ":"
278 #               "(" + `basename procname` + ")"
279 #               "[" + `basename procname` + "]"
280 #
281 #       If interpreter != ".", read the first line of procname, remove the
282 #       leading #!, normalise whitespace, append procname, and attempt to
283 #       match that against each command, either as is, or with extra words
284 #       at the end.  As an alternative, to deal with interpreted daemons
285 #       using perl, the basename of the interpreter plus a colon is also
286 #       tried as the prefix to procname.
287 #
288 _find_processes()
289 {
290         if [ $# -ne 3 ]; then
291                 err 3 'USAGE: _find_processes procname interpreter psargs'
292         fi
293         _procname=$1
294         _interpreter=$2
295         _psargs=$3
296
297         _pref=
298         if [ $_interpreter != "." ]; then       # an interpreted script
299                 _script=${_chroot}${_chroot:+"/"}$_procname
300                 if [ -r $_script ]; then
301                         read _interp < $_script # read interpreter name
302                         case "$_interp" in
303                         \#!*)
304                                 _interp=${_interp#\#!}  # strip #!
305                                 set -- $_interp
306                                 case $1 in
307                                 */bin/env)
308                                         shift   # drop env to get real name
309                                         ;;
310                                 esac
311                                 if [ $_interpreter != $1 ]; then
312                                         warn "\$command_interpreter $_interpreter != $1"
313                                 fi
314                                 ;;
315                         *)
316                                 warn "no shebang line in $_script"
317                                 set -- $_interpreter
318                                 ;;
319                         esac
320                 else
321                         warn "cannot read shebang line from $_script"
322                         set -- $_interpreter
323                 fi
324                 _interp="$* $_procname"         # cleanup spaces, add _procname
325                 _interpbn=${1##*/}
326                 _fp_args='_argv'
327                 _fp_match='case "$_argv" in
328                     ${_interp}|"${_interp} "*|"${_interpbn}: ${_procname}"*)'
329         else                                    # a normal daemon
330                 _procnamebn=${_procname##*/}
331                 _fp_args='_arg0 _argv'
332                 _fp_match='case "$_arg0" in
333                     $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})"|"[${_procnamebn}]")'
334         fi
335
336         _proccheck="\
337                 $PS 2>/dev/null -o pid= -o jid= -o command= $_psargs"' |
338                 while read _npid _jid '"$_fp_args"'; do
339                         '"$_fp_match"'
340                                 if [ "$JID" -eq "$_jid" ];
341                                 then echo -n "$_pref$_npid";
342                                 _pref=" ";
343                                 fi
344                                 ;;
345                         esac
346                 done'
347
348 #       debug "in _find_processes: proccheck is ($_proccheck)."
349         eval $_proccheck
350 }
351
352 #
353 # wait_for_pids pid [pid ...]
354 #       spins until none of the pids exist
355 #
356 wait_for_pids()
357 {
358         local _list _prefix _nlist _j
359
360         _list="$@"
361         if [ -z "$_list" ]; then
362                 return
363         fi
364         _prefix=
365         while true; do
366                 _nlist="";
367                 for _j in $_list; do
368                         if kill -0 $_j 2>/dev/null; then
369                                 _nlist="${_nlist}${_nlist:+ }$_j"
370                                 [ -n "$_prefix" ] && sleep 1
371                         fi
372                 done
373                 if [ -z "$_nlist" ]; then
374                         break
375                 fi
376                 _list=$_nlist
377                 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
378                 _prefix=", "
379                 pwait $_list 2>/dev/null
380         done
381         if [ -n "$_prefix" ]; then
382                 echo "."
383         fi
384 }
385
386 #
387 # check_startmsgs
388 #       If rc_quiet is set (usually as a result of using faststart at
389 #       boot time) check if rc_startmsgs is enabled.
390 #
391 check_startmsgs()
392 {
393         if [ -n "$rc_quiet" ]; then
394                 checkyesno rc_startmsgs
395         else
396                 return 0
397         fi
398 }
399
400 #
401 # run_rc_command argument
402 #       Search for argument in the list of supported commands, which is:
403 #               "start stop restart rcvar status poll ${extra_commands}"
404 #       If there's a match, run ${argument}_cmd or the default method
405 #       (see below).
406 #
407 #       If argument has a given prefix, then change the operation as follows:
408 #               Prefix  Operation
409 #               ------  ---------
410 #               fast    Skip the pid check, and set rc_fast=yes, rc_quiet=yes
411 #               force   Set ${rcvar} to YES, and set rc_force=yes
412 #               one     Set ${rcvar} to YES
413 #               quiet   Don't output some diagnostics, and set rc_quiet=yes
414 #
415 #       The following globals are used:
416 #
417 #       Name            Needed  Purpose
418 #       ----            ------  -------
419 #       name            y       Name of script.
420 #
421 #       command         n       Full path to command.
422 #                               Not needed if ${rc_arg}_cmd is set for
423 #                               each keyword.
424 #
425 #       command_args    n       Optional args/shell directives for command.
426 #
427 #       command_interpreter n   If not empty, command is interpreted, so
428 #                               call check_{pidfile,process}() appropriately.
429 #
430 #       desc            n       Description of script.
431 #
432 #       extra_commands  n       List of extra commands supported.
433 #
434 #       pidfile         n       If set, use check_pidfile $pidfile $command,
435 #                               otherwise use check_process $command.
436 #                               In either case, only check if $command is set.
437 #
438 #       procname        n       Process name to check for instead of $command.
439 #
440 #       rcvar           n       This is checked with checkyesno to determine
441 #                               if the action should be run.
442 #
443 #       ${name}_program n       Full path to command.
444 #                               Meant to be used in /etc/rc.conf to override
445 #                               ${command}.
446 #
447 #       ${name}_chroot  n       Directory to chroot to before running ${command}
448 #                               Requires /usr to be mounted.
449 #
450 #       ${name}_chdir   n       Directory to cd to before running ${command}
451 #                               (if not using ${name}_chroot).
452 #
453 #       ${name}_flags   n       Arguments to call ${command} with.
454 #                               NOTE:   $flags from the parent environment
455 #                                       can be used to override this.
456 #
457 #       ${name}_nice    n       Nice level to run ${command} at.
458 #
459 #       ${name}_user    n       User to run ${command} as, using su(1) if not
460 #                               using ${name}_chroot.
461 #                               Requires /usr to be mounted.
462 #
463 #       ${name}_group   n       Group to run chrooted ${command} as.
464 #                               Requires /usr to be mounted.
465 #
466 #       ${name}_groups  n       Comma separated list of supplementary groups
467 #                               to run the chrooted ${command} with.
468 #                               Requires /usr to be mounted.
469 #
470 #       ${rc_arg}_cmd   n       If set, use this as the method when invoked;
471 #                               Otherwise, use default command (see below)
472 #
473 #       ${rc_arg}_precmd n      If set, run just before performing the
474 #                               ${rc_arg}_cmd method in the default
475 #                               operation (i.e, after checking for required
476 #                               bits and process (non)existence).
477 #                               If this completes with a non-zero exit code,
478 #                               don't run ${rc_arg}_cmd.
479 #
480 #       ${rc_arg}_postcmd n     If set, run just after performing the
481 #                               ${rc_arg}_cmd method, if that method
482 #                               returned a zero exit code.
483 #
484 #       required_dirs   n       If set, check for the existence of the given
485 #                               directories before running a (re)start command.
486 #
487 #       required_files  n       If set, check for the readability of the given
488 #                               files before running a (re)start command.
489 #
490 #       required_modules n      If set, ensure the given kernel modules are
491 #                               loaded before running a (re)start command.
492 #                               The check and possible loads are actually
493 #                               done after start_precmd so that the modules
494 #                               aren't loaded in vain, should the precmd
495 #                               return a non-zero status to indicate a error.
496 #                               If a word in the list looks like "foo:bar",
497 #                               "foo" is the KLD file name and "bar" is the
498 #                               module name.  If a word looks like "foo~bar",
499 #                               "foo" is the KLD file name and "bar" is a
500 #                               egrep(1) pattern matching the module name.
501 #                               Otherwise the module name is assumed to be
502 #                               the same as the KLD file name, which is most
503 #                               common.  See load_kld().
504 #
505 #       required_vars   n       If set, perform checkyesno on each of the
506 #                               listed variables before running the default
507 #                               (re)start command.
508 #
509 #       Default behaviour for a given argument, if no override method is
510 #       provided:
511 #
512 #       Argument        Default behaviour
513 #       --------        -----------------
514 #       start           if !running && checkyesno ${rcvar}
515 #                               ${command}
516 #
517 #       stop            if ${pidfile}
518 #                               rc_pid=$(check_pidfile $pidfile $command)
519 #                       else
520 #                               rc_pid=$(check_process $command)
521 #                       kill $sig_stop $rc_pid
522 #                       wait_for_pids $rc_pid
523 #                       ($sig_stop defaults to TERM.)
524 #
525 #       reload          Similar to stop, except use $sig_reload instead,
526 #                       and doesn't wait_for_pids.
527 #                       $sig_reload defaults to HUP.
528 #                       Note that `reload' isn't provided by default,
529 #                       it should be enabled via $extra_commands.
530 #
531 #       restart         Run `stop' then `start'.
532 #
533 #       status          Show if ${command} is running, etc.
534 #
535 #       poll            Wait for ${command} to exit.
536 #
537 #       rcvar           Display what rc.conf variable is used (if any).
538 #
539 #       Variables available to methods, and after run_rc_command() has
540 #       completed:
541 #
542 #       Variable        Purpose
543 #       --------        -------
544 #       rc_arg          Argument to command, after fast/force/one processing
545 #                       performed
546 #
547 #       rc_flags        Flags to start the default command with.
548 #                       Defaults to ${name}_flags, unless overridden
549 #                       by $flags from the environment.
550 #                       This variable may be changed by the precmd method.
551 #
552 #       rc_pid          PID of command (if appropriate)
553 #
554 #       rc_fast         Not empty if "fast" was provided (q.v.)
555 #
556 #       rc_force        Not empty if "force" was provided (q.v.)
557 #
558 #       rc_quiet        Not empty if "quiet" was provided
559 #
560 #
561 run_rc_command()
562 {
563         _return=0
564         rc_arg=$1
565         if [ -z "$name" ]; then
566                 err 3 'run_rc_command: $name is not set.'
567         fi
568
569         # Don't repeat the first argument when passing additional command-
570         # line arguments to the command subroutines.
571         #
572         shift 1
573         rc_extra_args="$*"
574
575         _rc_prefix=
576         case "$rc_arg" in
577         fast*)                          # "fast" prefix; don't check pid
578                 rc_arg=${rc_arg#fast}
579                 rc_fast=yes
580                 rc_quiet=yes
581                 ;;
582         force*)                         # "force" prefix; always run
583                 rc_force=yes
584                 _rc_prefix=force
585                 rc_arg=${rc_arg#${_rc_prefix}}
586                 if [ -n "${rcvar}" ]; then
587                         eval ${rcvar}=YES
588                 fi
589                 ;;
590         one*)                           # "one" prefix; set ${rcvar}=yes
591                 _rc_prefix=one
592                 rc_arg=${rc_arg#${_rc_prefix}}
593                 if [ -n "${rcvar}" ]; then
594                         eval ${rcvar}=YES
595                 fi
596                 ;;
597         quiet*)                         # "quiet" prefix; omit some messages
598                 _rc_prefix=quiet
599                 rc_arg=${rc_arg#${_rc_prefix}}
600                 rc_quiet=yes
601                 ;;
602         esac
603
604         eval _override_command=\$${name}_program
605         command=${_override_command:-$command}
606
607         _keywords="start stop restart rcvar $extra_commands"
608         rc_pid=
609         _pidcmd=
610         _procname=${procname:-${command}}
611
612                                         # setup pid check command
613         if [ -n "$_procname" ]; then
614                 if [ -n "$pidfile" ]; then
615                         _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
616                 else
617                         _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
618                 fi
619                 if [ -n "$_pidcmd" ]; then
620                         _keywords="${_keywords} status poll"
621                 fi
622         fi
623
624         if [ -z "$rc_arg" ]; then
625                 rc_usage $_keywords
626         fi
627
628         if [ -n "$flags" ]; then        # allow override from environment
629                 rc_flags=$flags
630         else
631                 eval rc_flags=\$${name}_flags
632         fi
633         eval _chdir=\$${name}_chdir     _chroot=\$${name}_chroot \
634             _nice=\$${name}_nice        _user=\$${name}_user \
635             _group=\$${name}_group      _groups=\$${name}_groups
636
637         if [ -n "$_user" ]; then        # unset $_user if running as that user
638                 if [ "$_user" = "$(eval $IDCMD)" ]; then
639                         unset _user
640                 fi
641         fi
642
643         eval $_pidcmd                   # determine the pid if necessary
644
645         for _elem in $_keywords; do
646                 if [ "$_elem" != "$rc_arg" ]; then
647                         continue
648                 fi
649                                         # if ${rcvar} is set, $1 is not "rcvar"
650                                         # and ${rc_pid} is not set, then run
651                                         #       checkyesno ${rcvar}
652                                         # and return if that failed
653                                         #
654                 if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" -a -z "${rc_pid}" ]; then
655                         if ! checkyesno ${rcvar}; then
656                                 if [ -n "${rc_quiet}" ]; then
657                                         return 0
658                                 fi
659                                 echo -n "Cannot '${rc_arg}' $name. Set ${rcvar} to "
660                                 echo -n "YES in /etc/rc.conf or use 'one${rc_arg}' "
661                                 echo "instead of '${rc_arg}'."
662                                 return 0
663                         fi
664                 fi
665
666                                         # if there's a custom ${XXX_cmd},
667                                         # run that instead of the default
668                                         #
669                 eval _cmd=\$${rc_arg}_cmd \
670                      _precmd=\$${rc_arg}_precmd \
671                      _postcmd=\$${rc_arg}_postcmd
672
673                 if [ -n "$_cmd" ]; then
674                         _run_rc_precmd || return 1
675                         _run_rc_doit "$_cmd $rc_extra_args" || return 1
676                         _run_rc_postcmd
677                         return $_return
678                 fi
679
680                 case "$rc_arg" in       # default operations...
681
682                 status)
683                         _run_rc_precmd || return 1
684                         if [ -n "$rc_pid" ]; then
685                                 echo "${name} is running as pid $rc_pid."
686                         else
687                                 echo "${name} is not running."
688                                 return 1
689                         fi
690                         _run_rc_postcmd
691                         ;;
692
693                 start)
694                         if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
695                                 echo 1>&2 "${name} already running? (pid=$rc_pid)."
696                                 return 1
697                         fi
698
699                         if [ ! -x ${_chroot}${_chroot:+"/"}${command} ]; then
700                                 warn "run_rc_command: cannot run $command"
701                                 return 1
702                         fi
703
704                         if ! _run_rc_precmd; then
705                                 warn "failed precmd routine for ${name}"
706                                 return 1
707                         fi
708
709                                         # setup the full command to run
710                                         #
711                         check_startmsgs && echo "Starting ${name}."
712                         if [ -n "$_chroot" ]; then
713                                 _doit="\
714 ${_nice:+nice -n $_nice }\
715 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
716 $_chroot $command $rc_flags $command_args"
717                         else
718                                 _doit="\
719 ${_chdir:+cd $_chdir && }\
720 $command $rc_flags $command_args"
721                                 if [ -n "$_user" ]; then
722                                     _doit="su -m $_user -c 'sh -c \"$_doit\"'"
723                                 fi
724                                 if [ -n "$_nice" ]; then
725                                         if [ -z "$_user" ]; then
726                                                 _doit="sh -c \"$_doit\""
727                                         fi
728                                         _doit="nice -n $_nice $_doit"
729                                 fi
730                         fi
731
732                                         # run the full command
733                                         #
734                         if ! _run_rc_doit "$_doit"; then
735                                 warn "failed to start ${name}"
736                                 return 1
737                         fi
738
739                                         # finally, run postcmd
740                                         #
741                         _run_rc_postcmd
742                         ;;
743
744                 stop)
745                         if [ -z "$rc_pid" ]; then
746                                 [ -n "$rc_fast" ] && return 0
747                                 _run_rc_notrunning
748                                 return 1
749                         fi
750
751                         _run_rc_precmd || return 1
752
753                                         # send the signal to stop
754                                         #
755                         echo "Stopping ${name}."
756                         _doit=$(_run_rc_killcmd "${sig_stop:-TERM}")
757                         _run_rc_doit "$_doit" || return 1
758
759                                         # wait for the command to exit,
760                                         # and run postcmd.
761                         wait_for_pids $rc_pid
762
763                         _run_rc_postcmd
764                         ;;
765
766                 reload)
767                         if [ -z "$rc_pid" ]; then
768                                 _run_rc_notrunning
769                                 return 1
770                         fi
771
772                         _run_rc_precmd || return 1
773
774                         _doit=$(_run_rc_killcmd "${sig_reload:-HUP}")
775                         _run_rc_doit "$_doit" || return 1
776
777                         _run_rc_postcmd
778                         ;;
779
780                 restart)
781                                         # prevent restart being called more
782                                         # than once by any given script
783                                         #
784                         if ${_rc_restart_done:-false}; then
785                                 return 0
786                         fi
787                         _rc_restart_done=true
788
789                         _run_rc_precmd || return 1
790
791                         # run those in a subshell to keep global variables
792                         ( run_rc_command ${_rc_prefix}stop $rc_extra_args )
793                         ( run_rc_command ${_rc_prefix}start $rc_extra_args )
794                         _return=$?
795                         [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
796
797                         _run_rc_postcmd
798                         ;;
799
800                 poll)
801                         _run_rc_precmd || return 1
802                         if [ -n "$rc_pid" ]; then
803                                 wait_for_pids $rc_pid
804                         fi
805                         _run_rc_postcmd
806                         ;;
807
808                 rcvar)
809                         echo -n "# $name"
810                         if [ -n "$desc" ]; then
811                                 echo " : $desc"
812                         else
813                                 echo ""
814                         fi
815                         echo "#"
816                         # Get unique vars in $rcvar $rcvars
817                         for _v in $rcvar $rcvars; do
818                                 case $v in
819                                 $_v\ *|\ *$_v|*\ $_v\ *) ;;
820                                 *)      v="${v# } $_v" ;;
821                                 esac
822                         done
823
824                         # Display variables.
825                         for _v in $v; do
826                                 if [ -z "$_v" ]; then
827                                         continue
828                                 fi
829
830                                 eval _desc=\$${_v}_desc
831                                 eval _defval=\$${_v}_defval
832                                 _h="-"
833
834                                 eval echo \"$_v=\\\"\$$_v\\\"\"
835                                 # decode multiple lines of _desc
836                                 while [ -n "$_desc" ]; do
837                                         case $_desc in
838                                         *^^*)
839                                                 echo "# $_h ${_desc%%^^*}"
840                                                 _desc=${_desc#*^^}
841                                                 _h=" "
842                                                 ;;
843                                         *)
844                                                 echo "# $_h ${_desc}"
845                                                 break
846                                                 ;;
847                                         esac
848                                 done
849                                 echo "#   (default: \"$_defval\")"
850                         done
851                         echo ""
852                         ;;
853
854                 *)
855                         rc_usage $_keywords
856                         ;;
857
858                 esac
859                 return $_return
860         done
861
862         echo 1>&2 "$0: unknown directive '$rc_arg'."
863         rc_usage $_keywords
864         # not reached
865 }
866
867 #
868 # Helper functions for run_rc_command: common code.
869 # They use such global variables besides the exported rc_* ones:
870 #
871 #       name           R/W
872 #       ------------------
873 #       _precmd         R
874 #       _postcmd        R
875 #       _return         W
876 #
877 _run_rc_precmd()
878 {
879         check_required_before "$rc_arg" || return 1
880
881         if [ -n "$_precmd" ]; then
882                 debug "run_rc_command: ${rc_arg}_precmd: $_precmd $rc_extra_args"
883                 eval "$_precmd $rc_extra_args"
884                 _return=$?
885
886                 # If precmd failed and force isn't set, request exit.
887                 if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
888                         return 1
889                 fi
890         fi
891
892         check_required_after "$rc_arg" || return 1
893
894         return 0
895 }
896
897 _run_rc_postcmd()
898 {
899         if [ -n "$_postcmd" ]; then
900                 debug "run_rc_command: ${rc_arg}_postcmd: $_postcmd $rc_extra_args"
901                 eval "$_postcmd $rc_extra_args"
902                 _return=$?
903         fi
904         return 0
905 }
906
907 _run_rc_doit()
908 {
909         debug "run_rc_command: doit: $*"
910         eval "$@"
911         _return=$?
912
913         # If command failed and force isn't set, request exit.
914         if [ $_return -ne 0 ] && [ -z "$rc_force" ]; then
915                 return 1
916         fi
917
918         return 0
919 }
920
921 _run_rc_notrunning()
922 {
923         local _pidmsg
924
925         if [ -n "$pidfile" ]; then
926                 _pidmsg=" (check $pidfile)."
927         else
928                 _pidmsg=
929         fi
930         echo 1>&2 "${name} not running?${_pidmsg}"
931 }
932
933 _run_rc_killcmd()
934 {
935         local _cmd
936
937         _cmd="kill -$1 $rc_pid"
938         if [ -n "$_user" ]; then
939                 _cmd="su -m ${_user} -c 'sh -c \"${_cmd}\"'"
940         fi
941         echo "$_cmd"
942 }
943
944 #
945 # run_rc_script file arg
946 #       Start the script `file' with `arg', and correctly handle the
947 #       return value from the script.  If `file' ends with `.sh', it's
948 #       sourced into the current environment.  If `file' appears to be
949 #       a backup or scratch file, ignore it.  Otherwise if it's
950 #       executable run as a child process.
951 #
952 run_rc_script()
953 {
954         _file=$1
955         _arg=$2
956         if [ -z "$_file" -o -z "$_arg" ]; then
957                 err 3 'USAGE: run_rc_script file arg'
958         fi
959
960         unset   name command command_args command_interpreter \
961                 extra_commands pidfile procname \
962                 rcvar rcvars rcvars_obsolete required_dirs required_files \
963                 required_vars
964         eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
965
966         case "$_file" in
967         /etc/rc.d/*.sh)                 # no longer allowed in the base
968                 warn "Ignoring old-style startup script $_file"
969                 ;;
970         *[~#]|*.OLD|*.bak|*.orig|*,v)   # scratch file; skip
971                 warn "Ignoring scratch file $_file"
972                 ;;
973         *)                              # run in subshell
974                 if [ -x $_file ]; then
975                         if [ -n "$rc_fast_and_loose" ]; then
976                                 set $_arg; . $_file
977                         else
978                                 ( trap "echo Script $_file interrupted; kill -QUIT $$" 3
979                                   trap "echo Script $_file interrupted; exit 1" 2
980                                   trap "echo Script $_file running" 29
981                                   set $_arg; . $_file )
982                         fi
983                 fi
984                 ;;
985         esac
986 }
987
988 #
989 # load_rc_config name
990 #       Source in the configuration file for a given name.
991 #
992 load_rc_config()
993 {
994         local _name _var _defval _v _msg _new
995         _name=$1
996         if [ -z "$_name" ]; then
997                 err 3 'USAGE: load_rc_config name'
998         fi
999
1000         if ${_rc_conf_loaded:-false}; then
1001                 :
1002         else
1003                 if [ -r /etc/defaults/rc.conf ]; then
1004                         debug "Sourcing /etc/defaults/rc.conf"
1005                         . /etc/defaults/rc.conf
1006                         source_rc_confs
1007                 elif [ -r /etc/rc.conf ]; then
1008                         debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
1009                         . /etc/rc.conf
1010                 fi
1011                 _rc_conf_loaded=true
1012         fi
1013         if [ -f /etc/rc.conf.d/"$_name" ]; then
1014                 debug "Sourcing /etc/rc.conf.d/${_name}"
1015                 . /etc/rc.conf.d/"$_name"
1016         fi
1017
1018         # Old variable names support
1019         #
1020         [ -n "$enable_quotas" ] && quota_enable="$enable_quotas"
1021
1022         # Set defaults if defined.
1023         for _var in $rcvar $rcvars; do
1024                 _defval=`eval echo "\\\$${_var}_defval"`
1025                 if [ -n "$_defval" ]; then
1026                         eval : \${$_var:=\$${_var}_defval}
1027                 fi
1028         done
1029
1030         # check obsolete rc.conf variables
1031         for _var in $rcvars_obsolete; do
1032                 _v=`eval echo \\$$_var`
1033                 _msg=`eval echo \\$${_var}_obsolete_msg`
1034                 _new=`eval echo \\$${_var}_newvar`
1035                 case $_v in
1036                 "")
1037                         ;;
1038                 *)
1039                         if [ -z "$_new" ]; then
1040                                 _msg="Ignored."
1041                         else
1042                                 eval $_new=\"\$$_var\"
1043                                 if [ -z "$_msg" ]; then
1044                                         _msg="Use \$$_new instead."
1045                                 fi
1046                         fi
1047                         warn "\$$_var is obsolete.  $_msg"
1048                         ;;
1049                 esac
1050         done
1051 }
1052
1053 #
1054 # load_rc_config_var name var
1055 #       Read the rc.conf(5) var for name and set in the
1056 #       current shell, using load_rc_config in a subshell to prevent
1057 #       unwanted side effects from other variable assignments.
1058 #
1059 load_rc_config_var()
1060 {
1061         if [ $# -ne 2 ]; then
1062                 err 3 'USAGE: load_rc_config_var name var'
1063         fi
1064         eval $(eval '(
1065                 load_rc_config '$1' >/dev/null;
1066                 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1067                         echo '$2'=\'\''${'$2'}\'\'';
1068                 fi
1069         )' )
1070 }
1071
1072 #
1073 # rc_usage commands
1074 #       Print a usage string for $0, with `commands' being a list of
1075 #       valid commands.
1076 #
1077 rc_usage()
1078 {
1079         echo -n 1>&2 "Usage: $0 [fast|force|one]("
1080
1081         _sep=
1082         for _elem; do
1083                 echo -n 1>&2 "$_sep$_elem"
1084                 _sep="|"
1085         done
1086         echo 1>&2 ")"
1087         exit 1
1088 }
1089
1090 #
1091 # err exitval message
1092 #       Display message to stderr and log to the syslog, and exit with exitval.
1093 #
1094 err()
1095 {
1096         exitval=$1
1097         shift
1098
1099         if [ -x /usr/bin/logger ]; then
1100                 logger "$0: ERROR: $*"
1101         fi
1102         echo 1>&2 "$0: ERROR: $*"
1103         exit $exitval
1104 }
1105
1106 #
1107 # warn message
1108 #       Display message to stderr and log to the syslog.
1109 #
1110 warn()
1111 {
1112         if [ -x /usr/bin/logger ]; then
1113                 logger "$0: WARNING: $*"
1114         fi
1115         echo 1>&2 "$0: WARNING: $*"
1116 }
1117
1118 #
1119 # info message
1120 #       Display informational message to stdout and log to syslog.
1121 #
1122 info()
1123 {
1124         case ${rc_info} in
1125         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1126                 if [ -x /usr/bin/logger ]; then
1127                         logger "$0: INFO: $*"
1128                 fi
1129                 echo "$0: INFO: $*"
1130                 ;;
1131         esac
1132 }
1133
1134 #
1135 # debug message
1136 #       If debugging is enabled in rc.conf output message to stderr.
1137 #       BEWARE that you don't call any subroutine that itself calls this
1138 #       function.
1139 #
1140 debug()
1141 {
1142         case ${rc_debug} in
1143         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1144                 if [ -x /usr/bin/logger ]; then
1145                         logger "$0: DEBUG: $*"
1146                 fi
1147                 echo 1>&2 "$0: DEBUG: $*"
1148                 ;;
1149         esac
1150 }
1151
1152 #
1153 # backup_file action file cur backup
1154 #       Make a backup copy of `file' into `cur', and save the previous
1155 #       version of `cur' as `backup' or use rcs for archiving.
1156 #
1157 #       This routine checks the value of the backup_uses_rcs variable,
1158 #       which can be either YES or NO.
1159 #
1160 #       The `action' keyword can be one of the following:
1161 #
1162 #       add             `file' is now being backed up (and is possibly
1163 #                       being reentered into the backups system).  `cur'
1164 #                       is created and RCS files, if necessary, are
1165 #                       created as well.
1166 #
1167 #       update          `file' has changed and needs to be backed up.
1168 #                       If `cur' exists, it is copied to to `back' or
1169 #                       checked into RCS (if the repository file is old),
1170 #                       and then `file' is copied to `cur'.  Another RCS
1171 #                       check in done here if RCS is being used.
1172 #
1173 #       remove          `file' is no longer being tracked by the backups
1174 #                       system.  If RCS is not being used, `cur' is moved
1175 #                       to `back', otherwise an empty file is checked in,
1176 #                       and then `cur' is removed.
1177 #
1178 #
1179 backup_file()
1180 {
1181         _action=$1
1182         _file=$2
1183         _cur=$3
1184         _back=$4
1185
1186         if checkyesno backup_uses_rcs; then
1187                 _msg0="backup archive"
1188                 _msg1="update"
1189
1190                 # ensure that history file is not locked
1191                 if [ -f $_cur,v ]; then
1192                         rcs -q -u -U -M $_cur
1193                 fi
1194
1195                 # ensure after switching to rcs that the
1196                 # current backup is not lost
1197                 if [ -f $_cur ]; then
1198                         # no archive, or current newer than archive
1199                         if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1200                                 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1201                                 rcs -q -kb -U $_cur
1202                                 co -q -f -u $_cur
1203                         fi
1204                 fi
1205
1206                 case $_action in
1207                 add|update)
1208                         cp -p $_file $_cur
1209                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1210                         rcs -q -kb -U $_cur
1211                         co -q -f -u $_cur
1212                         chown root:wheel $_cur $_cur,v
1213                         ;;
1214                 remove)
1215                         cp /dev/null $_cur
1216                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1217                         rcs -q -kb -U $_cur
1218                         chown root:wheel $_cur $_cur,v
1219                         rm $_cur
1220                         ;;
1221                 esac
1222         else
1223                 case $_action in
1224                 add|update)
1225                         if [ -f $_cur ]; then
1226                                 cp -p $_cur $_back
1227                         fi
1228                         cp -p $_file $_cur
1229                         chown root:wheel $_cur
1230                         ;;
1231                 remove)
1232                         mv -f $_cur $_back
1233                         ;;
1234                 esac
1235         fi
1236 }
1237
1238 # make_symlink src link
1239 #       Make a symbolic link 'link' to src from basedir. If the
1240 #       directory in which link is to be created does not exist
1241 #       a warning will be displayed and an error will be returned.
1242 #       Returns 0 on sucess, 1 otherwise.
1243 #
1244 make_symlink()
1245 {
1246         local src link linkdir _me
1247         src="$1"
1248         link="$2"
1249         linkdir="`dirname $link`"
1250         _me="make_symlink()"
1251
1252         if [ -z "$src" -o -z "$link" ]; then
1253                 warn "$_me: requires two arguments."
1254                 return 1
1255         fi
1256         if [ ! -d "$linkdir" ]; then
1257                 warn "$_me: the directory $linkdir does not exist."
1258                 return 1
1259         fi
1260         if ! ln -sf $src $link; then
1261                 warn "$_me: unable to make a symbolic link from $link to $src"
1262                 return 1
1263         fi
1264         return 0
1265 }
1266
1267 # devfs_rulesets_from_file file
1268 #       Reads a set of devfs commands from file, and creates
1269 #       the specified rulesets with their rules. Returns non-zero
1270 #       if there was an error.
1271 #
1272 devfs_rulesets_from_file()
1273 {
1274         local file _err _me
1275         file="$1"
1276         _me="devfs_rulesets_from_file"
1277         _err=0
1278
1279         if [ -z "$file" ]; then
1280                 warn "$_me: you must specify a file"
1281                 return 1
1282         fi
1283         if [ ! -e "$file" ]; then
1284                 debug "$_me: no such file ($file)"
1285                 return 0
1286         fi
1287         debug "reading rulesets from file ($file)"
1288         { while read line
1289         do
1290                 case $line in
1291                 \#*)
1292                         continue
1293                         ;;
1294                 \[*\]*)
1295                         rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1296                         if [ -z "$rulenum" ]; then
1297                                 warn "$_me: cannot extract rule number ($line)"
1298                                 _err=1
1299                                 break
1300                         fi
1301                         rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1302                         if [ -z "$rulename" ]; then
1303                                 warn "$_me: cannot extract rule name ($line)"
1304                                 _err=1
1305                                 break;
1306                         fi
1307                         eval $rulename=\$rulenum
1308                         debug "found ruleset: $rulename=$rulenum"
1309                         if ! /sbin/devfs rule -s $rulenum delset; then
1310                                 _err=1
1311                                 break
1312                         fi
1313                         ;;
1314                 *)
1315                         rulecmd="${line%%"\#*"}"
1316                         # evaluate the command incase it includes
1317                         # other rules
1318                         if [ -n "$rulecmd" ]; then
1319                                 debug "adding rule ($rulecmd)"
1320                                 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1321                                 then
1322                                         _err=1
1323                                         break
1324                                 fi
1325                         fi
1326                         ;;
1327                 esac
1328                 if [ $_err -ne 0 ]; then
1329                         debug "error in $_me"
1330                         break
1331                 fi
1332         done } < $file
1333         return $_err
1334 }
1335
1336 # devfs_init_rulesets
1337 #       Initializes rulesets from configuration files. Returns
1338 #       non-zero if there was an error.
1339 #
1340 devfs_init_rulesets()
1341 {
1342         local file _me
1343         _me="devfs_init_rulesets"
1344
1345         # Go through this only once
1346         if [ -n "$devfs_rulesets_init" ]; then
1347                 debug "$_me: devfs rulesets already initialized"
1348                 return
1349         fi
1350         for file in $devfs_rulesets; do
1351                 devfs_rulesets_from_file $file || return 1
1352         done
1353         devfs_rulesets_init=1
1354         debug "$_me: devfs rulesets initialized"
1355         return 0
1356 }
1357
1358 # devfs_set_ruleset ruleset [dir]
1359 #       Sets the default ruleset of dir to ruleset. The ruleset argument
1360 #       must be a ruleset name as specified in devfs.rules(5) file.
1361 #       Returns non-zero if it could not set it successfully.
1362 #
1363 devfs_set_ruleset()
1364 {
1365         local devdir rs _me
1366         [ -n "$1" ] && eval rs=\$$1 || rs=
1367         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1368         _me="devfs_set_ruleset"
1369
1370         if [ -z "$rs" ]; then
1371                 warn "$_me: you must specify a ruleset number"
1372                 return 1
1373         fi
1374         debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1375         if ! /sbin/devfs $devdir ruleset $rs; then
1376                 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1377                 return 1
1378         fi
1379         return 0
1380 }
1381
1382 # devfs_apply_ruleset ruleset [dir]
1383 #       Apply ruleset number $ruleset to the devfs mountpoint $dir.
1384 #       The ruleset argument must be a ruleset name as specified
1385 #       in a devfs.rules(5) file.  Returns 0 on success or non-zero
1386 #       if it could not apply the ruleset.
1387 #
1388 devfs_apply_ruleset()
1389 {
1390         local devdir rs _me
1391         [ -n "$1" ] && eval rs=\$$1 || rs=
1392         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1393         _me="devfs_apply_ruleset"
1394
1395         if [ -z "$rs" ]; then
1396                 warn "$_me: you must specify a ruleset"
1397                 return 1
1398         fi
1399         debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1400         if ! /sbin/devfs $devdir rule -s $rs applyset; then
1401                 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1402                 return 1
1403         fi
1404         return 0
1405 }
1406
1407 # devfs_domount dir [ruleset]
1408 #       Mount devfs on dir. If ruleset is specified it is set
1409 #       on the mount-point. It must also be a ruleset name as specified
1410 #       in a devfs.rules(5) file. Returns 0 on success.
1411 #
1412 devfs_domount()
1413 {
1414         local devdir rs _me
1415         devdir="$1"
1416         [ -n "$2" ] && rs=$2 || rs=
1417         _me="devfs_domount()"
1418
1419         if [ -z "$devdir" ]; then
1420                 warn "$_me: you must specify a mount-point"
1421                 return 1
1422         fi
1423         debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1424         if ! mount -t devfs dev "$devdir"; then
1425                 warn "$_me: Unable to mount devfs on $devdir"
1426                 return 1
1427         fi
1428         if [ -n "$rs" ]; then
1429                 devfs_init_rulesets
1430                 devfs_set_ruleset $rs $devdir
1431                 devfs -m $devdir rule applyset
1432         fi
1433         return 0
1434 }
1435
1436 # devfs_mount_jail dir [ruleset]
1437 #       Mounts a devfs file system appropriate for jails
1438 #       on the directory dir. If ruleset is specified, the ruleset
1439 #       it names will be used instead.  If present, ruleset must
1440 #       be the name of a ruleset as defined in a devfs.rules(5) file.
1441 #       This function returns non-zero if an error occurs.
1442 #
1443 devfs_mount_jail()
1444 {
1445         local jdev rs _me
1446         jdev="$1"
1447         [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1448         _me="devfs_mount_jail"
1449
1450         devfs_init_rulesets
1451         if ! devfs_domount "$jdev" $rs; then
1452                 warn "$_me: devfs was not mounted on $jdev"
1453                 return 1
1454         fi
1455         return 0
1456 }
1457
1458 # Provide a function for normalizing the mounting of memory
1459 # filesystems.  This should allow the rest of the code here to remain
1460 # as close as possible between 5-current and 4-stable.
1461 #   $1 = size
1462 #   $2 = mount point
1463 #   $3 = (optional) extra mdmfs flags
1464 mount_md()
1465 {
1466         if [ -n "$3" ]; then
1467                 flags="$3"
1468         fi
1469         /sbin/mdmfs $flags -s $1 md $2
1470 }
1471
1472 # Code common to scripts that need to load a kernel module
1473 # if it isn't in the kernel yet. Syntax:
1474 #   load_kld [-e regex] [-m module] file
1475 # where -e or -m chooses the way to check if the module
1476 # is already loaded:
1477 #   regex is egrep'd in the output from `kldstat -v',
1478 #   module is passed to `kldstat -m'.
1479 # The default way is as though `-m file' were specified.
1480 load_kld()
1481 {
1482         local _loaded _mod _opt _re
1483
1484         while getopts "e:m:" _opt; do
1485                 case "$_opt" in
1486                 e) _re="$OPTARG" ;;
1487                 m) _mod="$OPTARG" ;;
1488                 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1489                 esac
1490         done
1491         shift $(($OPTIND - 1))
1492         if [ $# -ne 1 ]; then
1493                 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1494         fi
1495         _mod=${_mod:-$1}
1496         _loaded=false
1497         if [ -n "$_re" ]; then
1498                 if kldstat -v | egrep -q -e "$_re"; then
1499                         _loaded=true
1500                 fi
1501         else
1502                 if kldstat -q -m "$_mod"; then
1503                         _loaded=true
1504                 fi
1505         fi
1506         if ! $_loaded; then
1507                 if ! kldload "$1"; then
1508                         warn "Unable to load kernel module $1"
1509                         return 1
1510                 else
1511                         info "$1 kernel module loaded."
1512                 fi
1513         else
1514                 debug "load_kld: $1 kernel module already loaded."
1515         fi
1516         return 0
1517 }
1518
1519 # ltr str src dst
1520 #       Change every $src in $str to $dst.
1521 #       Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1522 #       awk(1).
1523 ltr()
1524 {
1525         local _str _src _dst _out _com
1526         _str=$1
1527         _src=$2
1528         _dst=$3
1529         _out=""
1530
1531         IFS=${_src}
1532         for _com in ${_str}; do
1533                 if [ -z "${_out}" ]; then
1534                         _out="${_com}"
1535                 else
1536                         _out="${_out}${_dst}${_com}"
1537                 fi
1538         done
1539         echo "${_out}"
1540 }
1541
1542 # Creates a list of providers for GELI encryption.
1543 geli_make_list()
1544 {
1545         local devices devices2
1546         local provider mountpoint type options rest
1547
1548         # Create list of GELI providers from fstab.
1549         while read provider mountpoint type options rest ; do
1550                 case ":${options}" in
1551                 :*noauto*)
1552                         noauto=yes
1553                         ;;
1554                 *)
1555                         noauto=no
1556                         ;;
1557                 esac
1558
1559                 case ":${provider}" in
1560                 :#*)
1561                         continue
1562                         ;;
1563                 *.eli)
1564                         # Skip swap devices.
1565                         if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1566                                 continue
1567                         fi
1568                         devices="${devices} ${provider}"
1569                         ;;
1570                 esac
1571         done < /etc/fstab
1572
1573         # Append providers from geli_devices.
1574         devices="${devices} ${geli_devices}"
1575
1576         for provider in ${devices}; do
1577                 provider=${provider%.eli}
1578                 provider=${provider#/dev/}
1579                 devices2="${devices2} ${provider}"
1580         done
1581
1582         echo ${devices2}
1583 }
1584
1585 # Find scripts in local_startup directories that use the old syntax
1586 #
1587 find_local_scripts_old () {
1588         zlist=''
1589         slist=''
1590         for dir in ${local_startup}; do
1591                 if [ -d "${dir}" ]; then
1592                         for file in ${dir}/[0-9]*.sh; do
1593                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1594                                     continue
1595                                 zlist="$zlist $file"
1596                         done
1597                         for file in ${dir}/[^0-9]*.sh; do
1598                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1599                                     continue
1600                                 slist="$slist $file"
1601                         done
1602                 fi
1603         done
1604 }
1605
1606 find_local_scripts_new () {
1607         local_rc=''
1608         for dir in ${local_startup}; do
1609                 if [ -d "${dir}" ]; then
1610                         for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1611                                 case "$file" in
1612                                 *.sample) ;;
1613                                 *)      if [ -x "$file" ]; then
1614                                                 local_rc="${local_rc} ${file}"
1615                                         fi
1616                                         ;;
1617                                 esac
1618                         done
1619                 fi
1620         done
1621 }
1622
1623 # check_required_{before|after} command
1624 #       Check for things required by the command before and after its precmd,
1625 #       respectively.  The two separate functions are needed because some
1626 #       conditions should prevent precmd from being run while other things
1627 #       depend on precmd having already been run.
1628 #
1629 check_required_before()
1630 {
1631         local _f
1632
1633         case "$1" in
1634         start)
1635                 for _f in $required_vars; do
1636                         if ! checkyesno $_f; then
1637                                 warn "\$${_f} is not enabled."
1638                                 if [ -z "$rc_force" ]; then
1639                                         return 1
1640                                 fi
1641                         fi
1642                 done
1643
1644                 for _f in $required_dirs; do
1645                         if [ ! -d "${_f}/." ]; then
1646                                 warn "${_f} is not a directory."
1647                                 if [ -z "$rc_force" ]; then
1648                                         return 1
1649                                 fi
1650                         fi
1651                 done
1652
1653                 for _f in $required_files; do
1654                         if [ ! -r "${_f}" ]; then
1655                                 warn "${_f} is not readable."
1656                                 if [ -z "$rc_force" ]; then
1657                                         return 1
1658                                 fi
1659                         fi
1660                 done
1661                 ;;
1662         esac
1663
1664         return 0
1665 }
1666
1667 check_required_after()
1668 {
1669         local _f _args
1670
1671         case "$1" in
1672         start)
1673                 for _f in $required_modules; do
1674                         case "${_f}" in
1675                                 *~*)    _args="-e ${_f#*~} ${_f%%~*}" ;;
1676                                 *:*)    _args="-m ${_f#*:} ${_f%%:*}" ;;
1677                                 *)      _args="${_f}" ;;
1678                         esac
1679                         if ! load_kld ${_args}; then
1680                                 if [ -z "$rc_force" ]; then
1681                                         return 1
1682                                 fi
1683                         fi
1684                 done
1685                 ;;
1686         esac
1687
1688         return 0
1689 }
1690
1691 fi
1692
1693 _rc_subr_loaded=: