]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - etc/rc.subr
This commit was generated by cvs2svn to compensate for changes in r130610,
[FreeBSD/FreeBSD.git] / etc / rc.subr
1 # $NetBSD: rc.subr,v 1.60 2003/07/26 05:13:47 lukem Exp $
2 # $FreeBSD$
3 #
4 # Copyright (c) 1997-2002 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 # 3. All advertising materials mentioning features or use of this software
19 #    must display the following acknowledgement:
20 #        This product includes software developed by the NetBSD
21 #        Foundation, Inc. and its contributors.
22 # 4. Neither the name of The NetBSD Foundation nor the names of its
23 #    contributors may be used to endorse or promote products derived
24 #    from this software without specific prior written permission.
25 #
26 # THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 # PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 # POSSIBILITY OF SUCH DAMAGE.
37 #
38 # rc.subr
39 #       functions used by various rc scripts
40 #
41
42 #
43 #       Operating System dependent/independent variables
44 #
45
46 SYSCTL="/sbin/sysctl"
47 SYSCTL_N="${SYSCTL} -n"
48 CMD_OSTYPE="${SYSCTL_N} kern.ostype"
49 OSTYPE=`${CMD_OSTYPE}`
50 ID="/usr/bin/id"
51 IDCMD="if [ -x $ID ]; then $ID -un; fi"
52
53 case ${OSTYPE} in
54 FreeBSD)
55         SYSCTL_W="${SYSCTL}"
56         ;;
57 NetBSD)
58         SYSCTL_W="${SYSCTL} -w"
59         ;;
60 esac
61
62 #
63 #       functions
64 #       ---------
65
66 #
67 # set_rcvar base_var
68 #       Set the variable name enabling a specific service.
69 #       FreeBSD uses ${service}_enable, while NetBSD uses
70 #       just the name of the service. For example:
71 #       FreeBSD: sendmail_enable="YES"
72 #       NetBSD : sendmail="YES"
73 #       $1 - if $name is not the base to work of off, specify
74 #            a different one
75 #
76 set_rcvar()
77 {
78         if [ -z "$1" ]; then
79                 base_var=${name}
80         else
81                 base_var="$1"
82         fi
83
84         case ${OSTYPE} in
85         FreeBSD)
86                 echo ${base_var}_enable
87                 ;;
88         NetBSD)
89                 echo ${base_var}
90                 ;;
91         *)
92                 echo 'XXX'
93                 ;;
94         esac
95 }
96
97 #
98 # force_depend script
99 #       Force a service to start. Intended for use by services
100 #       to resolve dependency issues. It is assumed the caller
101 #       has check to make sure this call is necessary
102 #       $1 - filename of script, in /etc/rc.d, to run
103 #
104 force_depend()
105 {
106         _depend="$1"
107
108         info "${name} depends on ${_depend}, which will be forced to start."
109         if ! /etc/rc.d/${_depend} forcestart ; then
110                 warn "Unable to force ${_depend}. It may already be running."
111                 return 1
112         fi
113         return 0
114 }
115
116 #
117 # checkyesno var
118 #       Test $1 variable, and warn if not set to YES or NO.
119 #       Return 0 if it's "yes" (et al), nonzero otherwise.
120 #
121 checkyesno()
122 {
123         eval _value=\$${1}
124         debug "checkyesno: $1 is set to $_value."
125         case $_value in
126
127                 #       "yes", "true", "on", or "1"
128         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
129                 return 0
130                 ;;
131
132                 #       "no", "false", "off", or "0"
133         [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
134                 return 1
135                 ;;
136         *)
137                 warn "\$${1} is not set properly - see rc.conf(5)."
138                 return 1
139                 ;;
140         esac
141 }
142
143 # reverse_list list
144 #       print the list in reverse order
145 #
146 reverse_list()
147 {
148         _revlist=
149         for _revfile; do
150                 _revlist="$_revfile $_revlist"
151         done
152         echo $_revlist
153 }
154
155 #
156 # mount_critical_filesystems type
157 #       Go through the list of critical filesystems as provided in
158 #       the rc.conf(5) variable $critical_filesystems_${type}, checking
159 #       each one to see if it is mounted, and if it is not, mounting it.
160 #
161 mount_critical_filesystems()
162 {
163         eval _fslist=\$critical_filesystems_${1}
164         for _fs in $_fslist; do
165                 mount | (
166                         _ismounted=false
167                         while read what _on on _type type; do
168                                 if [ $on = $_fs ]; then
169                                         _ismounted=true
170                                 fi
171                         done
172                         if $_ismounted; then
173                                 :
174                         else
175                                 mount $_fs >/dev/null 2>&1
176                         fi
177                 )
178         done
179 }
180
181 #
182 # check_pidfile pidfile procname [interpreter]
183 #       Parses the first line of pidfile for a PID, and ensures
184 #       that the process is running and matches procname.
185 #       Prints the matching PID upon success, nothing otherwise.
186 #       interpreter is optional; see _find_processes() for details.
187 #
188 check_pidfile()
189 {
190         _pidfile=$1
191         _procname=$2
192         _interpreter=$3
193         if [ -z "$_pidfile" -o -z "$_procname" ]; then
194                 err 3 'USAGE: check_pidfile pidfile procname [interpreter]'
195         fi
196         if [ ! -f $_pidfile ]; then
197                 debug "pid file {$_pidfile): not readable."
198                 return
199         fi
200         read _pid _junk < $_pidfile
201         if [ -z "$_pid" ]; then
202                 debug "pid file {$_pidfile): no pid in file."
203                 return
204         fi
205         _find_processes $_procname ${_interpreter:-.} '-p '"$_pid"
206 }
207
208 #
209 # check_process procname [interpreter]
210 #       Ensures that a process (or processes) named procname is running.
211 #       Prints a list of matching PIDs.
212 #       interpreter is optional; see _find_processes() for details.
213 #
214 check_process()
215 {
216         _procname=$1
217         _interpreter=$2
218         if [ -z "$_procname" ]; then
219                 err 3 'USAGE: check_process procname [interpreter]'
220         fi
221         _find_processes $_procname ${_interpreter:-.} '-ax'
222 }
223
224 #
225 # _find_processes procname interpreter psargs
226 #       Search for procname in the output of ps generated by psargs.
227 #       Prints the PIDs of any matching processes, space separated.
228 #
229 #       If interpreter == ".", check the following variations of procname
230 #       against the first word of each command:
231 #               procname
232 #               `basename procname`
233 #               `basename procname` + ":"
234 #               "(" + `basename procname` + ")"
235 #
236 #       If interpreter != ".", read the first line of procname, remove the
237 #       leading #!, normalise whitespace, append procname, and attempt to
238 #       match that against each command, either as is, or with extra words
239 #       at the end.
240 #
241 _find_processes()
242 {
243         if [ $# -ne 3 ]; then
244                 err 3 'USAGE: _find_processes procname interpreter psargs'
245         fi
246         _procname=$1
247         _interpreter=$2
248         _psargs=$3
249
250         _pref=
251         if [ $_interpreter != "." ]; then       # an interpreted script
252                 read _interp < $_procname       # read interpreter name
253                 _interp=${_interp#\#!}          # strip #!
254                 set -- $_interp
255                 if [ $_interpreter != $1 ]; then
256                         warn "\$command_interpreter $_interpreter != $1"
257                 fi
258                 _interp="$* $_procname"         # cleanup spaces, add _procname
259                 _fp_args='_argv'
260                 _fp_match='case "$_argv" in
261                     ${_interp}|"${_interp} "*)'
262         else                                    # a normal daemon
263                 _procnamebn=${_procname##*/}
264                 _fp_args='_arg0 _argv'
265                 _fp_match='case "$_arg0" in
266                     $_procname|$_procnamebn|${_procnamebn}:|"(${_procnamebn})")'
267         fi
268
269         _proccheck='
270                 ps 2>/dev/null -o "pid,command" '"$_psargs"' |
271                 while read _npid '"$_fp_args"'; do
272                         case "$_npid" in
273                             PID)
274                                 continue ;;
275                         esac ; '"$_fp_match"'
276                                 echo -n "$_pref$_npid" ;
277                                 _pref=" "
278                                 ;;
279                         esac
280                 done'
281
282 #       debug "in _find_processes: proccheck is ($_proccheck)."
283         eval $_proccheck
284 }
285
286 #
287 # wait_for_pids pid [pid ...]
288 #       spins until none of the pids exist
289 #
290 wait_for_pids()
291 {
292         _list="$@"
293         if [ -z "$_list" ]; then
294                 return
295         fi
296         _prefix=
297         while true; do
298                 _nlist="";
299                 for _j in $_list; do
300                         if kill -0 $_j 2>/dev/null; then
301                                 _nlist="${_nlist}${_nlist:+ }$_j"
302                         fi
303                 done
304                 if [ -z "$_nlist" ]; then
305                         break
306                 fi
307                 _list=$_nlist
308                 echo -n ${_prefix:-"Waiting for PIDS: "}$_list
309                 _prefix=", "
310                 sleep 2
311         done
312         if [ -n "$_prefix" ]; then
313                 echo "."
314         fi
315 }
316
317 #
318 # run_rc_command argument
319 #       Search for argument in the list of supported commands, which is:
320 #               "start stop restart rcvar status poll ${extra_commands}"
321 #       If there's a match, run ${argument}_cmd or the default method
322 #       (see below).
323 #
324 #       If argument has a given prefix, then change the operation as follows:
325 #               Prefix  Operation
326 #               ------  ---------
327 #               fast    Skip the pid check, and set rc_fast=yes
328 #               force   Set ${rcvar} to YES, and set rc_force=yes
329 #               one     Set ${rcvar} to YES
330 #
331 #       The following globals are used:
332 #
333 #       Name            Needed  Purpose
334 #       ----            ------  -------
335 #       name            y       Name of script.
336 #
337 #       command         n       Full path to command.
338 #                               Not needed if ${rc_arg}_cmd is set for
339 #                               each keyword.
340 #
341 #       command_args    n       Optional args/shell directives for command.
342 #
343 #       command_interpreter n   If not empty, command is interpreted, so
344 #                               call check_{pidfile,process}() appropriately.
345 #
346 #       extra_commands  n       List of extra commands supported.
347 #
348 #       pidfile         n       If set, use check_pidfile $pidfile $command,
349 #                               otherwise use check_process $command.
350 #                               In either case, only check if $command is set.
351 #
352 #       procname        n       Process name to check for instead of $command.
353 #
354 #       rcvar           n       This is checked with checkyesno to determine
355 #                               if the action should be run.
356 #
357 #       ${name}_chroot  n       Directory to chroot to before running ${command}
358 #                               Requires /usr to be mounted.
359 #
360 #       ${name}_chdir   n       Directory to cd to before running ${command}
361 #                               (if not using ${name}_chroot).
362 #
363 #       ${name}_flags   n       Arguments to call ${command} with.
364 #                               NOTE:   $flags from the parent environment
365 #                                       can be used to override this.
366 #
367 #       ${name}_nice    n       Nice level to run ${command} at.
368 #
369 #       ${name}_user    n       User to run ${command} as, using su(1) if not
370 #                               using ${name}_chroot.
371 #                               Requires /usr to be mounted.
372 #
373 #       ${name}_group   n       Group to run chrooted ${command} as.
374 #                               Requires /usr to be mounted.
375 #
376 #       ${name}_groups  n       Comma separated list of supplementary groups
377 #                               to run the chrooted ${command} with.
378 #                               Requires /usr to be mounted.
379 #
380 #       ${rc_arg}_cmd   n       If set, use this as the method when invoked;
381 #                               Otherwise, use default command (see below)
382 #
383 #       ${rc_arg}_precmd n      If set, run just before performing the
384 #                               ${rc_arg}_cmd method in the default
385 #                               operation (i.e, after checking for required
386 #                               bits and process (non)existence).
387 #                               If this completes with a non-zero exit code,
388 #                               don't run ${rc_arg}_cmd.
389 #
390 #       ${rc_arg}_postcmd n     If set, run just after performing the
391 #                               ${rc_arg}_cmd method, if that method
392 #                               returned a zero exit code.
393 #
394 #       required_dirs   n       If set, check for the existence of the given
395 #                               directories before running the default
396 #                               (re)start command.
397 #
398 #       required_files  n       If set, check for the readability of the given
399 #                               files before running the default (re)start
400 #                               command.
401 #
402 #       required_vars   n       If set, perform checkyesno on each of the
403 #                               listed variables before running the default
404 #                               (re)start command.
405 #
406 #       Default behaviour for a given argument, if no override method is
407 #       provided:
408 #
409 #       Argument        Default behaviour
410 #       --------        -----------------
411 #       start           if !running && checkyesno ${rcvar}
412 #                               ${command}
413 #
414 #       stop            if ${pidfile}
415 #                               rc_pid=$(check_pidfile $pidfile $command)
416 #                       else
417 #                               rc_pid=$(check_process $command)
418 #                       kill $sig_stop $rc_pid
419 #                       wait_for_pids $rc_pid
420 #                       ($sig_stop defaults to TERM.)
421 #
422 #       reload          Similar to stop, except use $sig_reload instead,
423 #                       and doesn't wait_for_pids.
424 #                       $sig_reload defaults to HUP.
425 #
426 #       restart         Run `stop' then `start'.
427 #
428 #       status          Show if ${command} is running, etc.
429 #
430 #       poll            Wait for ${command} to exit.
431 #
432 #       rcvar           Display what rc.conf variable is used (if any).
433 #
434 #       Variables available to methods, and after run_rc_command() has
435 #       completed:
436 #
437 #       Variable        Purpose
438 #       --------        -------
439 #       rc_arg          Argument to command, after fast/force/one processing
440 #                       performed
441 #
442 #       rc_flags        Flags to start the default command with.
443 #                       Defaults to ${name}_flags, unless overridden
444 #                       by $flags from the environment.
445 #                       This variable may be changed by the precmd method.
446 #
447 #       rc_pid          PID of command (if appropriate)
448 #
449 #       rc_fast         Not empty if "fast" was provided (q.v.)
450 #
451 #       rc_force        Not empty if "force" was provided (q.v.)
452 #
453 #
454 run_rc_command()
455 {
456         _return=0
457         rc_arg=$1
458         if [ -z "$name" ]; then
459                 err 3 'run_rc_command: $name is not set.'
460         fi
461
462         _rc_prefix=
463         case "$rc_arg" in
464         fast*)                          # "fast" prefix; don't check pid
465                 rc_arg=${rc_arg#fast}
466                 rc_fast=yes
467                 ;;
468         force*)                         # "force prefix; always run
469                 rc_force=yes
470                 _rc_prefix=force
471                 rc_arg=${rc_arg#${_rc_prefix}}
472                 if [ -n "${rcvar}" ]; then
473                         eval ${rcvar}=YES
474                 fi
475                 ;;
476         one*)                           # "one" prefix; set ${rcvar}=yes
477                 _rc_prefix=one
478                 rc_arg=${rc_arg#${_rc_prefix}}
479                 if [ -n "${rcvar}" ]; then
480                         eval ${rcvar}=YES
481                 fi
482                 ;;
483         esac
484
485         eval _overide_command=\$${name}_program
486         if [ -n "$_overide_command" ]; then
487                 command=$_overide_command
488         fi
489
490         _keywords="start stop restart rcvar $extra_commands"
491         rc_pid=
492         _pidcmd=
493         _procname=${procname:-${command}}
494
495                                         # setup pid check command if not fast
496         if [ -z "$rc_fast" -a -n "$_procname" ]; then
497                 if [ -n "$pidfile" ]; then
498                         _pidcmd='rc_pid=$(check_pidfile '"$pidfile $_procname $command_interpreter"')'
499                 else
500                         _pidcmd='rc_pid=$(check_process '"$_procname $command_interpreter"')'
501                 fi
502                 if [ -n "$_pidcmd" ]; then
503                         _keywords="${_keywords} status poll"
504                 fi
505         fi
506
507         if [ -z "$rc_arg" ]; then
508                 rc_usage "$_keywords"
509         fi
510
511         if [ -n "$flags" ]; then        # allow override from environment
512                 rc_flags=$flags
513         else
514                 eval rc_flags=\$${name}_flags
515         fi
516         eval _chdir=\$${name}_chdir     _chroot=\$${name}_chroot \
517             _nice=\$${name}_nice        _user=\$${name}_user \
518             _group=\$${name}_group      _groups=\$${name}_groups
519
520         if [ -n "$_user" ]; then        # unset $_user if running as that user
521                 if [ "$_user" = "$(eval $IDCMD)" ]; then
522                         unset _user
523                 fi
524         fi
525
526                                         # if ${rcvar} is set, and $1 is not
527                                         # "rcvar", then run
528                                         #       checkyesno ${rcvar}
529                                         # and return if that failed
530                                         #
531         if [ -n "${rcvar}" -a "$rc_arg" != "rcvar" ]; then
532                 if ! checkyesno ${rcvar}; then
533                         return 0
534                 fi
535         fi
536
537         eval $_pidcmd                   # determine the pid if necessary
538
539         for _elem in $_keywords; do
540                 if [ "$_elem" != "$rc_arg" ]; then
541                         continue
542                 fi
543
544                                         # if there's a custom ${XXX_cmd},
545                                         # run that instead of the default
546                                         #
547                 eval _cmd=\$${rc_arg}_cmd _precmd=\$${rc_arg}_precmd \
548                     _postcmd=\$${rc_arg}_postcmd
549                 if [ -n "$_cmd" ]; then
550                                         # if the precmd failed and force
551                                         # isn't set, exit
552                                         #
553                         if [ -n "$_precmd" ]; then
554                                 debug "run_rc_command: evaluating ${_precmd}()."
555                                 eval $_precmd
556                                 _return=$?
557                                 [ $_return -ne 0 ] && [ -z "$rc_force" ] &&
558                                     return 1
559                         fi
560
561                         if [ -n "$_cmd" ]; then
562                                 debug "run_rc_command: evaluating ${_cmd}()."
563                                 eval $_cmd
564                                 _return=$?
565                                 [ $_return -ne 0 ] && [ -z "$rc_force" ] &&
566                                     return 1
567                         fi
568
569                         if [ -n "$_postcmd" ]; then
570                                 debug "run_rc_command: evaluating ${_postcmd}()."
571                                  eval $_postcmd
572                                 _return=$?
573                         fi
574                         return $_return
575                 fi
576
577                 case "$rc_arg" in       # default operations...
578
579                 status)
580                         if [ -n "$rc_pid" ]; then
581                                 echo "${name} is running as pid $rc_pid."
582                         else
583                                 echo "${name} is not running."
584                                 return 1
585                         fi
586                         ;;
587
588                 start)
589                         if [ -n "$rc_pid" ]; then
590                                 echo "${name} already running? (pid=$rc_pid)."
591                                 exit 1
592                         fi
593
594                         if [ ! -x ${_chroot}${command} ]; then
595                                 info "run_rc_command: cannot run ($command)."
596                                 return 0
597                         fi
598
599                                         # check for required variables,
600                                         # directories, and files
601                                         #
602                         for _f in $required_vars; do
603                                 if ! checkyesno $_f; then
604                                         warn "\$${_f} is not set."
605                                         if [ -z "$rc_force" ]; then
606                                                 return 1
607                                         fi
608                                 fi
609                         done
610                         for _f in $required_dirs; do
611                                 if [ ! -d "${_f}/." ]; then
612                                         warn "${_f} is not a directory."
613                                         if [ -z "$rc_force" ]; then
614                                                 return 1
615                                         fi
616                                 fi
617                         done
618                         for _f in $required_files; do
619                                 if [ ! -r "${_f}" ]; then
620                                         warn "${_f} is not readable."
621                                         if [ -z "$rc_force" ]; then
622                                                 return 1
623                                         fi
624                                 fi
625                         done
626
627                                         # if the precmd failed and force
628                                         # isn't set, exit
629                                         #
630                         if [ -n "${_precmd}" ]; then
631                                 debug "run_rc_command: evaluating ${_precmd}()."
632                                 eval $_precmd
633                                 _return=$?
634                                 [ $_return -ne 0 ] && [ -z "$rc_force" ] &&
635                                     return 1
636                         fi
637
638                                         # setup the command to run, and run it
639                                         #
640                         echo "Starting ${name}."
641                         if [ -n "$_chroot" ]; then
642                                 _doit="\
643 ${_nice:+nice -n $_nice }\
644 chroot ${_user:+-u $_user }${_group:+-g $_group }${_groups:+-G $_groups }\
645 $_chroot $command $rc_flags $command_args"
646                         else
647                                 _doit="\
648 ${_chdir:+cd $_chdir; }\
649 ${_nice:+nice -n $_nice }\
650 $command $rc_flags $command_args"
651                                 if [ -n "$_user" ]; then
652                                     _doit="su -m $_user -c 'sh -c \"$_doit\"'"
653                                 fi
654                         fi
655
656                                         # if the cmd failed and force
657                                         # isn't set, exit
658                                         #
659                         debug "run_rc_command: _doit: $_doit"
660                         eval $_doit
661                         _return=$?
662                         [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
663
664                                         # finally, run postcmd
665                                         #
666                         if [ -n "${_postcmd}" ]; then
667                                 debug "run_rc_command: evaluating ${_postcmd}()."
668                                 eval $_postcmd
669                         fi
670                         ;;
671
672                 stop)
673                         if [ -z "$rc_pid" ]; then
674                                 if [ -n "$pidfile" ]; then
675                                         echo \
676                                     "${name} not running? (check $pidfile)."
677                                 else
678                                         echo "${name} not running?"
679                                 fi
680                                 exit 1
681                         fi
682
683                                         # if the precmd failed and force
684                                         # isn't set, exit
685                                         #
686                         if [ -n "$_precmd" ]; then
687                                 eval $_precmd
688                                 _return=$?
689                                 [ $_return -ne 0 ] && [ -z "$rc_force" ] &&
690                                     return 1
691                         fi
692
693                                         # send the signal to stop
694                                         #
695                         echo "Stopping ${name}."
696                         _doit="kill -${sig_stop:-TERM} $rc_pid"
697                         if [ -n "$_user" ]; then
698                                 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
699                         fi
700
701                                         # if the stop cmd failed and force
702                                         # isn't set, exit
703                                         #
704                         eval $_doit
705                         _return=$?
706                         [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
707
708                                         # wait for the command to exit,
709                                         # and run postcmd.
710                         wait_for_pids $rc_pid
711                         if [ -n "$_postcmd" ]; then
712                                 eval $_postcmd
713                                 _return=$?
714                         fi
715                         ;;
716
717                 reload)
718                         if [ -z "$rc_pid" ]; then
719                                 if [ -n "$pidfile" ]; then
720                                         echo \
721                                     "${name} not running? (check $pidfile)."
722                                 else
723                                         echo "${name} not running?"
724                                 fi
725                                 exit 1
726                         fi
727                         echo "Reloading ${name} config files."
728                         if [ -n "$_precmd" ]; then
729                                 eval $_precmd
730                                 _return=$?
731                                 [ $_return -ne 0 ] && [ -z "$rc_force" ] &&
732                                     return 1
733                         fi
734                         _doit="kill -${sig_reload:-HUP} $rc_pid"
735                         if [ -n "$_user" ]; then
736                                 _doit="su -m $_user -c 'sh -c \"$_doit\"'"
737                         fi
738                         eval $_doit
739                         _return=$?
740                         [ $_return -ne 0 ] && [ -z "$rc_force" ] && return 1
741                         if [ -n "$_postcmd" ]; then
742                                 eval $_postcmd
743                                 _return=$?
744                         fi
745                         ;;
746
747                 restart)
748                         if [ -n "$_precmd" ]; then
749                                 eval $_precmd
750                                 _return=$?
751                                 [ $_return -ne 0 ] && [ -z "$rc_force" ] &&
752                                     return 1
753                         fi
754                                         # prevent restart being called more
755                                         # than once by any given script
756                                         #
757                         if ${_rc_restart_done:-false}; then
758                                 return 0
759                         fi
760                         _rc_restart_done=true
761
762                         ( $0 ${_rc_prefix}stop )
763                         $0 ${_rc_prefix}start
764
765                         if [ -n "$_postcmd" ]; then
766                                 eval $_postcmd
767                                 _return=$?
768                         fi
769                         ;;
770
771                 poll)
772                         if [ -n "$rc_pid" ]; then
773                                 wait_for_pids $rc_pid
774                         fi
775                         ;;
776
777                 rcvar)
778                         echo "# $name"
779                         if [ -n "$rcvar" ]; then
780                                 if checkyesno ${rcvar}; then
781                                         echo "\$${rcvar}=YES"
782                                 else
783                                         echo "\$${rcvar}=NO"
784                                 fi
785                         fi
786                         ;;
787
788                 *)
789                         rc_usage "$_keywords"
790                         ;;
791
792                 esac
793                 return $_return
794         done
795
796         echo 1>&2 "$0: unknown directive '$rc_arg'."
797         rc_usage "$_keywords"
798         exit 1
799 }
800
801 #
802 # run_rc_script file arg
803 #       Start the script `file' with `arg', and correctly handle the
804 #       return value from the script.  If `file' ends with `.sh', it's
805 #       sourced into the current environment.  If `file' appears to be
806 #       a backup or scratch file, ignore it.  Otherwise if it's
807 #       executable run as a child process.
808 #
809 run_rc_script()
810 {
811         _file=$1
812         _arg=$2
813         if [ -z "$_file" -o -z "$_arg" ]; then
814                 err 3 'USAGE: run_rc_script file arg'
815         fi
816
817         unset   name command command_args command_interpreter \
818                 extra_commands pidfile procname \
819                 rcvar required_dirs required_files required_vars
820         eval unset ${_arg}_cmd ${_arg}_precmd ${_arg}_postcmd
821
822         case "$_file" in
823         *.sh)                           # run in current shell
824                 set $_arg ; . $_file
825                 ;;
826         *[~#]|*.OLD|*.orig|*,v)         # scratch file; skip
827                 warn "Ignoring scratch file $_file"
828                 ;;
829         *)                              # run in subshell
830                 if [ -x $_file ]; then
831                         if [ -n "$rc_fast_and_loose" ]; then
832                                 set $_arg ; . $_file
833                         else
834                                 ( trap "echo Script $_file interrupted; kill -QUIT $$" 3
835                                   trap "echo Script $_file interrupted; exit 1" 2
836                                   set $_arg ; . $_file )
837                         fi
838                 fi
839                 ;;
840         esac
841 }
842
843 #
844 # load_rc_config
845 #       Source in the configuration file for a given command.
846 #
847 load_rc_config()
848 {
849         _command=$1
850         if [ -z "$_command" ]; then
851                 err 3 'USAGE: load_rc_config command'
852         fi
853
854         if ${_rc_conf_loaded:-false}; then
855                 :
856         else
857                 if [ -r /etc/defaults/rc.conf ]; then
858                         debug "Sourcing /etc/defaults/rc.conf"
859                         . /etc/defaults/rc.conf
860                         source_rc_confs
861                 elif [ -r /etc/rc.conf ]; then
862                         debug "Sourcing /etc/rc.conf (/etc/defaults/rc.conf doesn't exist)."
863                         . /etc/rc.conf
864                 fi
865                 _rc_conf_loaded=true
866         fi
867         if [ -f /etc/rc.conf.d/"$_command" ]; then
868                 debug "Sourcing /etc/rc.conf.d/${_command}"
869                 . /etc/rc.conf.d/"$_command"
870         fi
871
872         # XXX - Deprecated variable name support
873         #
874         case ${OSTYPE} in
875         FreeBSD)
876                 [ -n "$portmap_enable" ] && rpcbind_enable="$portmap_enable"
877                 [ -n "$portmap_program" ] && rpcbind_program="$portmap_program"
878                 [ -n "$portmap_flags" ] && rpcbind_flags="$portmap_flags"
879                 [ -n "$single_mountd_enable" ] && mountd_enable="$single_mountd_enable"
880                 [ -n "$xntpd_enable" ] && ntpd_enable="$xntpd_enable"
881                 [ -n "$xntpd_program" ] && ntpd_program="$xntpd_program"
882                 [ -n "$xntpd_flags" ] && ntpd_flags="$xntpd_flags"
883                 [ -n "$dhcp_program" ] && dhclient_program="$dhcp_program"
884                 [ -n "$dhcp_flags" ] && dhclient_flags="$dhcp_flags"
885                 ;;
886         esac
887
888 }
889
890 #
891 # rc_usage commands
892 #       Print a usage string for $0, with `commands' being a list of
893 #       valid commands.
894 #
895 rc_usage()
896 {
897         echo -n 1>&2 "Usage: $0 [fast|force|one]("
898
899         _sep=
900         for _elem; do
901                 echo -n 1>&2 "$_sep$_elem"
902                 _sep="|"
903         done
904         echo 1>&2 ")"
905         exit 1
906 }
907
908 #
909 # err exitval message
910 #       Display message to stderr and log to the syslog, and exit with exitval.
911 #
912 err()
913 {
914         exitval=$1
915         shift
916
917         if [ -x /usr/bin/logger ]; then
918                 logger "$0: ERROR: $*"
919         fi
920         echo 1>&2 "$0: ERROR: $*"
921         exit $exitval
922 }
923
924 #
925 # warn message
926 #       Display message to stderr and log to the syslog.
927 #
928 warn()
929 {
930         if [ -x /usr/bin/logger ]; then
931                 logger "$0: WARNING: $*"
932         fi
933         echo 1>&2 "$0: WARNING: $*"
934 }
935
936 #
937 # info message
938 #       Display informational message to stdout and log to syslog.
939 #
940 info()
941 {
942         case ${rc_info} in
943         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
944                 if [ -x /usr/bin/logger ]; then
945                         logger "$0: INFO: $*"
946                 fi
947                 echo "$0: INFO: $*"
948                 ;;
949         esac
950 }
951
952 #
953 # debug message
954 #       If debugging is enabled in rc.conf output message to stderr.
955 #       BEWARE that you don't call any subroutine that itself calls this
956 #       function.
957 #
958 debug()
959 {
960         case ${rc_debug} in
961         [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn]|1)
962                 if [ -x /usr/bin/logger ]; then
963                         logger "$0: INFO: $*"
964                 fi
965                 echo 1>&2 "$0: DEBUG: $*"
966                 ;;
967         esac
968 }
969
970 #
971 # backup_file action file cur backup
972 #       Make a backup copy of `file' into `cur', and save the previous
973 #       version of `cur' as `backup' or use rcs for archiving.
974 #
975 #       This routine checks the value of the backup_uses_rcs variable,
976 #       which can be either YES or NO.
977 #
978 #       The `action' keyword can be one of the following:
979 #
980 #       add             `file' is now being backed up (and is possibly
981 #                       being reentered into the backups system).  `cur'
982 #                       is created and RCS files, if necessary, are
983 #                       created as well.
984 #
985 #       update          `file' has changed and needs to be backed up.
986 #                       If `cur' exists, it is copied to to `back' or
987 #                       checked into RCS (if the repository file is old),
988 #                       and then `file' is copied to `cur'.  Another RCS
989 #                       check in done here if RCS is being used.
990 #
991 #       remove          `file' is no longer being tracked by the backups
992 #                       system.  If RCS is not being used, `cur' is moved
993 #                       to `back', otherwise an empty file is checked in,
994 #                       and then `cur' is removed.
995 #
996 #
997 backup_file()
998 {
999         _action=$1
1000         _file=$2
1001         _cur=$3
1002         _back=$4
1003
1004         if checkyesno backup_uses_rcs; then
1005                 _msg0="backup archive"
1006                 _msg1="update"
1007
1008                 # ensure that history file is not locked
1009                 if [ -f $_cur,v ]; then
1010                         rcs -q -u -U -M $_cur
1011                 fi
1012
1013                 # ensure after switching to rcs that the
1014                 # current backup is not lost
1015                 if [ -f $_cur ]; then
1016                         # no archive, or current newer than archive
1017                         if [ ! -f $_cur,v -o $_cur -nt $_cur,v ]; then
1018                                 ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1019                                 rcs -q -kb -U $_cur
1020                                 co -q -f -u $_cur
1021                         fi
1022                 fi
1023
1024                 case $_action in
1025                 add|update)
1026                         cp -p $_file $_cur
1027                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1028                         rcs -q -kb -U $_cur
1029                         co -q -f -u $_cur
1030                         chown root:wheel $_cur $_cur,v
1031                         ;;
1032                 remove)
1033                         cp /dev/null $_cur
1034                         ci -q -f -u -t-"$_msg0" -m"$_msg1" $_cur
1035                         rcs -q -kb -U $_cur
1036                         chown root:wheel $_cur $_cur,v
1037                         rm $_cur
1038                         ;;
1039                 esac
1040         else
1041                 case $_action in
1042                 add|update)
1043                         if [ -f $_cur ]; then
1044                                 cp -p $_cur $_back
1045                         fi
1046                         cp -p $_file $_cur
1047                         chown root:wheel $_cur
1048                         ;;
1049                 remove)
1050                         mv -f $_cur $_back
1051                         ;;
1052                 esac
1053         fi
1054 }
1055
1056 # make_symlink src link
1057 #       Make a symbolic link 'link' to src from basedir. If the
1058 #       directory in which link is to be created does not exist
1059 #       a warning will be displayed and an error will be returned.
1060 #       Returns 0 on sucess, 1 otherwise.
1061 #
1062 make_symlink()
1063 {
1064         local src link linkdir _me
1065         src="$1"
1066         link="$2"
1067         linkdir="`dirname $link`"
1068         _me="make_symlink()"
1069
1070         if [ -z "$src" -o -z "$link" ]; then
1071                 warn "$_me: requires two arguments."
1072                 return 1
1073         fi
1074         if [ ! -d "$linkdir" ]; then
1075                 warn "$_me: the directory $linkdir does not exist"
1076                 return 1
1077         fi
1078         if ! ln -sf $src $link ; then
1079                 warn "$_me: unable to make a symbolic link from $link to $src"
1080                 return 1
1081         fi
1082         return 0
1083 }
1084
1085 # devfs_rulesets_from_file file
1086 #       Reads a set of devfs commands from file, and creates
1087 #       the specified rulesets with their rules. Returns non-zero
1088 #       if there was an error.
1089 #
1090 devfs_rulesets_from_file()
1091 {
1092         local file _err _me
1093         file="$1"
1094         _me="devfs_rulesets_from_file"
1095         _err=0
1096
1097         if [ -z "$file" ]; then
1098                 warn "$_me: you must specify a file"
1099                 return 1
1100         fi
1101         if [ ! -e "$file" ]; then
1102                 debug "$_me: no such file ($file)"
1103                 return 0
1104         fi
1105         debug "reading rulesets from file ($file)"
1106         { while read line
1107         do
1108                 case $line in
1109                 \#*)
1110                         continue
1111                         ;;
1112                 \[*\]*)
1113                         rulenum=`expr "$line" : "\[.*=\([0-9]*\)\]"`
1114                         if [ -z "$rulenum" ]; then
1115                                 warn "$_me: cannot extract rule number ($line)"
1116                                 _err=1
1117                                 break
1118                         fi
1119                         rulename=`expr "$line" : "\[\(.*\)=[0-9]*\]"`
1120                         if [ -z "$rulename" ]; then
1121                                 warn "$_me: cannot extract rule name ($line)"
1122                                 _err=1
1123                                 break;
1124                         fi
1125                         eval $rulename=\$rulenum
1126                         debug "found ruleset: $rulename=$rulenum"
1127                         if ! /sbin/devfs rule -s $rulenum delset ; then
1128                                 _err=1
1129                                 break
1130                         fi
1131                         ;;
1132                 *)
1133                         rulecmd="${line%%"\#*"}"
1134                         # evaluate the command incase it includes
1135                         # other rules
1136                         if [ -n "$rulecmd" ]; then
1137                                 debug "adding rule ($rulecmd)"
1138                                 if ! eval /sbin/devfs rule -s $rulenum $rulecmd
1139                                 then
1140                                         _err=1
1141                                         break
1142                                 fi
1143                         fi
1144                         ;;
1145                 esac
1146                 if [ $_err -ne 0 ]; then
1147                         debug "error in $_me"
1148                         break
1149                 fi
1150         done } < $file
1151         return $_err
1152 }
1153
1154 # devfs_init_rulesets
1155 #       Initializes rulesets from configuration files. Returns
1156 #       non-zero if there was an error.
1157 #
1158 devfs_init_rulesets()
1159 {
1160         local file _me
1161         _me="devfs_init_rulesets"
1162
1163         # Go through this only once
1164         if [ -n "$devfs_rulesets_init" ]; then
1165                 debug "$_me: devfs rulesets already initialized"
1166                 return
1167         fi
1168         for file in $devfs_rulesets ; do
1169                 devfs_rulesets_from_file $file || return 1
1170         done
1171         devfs_rulesets_init=1
1172         debug "$_me: devfs rulesets initialized"
1173         return 0
1174 }
1175
1176 # devfs_set_ruleset ruleset [dir]
1177 #       Sets the default ruleset of dir to ruleset. The ruleset arguement
1178 #       must be a ruleset name as specified in devfs.rules(5) file.
1179 #       Returns non-zero if it could not set it successfully.
1180 #
1181 devfs_set_ruleset()
1182 {
1183         local devdir rs _me
1184         [ -n "$1" ] && eval rs=\$$1 || rs=
1185         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1186         _me="devfs_set_ruleset"
1187
1188         if [ -z "$rs" ]; then
1189                 warn "$_me: you must specify a ruleset number"
1190                 return 1
1191         fi
1192         debug "$_me: setting ruleset ($rs) on mount-point (${devdir#-m })"
1193         if ! /sbin/devfs $devdir ruleset $rs ; then
1194                 warn "$_me: unable to set ruleset $rs to ${devdir#-m }"
1195                 return 1
1196         fi
1197         return 0
1198 }
1199
1200 # devfs_apply_ruleset ruleset [dir]
1201 #       Apply ruleset number $ruleset to the devfs mountpoint $dir.
1202 #       The ruleset argument must be a ruleset name as specified
1203 #       in a devfs.rules(5) file.  Returns 0 on success or non-zero
1204 #       if it could not apply the ruleset.
1205 #
1206 devfs_apply_ruleset()
1207 {
1208         local devdir rs _me
1209         [ -n "$1" ] && eval rs=\$$1 || rs=
1210         [ -n "$2" ] && devdir="-m "$2"" || devdir=
1211         _me="devfs_apply_ruleset"
1212
1213         if [ -z "$rs" ]; then
1214                 warn "$_me: you must specify a ruleset"
1215                 return 1
1216         fi
1217         debug "$_me: applying ruleset ($rs) to mount-point (${devdir#-m })"
1218         if ! /sbin/devfs $devdir rule -s $rs applyset ; then
1219                 warn "$_me: unable to apply ruleset $rs to ${devdir#-m }"
1220                 return 1
1221         fi
1222         return 0
1223 }
1224
1225 # devfs_domount dir [ruleset]
1226 #       Mount devfs on dir. If ruleset is specified it is set
1227 #       on the mount-point. It must also be a ruleset name as specified
1228 #       in a devfs.rules(5) file. Returns 0 on success.
1229 #
1230 devfs_domount()
1231 {
1232         local devdir rs _me
1233         devdir="$1"
1234         [ -n "$2" ] && rs=$2 || rs=
1235         _me="devfs_domount()"
1236
1237         if [ -z "$devdir" ]; then
1238                 warn "$_me: you must specify a mount-point"
1239                 return 1
1240         fi
1241         debug "$_me: mount-point is ($devdir), ruleset is ($rs)"
1242         if ! mount -t devfs dev "$devdir" ; then
1243                 warn "$_me: Unable to mount devfs on $devdir"
1244                 return 1
1245         fi
1246         if [ -n "$rs" ]; then
1247                 devfs_init_rulesets
1248                 devfs_set_ruleset $rs $devdir
1249                 devfs -m $devdir rule applyset
1250         fi
1251         return 0
1252 }
1253
1254 # devfs_mount_jail dir [ruleset]
1255 #       Mounts a devfs file system appropriate for jails
1256 #       on the directory dir. If ruleset is specified, the ruleset
1257 #       it names will be used instead.  If present, ruleset must
1258 #       be the name of a ruleset as defined in a devfs.rules(5) file.
1259 #       This function returns non-zero if an error occurs.
1260 #
1261 devfs_mount_jail()
1262 {
1263         local jdev rs _me
1264         jdev="$1"
1265         [ -n "$2" ] && rs=$2 || rs="devfsrules_jail"
1266         _me="devfs_mount_jail"
1267
1268         devfs_init_rulesets
1269         if ! devfs_domount "$jdev" $rs ; then
1270                 warn "$_me: devfs was not mounted on $jdev"
1271                 return 1
1272         fi
1273         return 0
1274 }
1275
1276 # Provide a function for normalizing the mounting of memory
1277 # filesystems.  This should allow the rest of the code here to remain
1278 # as close as possible between 5-current and 4-stable.
1279 #   $1 = size
1280 #   $2 = mount point
1281 #   $3 = (optional) bytes-per-inode
1282 mount_md() {
1283         if [ -n "$3" ]; then
1284                 bpi="-i $3"
1285         fi
1286         /sbin/mdmfs $bpi -s $1 -M md $2
1287 }