From e0391d7cbb1afc3163d50424a2a5fe2d17fb3af5 Mon Sep 17 00:00:00 2001 From: Tom Scavo Date: Sat, 10 Dec 2016 09:43:41 -0500 Subject: [PATCH] Commit initial versions of percent_encode and percent_decode --- lib/http_tools.sh | 57 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/lib/http_tools.sh b/lib/http_tools.sh index 88afc0b..04fed79 100755 --- a/lib/http_tools.sh +++ b/lib/http_tools.sh @@ -490,6 +490,63 @@ get_header_value () { return 0 } +####################################################################### +# This function percent-encodes all characters except the "Unreserved +# Characters" defined in section 2.3 of RFC 3986. +# +# See: https://gist.github.com/cdown/1163649 +# https://en.wikipedia.org/wiki/Percent-encoding +####################################################################### +percent_encode () { + # percent_encode + + # make sure there is one (and only one) command-line argument + if [ $# -ne 1 ]; then + echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (1 required)" >&2 + return 2 + fi + + # this implementation assumes a particular collating sequence + local LC_COLLATE=C + + local length + local c + + length="${#1}" + for (( i = 0; i < length; i++ )); do + c="${1:i:1}" + case "$c" in + [a-zA-Z0-9.~_-]) printf "$c" ;; + *) printf '%%%02X' "'$c" + esac + done +} + +####################################################################### +# This function percent-decodes all percent-encoded characters. +####################################################################### +percent_decode () { + # percent_decode + + # make sure there is one (and only one) command-line argument + if [ $# -ne 1 ]; then + echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (1 required)" >&2 + return 2 + fi + + local encoded_string + + # the percent_encode function doesn't convert spaces to + # plus signs (+) but the input string to the percent_decode + # function may have been encoded in some other manner so we + # first decode plus signs (+) into spaces + encoded_string="${1//+/ }" + + printf '%b' "${encoded_string//%/\\x}" +} + +# DEPRECATED: Use percent_encode and percent_decode instead. +# # URL encoder/decoder # see: https://gist.github.com/cdown/1163649 url_encode () {