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