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