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