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