summaryrefslogtreecommitdiffstats
path: root/usr.sbin/bsdconfig/share/strings.subr
blob: e624fb5c7cd70dac22f654e5de4f428eab2dc250 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
if [ ! "$_STRINGS_SUBR" ]; then _STRINGS_SUBR=1
#
# Copyright (c) 2006-2013 Devin Teske
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# $FreeBSD$
#
############################################################ INCLUDES

BSDCFG_SHARE="/usr/share/bsdconfig"
. $BSDCFG_SHARE/common.subr || exit 1

############################################################ GLOBALS

#
# A Literal newline (for use with f_replace_all(), or IFS, or whatever)
#
NL="
" # END-QUOTE

#
# Valid characters that can appear in an sh(1) variable name
#
# Please note that the character ranges A-Z and a-z should be avoided because
# these can include accent characters (which are not valid in a variable name).
# For example, A-Z matches any character that sorts after A but before Z,
# including A and Z. Although ASCII order would make more sense, that is not
# how it works.
#
VALID_VARNAME_CHARS="0-9ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"

############################################################ FUNCTIONS

# f_substr "$string" $start [$length]
#
# Simple wrapper to awk(1)'s `substr' function.
#
f_substr()
{
	local string="$1" start="${2:-0}" len="${3:-0}"
	echo "$string" | awk "{ print substr(\$0, $start, $len) }"
}

# f_snprintf $var_to_set $size $format [$arguments ...]
#
# Similar to snprintf(3), write at most $size number of bytes into $var_to_set
# using printf(1) syntax (`$format [$arguments ...]'). The value of $var_to_set
# is NULL unless at-least one byte is stored from the output.
#
f_snprintf()
{
	local __var_to_set="$1" __size="$2"
	shift 2 # var_to_set size
	eval "$__var_to_set"=\$\( printf -- \"\$@\" \| \
		awk -v max=\"\$__size\" \''
	{
		len = length($0)
		max -= len
		print substr($0,0,(max > 0 ? len : max + len))
		if ( max < 0 ) exit
		max--
	}'\' \)
}

# f_sprintf $var_to_set $format [$arguments ...]
#
# Similar to sprintf(3), write a string into $var_to_set using printf(1) syntax
# (`$format [$arguments ...]').
#
f_sprintf()
{
	local __var_to_set="$1"
	shift 1 # var_to_set
	eval "$__var_to_set"=\$\( printf -- \"\$@\" \)
}

# f_vsnprintf $var_to_set $size $format $format_args
#
# Similar to vsnprintf(3), write at most $size number of bytes into $var_to_set
# using printf(1) syntax (`$format $format_args'). The value of $var_to_set is
# NULL unless at-least one byte is stored from the output.
#
# Example 1:
#
# 	limit=7 format="%s"
# 	format_args="'abc   123'" # 3-spaces between abc and 123
# 	f_vsnprintf foo $limit "$format" "$format_args" # foo=[abc   1]
#
# Example 2:
#
# 	limit=12 format="%s %s"
# 	format_args="   'doghouse'      'fox'   "
# 		# even more spaces added to illustrate escape-method
# 	f_vsnprintf foo $limit "$format" "$format_args" # foo=[doghouse fox]
#
# Example 3:
#
# 	limit=13 format="%s %s"
# 	f_shell_escape arg1 'aaa"aaa' # arg1=[aaa"aaa] (no change)
# 	f_shell_escape arg2 "aaa'aaa" # arg2=[aaa'\''aaa] (escaped s-quote)
# 	format_args="'$arg1' '$arg2'" # use single-quotes to surround args
# 	f_vsnprintf foo $limit "$format" "$format_args" # foo=[aaa"aaa aaa'a]
#
# In all of the above examples, the call to f_vsnprintf() does not change. Only
# the contents of $limit, $format, and $format_args changes in each example.
#
f_vsnprintf()
{
	eval f_snprintf \"\$1\" \"\$2\" \"\$3\" $4
}

# f_vsprintf $var_to_set $format $format_args
#
# Similar to vsprintf(3), write a string into $var_to_set using printf(1)
# syntax (`$format $format_args').
#
f_vsprintf()
{
	eval f_sprintf \"\$1\" \"\$2\" $3
}

# f_longest_line_length
#
# Simple wrapper to an awk(1) script to print the length of the longest line of
# input (read from stdin). Supports the newline escape-sequence `\n' for
# splitting a single line into multiple lines.
#
f_longest_line_length_awk='
BEGIN { longest = 0 }
{
	if (split($0, lines, /\\n/) > 1)
	{
		for (n in lines)
		{
			len = length(lines[n])
			longest = ( len > longest ? len : longest )
		}
	}
	else
	{
		len = length($0)
		longest = ( len > longest ? len : longest )
	}
}
END { print longest }
'
f_longest_line_length()
{
	awk "$f_longest_line_length_awk"
}

# f_number_of_lines
#
# Simple wrapper to an awk(1) script to print the number of lines read from
# stdin. Supports newline escape-sequence `\n' for splitting a single line into
# multiple lines.
#
f_number_of_lines_awk='
BEGIN { num_lines = 0 }
{
	num_lines += split(" "$0, unused, /\\n/)
}
END { print num_lines }
'
f_number_of_lines()
{
	awk "$f_number_of_lines_awk"
}

# f_isinteger $arg
#
# Returns true if argument is a positive/negative whole integer.
#
f_isinteger()
{
	local arg="${1#-}"
	[ "${arg:-x}" = "${arg%[!0-9]*}" ]
}

# f_uriencode [$text]
#
# Encode $text for the purpose of embedding safely into a URL. Non-alphanumeric
# characters are converted to `%XX' sequence where XX represents the hexa-
# decimal ordinal of the non-alphanumeric character. If $text is missing, data
# is instead read from standard input.
#
f_uriencode_awk='
BEGIN {
	output = ""
	for (n = 0; n < 256; n++) pack[sprintf("%c", n)] = sprintf("%%%02x", n)
}
{
	sline = ""
	slen = length($0)
	for (n = 1; n <= slen; n++) {
		char = substr($0, n, 1)
		if ( char !~ /^[[:alnum:]_]$/ ) char = pack[char]
		sline = sline char
	}
	output = output ( output ? "%0a" : "" ) sline
}
END { print output }
'
f_uriencode()
{
	if [ $# -gt 0 ]; then
		echo "$1" | awk "$f_uriencode_awk"
	else
		awk "$f_uriencode_awk"
	fi
}

# f_uridecode [$text]
#
# Decode $text from a URI. Encoded characters are converted from their `%XX'
# sequence into original unencoded ASCII sequences. If $text is missing, data
# is instead read from standard input.
#
f_uridecode_awk='
BEGIN { for (n = 0; n < 256; n++) chr[n] = sprintf("%c", n) }
{
	sline = ""
	slen = length($0)
	for (n = 1; n <= slen; n++)
	{
		seq = substr($0, n, 3)
		if ( seq ~ /^%[[:xdigit:]][[:xdigit:]]$/ ) {
			hex = substr(seq, 2, 2)
			sline = sline chr[sprintf("%u", "0x"hex)]
			n += 2
		} else
			sline = sline substr(seq, 1, 1)
	}
	print sline
}
'
f_uridecode()
{
	if [ $# -gt 0 ]; then
		echo "$1" | awk "$f_uridecode_awk"
	else
		awk "$f_uridecode_awk"
	fi
}

# f_replaceall $string $find $replace [$var_to_set]
#
# Replace all occurrences of $find in $string with $replace. If $var_to_set is
# either missing or NULL, the variable name is produced on standard out for
# capturing in a sub-shell (which is less recommended due to performance
# degradation).
#
# To replace newlines or a sequence containing the newline character, use $NL
# as `\n' is not supported.
#
f_replaceall()
{
	local __left="" __right="$1"
	local __find="$2" __replace="$3" __var_to_set="$4"
	while :; do
		case "$__right" in *$__find*)
			__left="$__left${__right%%$__find*}$__replace"
			__right="${__right#*$__find}"
			continue
		esac
		break
	done
	__left="$__left${__right#*$__find}"
	if [ "$__var_to_set" ]; then
		setvar "$__var_to_set" "$__left"
	else
		echo "$__left"
	fi
}

# f_str2varname $string [$var_to_set]
#
# Convert a string into a suitable value to be used as a variable name
# by converting unsuitable characters into the underscrore [_]. If $var_to_set
# is either missing or NULL, the variable name is produced on standard out for
# capturing in a sub-shell (which is less recommended due to performance
# degradation).
#
f_str2varname()
{
	local __string="$1" __var_to_set="$2"
	f_replaceall "$__string" "[!$VALID_VARNAME_CHARS]" "_" "$__var_to_set"
}

# f_shell_escape $string [$var_to_set]
#
# Escape $string for shell eval statement(s) by replacing all single-quotes
# with a special sequence that creates a compound string when interpolated
# by eval with surrounding single-quotes.
#
# For example:
#
# 	foo="abc'123"
# 	f_shell_escape "$foo" bar # bar=[abc'\''123]
# 	eval echo \'$bar\' # produces abc'123
#
# This is helpful when processing an argument list that has to retain its
# escaped structure for later evaluations.
#
# WARNING: Surrounding single-quotes are not added; this is the responsibility
# of the code passing the escaped values to eval (which also aids readability).
#
f_shell_escape()
{
	local __string="$1" __var_to_set="$2"
	f_replaceall "$__string" "'" "'\\''" "$__var_to_set"
}

# f_shell_unescape $string [$var_to_set]
#
# The antithesis of f_shell_escape(), this function takes an escaped $string
# and expands it.
#
# For example:
#
# 	foo="abc'123"
# 	f_shell_escape "$foo" bar # bar=[abc'\''123]
# 	f_shell_unescape "$bar" # produces abc'123
#
f_shell_unescape()
{
	local __string="$1" __var_to_set="$2"
	f_replaceall "$__string" "'\\''" "'" "$__var_to_set"
}

# f_expand_number $string [$var_to_set]
#
# Unformat $string into a number, optionally to be stored in $var_to_set. This
# function follows the SI power of two convention.
#
# The prefixes are:
#
# 	Prefix	Description	Multiplier
# 	k	kilo		1024
# 	M	mega		1048576
# 	G	giga		1073741824
# 	T	tera		1099511627776
# 	P	peta		1125899906842624
# 	E	exa		1152921504606846976
#
# NOTE: Prefixes are case-insensitive.
#
# Upon successful completion, success status is returned; otherwise the number
# -1 is produced ($var_to_set set to -1 or if $var_to_set is NULL or missing)
# on standard output. In the case of failure, the error status will be one of:
#
# 	Status	Reason
# 	1	Given $string contains no digits
# 	2	An unrecognized prefix was given
# 	3	Result too large to calculate
#
f_expand_number()
{
	local __string="$1" __var_to_set="$2"
	local __cp __num __bshift __maxinput

	# Remove any leading non-digits
	__string="${__string#${__string%%[0-9]*}}"

	# Store the numbers (no trailing suffix)
	__num="${__string%%[!0-9]*}"

	# Produce `-1' if string didn't contain any digits
	if [ ! "$__num" ]; then
		if [ "$__var_to_set" ]; then
			setvar "$__var_to_set" -1
		else
			echo -1
		fi
		return 1 # 1 = "Given $string contains no digits"
	fi

	# Remove all the leading numbers from the string to get at the prefix
	__string="${__string#"$__num"}"

	#
	# Test for invalid prefix (and determine bitshift length)
	#
	case "$__string" in
	""|[[:space:]]*) # Shortcut
		if [ "$__var_to_set" ]; then
			setvar "$__var_to_set" $__num
		else
			echo $__num
		fi
		return $SUCCESS ;;
	[Kk]*) __bshift=10 ;;
	[Mm]*) __bshift=20 ;;
	[Gg]*) __bshift=30 ;;
	[Tt]*) __bshift=40 ;;
	[Pp]*) __bshift=50 ;;
	[Ee]*) __bshift=60 ;;
	*)
		# Unknown prefix
		if [ "$__var_to_set" ]; then
			setvar "$__var_to_set" -1
		else
			echo -1
		fi
		return 2 # 2 = "An unrecognized prefix was given"
	esac

	# Determine if the wheels fall off
	__maxinput=$(( 0x7fffffffffffffff >> $__bshift ))
	if [ $__num -gt $__maxinput ]; then
		# Input (before expanding) would exceed 64-bit signed int
		if [ "$__var_to_set" ]; then
			setvar "$__var_to_set" -1
		else
			echo -1
		fi
		return 3 # 3 = "Result too large to calculate"
	fi

	# Shift the number out and produce it
	__num=$(( $__num << $__bshift ))
	if [ "$__var_to_set" ]; then
		setvar "$__var_to_set" $__num
	else
		echo $__num
	fi
}

############################################################ MAIN

f_dprintf "%s: Successfully loaded." strings.subr

fi # ! $_STRINGS_SUBR
OpenPOWER on IntegriCloud