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