3 # Copyright 2017 Paul Hänsch
6 # A collection of posix shell functions for writing CGI scripts.
8 # CGIlite is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # CGIlite is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Affero General Public License for more details.
18 # You should have received a copy of the GNU Affero General Public License
19 # along with CGIlite. If not, see <http://www.gnu.org/licenses/>.
21 # ksh and zsh workaround
22 set -o posix -o OCTAL_ZEROES 2>&-
24 if [ "$REQUEST_METHOD" = POST -a "${HTTP_CONTENT_LENGTH:=${CONTENT_LENGTH:=0}}" -gt 0 ]; then
25 cgilite_post="$(head -c "$HTTP_CONTENT_LENGTH")"
31 GET) printf %s "${QUERY_STRING}";;
32 POST) printf %s "?${cgilite_post}";;
33 REF) printf %s "?${HTTP_REFERER#*\?}";;
35 | grep -Eo '[&?]'"$2"'=[^&]*' \
43 GET) printf %s "${QUERY_STRING}";;
44 POST) printf %s "?${cgilite_post}";;
45 REF) printf %s "?${HTTP_REFERER#*\?}";;
47 | grep -Eo '[&?]'"$2"'=[^&]*' \
48 | sed -rn "${3:-1}"'{s;^[^=]+=;;; s;\+; ;g; s;\\;\\\\;g; s;%;\\x;g; p}'
75 printf %s " ${HTTP_COOKIE}" \
76 | grep -Eo '[; ]'"$1"'=[^;]*' \
77 | sed -rn "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; s;\\;\\\\;g; s;%;\\x;g; p}'
83 # Prints UTF-8 string as decimal Unicode Code Points
84 # Useful for escaping user input for use in HTML text and attributes
86 | hexdump -ve '/1 "%03o\n"' \
89 [01]??) printf '0000%s' $n;;
90 2??) printf '%s' ${n#2};;
91 3[0123]?) printf '000%s' ${n#3};;
92 34?) printf '00%s' ${n#34};;
93 35?) printf '01%s' ${n#35};;
94 36?) printf '%s' ${n#36};;
97 | sed -r 's;.{7};&\n;g;' \
99 printf '&#%d;' $((0$n))
104 # Code every character in URL escape hex format
105 # except alphanumeric ascii
108 | hexdump -v -e '/1 ",%02X"' \
113 printf '%s\r\n\r\n' "Location: $(urlsafe $*)"
119 session|0) expire='';;
120 ''|default) expire="$(LANG=C date -d "+ 1 week" +'%a, %d %b %Y %T %Z')";;
121 *) expire="$(LANG=C date -d "$1" +'%a, %d %b %Y %T %Z' 2>&-)";;
125 printf 'Set-Cookie: %s' "$cookie"
126 [ -n "$expire" ] && printf '; Expires=%s' "$expire"
127 [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"