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