1 if [ ! "$_SYSRC_SUBR" ]; then _SYSRC_SUBR=1
3 # Copyright (c) 2006-2015 Devin Teske
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
15 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 ############################################################ INCLUDES
31 BSDCFG_SHARE="/usr/share/bsdconfig"
32 [ "$_COMMON_SUBR" ] || . $BSDCFG_SHARE/common.subr || exit 1
34 BSDCFG_LIBE="/usr/libexec/bsdconfig"
35 if [ ! "$_SYSRC_JAILED" ]; then
36 f_dprintf "%s: loading includes..." sysrc.subr
37 f_include_lang $BSDCFG_LIBE/include/messages.subr
40 ############################################################ CONFIGURATION
43 # Standard pathnames (inherit values from shell if available)
45 : ${RC_DEFAULTS:="/etc/defaults/rc.conf"}
47 ############################################################ GLOBALS
50 # Global exit status variables
56 # Valid characters that can appear in an sh(1) variable name
58 # Please note that the character ranges A-Z and a-z should be avoided because
59 # these can include accent characters (which are not valid in a variable name).
60 # For example, A-Z matches any character that sorts after A but before Z,
61 # including A and Z. Although ASCII order would make more sense, that is not
64 VALID_VARNAME_CHARS="0-9ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
66 ############################################################ FUNCTIONS
68 # f_clean_env [ --except $varname ... ]
70 # Unset all environment variables in the current scope. An optional list of
71 # arguments can be passed, indicating which variables to avoid unsetting; the
72 # `--except' is required to enable the exclusion-list as the remainder of
73 # positional arguments.
75 # Be careful not to call this in a shell that you still expect to perform
76 # $PATH expansion in, because this will blow $PATH away. This is best used
77 # within a sub-shell block "(...)" or "$(...)" or "`...`".
84 # Should we process an exclusion-list?
86 if [ "$1" = "--except" ]; then
92 # Loop over a list of variable names from set(1) built-in.
94 for var in $( set | awk -F= \
95 '/^[[:alpha:]_][[:alnum:]_]*=/ {print $1}' \
99 # In POSIX bourne-shell, attempting to unset(1) OPTIND results
100 # in "unset: Illegal number:" and causes abrupt termination.
102 [ "$var" = OPTIND ] && continue
105 # Process the exclusion-list?
107 if [ "$except" ]; then
108 for arg in "$@" ""; do
109 [ "$var" = "$arg" ] && break
111 [ "$arg" ] && continue
118 # f_sysrc_get $varname
120 # Get a system configuration setting from the collection of system-
121 # configuration files (in order: /etc/defaults/rc.conf /etc/rc.conf and
122 # /etc/rc.conf.local)
124 # NOTE: Additional shell parameter-expansion formats are supported. For
125 # example, passing an argument of "hostname%%.*" (properly quoted) will
126 # return the hostname up to (but not including) the first `.' (see sh(1),
127 # "Parameter Expansion" for more information on additional formats).
132 [ -f "$RC_DEFAULTS" -a -r "$RC_DEFAULTS" ] || return $FAILURE
134 # Taint-check variable name
137 # Don't expand possible positional parameters
140 [ "$1" ] || return $FAILURE
143 ( # Execute within sub-shell to protect parent environment
146 # Clear the environment of all variables, preventing the
147 # expansion of normals such as `PS1', `TERM', etc.
149 f_clean_env --except IFS RC_CONFS RC_DEFAULTS
151 . "$RC_DEFAULTS" > /dev/null 2>&1
157 # If the query is for `rc_conf_files' then store the value that
158 # we inherited from sourcing RC_DEFAULTS (above) so that we may
159 # conditionally restore this value after source_rc_confs in the
160 # event that RC_CONFS does not customize the value.
162 if [ "$1" = "rc_conf_files" ]; then
163 _rc_conf_files="$rc_conf_files"
167 # If RC_CONFS is defined, set $rc_conf_files to an explicit
168 # value, modifying the default behavior of source_rc_confs().
170 if [ "${RC_CONFS+set}" ]; then
171 rc_conf_files="$RC_CONFS"
175 source_rc_confs > /dev/null 2>&1
178 # If the query was for `rc_conf_files' AND after calling
179 # source_rc_confs the value has not changed, then we should
180 # restore the value to the one inherited from RC_DEFAULTS
181 # before performing the final query (preventing us from
182 # returning what was set via RC_CONFS when the intent was
183 # instead to query the value from the file(s) specified).
185 if [ "$1" = "rc_conf_files" -a \
186 "$_rc_confs_set" -a \
187 "$rc_conf_files" = "$RC_CONFS" \
189 rc_conf_files="$_rc_conf_files"
198 # This must be the last functional line for both the sub-shell
199 # and the function to preserve the return status from formats
200 # such as "${varname?}" and "${varname:?}" (see "Parameter
201 # Expansion" in sh(1) for more information).
203 eval echo '"${'"$1"'}"' 2> /dev/null
207 # f_sysrc_service_configs [-a|-p] $name [$var_to_set]
209 # Get a list of optional `rc.conf.d' entries sourced by system `rc.d' script
210 # $name (see rc.subr(8) for additional information on `rc.conf.d'). If $name
211 # exists in `/etc/rc.d' or $local_startup directories and is an rc(8) script
212 # the result is a space separated list of `rc.conf.d' entries sourced by the
213 # $name `rc.d' script. Otherwise, if $name exists as a binary `rc.d' script,
214 # the result is ``/etc/rc.conf.d/$name /usr/local/etc/rc.conf.d/$name''. The
215 # result is NULL if $name does not exist.
217 # If $var_to_set is missing or NULL, output is to standard out. Returns success
218 # if $name was found, failure otherwise.
220 # If `-a' flag is given and $var_to_set is non-NULL, append result to value of
221 # $var_to_set rather than overwriting current contents.
223 # If `-p' flag is given and $var_to_set is non-NULL, prepend result to value of
224 # $var_to_set rather than overwriting current contents.
226 # NB: The `-a' and `-p' option flags are mutually exclusive.
228 f_sysrc_service_configs()
230 local OPTIND=1 OPTARG __flag __append= __prepend=
231 local __local_startup __dir __spath __stype __names=
233 while getopts ap __flag; do
235 a) __append=1 __prepend= ;;
236 p) __prepend=1 __append= ;;
239 shift $(( $OPTIND - 1 ))
241 [ $# -gt 0 ] || return $FAILURE
242 local __sname="$1" __var_to_set="$2"
244 __local_startup=$( f_sysrc_get local_startup )
245 for __dir in /etc/rc.d $__local_startup; do
246 __spath="$__dir/$__sname"
247 [ -f "$__spath" -a -x "$__spath" ] || __spath= continue
250 [ "$__spath" ] || return $FAILURE
252 __stype=$( file -b "$__spath" 2> /dev/null )
255 __names=$( exec 9<&1 1>&- 2>&-
259 [ "$name" = "$last_name" ] && return
264 gsub(/load_rc_config /, "print_name ")
265 gsub(/run_rc_command /, ": ")
273 local __name __test_path __configs=
274 for __name in $__names; do
275 for __dir in /etc/rc.d $__local_startup; do
276 __test_path="${__dir%/rc.d}/rc.conf.d/$__name"
277 [ -d "$__test_path" ] ||
278 __configs="$__configs $__test_path" continue
279 for __test_path in "$__test_path"/*; do
280 [ -f "$__test_path" ] || continue
281 __configs="$__configs $__test_path"
285 __configs="${__configs# }"
287 if [ "$__var_to_set" ]; then
289 [ "$__append" -o "$__prepend" ] &&
290 f_getvar "$__var_to_set" __cur
291 [ "$__append" ] && __configs="$__cur{$__cur:+ }$__configs"
292 [ "$__prepend" ] && __configs="$__configs${__cur:+ }$__cur"
293 setvar "$__var_to_set" "$__configs"
301 # f_sysrc_get_default $varname
303 # Get a system configuration default setting from the default rc.conf(5) file
304 # (or whatever RC_DEFAULTS points at).
306 f_sysrc_get_default()
309 [ -f "$RC_DEFAULTS" -a -r "$RC_DEFAULTS" ] || return $FAILURE
311 # Taint-check variable name
314 # Don't expand possible positional parameters
317 [ "$1" ] || return $FAILURE
320 ( # Execute within sub-shell to protect parent environment
323 # Clear the environment of all variables, preventing the
324 # expansion of normals such as `PS1', `TERM', etc.
326 f_clean_env --except RC_DEFAULTS
328 . "$RC_DEFAULTS" > /dev/null 2>&1
334 # This must be the last functional line for both the sub-shell
335 # and the function to preserve the return status from formats
336 # such as "${varname?}" and "${varname:?}" (see "Parameter
337 # Expansion" in sh(1) for more information).
339 eval echo '"${'"$1"'}"' 2> /dev/null
343 # f_sysrc_find $varname
345 # Find which file holds the effective last-assignment to a given variable
346 # within the rc.conf(5) file(s).
348 # If the variable is found in any of the rc.conf(5) files, the function prints
349 # the filename it was found in and then returns success. Otherwise output is
350 # NULL and the function returns with error status.
354 local varname="${1%%[!$VALID_VARNAME_CHARS]*}"
355 local regex="^[[:space:]]*$varname="
356 local rc_conf_files="$( f_sysrc_get rc_conf_files )"
362 ""|[0-9]*) return $FAILURE
366 # If RC_CONFS is defined, set $rc_conf_files to an explicit
367 # value, modifying the default behavior of source_rc_confs().
369 [ "${RC_CONFS+set}" ] && rc_conf_files="$RC_CONFS"
372 # Reverse the order of files in rc_conf_files (the boot process sources
373 # these in order, so we will search them in reverse-order to find the
374 # last-assignment -- the one that ultimately effects the environment).
376 for file in $rc_conf_files; do
377 conf_files="$file${conf_files:+ }$conf_files"
381 # Append the defaults file (since directives in the defaults file
382 # indeed affect the boot process, we'll want to know when a directive
385 conf_files="$conf_files${conf_files:+ }$RC_DEFAULTS"
388 # Find which file matches assignment to the given variable name.
390 for file in $conf_files; do
391 [ -f "$file" -a -r "$file" ] || continue
392 if grep -Eq "$regex" $file; then
398 return $FAILURE # Not found
401 # f_sysrc_desc $varname
403 # Attempts to return the comments associated with varname from the rc.conf(5)
404 # defaults file `/etc/defaults/rc.conf' (or whatever RC_DEFAULTS points to).
406 # Multi-line comments are joined together. Results are NULL if no description
409 # This function is a two-parter. Below is the awk(1) portion of the function,
410 # afterward is the sh(1) function which utilizes the below awk script.
413 # Variables that should be defined on the invocation line:
414 # -v varname="varname"
417 regex = "^[[:space:]]*"varname"="
424 if ( ! match($0, regex) ) next
427 sub(/^[^#]*(#[[:space:]]*)?/, "")
432 if ( !/^[[:space:]]*#/ ||
433 /^[[:space:]]*[[:alpha:]_][[:alnum:]_]*=/ ||
434 /^[[:space:]]*#[[:alpha:]_][[:alnum:]_]*=/ ||
435 /^[[:space:]]*$/ ) exit
437 sub(/(.*#)*[[:space:]]*/, "")
441 # Clean up the buffer
442 sub(/^[[:space:]]*/, "", buffer)
443 sub(/[[:space:]]*$/, "", buffer)
451 awk -v varname="$1" "$f_sysrc_desc_awk" < "$RC_DEFAULTS"
454 # f_sysrc_set $varname $new_value
456 # Change a setting in the system configuration files (edits the files in-place
457 # to change the value in the last assignment to the variable). If the variable
458 # does not appear in the source file, it is appended to the end of the primary
459 # system configuration file `/etc/rc.conf'.
461 # This function is a two-parter. Below is the awk(1) portion of the function,
462 # afterward is the sh(1) function which utilizes the below awk script.
465 # Variables that should be defined on the invocation line:
466 # -v varname="varname"
467 # -v new_value="new_value"
470 regex = "^[[:space:]]*"varname"="
474 # If already found... just spew
475 if ( found ) { print; next }
477 # Does this line match an assignment to our variable?
478 if ( ! match($0, regex) ) { print; next }
480 # Save important match information
482 matchlen = RSTART + RLENGTH - 1
484 # Store the value text for later munging
485 value = substr($0, matchlen + 1, length($0) - matchlen)
487 # Store the first character of the value
488 t1 = t2 = substr(value, 0, 1)
490 # Assignment w/ back-ticks, expression, or misc.
491 # We ignore these since we did not generate them
493 if ( t1 ~ /[`$\\]/ ) { retval = 1; print; next }
495 # Assignment w/ single-quoted value
496 else if ( t1 == "'\''" ) {
497 sub(/^'\''[^'\'']*/, "", value)
498 if ( length(value) == 0 ) t2 = ""
499 sub(/^'\''/, "", value)
502 # Assignment w/ double-quoted value
503 else if ( t1 == "\"" ) {
504 sub(/^"(.*\\\\+")*[^"]*/, "", value)
505 if ( length(value) == 0 ) t2 = ""
509 # Assignment w/ non-quoted value
510 else if ( t1 ~ /[^[:space:];]/ ) {
512 sub(/^[^[:space:]]*/, "", value)
516 else if ( t1 ~ /[[:space:];]/ ) { t1 = t2 = "\"" }
518 printf "%s%c%s%c%s\n", substr($0, 0, matchlen), \
519 t1, new_value, t2, value
525 local funcname=f_sysrc_set
526 local varname="$1" new_value="$2"
529 [ "$varname" ] || return $FAILURE
532 # Find which rc.conf(5) file contains the last-assignment
535 local file="$( f_sysrc_find "$varname" )"
536 if [ "$file" = "$RC_DEFAULTS" -o ! "$file" ]; then
538 # We either got a null response (not found) or the variable
539 # was only found in the rc.conf(5) defaults. In either case,
540 # let's instead modify the first file from $rc_conf_files.
546 # If RC_CONFS is defined, use $RC_CONFS
547 # rather than $rc_conf_files.
549 if [ "${RC_CONFS+set}" ]; then
550 file="${RC_CONFS%%[$IFS]*}"
552 file=$( f_sysrc_get 'rc_conf_files%%[$IFS]*' )
557 # If not found, append new value to last file and return.
559 if [ "$not_found" ]; then
560 echo "$varname=\"$new_value\"" >> "$file"
565 # Perform sanity checks.
567 if [ ! -w "$file" ]; then
568 f_err "$msg_cannot_create_permission_denied\n" \
574 # Create a new temporary file to write to.
577 if ! f_eval_catch -dk tmpfile $funcname mktemp 'mktemp -t "%s"' "$pgm"
584 # Fixup permissions (else we're in for a surprise, as mktemp(1) creates
585 # the temporary file with 0600 permissions, and if we simply mv(1) the
586 # temporary file over the destination, the destination will inherit the
587 # permissions from the temporary file).
590 f_eval_catch -dk mode $funcname stat 'stat -f "%%#Lp" "%s"' "$file" ||
592 f_eval_catch -d $funcname chmod 'chmod "%s" "%s"' "$mode" "$tmpfile"
595 # Fixup ownership. The destination file _is_ writable (we tested
596 # earlier above). However, this will fail if we don't have sufficient
597 # permissions (so we throw stderr into the bit-bucket).
600 f_eval_catch -dk owner $funcname stat \
601 'stat -f "%%u:%%g" "%s"' "$file" || owner="root:wheel"
602 f_eval_catch -d $funcname chown 'chown "%s" "%s"' "$owner" "$tmpfile"
605 # Operate on the matching file, replacing only the last occurrence.
607 local new_contents retval
608 new_contents=$( tail -r $file 2> /dev/null )
609 new_contents=$( echo "$new_contents" | awk -v varname="$varname" \
610 -v new_value="$new_value" "$f_sysrc_set_awk" )
614 # Write the temporary file contents.
616 echo "$new_contents" | tail -r > "$tmpfile" || return $FAILURE
617 if [ $retval -ne $SUCCESS ]; then
618 echo "$varname=\"$new_value\"" >> "$tmpfile"
622 # Taint-check our results.
624 if ! f_eval_catch -d $funcname sh '/bin/sh -n "%s"' "$tmpfile"; then
625 f_err "$msg_previous_syntax_errors\n" "$pgm" "$file"
631 # Finally, move the temporary file into place.
633 f_eval_catch -de $funcname mv 'mv "%s" "%s"' "$tmpfile" "$file"
636 # f_sysrc_delete $varname
638 # Remove a setting from the system configuration files (edits files in-place).
639 # Deletes all assignments to the given variable in all config files. If the
640 # `-f file' option is passed, the removal is restricted to only those files
641 # specified, otherwise the system collection of rc_conf_files is used.
643 # This function is a two-parter. Below is the awk(1) portion of the function,
644 # afterward is the sh(1) function which utilizes the below awk script.
647 # Variables that should be defined on the invocation line:
648 # -v varname="varname"
651 regex = "^[[:space:]]*"varname"="
664 local funcname=f_sysrc_delete
669 [ "$varname" ] || return $FAILURE
672 # Operate on each of the specified files
675 for file in ${RC_CONFS-$( f_sysrc_get rc_conf_files )}; do
676 [ -e "$file" ] || continue
679 # Create a new temporary file to write to.
681 if ! f_eval_catch -dk tmpfile $funcname mktemp \
682 'mktemp -t "%s"' "$pgm"
689 # Fixup permissions and ownership (mktemp(1) defaults to 0600
690 # permissions) to instead match the destination file.
693 f_eval_catch -dk mode $funcname stat \
694 'stat -f "%%#Lp" "%s"' "$file" || mode=0644
695 f_eval_catch -dk owner $funcname stat \
696 'stat -f "%%u:%%g" "%s"' "$file" || owner="root:wheel"
697 f_eval_catch -d $funcname chmod \
698 'chmod "%s" "%s"' "$mode" "$tmpfile"
699 f_eval_catch -d $funcname chown \
700 'chown "%s" "%s"' "$owner" "$tmpfile"
703 # Operate on the file, removing all occurrences, saving the
704 # output in our temporary file.
706 awk -v varname="$varname" "$f_sysrc_delete_awk" "$file" \
708 if [ $? -ne $SUCCESS ]; then
709 # The file didn't contain any assignments
715 # Taint-check our results.
717 if ! f_eval_catch -d $funcname sh '/bin/sh -n "%s"' "$tmpfile"
719 f_err "$msg_previous_syntax_errors\n" \
726 # Perform sanity checks
728 if [ ! -w "$file" ]; then
729 f_err "$msg_permission_denied\n" "$pgm" "$file"
735 # Finally, move the temporary file into place.
737 f_eval_catch -de $funcname mv \
738 'mv "%s" "%s"' "$tmpfile" "$file" || return $FAILURE
742 ############################################################ MAIN
744 f_dprintf "%s: Successfully loaded." sysrc.subr