xref: /freebsd/usr.sbin/bsdconfig/share/strings.subr (revision 0fd00e0caa889111fc31617db9cd9aa52e9c5eec)
1if [ ! "$_STRINGS_SUBR" ]; then _STRINGS_SUBR=1
2#
3# Copyright (c) 2006-2016 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$
28#
29############################################################ INCLUDES
30
31BSDCFG_SHARE="/usr/share/bsdconfig"
32. $BSDCFG_SHARE/common.subr || exit 1
33
34############################################################ GLOBALS
35
36#
37# A Literal newline (for use with f_replace_all(), or IFS, or whatever)
38#
39NL="
40" # END-QUOTE
41
42#
43# Valid characters that can appear in an sh(1) variable name
44#
45# Please note that the character ranges A-Z and a-z should be avoided because
46# these can include accent characters (which are not valid in a variable name).
47# For example, A-Z matches any character that sorts after A but before Z,
48# including A and Z. Although ASCII order would make more sense, that is not
49# how it works.
50#
51VALID_VARNAME_CHARS="0-9ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
52
53############################################################ FUNCTIONS
54
55# f_isinteger $arg
56#
57# Returns true if argument is a positive/negative whole integer.
58#
59f_isinteger()
60{
61	local arg="${1#-}"
62	[ "${arg:-x}" = "${arg%[!0-9]*}" ]
63}
64
65# f_substr [-v $var_to_set] $string $start [$length]
66#
67# Similar to awk(1)'s substr(), return length substring of string that begins
68# at start position counted from 1.
69#
70f_substr()
71{
72	local OPTIND=1 OPTARG __flag __var_to_set=
73	while getopts v: __flag; do
74		case "$__flag" in
75		v) __var_to_set="$OPTARG" ;;
76		esac
77	done
78	shift $(( $OPTIND - 1 ))
79
80	local __tmp="$1" __start="${2:-1}" __size="$3"
81	local __tbuf __tbuf_len __trim __trimq
82
83	if [ ! "$__tmp" ]; then
84		[ "$__var_to_set" ] && setvar "$__var_to_set" ""
85		return ${SUCCESS:-0}
86	fi
87	[ "$__start" -ge 1 ] 2> /dev/null || __start=1
88	if ! [ "${__size:-1}" -ge 1 ] 2> /dev/null; then
89		[ "$__var_to_set" ] && setvar "$__var_to_set" ""
90		return ${FAILURE:-1}
91	fi
92
93	__trim=$(( $__start - 1 ))
94	while [ $__trim -gt 0 ]; do
95		__tbuf="?"
96		__tbuf_len=1
97		while [ $__tbuf_len -lt $(( $__trim / $__tbuf_len )) ]; do
98			__tbuf="$__tbuf?"
99			__tbuf_len=$(( $__tbuf_len + 1 ))
100		done
101		__trimq=$(( $__trim / $__tbuf_len ))
102		__trim=$(( $__trim - $__tbuf_len * $__trimq ))
103		while [ $__trimq -gt 0 ]; do
104			__tmp="${__tmp#$__tbuf}"
105			__trimq=$(( $__trimq - 1 ))
106		done
107	done
108
109	local __tmp_size=${#__tmp}
110	local __mask __mask_len
111	__trim=$(( $__tmp_size - ${__size:-$__tmp_size} ))
112	while [ $__trim -gt 0 ]; do
113		__tbuf="?"
114		__tbuf_len=1
115		if [ $__trim -le $__size ]; then
116			while [ $__tbuf_len -lt $(( $__trim / $__tbuf_len )) ]
117			do
118				__tbuf="$__tbuf?"
119				__tbuf_len=$(( $__tbuf_len + 1 ))
120			done
121			__trimq=$(( $__trim / $__tbuf_len ))
122			__trim=$(( $__trim - $__tbuf_len * $__trimq ))
123			while [ $__trimq -gt 0 ]; do
124				__tmp="${__tmp%$__tbuf}"
125				__trimq=$(( $__trimq - 1 ))
126			done
127		else
128			__mask="$__tmp"
129			while [ $__tbuf_len -lt $(( $__size / $__tbuf_len )) ]
130			do
131				__tbuf="$__tbuf?"
132				__tbuf_len=$(( $__tbuf_len + 1 ))
133			done
134			__trimq=$(( $__size / $__tbuf_len ))
135			if [ $(( $__trimq * $__tbuf_len )) -ne $__size ]; then
136				__tbuf="$__tbuf?"
137				__tbuf_len=$(( $__tbuf_len + 1 ))
138			fi
139			__mask_len=$(( $__tmp_size - $__tbuf_len * $__trimq ))
140			__trim=$(( $__tmp_size - $__mask_len - $__size ))
141			while [ $__trimq -gt 0 ]; do
142				__mask="${__mask#$__tbuf}"
143				__trimq=$(( $__trimq - 1 ))
144			done
145			__tmp="${__tmp%"$__mask"}"
146		fi
147	done
148
149	setvar "$__var_to_set" "$__tmp"
150}
151
152# f_sprintf $var_to_set $format [$arguments ...]
153#
154# Similar to sprintf(3), write a string into $var_to_set using printf(1) syntax
155# (`$format [$arguments ...]').
156#
157f_sprintf()
158{
159	local __var_to_set="$1"
160	shift 1 # var_to_set
161
162	case "$BASH_VERSION" in
163	3.1*|4.*)
164		local __tmp
165		printf -v __tmp "$@"
166		eval "$__var_to_set"=\"\${__tmp%\$NL}\"
167		;;
168	*) eval "$__var_to_set"=\$\( printf -- \"\$@\" \)
169	esac
170}
171
172# f_vsprintf $var_to_set $format $format_args
173#
174# Similar to vsprintf(3), write a string into $var_to_set using printf(1)
175# syntax (`$format $format_args').
176#
177f_vsprintf()
178{
179	eval f_sprintf \"\$1\" \"\$2\" $3
180}
181
182# f_snprintf $var_to_set $size $format [$arguments ...]
183#
184# Similar to snprintf(3), write at most $size number of bytes into $var_to_set
185# using printf(1) syntax (`$format [$arguments ...]').
186#
187f_snprintf()
188{
189	local __var_to_set="$1" __size="$2"
190	shift 2 # var_to_set size
191
192	local __f_snprintf_tmp
193	f_sprintf __f_snprintf_tmp "$@"
194	f_substr "$__var_to_set" "$__f_snprintf_tmp" 1 "$__size"
195}
196
197# f_vsnprintf $var_to_set $size $format $format_args
198#
199# Similar to vsnprintf(3), write at most $size number of bytes into $var_to_set
200# using printf(1) syntax (`$format $format_args'). The value of $var_to_set is
201# NULL unless at-least one byte is stored from the output.
202#
203# Example 1:
204#
205# 	limit=7 format="%s"
206# 	format_args="'abc   123'" # 3-spaces between abc and 123
207# 	f_vsnprintf foo $limit "$format" "$format_args" # foo=[abc   1]
208#
209# Example 2:
210#
211# 	limit=12 format="%s %s"
212# 	format_args="   'doghouse'      'fox'   "
213# 		# even more spaces added to illustrate escape-method
214# 	f_vsnprintf foo $limit "$format" "$format_args" # foo=[doghouse fox]
215#
216# Example 3:
217#
218# 	limit=13 format="%s %s"
219# 	f_shell_escape arg1 'aaa"aaa' # arg1=[aaa"aaa] (no change)
220# 	f_shell_escape arg2 "aaa'aaa" # arg2=[aaa'\''aaa] (escaped s-quote)
221# 	format_args="'$arg1' '$arg2'" # use single-quotes to surround args
222# 	f_vsnprintf foo $limit "$format" "$format_args" # foo=[aaa"aaa aaa'a]
223#
224# In all of the above examples, the call to f_vsnprintf() does not change. Only
225# the contents of $limit, $format, and $format_args changes in each example.
226#
227f_vsnprintf()
228{
229	eval f_snprintf \"\$1\" \"\$2\" \"\$3\" $4
230}
231
232# f_replaceall $string $find $replace [$var_to_set]
233#
234# Replace all occurrences of $find in $string with $replace. If $var_to_set is
235# either missing or NULL, the variable name is produced on standard out for
236# capturing in a sub-shell (which is less recommended due to performance
237# degradation).
238#
239# To replace newlines or a sequence containing the newline character, use $NL
240# as `\n' is not supported.
241#
242f_replaceall()
243{
244	local __left="" __right="$1"
245	local __find="$2" __replace="$3" __var_to_set="$4"
246	while :; do
247		case "$__right" in *$__find*)
248			__left="$__left${__right%%$__find*}$__replace"
249			__right="${__right#*$__find}"
250			continue
251		esac
252		break
253	done
254	__left="$__left${__right#*$__find}"
255	if [ "$__var_to_set" ]; then
256		setvar "$__var_to_set" "$__left"
257	else
258		echo "$__left"
259	fi
260}
261
262# f_str2varname $string [$var_to_set]
263#
264# Convert a string into a suitable value to be used as a variable name
265# by converting unsuitable characters into the underscrore [_]. If $var_to_set
266# is either missing or NULL, the variable name is produced on standard out for
267# capturing in a sub-shell (which is less recommended due to performance
268# degradation).
269#
270f_str2varname()
271{
272	local __string="$1" __var_to_set="$2"
273	f_replaceall "$__string" "[!$VALID_VARNAME_CHARS]" "_" "$__var_to_set"
274}
275
276# f_shell_escape $string [$var_to_set]
277#
278# Escape $string for shell eval statement(s) by replacing all single-quotes
279# with a special sequence that creates a compound string when interpolated
280# by eval with surrounding single-quotes.
281#
282# For example:
283#
284# 	foo="abc'123"
285# 	f_shell_escape "$foo" bar # bar=[abc'\''123]
286# 	eval echo \'$bar\' # produces abc'123
287#
288# This is helpful when processing an argument list that has to retain its
289# escaped structure for later evaluations.
290#
291# WARNING: Surrounding single-quotes are not added; this is the responsibility
292# of the code passing the escaped values to eval (which also aids readability).
293#
294f_shell_escape()
295{
296	local __string="$1" __var_to_set="$2"
297	f_replaceall "$__string" "'" "'\\''" "$__var_to_set"
298}
299
300# f_shell_unescape $string [$var_to_set]
301#
302# The antithesis of f_shell_escape(), this function takes an escaped $string
303# and expands it.
304#
305# For example:
306#
307# 	foo="abc'123"
308# 	f_shell_escape "$foo" bar # bar=[abc'\''123]
309# 	f_shell_unescape "$bar" # produces abc'123
310#
311f_shell_unescape()
312{
313	local __string="$1" __var_to_set="$2"
314	f_replaceall "$__string" "'\\''" "'" "$__var_to_set"
315}
316
317# f_expand_number $string [$var_to_set]
318#
319# Unformat $string into a number, optionally to be stored in $var_to_set. This
320# function follows the SI power of two convention.
321#
322# The prefixes are:
323#
324# 	Prefix	Description	Multiplier
325# 	k	kilo		1024
326# 	M	mega		1048576
327# 	G	giga		1073741824
328# 	T	tera		1099511627776
329# 	P	peta		1125899906842624
330# 	E	exa		1152921504606846976
331#
332# NOTE: Prefixes are case-insensitive.
333#
334# Upon successful completion, success status is returned; otherwise the number
335# -1 is produced ($var_to_set set to -1 or if $var_to_set is NULL or missing)
336# on standard output. In the case of failure, the error status will be one of:
337#
338# 	Status	Reason
339# 	1	Given $string contains no digits
340# 	2	An unrecognized prefix was given
341# 	3	Result too large to calculate
342#
343f_expand_number()
344{
345	local __string="$1" __var_to_set="$2"
346	local __cp __num __bshift __maxinput
347
348	# Remove any leading non-digits
349	__string="${__string#${__string%%[0-9]*}}"
350
351	# Store the numbers (no trailing suffix)
352	__num="${__string%%[!0-9]*}"
353
354	# Produce `-1' if string didn't contain any digits
355	if [ ! "$__num" ]; then
356		if [ "$__var_to_set" ]; then
357			setvar "$__var_to_set" -1
358		else
359			echo -1
360		fi
361		return 1 # 1 = "Given $string contains no digits"
362	fi
363
364	# Remove all the leading numbers from the string to get at the prefix
365	__string="${__string#"$__num"}"
366
367	#
368	# Test for invalid prefix (and determine bitshift length)
369	#
370	case "$__string" in
371	""|[[:space:]]*) # Shortcut
372		if [ "$__var_to_set" ]; then
373			setvar "$__var_to_set" $__num
374		else
375			echo $__num
376		fi
377		return $SUCCESS ;;
378	[Kk]*) __bshift=10 ;;
379	[Mm]*) __bshift=20 ;;
380	[Gg]*) __bshift=30 ;;
381	[Tt]*) __bshift=40 ;;
382	[Pp]*) __bshift=50 ;;
383	[Ee]*) __bshift=60 ;;
384	*)
385		# Unknown prefix
386		if [ "$__var_to_set" ]; then
387			setvar "$__var_to_set" -1
388		else
389			echo -1
390		fi
391		return 2 # 2 = "An unrecognized prefix was given"
392	esac
393
394	# Determine if the wheels fall off
395	__maxinput=$(( 0x7fffffffffffffff >> $__bshift ))
396	if [ $__num -gt $__maxinput ]; then
397		# Input (before expanding) would exceed 64-bit signed int
398		if [ "$__var_to_set" ]; then
399			setvar "$__var_to_set" -1
400		else
401			echo -1
402		fi
403		return 3 # 3 = "Result too large to calculate"
404	fi
405
406	# Shift the number out and produce it
407	__num=$(( $__num << $__bshift ))
408	if [ "$__var_to_set" ]; then
409		setvar "$__var_to_set" $__num
410	else
411		echo $__num
412	fi
413}
414
415# f_longest_line_length
416#
417# Simple wrapper to an awk(1) script to print the length of the longest line of
418# input (read from stdin). Supports the newline escape-sequence `\n' for
419# splitting a single line into multiple lines.
420#
421f_longest_line_length_awk='
422BEGIN { longest = 0 }
423{
424	if (split($0, lines, /\\n/) > 1)
425	{
426		for (n in lines)
427		{
428			len = length(lines[n])
429			longest = ( len > longest ? len : longest )
430		}
431	}
432	else
433	{
434		len = length($0)
435		longest = ( len > longest ? len : longest )
436	}
437}
438END { print longest }
439'
440f_longest_line_length()
441{
442	awk "$f_longest_line_length_awk"
443}
444
445# f_number_of_lines
446#
447# Simple wrapper to an awk(1) script to print the number of lines read from
448# stdin. Supports newline escape-sequence `\n' for splitting a single line into
449# multiple lines.
450#
451f_number_of_lines_awk='
452BEGIN { num_lines = 0 }
453{
454	num_lines += split(" "$0, unused, /\\n/)
455}
456END { print num_lines }
457'
458f_number_of_lines()
459{
460	awk "$f_number_of_lines_awk"
461}
462
463# f_uriencode [$text]
464#
465# Encode $text for the purpose of embedding safely into a URL. Non-alphanumeric
466# characters are converted to `%XX' sequence where XX represents the hexa-
467# decimal ordinal of the non-alphanumeric character. If $text is missing, data
468# is instead read from standard input.
469#
470f_uriencode_awk='
471BEGIN {
472	output = ""
473	for (n = 0; n < 256; n++) pack[sprintf("%c", n)] = sprintf("%%%02x", n)
474}
475{
476	sline = ""
477	slen = length($0)
478	for (n = 1; n <= slen; n++) {
479		char = substr($0, n, 1)
480		if ( char !~ /^[[:alnum:]_]$/ ) char = pack[char]
481		sline = sline char
482	}
483	output = output ( output ? "%0a" : "" ) sline
484}
485END { print output }
486'
487f_uriencode()
488{
489	if [ $# -gt 0 ]; then
490		echo "$1" | awk "$f_uriencode_awk"
491	else
492		awk "$f_uriencode_awk"
493	fi
494}
495
496# f_uridecode [$text]
497#
498# Decode $text from a URI. Encoded characters are converted from their `%XX'
499# sequence into original unencoded ASCII sequences. If $text is missing, data
500# is instead read from standard input.
501#
502f_uridecode_awk='
503BEGIN { for (n = 0; n < 256; n++) chr[n] = sprintf("%c", n) }
504{
505	sline = ""
506	slen = length($0)
507	for (n = 1; n <= slen; n++)
508	{
509		seq = substr($0, n, 3)
510		if ( seq ~ /^%[[:xdigit:]][[:xdigit:]]$/ ) {
511			hex = substr(seq, 2, 2)
512			sline = sline chr[sprintf("%u", "0x"hex)]
513			n += 2
514		} else
515			sline = sline substr(seq, 1, 1)
516	}
517	print sline
518}
519'
520f_uridecode()
521{
522	if [ $# -gt 0 ]; then
523		echo "$1" | awk "$f_uridecode_awk"
524	else
525		awk "$f_uridecode_awk"
526	fi
527}
528
529############################################################ MAIN
530
531f_dprintf "%s: Successfully loaded." strings.subr
532
533fi # ! $_STRINGS_SUBR
534