]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - etc/rc.subr
MFC r242183:
[FreeBSD/stable/9.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}: ${_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         # Set defaults if defined.
1070         for _var in $rcvar $rcvars; do
1071                 eval _defval=\$${_var}_defval
1072                 if [ -n "$_defval" ]; then
1073                         eval : \${$_var:=\$${_var}_defval}
1074                 fi
1075         done
1076
1077         # check obsolete rc.conf variables
1078         for _var in $rcvars_obsolete; do
1079                 eval _v=\$$_var
1080                 eval _msg=\$${_var}_obsolete_msg
1081                 eval _new=\$${_var}_newvar
1082                 case $_v in
1083                 "")
1084                         ;;
1085                 *)
1086                         if [ -z "$_new" ]; then
1087                                 _msg="Ignored."
1088                         else
1089                                 eval $_new=\"\$$_var\"
1090                                 if [ -z "$_msg" ]; then
1091                                         _msg="Use \$$_new instead."
1092                                 fi
1093                         fi
1094                         warn "\$$_var is obsolete.  $_msg"
1095                         ;;
1096                 esac
1097         done
1098 }
1099
1100 #
1101 # load_rc_config_var name var
1102 #       Read the rc.conf(5) var for name and set in the
1103 #       current shell, using load_rc_config in a subshell to prevent
1104 #       unwanted side effects from other variable assignments.
1105 #
1106 load_rc_config_var()
1107 {
1108         if [ $# -ne 2 ]; then
1109                 err 3 'USAGE: load_rc_config_var name var'
1110         fi
1111         eval $(eval '(
1112                 load_rc_config '$1' >/dev/null;
1113                 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
1114                         echo '$2'=\'\''${'$2'}\'\'';
1115                 fi
1116         )' )
1117 }
1118
1119 #
1120 # rc_usage commands
1121 #       Print a usage string for $0, with `commands' being a list of
1122 #       valid commands.
1123 #
1124 rc_usage()
1125 {
1126         echo -n 1>&2 "Usage: $0 [fast|force|one|quiet]("
1127
1128         _sep=
1129         for _elem; do
1130                 echo -n 1>&2 "$_sep$_elem"
1131                 _sep="|"
1132         done
1133         echo 1>&2 ")"
1134         exit 1
1135 }
1136
1137 #
1138 # err exitval message
1139 #       Display message to stderr and log to the syslog, and exit with exitval.
1140 #
1141 err()
1142 {
1143         exitval=$1
1144         shift
1145
1146         if [ -x /usr/bin/logger ]; then
1147                 logger "$0: ERROR: $*"
1148         fi
1149         echo 1>&2 "$0: ERROR: $*"
1150         exit $exitval
1151 }
1152
1153 #
1154 # warn message
1155 #       Display message to stderr and log to the syslog.
1156 #
1157 warn()
1158 {
1159         if [ -x /usr/bin/logger ]; then
1160                 logger "$0: WARNING: $*"
1161         fi
1162         echo 1>&2 "$0: WARNING: $*"
1163 }
1164
1165 #
1166 # info message
1167 #       Display informational message to stdout and log to syslog.
1168 #
1169 info()
1170 {
1171         case ${rc_info} in
1172         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1173                 if [ -x /usr/bin/logger ]; then
1174                         logger "$0: INFO: $*"
1175                 fi
1176                 echo "$0: INFO: $*"
1177                 ;;
1178         esac
1179 }
1180
1181 #
1182 # debug message
1183 #       If debugging is enabled in rc.conf output message to stderr.
1184 #       BEWARE that you don't call any subroutine that itself calls this
1185 #       function.
1186 #
1187 debug()
1188 {
1189         case ${rc_debug} in
1190         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
1191                 if [ -x /usr/bin/logger ]; then
1192                         logger "$0: DEBUG: $*"
1193                 fi
1194                 echo 1>&2 "$0: DEBUG: $*"
1195                 ;;
1196         esac
1197 }
1198
1199 #
1200 # backup_file action file cur backup
1201 #       Make a backup copy of `file' into `cur', and save the previous
1202 #       version of `cur' as `backup' or use rcs for archiving.
1203 #
1204 #       This routine checks the value of the backup_uses_rcs variable,
1205 #       which can be either YES or NO.
1206 #
1207 #       The `action' keyword can be one of the following:
1208 #
1209 #       add             `file' is now being backed up (and is possibly
1210 #                       being reentered into the backups system).  `cur'
1211 #                       is created and RCS files, if necessary, are
1212 #                       created as well.
1213 #
1214 #       update          `file' has changed and needs to be backed up.
1215 #                       If `cur' exists, it is copied to to `back' or
1216 #                       checked into RCS (if the repository file is old),
1217 #                       and then `file' is copied to `cur'.  Another RCS
1218 #                       check in done here if RCS is being used.
1219 #
1220 #       remove          `file' is no longer being tracked by the backups
1221 #                       system.  If RCS is not being used, `cur' is moved
1222 #                       to `back', otherwise an empty file is checked in,
1223 #                       and then `cur' is removed.
1224 #
1225 #
1226 backup_file()
1227 {
1228         _action=$1
1229         _file=$2
1230         _cur=$3
1231         _back=$4
1232
1233         if checkyesno backup_uses_rcs; then
1234                 _msg0="backup archive"
1235                 _msg1="update"
1236
1237                 # ensure that history file is not locked
1238                 if [ -f $_cur,v ]; then
1239                         rcs -q -u -U -M $_cur
1240                 fi
1241
1242                 # ensure after switching to rcs that the
1243                 # current backup is not lost
1244                 if [ -f $_cur ]; then
1245                         # no archive, or current newer than archive
1246                         if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1247                                 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1248                                 rcs -q -kb -U $_cur
1249                                 co -q -f -u $_cur
1250                         fi
1251                 fi
1252
1253                 case $_action in
1254                 add|update)
1255                         cp -p $_file $_cur
1256                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1257                         rcs -q -kb -U $_cur
1258                         co -q -f -u $_cur
1259                         chown root:wheel $_cur $_cur,v
1260                         ;;
1261                 remove)
1262                         cp /dev/null $_cur
1263                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1264                         rcs -q -kb -U $_cur
1265                         chown root:wheel $_cur $_cur,v
1266                         rm $_cur
1267                         ;;
1268                 esac
1269         else
1270                 case $_action in
1271                 add|update)
1272                         if [ -f $_cur ]; then
1273                                 cp -p $_cur $_back
1274                         fi
1275                         cp -p $_file $_cur
1276                         chown root:wheel $_cur
1277                         ;;
1278                 remove)
1279                         mv -f $_cur $_back
1280                         ;;
1281                 esac
1282         fi
1283 }
1284
1285 # make_symlink src link
1286 #       Make a symbolic link 'link' to src from basedir. If the
1287 #       directory in which link is to be created does not exist
1288 #       a warning will be displayed and an error will be returned.
1289 #       Returns 0 on sucess, 1 otherwise.
1290 #
1291 make_symlink()
1292 {
1293         local src link linkdir _me
1294         src="$1"
1295         link="$2"
1296         linkdir="`dirname $link`"
1297         _me="make_symlink()"
1298
1299         if [ -z "$src" -o -z "$link" ]; then
1300                 warn "$_me: requires two arguments."
1301                 return 1
1302         fi
1303         if [ ! -d "$linkdir" ]; then
1304                 warn "$_me: the directory $linkdir does not exist."
1305                 return 1
1306         fi
1307         if ! ln -sf $src $link; then
1308                 warn "$_me: unable to make a symbolic link from $link to $src"
1309                 return 1
1310         fi
1311         return 0
1312 }
1313
1314 # devfs_rulesets_from_file file
1315 #       Reads a set of devfs commands from file, and creates
1316 #       the specified rulesets with their rules. Returns non-zero
1317 #       if there was an error.
1318 #
1319 devfs_rulesets_from_file()
1320 {
1321         local file _err _me
1322         file="$1"
1323         _me="devfs_rulesets_from_file"
1324         _err=0
1325
1326         if [ -z "$file" ]; then
1327                 warn "$_me: you must specify a file"
1328                 return 1
1329         fi
1330         if [ ! -e "$file" ]; then
1331                 debug "$_me: no such file ($file)"
1332                 return 0
1333         fi
1334         debug "reading rulesets from file ($file)"
1335         { while read line
1336         do
1337                 case $line in
1338                 \#*)
1339                         continue
1340                         ;;
1341                 \[*\]*)
1342                         rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1343                         if [ -z "$rulenum" ]; then
1344                                 warn "$_me: cannot extract rule number ($line)"
1345                                 _err=1
1346                                 break
1347                         fi
1348                         rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1349                         if [ -z "$rulename" ]; then
1350                                 warn "$_me: cannot extract rule name ($line)"
1351                                 _err=1
1352                                 break;
1353                         fi
1354                         eval $rulename=\$rulenum
1355                         debug "found ruleset: $rulename=$rulenum"
1356                         if ! /sbin/devfs rule -s $rulenum delset; then
1357                                 _err=1
1358                                 break
1359                         fi
1360                         ;;
1361                 *)
1362                         rulecmd="${line%%"\#*"}"
1363                         # evaluate the command incase it includes
1364                         # other rules
1365                         if [ -n "$rulecmd" ]; then
1366                                 debug "adding rule ($rulecmd)"
1367                                 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1368                                 then
1369                                         _err=1
1370                                         break
1371                                 fi
1372                         fi
1373                         ;;
1374                 esac
1375                 if [ $_err -ne 0 ]; then
1376                         debug "error in $_me"
1377                         break
1378                 fi
1379         done } < $file
1380         return $_err
1381 }
1382
1383 # devfs_init_rulesets
1384 #       Initializes rulesets from configuration files. Returns
1385 #       non-zero if there was an error.
1386 #
1387 devfs_init_rulesets()
1388 {
1389         local file _me
1390         _me="devfs_init_rulesets"
1391
1392         # Go through this only once
1393         if [ -n "$devfs_rulesets_init" ]; then
1394                 debug "$_me: devfs rulesets already initialized"
1395                 return
1396         fi
1397         for file in $devfs_rulesets; do
1398                 if ! devfs_rulesets_from_file $file; then
1399                         warn "$_me: could not read rules from $file"
1400                         return 1
1401                 fi
1402         done
1403         devfs_rulesets_init=1
1404         debug "$_me: devfs rulesets initialized"
1405         return 0
1406 }
1407
1408 # devfs_set_ruleset ruleset [dir]
1409 #       Sets the default ruleset of dir to ruleset. The ruleset argument
1410 #       must be a ruleset name as specified in devfs.rules(5) file.
1411 #       Returns non-zero if it could not set it successfully.
1412 #
1413 devfs_set_ruleset()
1414 {
1415         local devdir rs _me
1416         [ -n "$1" ] && eval rs=\$$1 || rs=
1417         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1418         _me="devfs_set_ruleset"
1419
1420         if [ -z "$rs" ]; then
1421                 warn "$_me: you must specify a ruleset number"
1422                 return 1
1423         fi
1424         debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1425         if ! /sbin/devfs $devdir ruleset $rs; then
1426                 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1427                 return 1
1428         fi
1429         return 0
1430 }
1431
1432 # devfs_apply_ruleset ruleset [dir]
1433 #       Apply ruleset number $ruleset to the devfs mountpoint $dir.
1434 #       The ruleset argument must be a ruleset name as specified
1435 #       in a devfs.rules(5) file.  Returns 0 on success or non-zero
1436 #       if it could not apply the ruleset.
1437 #
1438 devfs_apply_ruleset()
1439 {
1440         local devdir rs _me
1441         [ -n "$1" ] && eval rs=\$$1 || rs=
1442         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1443         _me="devfs_apply_ruleset"
1444
1445         if [ -z "$rs" ]; then
1446                 warn "$_me: you must specify a ruleset"
1447                 return 1
1448         fi
1449         debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1450         if ! /sbin/devfs $devdir rule -s $rs applyset; then
1451                 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1452                 return 1
1453         fi
1454         return 0
1455 }
1456
1457 # devfs_domount dir [ruleset]
1458 #       Mount devfs on dir. If ruleset is specified it is set
1459 #       on the mount-point. It must also be a ruleset name as specified
1460 #       in a devfs.rules(5) file. Returns 0 on success.
1461 #
1462 devfs_domount()
1463 {
1464         local devdir rs _me
1465         devdir="$1"
1466         [ -n "$2" ] && rs=$2 || rs=
1467         _me="devfs_domount()"
1468
1469         if [ -z "$devdir" ]; then
1470                 warn "$_me: you must specify a mount-point"
1471                 return 1
1472         fi
1473         debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1474         if ! mount -t devfs dev "$devdir"; then
1475                 warn "$_me: Unable to mount devfs on $devdir"
1476                 return 1
1477         fi
1478         if [ -n "$rs" ]; then
1479                 devfs_init_rulesets
1480                 devfs_set_ruleset $rs $devdir
1481                 devfs -m $devdir rule applyset
1482         fi
1483         return 0
1484 }
1485
1486 # devfs_mount_jail dir [ruleset]
1487 #       Mounts a devfs file system appropriate for jails
1488 #       on the directory dir. If ruleset is specified, the ruleset
1489 #       it names will be used instead.  If present, ruleset must
1490 #       be the name of a ruleset as defined in a devfs.rules(5) file.
1491 #       This function returns non-zero if an error occurs.
1492 #
1493 devfs_mount_jail()
1494 {
1495         local jdev rs _me
1496         jdev="$1"
1497         [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1498         _me="devfs_mount_jail"
1499
1500         devfs_init_rulesets
1501         if ! devfs_domount "$jdev" $rs; then
1502                 warn "$_me: devfs was not mounted on $jdev"
1503                 return 1
1504         fi
1505         return 0
1506 }
1507
1508 # Provide a function for normalizing the mounting of memory
1509 # filesystems.  This should allow the rest of the code here to remain
1510 # as close as possible between 5-current and 4-stable.
1511 #   $1 = size
1512 #   $2 = mount point
1513 #   $3 = (optional) extra mdmfs flags
1514 mount_md()
1515 {
1516         if [ -n "$3" ]; then
1517                 flags="$3"
1518         fi
1519         /sbin/mdmfs $flags -s $1 md $2
1520 }
1521
1522 # Code common to scripts that need to load a kernel module
1523 # if it isn't in the kernel yet. Syntax:
1524 #   load_kld [-e regex] [-m module] file
1525 # where -e or -m chooses the way to check if the module
1526 # is already loaded:
1527 #   regex is egrep'd in the output from `kldstat -v',
1528 #   module is passed to `kldstat -m'.
1529 # The default way is as though `-m file' were specified.
1530 load_kld()
1531 {
1532         local _loaded _mod _opt _re
1533
1534         while getopts "e:m:" _opt; do
1535                 case "$_opt" in
1536                 e) _re="$OPTARG" ;;
1537                 m) _mod="$OPTARG" ;;
1538                 *) err 3 'USAGE: load_kld [-e regex] [-m module] file' ;;
1539                 esac
1540         done
1541         shift $(($OPTIND - 1))
1542         if [ $# -ne 1 ]; then
1543                 err 3 'USAGE: load_kld [-e regex] [-m module] file'
1544         fi
1545         _mod=${_mod:-$1}
1546         _loaded=false
1547         if [ -n "$_re" ]; then
1548                 if kldstat -v | egrep -q -e "$_re"; then
1549                         _loaded=true
1550                 fi
1551         else
1552                 if kldstat -q -m "$_mod"; then
1553                         _loaded=true
1554                 fi
1555         fi
1556         if ! $_loaded; then
1557                 if ! kldload "$1"; then
1558                         warn "Unable to load kernel module $1"
1559                         return 1
1560                 else
1561                         info "$1 kernel module loaded."
1562                 fi
1563         else
1564                 debug "load_kld: $1 kernel module already loaded."
1565         fi
1566         return 0
1567 }
1568
1569 # ltr str src dst
1570 #       Change every $src in $str to $dst.
1571 #       Useful when /usr is not yet mounted and we cannot use tr(1), sed(1) nor
1572 #       awk(1).
1573 ltr()
1574 {
1575         local _str _src _dst _out _com
1576         _str=$1
1577         _src=$2
1578         _dst=$3
1579         _out=""
1580
1581         IFS=${_src}
1582         for _com in ${_str}; do
1583                 if [ -z "${_out}" ]; then
1584                         _out="${_com}"
1585                 else
1586                         _out="${_out}${_dst}${_com}"
1587                 fi
1588         done
1589         echo "${_out}"
1590 }
1591
1592 # Creates a list of providers for GELI encryption.
1593 geli_make_list()
1594 {
1595         local devices devices2
1596         local provider mountpoint type options rest
1597
1598         # Create list of GELI providers from fstab.
1599         while read provider mountpoint type options rest ; do
1600                 case ":${options}" in
1601                 :*noauto*)
1602                         noauto=yes
1603                         ;;
1604                 *)
1605                         noauto=no
1606                         ;;
1607                 esac
1608
1609                 case ":${provider}" in
1610                 :#*)
1611                         continue
1612                         ;;
1613                 *.eli)
1614                         # Skip swap devices.
1615                         if [ "${type}" = "swap" -o "${options}" = "sw" -o "${noauto}" = "yes" ]; then
1616                                 continue
1617                         fi
1618                         devices="${devices} ${provider}"
1619                         ;;
1620                 esac
1621         done < /etc/fstab
1622
1623         # Append providers from geli_devices.
1624         devices="${devices} ${geli_devices}"
1625
1626         for provider in ${devices}; do
1627                 provider=${provider%.eli}
1628                 provider=${provider#/dev/}
1629                 devices2="${devices2} ${provider}"
1630         done
1631
1632         echo ${devices2}
1633 }
1634
1635 # Find scripts in local_startup directories that use the old syntax
1636 #
1637 find_local_scripts_old () {
1638         zlist=''
1639         slist=''
1640         for dir in ${local_startup}; do
1641                 if [ -d "${dir}" ]; then
1642                         for file in ${dir}/[0-9]*.sh; do
1643                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1644                                     continue
1645                                 zlist="$zlist $file"
1646                         done
1647                         for file in ${dir}/[^0-9]*.sh; do
1648                                 grep '^# PROVIDE:' $file >/dev/null 2>&1 &&
1649                                     continue
1650                                 slist="$slist $file"
1651                         done
1652                 fi
1653         done
1654 }
1655
1656 find_local_scripts_new () {
1657         local_rc=''
1658         for dir in ${local_startup}; do
1659                 if [ -d "${dir}" ]; then
1660                         for file in `grep -l '^# PROVIDE:' ${dir}/* 2>/dev/null`; do
1661                                 case "$file" in
1662                                 *.sample) ;;
1663                                 *)      if [ -x "$file" ]; then
1664                                                 local_rc="${local_rc} ${file}"
1665                                         fi
1666                                         ;;
1667                                 esac
1668                         done
1669                 fi
1670         done
1671 }
1672
1673 # check_required_{before|after} command
1674 #       Check for things required by the command before and after its precmd,
1675 #       respectively.  The two separate functions are needed because some
1676 #       conditions should prevent precmd from being run while other things
1677 #       depend on precmd having already been run.
1678 #
1679 check_required_before()
1680 {
1681         local _f
1682
1683         case "$1" in
1684         start)
1685                 for _f in $required_vars; do
1686                         if ! checkyesno $_f; then
1687                                 warn "\$${_f} is not enabled."
1688                                 if [ -z "$rc_force" ]; then
1689                                         return 1
1690                                 fi
1691                         fi
1692                 done
1693
1694                 for _f in $required_dirs; do
1695                         if [ ! -d "${_f}/." ]; then
1696                                 warn "${_f} is not a directory."
1697                                 if [ -z "$rc_force" ]; then
1698                                         return 1
1699                                 fi
1700                         fi
1701                 done
1702
1703                 for _f in $required_files; do
1704                         if [ ! -r "${_f}" ]; then
1705                                 warn "${_f} is not readable."
1706                                 if [ -z "$rc_force" ]; then
1707                                         return 1
1708                                 fi
1709                         fi
1710                 done
1711                 ;;
1712         esac
1713
1714         return 0
1715 }
1716
1717 check_required_after()
1718 {
1719         local _f _args
1720
1721         case "$1" in
1722         start)
1723                 for _f in $required_modules; do
1724                         case "${_f}" in
1725                                 *~*)    _args="-e ${_f#*~} ${_f%%~*}" ;;
1726                                 *:*)    _args="-m ${_f#*:} ${_f%%:*}" ;;
1727                                 *)      _args="${_f}" ;;
1728                         esac
1729                         if ! load_kld ${_args}; then
1730                                 if [ -z "$rc_force" ]; then
1731                                         return 1
1732                                 fi
1733                         fi
1734                 done
1735                 ;;
1736         esac
1737
1738         return 0
1739 }
1740
1741 # check_kern_features mib
1742 #       Return existence of kern.features.* sysctl MIB as true or
1743 #       false.  The result will be cached in $_rc_cache_kern_features_
1744 #       namespace.  "0" means the kern.features.X exists.
1745
1746 check_kern_features()
1747 {
1748         local _v
1749
1750         [ -n "$1" ] || return 1;
1751         eval _v=\$_rc_cache_kern_features_$1
1752         [ -n "$_v" ] && return "$_v";
1753
1754         if ${SYSCTL_N} kern.features.$1 > /dev/null 2>&1; then
1755                 eval _rc_cache_kern_features_$1=0
1756                 return 0
1757         else
1758                 eval _rc_cache_kern_features_$1=1
1759                 return 1
1760         fi
1761 }
1762
1763 # _echoonce var msg mode
1764 #       mode=0: Echo $msg if ${$var} is empty.
1765 #               After doing echo, a string is set to ${$var}.
1766 #
1767 #       mode=1: Echo $msg if ${$var} is a string with non-zero length.
1768 #
1769 _echoonce()
1770 {
1771         local _var _msg _mode
1772         eval _var=\$$1
1773         _msg=$2
1774         _mode=$3
1775
1776         case $_mode in
1777         1)      [ -n "$_var" ] && echo "$_msg" ;;
1778         *)      [ -z "$_var" ] && echo -n "$_msg" && eval "$1=finished" ;;
1779         esac
1780 }
1781
1782 fi # [ -z "${_rc_subr_loaded}" ]
1783
1784 _rc_subr_loaded=: