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