sysrc revision 260679
1#!/bin/sh
2#-
3# Copyright (c) 2010-2013 Devin Teske
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
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.
14#
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
25# SUCH DAMAGE.
26#
27# $FreeBSD: stable/10/usr.sbin/sysrc/sysrc 260679 2014-01-15 08:03:01Z dteske $
28#
29############################################################ INCLUDES
30
31# Prevent `-d' from being interpreted as a debug flag by common.subr
32DEBUG_SELF_INITIALIZE=
33
34BSDCFG_SHARE="/usr/share/bsdconfig"
35[ "$_COMMON_SUBR" ] || . $BSDCFG_SHARE/common.subr || exit 1
36[ "$_SYSRC_SUBR"  ] || f_include $BSDCFG_SHARE/sysrc.subr
37
38############################################################ GLOBALS
39
40#
41# Version information
42#
43SYSRC_VERSION="6.0 Nov-07,2013"
44
45#
46# Options
47#
48CHECK_ONLY=
49DELETE=
50DESCRIBE=
51IGNORE_UNKNOWNS=
52JAIL=
53QUIET=
54ROOTDIR=
55SHOW_ALL=
56SHOW_EQUALS=
57SHOW_FILE=
58SHOW_NAME=1
59SHOW_VALUE=1
60SYSRC_VERBOSE=
61
62############################################################ FUNCTIONS
63
64# die [ $fmt [ $opts ... ]]
65#
66# Optionally print a message to stderr before exiting with failure status.
67#
68die()
69{
70	local fmt="$1"
71	[ $# -gt 0 ] && shift 1
72	[  "$fmt"  ] && f_err "$fmt\n" "$@"
73
74	exit $FAILURE
75}
76
77# usage
78#
79# Prints a short syntax statement and exits.
80#
81usage()
82{
83	f_err "Usage: %s [OPTIONS] name[=value] ...\n" "$pgm"
84	f_err "Try \`%s --help' for more information.\n" "$pgm"
85	die
86}
87
88# help
89#
90# Prints a full syntax statement and exits.
91#
92help()
93{
94	local optfmt="\t%-11s%s\n"
95	local envfmt="\t%-17s%s\n"
96
97	f_err "Usage: %s [OPTIONS] name[=value] ...\n" "$pgm"
98
99	f_err "OPTIONS:\n"
100	f_err "$optfmt" "-a" \
101	      "Dump a list of all non-default configuration variables."
102	f_err "$optfmt" "-A" \
103	      "Dump a list of all configuration variables (incl. defaults)."
104	f_err "$optfmt" "-c" \
105	      "Check. Return success if no changes needed, else error."
106	f_err "$optfmt" "-d" \
107	      "Print a description of the given variable."
108	f_err "$optfmt" "-D" \
109	      "Show default value(s) only (this is the same as setting"
110	f_err "$optfmt" "" \
111	      "RC_CONFS to NULL or passing \`-f' with a NULL file-argument)."
112	f_err "$optfmt" "-e" \
113	      "Print query results as \`var=value' (useful for producing"
114	f_err "$optfmt" "" \
115	      "output to be fed back in). Ignored if \`-n' is specified."
116	f_err "$optfmt" "-f file" \
117	      "Operate on the specified file(s) instead of rc_conf_files."
118	f_err "$optfmt" "" \
119	      "Can be specified multiple times for additional files."
120	f_err "$optfmt" "-F" \
121	      "Show only the last rc.conf(5) file each directive is in."
122	f_err "$optfmt" "-h" \
123	      "Print a short usage statement to stderr and exit."
124	f_err "$optfmt" "--help" \
125	      "Print this message to stderr and exit."
126	f_err "$optfmt" "-i" \
127	      "Ignore unknown variables."
128	f_err "$optfmt" "-j jail" \
129	      "The jid or name of the jail to operate within (overrides"
130	f_err "$optfmt" "" \
131	      "\`-R dir'; requires jexec(8))."
132	f_err "$optfmt" "-n" \
133	      "Show only variable values, not their names."
134	f_err "$optfmt" "-N" \
135	      "Show only variable names, not their values."
136	f_err "$optfmt" "-q" \
137	      "Quiet. Ignore previous \`-v' and/or SYSRC_VERBOSE."
138	f_err "$optfmt" "-R dir" \
139	      "Operate within the root directory \`dir' rather than \`/'."
140	f_err "$optfmt" "-v" \
141	      "Verbose. Print the pathname of the specific rc.conf(5)"
142	f_err "$optfmt" "" \
143	      "file where the directive was found."
144	f_err "$optfmt" "--version" \
145	      "Print version information to stdout and exit."
146	f_err "$optfmt" "-x" \
147	      "Remove variable(s) from specified file(s)."
148	f_err "\n"
149
150	f_err "ENVIRONMENT:\n"
151	f_err "$envfmt" "RC_CONFS" \
152	      "Override default rc_conf_files (even if set to NULL)."
153	f_err "$envfmt" "RC_DEFAULTS" \
154	      "Location of \`/etc/defaults/rc.conf' file."
155	f_err "$envfmt" "SYSRC_VERBOSE" \
156	      "Default verbosity. Set to non-NULL to enable."
157
158	die
159}
160
161# jail_depend
162#
163# Dump dependencies such as language-file variables and include files to stdout
164# to be piped-into sh(1) running via jexec(8)/chroot(8). As a security measure,
165# this prevents existing language files and library files from being loaded in
166# the jail. This also relaxes the requirement to have these files in every jail
167# before sysrc can be used on said jail.
168#
169jail_depend()
170{
171	#
172	# Indicate that we are jailed
173	#
174	echo export _SYSRC_JAILED=1
175
176	#
177	# Print i18n language variables (their current values are sanitized
178	# and re-printed for interpretation so that the i18n language files
179	# do not need to exist within the jail).
180	#
181	local var val
182	for var in \
183		msg_cannot_create_permission_denied \
184		msg_permission_denied \
185		msg_previous_syntax_errors \
186	; do
187		val=$( eval echo \"\$$var\" |
188			awk '{ gsub(/'\''/, "'\''\\'\'\''"); print }' )
189		echo $var="'$val'"
190	done
191
192	#
193	# Print include dependencies
194	#
195	echo DEBUG_SELF_INITIALIZE=
196	cat $BSDCFG_SHARE/common.subr
197	cat $BSDCFG_SHARE/sysrc.subr
198}
199
200############################################################ MAIN SOURCE
201
202#
203# Perform sanity checks
204#
205[ $# -gt 0 ] || usage
206
207#
208# Check for `--help' and `--version' command-line option
209#
210( # Operate in sub-shell to protect $@ in parent
211	while [ $# -gt 0 ]; do
212		case "$1" in
213		--help) help ;;
214		--version) # see GLOBALS
215			echo "$SYSRC_VERSION"
216			exit 1 ;;
217		-[fRj]) # These flags take an argument
218			shift 1 ;;
219		esac
220		shift 1
221	done
222	exit 0
223) || die
224
225#
226# Process command-line flags
227#
228while getopts aAcdDef:Fhij:nNqR:vxX flag; do
229	case "$flag" in
230	a) SHOW_ALL=${SHOW_ALL:-1};;
231	A) SHOW_ALL=2;;
232	c) CHECK_ONLY=1;;
233	d) DESCRIBE=1;;
234	D) RC_CONFS=;;
235	e) SHOW_EQUALS=1;;
236	f) RC_CONFS="$RC_CONFS${RC_CONFS:+ }$OPTARG";;
237	F) SHOW_FILE=1;;
238	h) usage;;
239	i) IGNORE_UNKNOWNS=1;;
240	j) [ "$OPTARG" ] || die \
241	   	"%s: Missing or null argument to \`-j' flag" "$pgm"
242	   JAIL="$OPTARG";;
243	n) SHOW_NAME=;;
244	N) SHOW_VALUE=;;
245	q) QUIET=1 SYSRC_VERBOSE=;;
246	R) [ "$OPTARG" ] || die \
247	   	"%s: Missing or null argument to \`-R' flag" "$pgm"
248	   ROOTDIR="$OPTARG";;
249	v) SYSRC_VERBOSE=1 QUIET=;;
250	x) DELETE=${DELETE:-1};;
251	X) DELETE=2;;
252	\?) usage;;
253	esac
254done
255shift $(( $OPTIND - 1 ))
256
257#
258# [More] Sanity checks (e.g., "sysrc --")
259#
260[ $# -eq 0 -a ! "$SHOW_ALL" ] && usage
261
262#
263# Taint-check all rc.conf(5) files
264#
265errmsg="$pgm: Exiting due to previous syntax errors"
266if [ "${RC_CONFS+set}" ]; then
267	( for i in $RC_CONFS; do
268	  	[ -e "$i" ] || continue
269	  	/bin/sh -n "$i" || exit $FAILURE
270	  done
271	  exit $SUCCESS
272	) || die "$errmsg"
273else
274	/bin/sh -n "$RC_DEFAULTS" || die "$errmsg"
275	( . "$RC_DEFAULTS"
276	  for i in $rc_conf_files; do
277	  	[ -e "$i" ] || continue
278	  	/bin/sh -n "$i" || exit $FAILURE
279	  done
280	  exit $SUCCESS
281	) || die "$errmsg"
282fi
283
284#
285# Process `-x' (and secret `-X') command-line options
286#
287errmsg="$pgm: \`-x' option incompatible with \`-a'/\`-A' options"
288errmsg="$errmsg (use \`-X' to override)"
289if [ "$DELETE" -a "$SHOW_ALL" ]; then
290	[ "$DELETE" = "2" ] || die "$errmsg"
291fi
292
293#
294# Pre-flight for `-c' command-line option
295#
296[ "$CHECK_ONLY" -a "$SHOW_ALL" ] &&
297	die "$pgm: \`-c' option incompatible with \`-a'/\`-A' options"
298
299#
300# Process `-e', `-n', and `-N' command-line options
301#
302SEP=': '
303[ "$SHOW_FILE" ] && SHOW_EQUALS=
304[ "$SHOW_NAME" ] || SHOW_EQUALS=
305[ "$SYSRC_VERBOSE" = "0" ] && SYSRC_VERBOSE=
306if [ ! "$SHOW_VALUE" ]; then
307	SHOW_NAME=1
308	SHOW_EQUALS=
309fi
310[ "$SHOW_EQUALS" ] && SEP='="'
311
312#
313# Process `-j jail' and `-R dir' command-line options
314#
315if [ "$JAIL" -o "$ROOTDIR" ]; then
316	#
317	# Reconstruct the arguments that we want to carry-over
318	#
319	args="
320		${SYSRC_VERBOSE:+-v}
321		${QUIET:+-q}
322		$( [ "$DELETE" = "1" ] && echo \ -x )
323		$( [ "$DELETE" = "2" ] && echo \ -X )
324		$( [ "$SHOW_ALL" = "1" ] && echo \ -a )
325		$( [ "$SHOW_ALL" = "2" ] && echo \ -A )
326		${CHECK_ONLY:+-c}
327		${DESCRIBE:+-d}
328		${SHOW_EQUALS:+-e}
329		${IGNORE_UNKNOWNS:+-i}
330		$( [ "$SHOW_NAME"  ] || echo \ -n )
331		$( [ "$SHOW_VALUE" ] || echo \ -N )
332		$( [ "$SHOW_FILE"  ] && echo \ -F )
333	"
334	if [ "${RC_CONFS+set}" ]; then
335		args="$args -f '$RC_CONFS'"
336	fi
337	for arg in "$@"; do
338		args="$args '$arg'"
339	done
340
341	#
342	# If both are supplied, `-j jail' supercedes `-R dir'
343	#
344	if [ "$JAIL" ]; then
345		#
346		# Re-execute ourselves with sh(1) via jexec(8)
347		#
348		( echo set -- $args
349		  jail_depend
350		  cat $0
351		) | env - RC_DEFAULTS="$RC_DEFAULTS" \
352		    	/usr/sbin/jexec "$JAIL" /bin/sh
353		exit $?
354	elif [ "$ROOTDIR" ]; then
355		#
356		# Make sure that the root directory specified is not to any
357		# running jails.
358		#
359		# NOTE: To maintain backward compatibility with older jails on
360		# older systems, we will not perform this check if either the
361		# jls(1) or jexec(8) utilities are missing.
362		#
363		if f_have jexec && f_have jls; then
364			jid="`jls jid path | \
365			(
366				while read JID JROOT; do
367					[ "$JROOT" = "$ROOTDIR" ] || continue
368					echo $JID
369				done
370			)`"
371
372			#
373			# If multiple running jails match the specified root
374			# directory, exit with error.
375			#
376			if [ "$jid" -a "${jid%[$IFS]*}" != "$jid" ]; then
377				die "%s: %s: %s" "$pgm" "$ROOTDIR" \
378				    "$( echo "Multiple jails claim this" \
379				             "directory as their root." \
380				             "(use \`-j jail' instead)" )"
381			fi
382
383			#
384			# If only a single running jail matches the specified
385			# root directory, implicitly use `-j jail'.
386			#
387			if [ "$jid" ]; then
388				#
389				# Re-execute outselves with sh(1) via jexec(8)
390				#
391				( echo set -- $args
392				  jail_depend
393				  cat $0
394				) | env - RC_DEFAULTS="$RC_DEFAULTS" \
395					/usr/sbin/jexec "$jid" /bin/sh
396				exit $?
397			fi
398
399			# Otherwise, fall through and allow chroot(8)
400		fi
401
402		#
403		# Re-execute ourselves with sh(1) via chroot(8)
404		#
405		( echo set -- $args
406		  jail_depend
407		  cat $0
408		) | env - RC_DEFAULTS="$RC_DEFAULTS" \
409		    	/usr/sbin/chroot "$ROOTDIR" /bin/sh
410		exit $?
411	fi
412fi
413
414#
415# Process `-a' or `-A' command-line options
416#
417if [ "$SHOW_ALL" ]; then
418	#
419	# Get a list of variables that are currently set in the rc.conf(5)
420	# files (included `/etc/defaults/rc.conf') by performing a call to
421	# source_rc_confs() in a clean environment.
422	#
423	( # Operate in a sub-shell to protect the parent environment
424		#
425		# Set which variables we want to preserve in the environment.
426		# Append the pipe-character (|) to the list of internal field
427		# separation (IFS) characters, allowing us to use the below
428		# list both as an extended grep (-E) pattern and argument list
429		# (required to first get f_clean_env() to preserve these in the
430		# environment and then later to prune them from the list of
431		# variables produced by set(1)).
432		#
433		IFS="$IFS|"
434		EXCEPT="IFS|EXCEPT|PATH|RC_DEFAULTS|OPTIND|DESCRIBE|SEP"
435		EXCEPT="$EXCEPT|DELETE|SHOW_ALL|SHOW_EQUALS|SHOW_NAME"
436		EXCEPT="$EXCEPT|SHOW_VALUE|SHOW_FILE|SYSRC_VERBOSE|RC_CONFS"
437		EXCEPT="$EXCEPT|pgm|SUCCESS|FAILURE|CHECK_ONLY"
438		EXCEPT="$EXCEPT|f_sysrc_desc_awk|f_sysrc_delete_awk"
439
440		#
441		# Clean the environment (except for our required variables)
442		# and then source the required files.
443		#
444		f_clean_env --except $EXCEPT
445		if [ -f "$RC_DEFAULTS" -a -r "$RC_DEFAULTS" ]; then
446			. "$RC_DEFAULTS"
447
448			#
449			# If passed `-a' (rather than `-A'), re-purge the
450			# environment, removing the rc.conf(5) defaults.
451			#
452			[ "$SHOW_ALL" = "1" ] \
453				&& f_clean_env --except rc_conf_files $EXCEPT
454
455			#
456			# If `-f file' was passed, set $rc_conf_files to an
457			# explicit value, modifying the default behavior of
458			# source_rc_confs().
459			#
460			[ "${RC_CONFS+set}" ] && rc_conf_files="$RC_CONFS"
461
462			source_rc_confs
463
464			#
465			# If passed `-a' (rather than `-A'), remove
466			# `rc_conf_files' unless it was defined somewhere
467			# other than rc.conf(5) defaults.
468			#
469			[ "$SHOW_ALL" = "1" -a \
470			  "$( f_sysrc_find rc_conf_files )" = "$RC_DEFAULTS" \
471			] \
472			&& unset rc_conf_files
473		fi
474
475		for NAME in $( set |
476			awk -F= '/^[[:alpha:]_][[:alnum:]_]*=/ {print $1}' |
477			grep -Ev "^($EXCEPT)$"
478		); do
479			#
480			# If enabled, describe rather than expand value
481			#
482			if [ "$DESCRIBE" ]; then
483				echo "$NAME: $( f_sysrc_desc "$NAME" )"
484				continue
485			fi
486
487			#
488			# If `-F' is passed, find it and move on
489			#
490			if [ "$SHOW_FILE" ]; then
491				[ "$SHOW_NAME" ] && echo -n "$NAME: "
492				f_sysrc_find "$NAME"
493				continue
494			fi
495
496			#
497			# If `-X' is passed, delete the variables
498			#
499			if [ "$DELETE" = "2" ]; then
500				f_sysrc_delete "$NAME"
501				continue
502			fi
503
504			[ "$SYSRC_VERBOSE" ] && \
505				echo -n "$( f_sysrc_find "$NAME" ): "
506
507			#
508			# If `-N' is passed, simplify the output
509			#
510			if [ ! "$SHOW_VALUE" ]; then
511				echo "$NAME"
512				continue
513			fi
514
515			echo "${SHOW_NAME:+$NAME$SEP}$(
516			      f_sysrc_get "$NAME" )${SHOW_EQUALS:+\"}"
517
518		done
519	)
520
521	#
522	# Ignore the remainder of positional arguments.
523	#
524	exit $SUCCESS
525fi
526
527#
528# Process command-line arguments
529#
530costatus=$SUCCESS
531while [ $# -gt 0 ]; do
532	NAME="${1%%=*}"
533
534	[ "$DESCRIBE" ] && \
535		echo "$NAME: $( f_sysrc_desc "$NAME" )"
536
537	case "$1" in
538	*=*)
539		#
540		# Like sysctl(8), if both `-d' AND "name=value" is passed,
541		# first describe (done above), then attempt to set
542		#
543
544		# If verbose, prefix line with where the directive lives
545		if [ "$SYSRC_VERBOSE" -a ! "$CHECK_ONLY" ]; then
546			file=$( f_sysrc_find "$NAME" )
547			[ "$file" = "$RC_DEFAULTS" -o ! "$file" ] && \
548				file=$( f_sysrc_get 'rc_conf_files%%[$IFS]*' )
549			if [ "$SHOW_EQUALS" ]; then
550				echo -n ": $file; "
551			else
552				echo -n "$file: "
553			fi
554		fi
555
556		#
557		# If `-x' or `-X' is passed, delete the variable and ignore the
558		# desire to set some value
559		#
560		if [ "$DELETE" ]; then
561			f_sysrc_delete "$NAME"
562			shift 1
563			continue
564		fi
565
566		#
567		# If `-c' is passed, simply compare and move on
568		#
569		if [ "$CHECK_ONLY" ]; then
570			if ! IGNORED=$( f_sysrc_get "$NAME?" ); then
571				costatus=$FAILURE
572			else
573				value=$( f_sysrc_get "$NAME" )
574				[ "$value" = "${1#*=}" ] || costatus=$FAILURE
575			fi
576			shift 1
577			continue
578		fi
579
580		#
581		# If `-N' is passed, simplify the output
582		#
583		if [ ! "$SHOW_VALUE" ]; then
584			echo "$NAME"
585			f_sysrc_set "$NAME" "${1#*}"
586		else
587			if [ "$SHOW_FILE" ]; then
588				before=$( f_sysrc_find "$NAME" )
589			else
590				before=$( f_sysrc_get "$NAME" )
591			fi
592			if f_sysrc_set "$NAME" "${1#*=}"; then
593				if [ "$SHOW_FILE" ]; then
594					after=$( f_sysrc_find "$NAME" )
595				else
596					after=$( f_sysrc_get "$NAME" )
597				fi
598				echo -n "${SHOW_NAME:+$NAME$SEP}"
599				echo -n "$before${SHOW_EQUALS:+\" #}"
600				echo -n " -> ${SHOW_EQUALS:+\"}$after"
601				echo "${SHOW_EQUALS:+\"}"
602			fi
603		fi
604		;;
605	*)
606		if ! IGNORED=$( f_sysrc_get "$NAME?" ); then
607			[ "$IGNORE_UNKNOWNS" ] ||
608				echo "$pgm: unknown variable '$NAME'"
609			shift 1
610			costatus=$FAILURE
611			continue
612		fi
613
614		# The above check told us what we needed for `-c'
615		if [ "$CHECK_ONLY" ]; then
616			shift 1
617			continue
618		fi
619
620		#
621		# Like sysctl(8), when `-d' is passed, desribe it
622		# (already done above) rather than expanding it
623		#
624
625		if [ "$DESCRIBE" ]; then
626			shift 1
627			continue
628		fi
629
630		#
631		# If `-x' or `-X' is passed, delete the variable
632		#
633		if [ "$DELETE" ]; then
634			f_sysrc_delete "$NAME"
635			shift 1
636			continue
637		fi
638
639		#
640		# If `-F' is passed, find it and move on
641		#
642		if [ "$SHOW_FILE" ]; then
643			[ "$SHOW_NAME" ] && echo -n "$NAME: "
644			f_sysrc_find "$NAME"
645			shift 1
646			continue
647		fi
648
649		if [ "$SYSRC_VERBOSE" ]; then
650			if [ "$SHOW_EQUALS" ]; then
651				echo -n ": $( f_sysrc_find "$NAME" ); "
652			else
653				echo -n "$( f_sysrc_find "$NAME" ): "
654			fi
655		fi
656
657		#
658		# If `-N' is passed, simplify the output
659		#
660		if [ ! "$SHOW_VALUE" ]; then
661			echo "$NAME"
662		else
663			echo "${SHOW_NAME:+$NAME$SEP}$(
664			      f_sysrc_get "$NAME" )${SHOW_EQUALS:+\"}"
665		fi
666	esac
667	shift 1
668done
669
670[ ! "$CHECK_ONLY" ] || exit $costatus
671
672################################################################################
673# END
674################################################################################
675