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