Remove unneeded t_event.debug (t_event is a shell script).
[netbsd-mini2440.git] / etc / rc.subr
blobedef41c6c6008bd3dca1426f21ebd713cbd4e23c
1 # $NetBSD: rc.subr,v 1.79 2009/09/14 12:05:12 apb Exp $
3 # Copyright (c) 1997-2004 The NetBSD Foundation, Inc.
4 # All rights reserved.
6 # This code is derived from software contributed to The NetBSD Foundation
7 # by Luke Mewburn.
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 # 1. Redistributions of source code must retain the above copyright
13 #    notice, this list of conditions and the following disclaimer.
14 # 2. Redistributions in binary form must reproduce the above copyright
15 #    notice, this list of conditions and the following disclaimer in the
16 #    documentation and/or other materials provided with the distribution.
18 # THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
19 # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
22 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
30 # rc.subr
31 #       functions used by various rc scripts
34 : ${rcvar_manpage:='rc.conf(5)'}
35 : ${RC_PID:=$$} ; export RC_PID
36 nl='
37 ' # a literal newline
40 #       functions
41 #       ---------
44 # checkyesno var
45 #       Test $1 variable, and warn if not set to YES or NO.
46 #       Return 0 if it's "yes" (et al), nonzero otherwise.
48 checkyesno()
50         eval _value=\$${1}
51         case $_value in
53                 #       "yes", "true", "on", or "1"
54         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
55                 return 0
56                 ;;
58                 #       "no", "false", "off", or "0"
59         [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
60                 return 1
61                 ;;
62         *)
63                 warn "\$${1} is not set properly - see ${rcvar_manpage}."
64                 return 1
65                 ;;
66         esac
70 # yesno_to_truefalse var
71 #       Convert the value of a variable from any of the values
72 #       understood by checkyesno() to "true" or "false".
74 yesno_to_truefalse()
76         local var=$1
77         if checkyesno $var; then
78                 eval $var=true
79                 return 0
80         else
81                 eval $var=false
82                 return 1
83         fi
87 # reverse_list list
88 #       print the list in reverse order
90 reverse_list()
92         _revlist=
93         for _revfile; do
94                 _revlist="$_revfile $_revlist"
95         done
96         echo $_revlist
100 # If booting directly to multiuser, send SIGTERM to
101 # the parent (/etc/rc) to abort the boot.
102 # Otherwise just exit.
104 stop_boot()
106         if [ "$autoboot" = yes ]; then
107                 echo "ERROR: ABORTING BOOT (sending SIGTERM to parent)!"
108                 kill -TERM ${RC_PID}
109         fi
110         exit 1
114 # mount_critical_filesystems type
115 #       Go through the list of critical filesystems as provided in
116 #       the rc.conf(5) variable $critical_filesystems_${type}, checking
117 #       each one to see if it is mounted, and if it is not, mounting it.
118 #       It's not an error if file systems prefixed with "OPTIONAL:"
119 #       are not mentioned in /etc/fstab.
121 mount_critical_filesystems()
123         eval _fslist=\$critical_filesystems_${1}
124         _mountcrit_es=0
125         for _fs in $_fslist; do
126                 _optional=false
127                 case "$_fs" in
128                 OPTIONAL:*)
129                         _optional=true
130                         _fs="${_fs#*:}"
131                         ;;
132                 esac
133                 _ismounted=false
134                 # look for a line like "${fs} on * type *"
135                 # or "* on ${fs} type *" in the output from mount.
136                 case "${nl}$( mount )${nl}" in
137                 *" on ${_fs} type "*)
138                         _ismounted=true
139                         ;;
140                 *"${nl}${_fs} on "*)
141                         _ismounted=true
142                         ;;
143                 esac
144                 if $_ismounted; then
145                         print_rc_metadata \
146                         "note:File system ${_fs} was already mounted"
147                 else
148                         _mount_output=$( mount $_fs 2>&1 )
149                         _mount_es=$?
150                         case "$_mount_output" in
151                         *"${nl}"*)
152                                 # multiple lines can't be good,
153                                 # not even if $_optional is true
154                                 ;;
155                         *'unknown special file or file system'*)
156                                 if $_optional; then
157                                         # ignore this error
158                                         print_rc_metadata \
159                         "note:Optional file system ${_fs} is not present"
160                                         _mount_es=0
161                                         _mount_output=""
162                                 fi
163                                 ;;
164                         esac
165                         if [ -n "$_mount_output" ]; then
166                                 printf >&2 "%s\n" "$_mount_output"
167                         fi
168                         if [ "$_mount_es" != 0 ]; then
169                                 _mountcrit_es="$_mount_es"
170                         fi
171                 fi
172         done
173         return $_mountcrit_es
177 # check_pidfile pidfile procname [interpreter]
178 #       Parses the first line of pidfile for a PID, and ensures
179 #       that the process is running and matches procname.
180 #       Prints the matching PID upon success, nothing otherwise.
181 #       interpreter is optional; see _find_processes() for details.
183 check_pidfile()
185         _pidfile=$1
186         _procname=$2
187         _interpreter=$3
188         if [ -z "$_pidfile" -o -z "$_procname" ]; then
189                 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
190         fi
191         if [ ! -f $_pidfile ]; then
192                 return
193         fi
194         read _pid _junk < $_pidfile
195         if [ -z "$_pid" ]; then
196                 return
197         fi
198         _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
202 # check_process procname [interpreter]
203 #       Ensures that a process (or processes) named procname is running.
204 #       Prints a list of matching PIDs.
205 #       interpreter is optional; see _find_processes() for details.
207 check_process()
209         _procname=$1
210         _interpreter=$2
211         if [ -z "$_procname" ]; then
212                 err 3 'USAGE: check_process procname [interpreter]'
213         fi
214         _find_processes $_procname ${_interpreter:-.} '-ax'
218 # _find_processes procname interpreter psargs
219 #       Search for procname in the output of ps generated by psargs.
220 #       Prints the PIDs of any matching processes, space separated.
222 #       If interpreter == ".", check the following variations of procname
223 #       against the first word of each command:
224 #               procname
225 #               `basename procname`
226 #               `basename procname` + ":"
227 #               "(" + `basename procname` + ")"
229 #       If interpreter != ".", read the first line of procname, remove the
230 #       leading #!, normalise whitespace, append procname, and attempt to
231 #       match that against each command, either as is, or with extra words
232 #       at the end.  As an alternative, to deal with interpreted daemons
233 #       using perl, the basename of the interpreter plus a colon is also
234 #       tried as the prefix to procname.
236 _find_processes()
238         if [ $# -ne 3 ]; then
239                 err 3 'USAGE: _find_processes procname interpreter psargs'
240         fi
241         _procname=$1
242         _interpreter=$2
243         _psargs=$3
245         _pref=
246         _procnamebn=${_procname##*/}
247         if [ $_interpreter != "." ]; then       # an interpreted script
248                 read _interp < ${_chroot:-}/$_procname  # read interpreter name
249                 _interp=${_interp#\#!}          # strip #!
250                 set -- $_interp
251                 if [ $_interpreter != $1 ]; then
252                         warn "\$command_interpreter $_interpreter != $1"
253                 fi
254                 _interp="$* $_procname"         # cleanup spaces, add _procname
255                 _interpbn=${1##*/}
256                 _fp_args='_argv'
257                 _fp_match='case "$_argv" in
258                     ${_interp}|"${_interp} "*|"${_interpbn}: "*${_procnamebn}*)'
259         else                                    # a normal daemon
260                 _fp_args='_arg0 _argv'
261                 _fp_match='case "$_arg0" in
262                     $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")'
263         fi
265         _proccheck='
266                 ps -o "pid,command" '"$_psargs"' |
267                 while read _npid '"$_fp_args"'; do
268                         case "$_npid" in
269                             PID)
270                                 continue ;;
271                         esac ; '"$_fp_match"'
272                                 echo -n "$_pref$_npid" ;
273                                 _pref=" "
274                                 ;;
275                         esac
276                 done'
278 #echo 1>&2 "proccheck is :$_proccheck:"
279         eval $_proccheck
283 # wait_for_pids pid [pid ...]
284 #       spins until none of the pids exist
286 wait_for_pids()
288         _list="$@"
289         if [ -z "$_list" ]; then
290                 return
291         fi
292         _prefix=
293         while true; do
294                 _nlist="";
295                 for _j in $_list; do
296                         if kill -0 $_j 2>/dev/null; then
297                                 _nlist="${_nlist}${_nlist:+ }$_j"
298                         fi
299                 done
300                 if [ -z "$_nlist" ]; then
301                         break
302                 fi
303                 _list=$_nlist
304                 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
305                 _prefix=", "
306                 sleep 2
307         done
308         if [ -n "$_prefix" ]; then
309                 echo "."
310         fi
314 # run_rc_command argument
315 #       Search for argument in the list of supported commands, which is:
316 #               "start stop restart rcvar status poll ${extra_commands}"
317 #       If there's a match, run ${argument}_cmd or the default method
318 #       (see below).
320 #       If argument has a given prefix, then change the operation as follows:
321 #               Prefix  Operation
322 #               ------  ---------
323 #               fast    Skip the pid check, and set rc_fast=yes
324 #               force   Set ${rcvar} to YES, and set rc_force=yes
325 #               one     Set ${rcvar} to YES
327 #       The following globals are used:
329 #       Name            Needed  Purpose
330 #       ----            ------  -------
331 #       name            y       Name of script.
333 #       command         n       Full path to command.
334 #                               Not needed if ${rc_arg}_cmd is set for
335 #                               each keyword.
337 #       command_args    n       Optional args/shell directives for command.
339 #       command_interpreter n   If not empty, command is interpreted, so
340 #                               call check_{pidfile,process}() appropriately.
342 #       extra_commands  n       List of extra commands supported.
344 #       pidfile         n       If set, use check_pidfile $pidfile $command,
345 #                               otherwise use check_process $command.
346 #                               In either case, only check if $command is set.
348 #       procname        n       Process name to check for instead of $command.
350 #       rcvar           n       This is checked with checkyesno to determine
351 #                               if the action should be run.
353 #       ${name}_chroot  n       Directory to chroot to before running ${command}
354 #                               Requires /usr to be mounted.
356 #       ${name}_chdir   n       Directory to cd to before running ${command}
357 #                               (if not using ${name}_chroot).
359 #       ${name}_flags   n       Arguments to call ${command} with.
360 #                               NOTE:   $flags from the parent environment
361 #                                       can be used to override this.
363 #       ${name}_env     n       Additional environment variable settings
364 #                               for running ${command}
366 #       ${name}_nice    n       Nice level to run ${command} at.
368 #       ${name}_user    n       User to run ${command} as, using su(1) if not
369 #                               using ${name}_chroot.
370 #                               Requires /usr to be mounted.
372 #       ${name}_group   n       Group to run chrooted ${command} as.
373 #                               Requires /usr to be mounted.
375 #       ${name}_groups  n       Comma separated list of supplementary groups
376 #                               to run the chrooted ${command} with.
377 #                               Requires /usr to be mounted.
379 #       ${rc_arg}_cmd   n       If set, use this as the method when invoked;
380 #                               Otherwise, use default command (see below)
382 #       ${rc_arg}_precmd n      If set, run just before performing the
383 #                               ${rc_arg}_cmd method in the default
384 #                               operation (i.e, after checking for required
385 #                               bits and process (non)existence).
386 #                               If this completes with a non-zero exit code,
387 #                               don't run ${rc_arg}_cmd.
389 #       ${rc_arg}_postcmd n     If set, run just after performing the
390 #                               ${rc_arg}_cmd method, if that method
391 #                               returned a zero exit code.
393 #       required_dirs   n       If set, check for the existence of the given
394 #                               directories before running the default
395 #                               (re)start command.
397 #       required_files  n       If set, check for the readability of the given
398 #                               files before running the default (re)start
399 #                               command.
401 #       required_vars   n       If set, perform checkyesno on each of the
402 #                               listed variables before running the default
403 #                               (re)start command.
405 #       Default behaviour for a given argument, if no override method is
406 #       provided:
408 #       Argument        Default behaviour
409 #       --------        -----------------
410 #       start           if !running && checkyesno ${rcvar}
411 #                               ${command}
413 #       stop            if ${pidfile}
414 #                               rc_pid=$(check_pidfile $pidfile $command)
415 #                       else
416 #                               rc_pid=$(check_process $command)
417 #                       kill $sig_stop $rc_pid
418 #                       wait_for_pids $rc_pid
419 #                       ($sig_stop defaults to TERM.)
421 #       reload          Similar to stop, except use $sig_reload instead,
422 #                       and doesn't wait_for_pids.
423 #                       $sig_reload defaults to HUP.
425 #       restart         Run `stop' then `start'.
427 #       status          Show if ${command} is running, etc.
429 #       poll            Wait for ${command} to exit.
431 #       rcvar           Display what rc.conf variable is used (if any).
433 #       Variables available to methods, and after run_rc_command() has
434 #       completed:
436 #       Variable        Purpose
437 #       --------        -------
438 #       rc_arg          Argument to command, after fast/force/one processing
439 #                       performed
441 #       rc_flags        Flags to start the default command with.
442 #                       Defaults to ${name}_flags, unless overridden
443 #                       by $flags from the environment.
444 #                       This variable may be changed by the precmd method.
446 #       rc_pid          PID of command (if appropriate)
448 #       rc_fast         Not empty if "fast" was provided (q.v.)
450 #       rc_force        Not empty if "force" was provided (q.v.)
453 run_rc_command()
455         rc_arg=$1
456         if [ -z "$name" ]; then
457                 err 3 'run_rc_command: $name is not set.'
458         fi
460         _rc_prefix=
461         case "$rc_arg" in
462         fast*)                          # "fast" prefix; don't check pid
463                 rc_arg=${rc_arg#fast}
464                 rc_fast=yes
465                 ;;
466         force*)                         # "force" prefix; always run
467                 rc_force=yes
468                 _rc_prefix=force
469                 rc_arg=${rc_arg#${_rc_prefix}}
470                 if [ -n "${rcvar}" ]; then
471                         eval ${rcvar}=YES
472                 fi
473                 ;;
474         one*)                           # "one" prefix; set ${rcvar}=yes
475                 _rc_prefix=one
476                 rc_arg=${rc_arg#${_rc_prefix}}
477                 if [ -n "${rcvar}" ]; then
478                         eval ${rcvar}=YES
479                 fi
480                 ;;
481         esac
483         _keywords="start stop restart rcvar"
484         if [ -n "$extra_commands" ]; then
485                 _keywords="${_keywords} ${extra_commands}"
486         fi
487         rc_pid=
488         _pidcmd=
489         _procname=${procname:-${command}}
491                                         # setup pid check command if not fast
492         if [ -z "$rc_fast" -a -n "$_procname" ]; then
493                 if [ -n "$pidfile" ]; then
494                         _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
495                 else
496                         _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
497                 fi
498                 if [ -n "$_pidcmd" ]; then
499                         _keywords="${_keywords} status poll"
500                 fi
501         fi
503         if [ -z "$rc_arg" ]; then
504                 rc_usage "$_keywords"
505         fi
507         if [ -n "$flags" ]; then        # allow override from environment
508                 rc_flags=$flags
509         else
510                 eval rc_flags=\$${name}_flags
511         fi
512         eval _chdir=\$${name}_chdir     _chroot=\$${name}_chroot \
513             _nice=\$${name}_nice        _user=\$${name}_user \
514             _group=\$${name}_group      _groups=\$${name}_groups \
515             _env=\"\$${name}_env\"
517         if [ -n "$_user" ]; then        # unset $_user if running as that user
518                 if [ "$_user" = "$(id -un)" ]; then
519                         unset _user
520                 fi
521         fi
523                                         # if ${rcvar} is set, and $1 is not
524                                         # "rcvar", then run
525                                         #       checkyesno ${rcvar}
526                                         # and return if that failed or warn
527                                         # user and exit when interactive
528                                         #
529         if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
530                 if ! checkyesno ${rcvar}; then
531                                         # check whether interactive or not
532                         if [ -n "$_run_rc_script" ]; then
533                                 return 0
534                         fi
535                         for _elem in $_keywords; do
536                                 if [ "$_elem" = "$rc_arg" ]; then
537                                         echo 1>&2 "\$${rcvar} is not enabled - see ${rcvar_manpage}."
538                                         echo 1>&2 "Use the following if you wish to perform the operation:"
539                                         echo 1>&2 "  $0 one${rc_arg}"
540                                         exit 1
541                                 fi
542                         done
543                         echo 1>&2 "$0: unknown directive '$rc_arg'."
544                         rc_usage "$_keywords"
545                 fi
546         fi
548         eval $_pidcmd                   # determine the pid if necessary
550         for _elem in $_keywords; do
551                 if [ "$_elem" != "$rc_arg" ]; then
552                         continue
553                 fi
555                                         # if there's a custom ${XXX_cmd},
556                                         # run that instead of the default
557                                         #
558                 eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \
559                     _postcmd=\$${rc_arg}_postcmd
560                 if [ -n "$_cmd" ]; then
561                                         # if the precmd failed and force
562                                         # isn't set, exit
563                                         #
564                         if ! eval $_precmd && [ -z "$rc_force" ]; then
565                                 return 1
566                         fi
568                         if ! eval $_cmd && [ -z "$rc_force" ]; then
569                                 return 1
570                         fi
571                         eval $_postcmd
572                         return 0
573                 fi
575                 case "$rc_arg" in       # default operations...
577                 status)
578                         if [ -n "$rc_pid" ]; then
579                                 echo "${name} is running as pid $rc_pid."
580                         else
581                                 echo "${name} is not running."
582                                 return 1
583                         fi
584                         ;;
586                 start)
587                         if [ -n "$rc_pid" ]; then
588                                 echo 1>&2 "${name} already running? (pid=$rc_pid)."
589                                 exit 1
590                         fi
592                         if [ ! -x ${_chroot}${command} ]; then
593                                 return 0
594                         fi
596                                         # check for required variables,
597                                         # directories, and files
598                                         #
599                         for _f in $required_vars; do
600                                 if ! checkyesno $_f; then
601                                         warn "\$${_f} is not enabled."
602                                         if [ -z "$rc_force" ]; then
603                                                 return 1
604                                         fi
605                                 fi
606                         done
607                         for _f in $required_dirs; do
608                                 if [ ! -d "${_f}/." ]; then
609                                         warn "${_f} is not a directory."
610                                         if [ -z "$rc_force" ]; then
611                                                 return 1
612                                         fi
613                                 fi
614                         done
615                         for _f in $required_files; do
616                                 if [ ! -r "${_f}" ]; then
617                                         warn "${_f} is not readable."
618                                         if [ -z "$rc_force" ]; then
619                                                 return 1
620                                         fi
621                                 fi
622                         done
624                                         # if the precmd failed and force
625                                         # isn't set, exit
626                                         #
627                         if ! eval $_precmd && [ -z "$rc_force" ]; then
628                                 return 1
629                         fi
631                                         # setup the command to run, and run it
632                                         #
633                         echo "Starting ${name}."
634                         if [ -n "$_chroot" ]; then
635                                 _doit="\
636 ${_env:+env $_env }\
637 ${_nice:+nice -n $_nice }\
638 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
639 $_chroot $command $rc_flags $command_args"
640                         else
641                                 _doit="\
642 ${_chdir:+cd $_chdir; }\
643 ${_env:+env $_env }\
644 ${_nice:+nice -n $_nice }\
645 $command $rc_flags $command_args"
646                                 if [ -n "$_user" ]; then
647                                     _doit="su -m $_user -c 'sh -c \"$_doit\"'"
648                                 fi
649                         fi
651                                         # if the cmd failed and force
652                                         # isn't set, exit
653                                         #
654                         if ! eval $_doit && [ -z "$rc_force" ]; then
655                                 return 1
656                         fi
658                                         # finally, run postcmd
659                                         #
660                         eval $_postcmd
661                         ;;
663                 stop)
664                         if [ -z "$rc_pid" ]; then
665                                 if [ -n "$pidfile" ]; then
666                                         echo 1>&2 \
667                                     "${name} not running? (check $pidfile)."
668                                 else
669                                         echo 1>&2 "${name} not running?"
670                                 fi
671                                 exit 1
672                         fi
674                                         # if the precmd failed and force
675                                         # isn't set, exit
676                                         #
677                         if ! eval $_precmd && [ -z "$rc_force" ]; then
678                                 return 1
679                         fi
681                                         # send the signal to stop
682                                         #
683                         echo "Stopping ${name}."
684                         _doit="kill -${sig_stop:-TERM} $rc_pid"
685                         if [ -n "$_user" ]; then
686                                 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
687                         fi
689                                         # if the stop cmd failed and force
690                                         # isn't set, exit
691                                         #
692                         if ! eval $_doit && [ -z "$rc_force" ]; then
693                                 return 1
694                         fi
696                                         # wait for the command to exit,
697                                         # and run postcmd.
698                         wait_for_pids $rc_pid
699                         eval $_postcmd
700                         ;;
702                 reload)
703                         if [ -z "$rc_pid" ]; then
704                                 if [ -n "$pidfile" ]; then
705                                         echo 1>&2 \
706                                     "${name} not running? (check $pidfile)."
707                                 else
708                                         echo 1>&2 "${name} not running?"
709                                 fi
710                                 exit 1
711                         fi
712                         echo "Reloading ${name} config files."
713                         if ! eval $_precmd && [ -z "$rc_force" ]; then
714                                 return 1
715                         fi
716                         _doit="kill -${sig_reload:-HUP} $rc_pid"
717                         if [ -n "$_user" ]; then
718                                 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
719                         fi
720                         if ! eval $_doit && [ -z "$rc_force" ]; then
721                                 return 1
722                         fi
723                         eval $_postcmd
724                         ;;
726                 restart)
727                         if ! eval $_precmd && [ -z "$rc_force" ]; then
728                                 return 1
729                         fi
730                                         # prevent restart being called more
731                                         # than once by any given script
732                                         #
733                         if ${_rc_restart_done:-false}; then
734                                 return 0
735                         fi
736                         _rc_restart_done=true
738                         ( $0 ${_rc_prefix}stop )
739                         $0 ${_rc_prefix}start
741                         eval $_postcmd
742                         ;;
744                 poll)
745                         if [ -n "$rc_pid" ]; then
746                                 wait_for_pids $rc_pid
747                         fi
748                         ;;
750                 rcvar)
751                         echo "# $name"
752                         if [ -n "$rcvar" ]; then
753                                 if checkyesno ${rcvar}; then
754                                         echo "\$${rcvar}=YES"
755                                 else
756                                         echo "\$${rcvar}=NO"
757                                 fi
758                         fi
759                         ;;
761                 *)
762                         rc_usage "$_keywords"
763                         ;;
765                 esac
766                 return 0
767         done
769         echo 1>&2 "$0: unknown directive '$rc_arg'."
770         rc_usage "$_keywords"
771         exit 1
775 # run_rc_script file arg
776 #       Start the script `file' with `arg', and correctly handle the
777 #       return value from the script.  If `file' ends with `.sh', it's
778 #       sourced into the current environment.  If `file' appears to be
779 #       a backup or scratch file, ignore it.  Otherwise if it's
780 #       executable run as a child process.
782 #       If `file' contains "KEYWORD: interactive" and if we are
783 #       running inside /etc/rc with postprocessing (as signified by
784 #       _rc_postprocessor_fd being defined) then the script's stdout
785 #       and stderr are redirected to $_rc_original_stdout_fd and
786 #       $_rc_original_stderr_fd, so the output will be displayed on the
787 #       console but not intercepted by /etc/rc's postprocessor.
789 run_rc_script()
791         _file=$1
792         _arg=$2
793         if [ -z "$_file" -o -z "$_arg" ]; then
794                 err 3 'USAGE: run_rc_script file arg'
795         fi
797         _run_rc_script=true
799         unset   name command command_args command_interpreter \
800                 extra_commands pidfile procname \
801                 rcvar required_dirs required_files required_vars
802         eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
804         _must_redirect=false
805         if [ -n "${_rc_postprocessor_fd}" ] \
806             && _has_rcorder_keyword interactive $_file
807         then
808                 _must_redirect=true
809         fi
811         case "$_file" in
812         *.sh)                           # run in current shell
813                 if $_must_redirect; then
814                         print_rc_metadata \
815                             "note:Output from ${_file} is not logged"
816                         no_rc_postprocess eval \
817                             'set $_arg ; . $_file'
818                 else
819                         set $_arg ; . $_file
820                 fi
821                 ;;
822         *[~#]|*.OLD|*.orig|*,v)         # scratch file; skip
823                 warn "Ignoring scratch file $_file"
824                 ;;
825         *)                              # run in subshell
826                 if [ -x $_file ] && $_must_redirect; then
827                         print_rc_metadata \
828                             "note:Output from ${_file} is not logged"
829                         if [ -n "$rc_fast_and_loose" ]; then
830                                 no_rc_postprocess eval \
831                                     'set $_arg ; . $_file'
832                         else
833                                 no_rc_postprocess eval \
834                                     '( set $_arg ; . $_file )'
835                         fi
836                 elif [ -x $_file ]; then
837                         if [ -n "$rc_fast_and_loose" ]; then
838                                 set $_arg ; . $_file
839                         else
840                                 ( set $_arg ; . $_file )
841                         fi
842                 else
843                         warn "Ignoring non-executable file $_file"
844                 fi
845                 ;;
846         esac
850 # load_rc_config command
851 #       Source in the configuration file for a given command.
853 load_rc_config()
855         _command=$1
856         if [ -z "$_command" ]; then
857                 err 3 'USAGE: load_rc_config command'
858         fi
860         if ${_rc_conf_loaded:-false}; then
861                 :
862         else
863                 . /etc/rc.conf
864                 _rc_conf_loaded=true
865         fi
866         if [ -f /etc/rc.conf.d/"$_command" ]; then
867                 . /etc/rc.conf.d/"$_command"
868         fi
872 # load_rc_config_var cmd var
873 #       Read the rc.conf(5) var for cmd and set in the
874 #       current shell, using load_rc_config in a subshell to prevent
875 #       unwanted side effects from other variable assignments.
877 load_rc_config_var()
879         if [ $# -ne 2 ]; then
880                 err 3 'USAGE: load_rc_config_var cmd var'
881         fi
882         eval $(eval '(
883                 load_rc_config '$1' >/dev/null;
884                 if [ -n "${'$2'}" -o "${'$2'-UNSET}" != "UNSET" ]; then
885                         echo '$2'=\'\''${'$2'}\'\'';
886                 fi
887         )' )
891 # rc_usage commands
892 #       Print a usage string for $0, with `commands' being a list of
893 #       valid commands.
895 rc_usage()
897         echo -n 1>&2 "Usage: $0 [fast|force|one]("
899         _sep=
900         for _elem; do
901                 echo -n 1>&2 "$_sep$_elem"
902                 _sep="|"
903         done
904         echo 1>&2 ")"
905         exit 1
909 # err exitval message
910 #       Display message to stderr and log to the syslog, and exit with exitval.
912 err()
914         exitval=$1
915         shift
917         if [ -x /usr/bin/logger ]; then
918                 logger "$0: ERROR: $*"
919         fi
920         echo 1>&2 "$0: ERROR: $*"
921         exit $exitval
925 # warn message
926 #       Display message to stderr and log to the syslog.
928 warn()
930         if [ -x /usr/bin/logger ]; then
931                 logger "$0: WARNING: $*"
932         fi
933         echo 1>&2 "$0: WARNING: $*"
937 # backup_file action file cur backup
938 #       Make a backup copy of `file' into `cur', and save the previous
939 #       version of `cur' as `backup' or use rcs for archiving.
941 #       This routine checks the value of the backup_uses_rcs variable,
942 #       which can be either YES or NO.
944 #       The `action' keyword can be one of the following:
946 #       add             `file' is now being backed up (and is possibly
947 #                       being reentered into the backups system).  `cur'
948 #                       is created and RCS files, if necessary, are
949 #                       created as well.
951 #       update          `file' has changed and needs to be backed up.
952 #                       If `cur' exists, it is copied to to `back' or
953 #                       checked into RCS (if the repository file is old),
954 #                       and then `file' is copied to `cur'.  Another RCS
955 #                       check in done here if RCS is being used.
957 #       remove          `file' is no longer being tracked by the backups
958 #                       system.  If RCS is not being used, `cur' is moved
959 #                       to `back', otherwise an empty file is checked in,
960 #                       and then `cur' is removed.
963 backup_file()
965         _action=$1
966         _file=$2
967         _cur=$3
968         _back=$4
970         if checkyesno backup_uses_rcs; then
971                 _msg0="backup archive"
972                 _msg1="update"
974                 # ensure that history file is not locked
975                 if [ -f $_cur,v ]; then
976                         rcs -q -u -U -M $_cur
977                 fi
979                 # ensure after switching to rcs that the
980                 # current backup is not lost
981                 if [ -f $_cur ]; then
982                         # no archive, or current newer than archive
983                         if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
984                                 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
985                                 rcs -q -kb -U $_cur
986                                 co -q -f -u $_cur
987                         fi
988                 fi
990                 case $_action in
991                 add|update)
992                         cp -p $_file $_cur
993                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
994                         rcs -q -kb -U $_cur
995                         co -q -f -u $_cur
996                         chown root:wheel $_cur $_cur,v
997                         ;;
998                 remove)
999                         cp /dev/null $_cur
1000                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1001                         rcs -q -kb -U $_cur
1002                         chown root:wheel $_cur $_cur,v
1003                         rm $_cur
1004                         ;;
1005                 esac
1006         else
1007                 case $_action in
1008                 add|update)
1009                         if [ -f $_cur ]; then
1010                                 cp -p $_cur $_back
1011                         fi
1012                         cp -p $_file $_cur
1013                         chown root:wheel $_cur
1014                         ;;
1015                 remove)
1016                         mv -f $_cur $_back
1017                         ;;
1018                 esac
1019         fi
1023 # handle_fsck_error fsck_exit_code
1024 #       Take action depending on the return code from fsck.
1026 handle_fsck_error()
1028         case $1 in
1029         0)      # OK
1030                 return
1031                 ;;
1032         2)      # Needs re-run, still fs errors
1033                 echo "File system still has errors; re-run fsck manually!"
1034                 ;;
1035         4)      # Root modified
1036                 echo "Root filesystem was modified, rebooting ..."
1037                 reboot -n
1038                 echo "Reboot failed; help!"
1039                 ;;
1040         8)      # Check failed
1041                 echo "Automatic file system check failed; help!"
1042                 ;;
1043         12)     # Got signal
1044                 echo "Boot interrupted."
1045                 ;;
1046         *)
1047                 echo "Unknown error $1; help!"
1048                 ;;
1049         esac
1050         stop_boot
1054 # _has_rcorder_keyword word file
1055 #       Check whether a file contains a "# KEYWORD:" comment with a
1056 #       specified keyword in the style used by rcorder(8).
1058 _has_rcorder_keyword()
1060         local word="$1"
1061         local file="$2"
1062         local line
1064         [ -r "$file" ] || return 1
1065         while read line; do
1066                 case "${line} " in
1067                 "# KEYWORD:"*[\ \       ]"${word}"[\ \  ]*)
1068                         return 0
1069                         ;;
1070                 "#"*)
1071                         continue
1072                         ;;
1073                 *[A-Za-z0-9]*)
1074                         # give up at the first non-empty non-comment line
1075                         return 1
1076                         ;;
1077                 esac
1078         done <"$file"
1079         return 1
1083 # print_rc_metadata string
1084 #       Print the specified string in such a way that the post-processor
1085 #       inside /etc/rc will treat it as meta-data.
1087 #       If we are not running inside /etc/rc, do nothing.
1089 #       For public use by any rc.d script, the string must begin with
1090 #       "note:", followed by arbitrary text.  The intent is that the text
1091 #       will appear in a log file but not on the console.
1093 #       For private use within /etc/rc, the string must contain a
1094 #       keyword recognised by the rc_postprocess_metadata() function
1095 #       defined in /etc/rc, followed by a colon, followed by one or more
1096 #       colon-separated arguments associated with the keyword.
1098 print_rc_metadata()
1100         # _rc_postprocessor fd, if defined, is the fd to which we must
1101         # print, prefixing the output with $_rc_metadata_prefix.
1102         #
1103         if [ -n "$_rc_postprocessor_fd" ]; then
1104                 printf "%s%s\n" "$rc_metadata_prefix" "$1" \
1105                         >&${_rc_postprocessor_fd}
1106         fi
1110 # print_rc_normal string
1111 #       Print the specified string in such way that it is treated as
1112 #       normal output, regardless of whether or not we are running
1113 #       inside /etc/rc with post-processing.
1115 #       Ths intent is that a script that is run via the
1116 #       no_rc_postprocess() function (so its output would ordinarily be
1117 #       invisible to the post-processor) can nevertheless arrange for
1118 #       the post-processor to see things printed with print_rc_normal().
1120 print_rc_normal()
1122         # If _rc_postprocessor_fd is defined, then it is the fd
1123         # to shich we must print; otherwise print to stdout.
1124         #
1125         printf "%s\n" "$1" >&${_rc_postprocessor_fd:-1}
1129 # no_rc_postprocess cmd...
1130 #       Execute the specified command in such a way that its output
1131 #       bypasses the post-processor that handles the output from
1132 #       most commands that are run inside /etc/rc.  If we are not
1133 #       inside /etc/rc, then just execute the command without special
1134 #       treatment.
1136 #       The intent is that interactive commands can be run via
1137 #       no_rc_postprocess(), and their output will apear immediately
1138 #       on the console instead of being hidden or delayed by the
1139 #       post-processor.  An unfortunate consequence of the output
1140 #       bypassing the post-processor is that the output will not be
1141 #       logged.
1143 no_rc_postprocess()
1145         if [ -n "${_rc_postprocessor_fd}" ]; then
1146                 "$@" >&${_rc_original_stdout_fd} 2>&${_rc_original_stderr_fd}
1147         else
1148                 "$@"
1149         fi
1153 # twiddle
1154 #       On each call, print a different one of "/", "-", "\\", "|",
1155 #       followed by a backspace.  The most recently printed value is
1156 #       saved in $_twiddle_state.
1158 #       Output is to /dev/tty, so this function may be useful even inside
1159 #       a script whose output is redirected.
1161 twiddle()
1163         case "$_twiddle_state" in
1164         '/')    _next='-' ;;
1165         '-')    _next='\' ;;
1166         '\')    _next='|' ;;
1167         *)      _next='/' ;;
1168         esac
1169         printf "%s\b" "$_next" >/dev/tty
1170         _twiddle_state="$_next"
1173 _rc_subr_loaded=: