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 # ksh, not portable
23 setopt -o OCTAL_ZEROES 2>&-
25 if [ "$REQUEST_METHOD" = POST -a "${HTTP_CONTENT_LENGTH:=${CONTENT_LENGTH:=0}}" -gt 0 ]; then
26 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"'=[^&]*' \
42 GET) printf %s "${QUERY_STRING}";;
43 POST) printf %s "?${cgilite_post}";;
44 REF) printf %s "?${HTTP_REFERER#*\?}";;
46 | grep -Eo '[&?]'"$2"'=[^&]*' \
47 | sed -rn "${3:-1}"'{s;^[^=]+=;;; s;\+; ;g; s;\\;\\\\;g; s;%;\\x;g; p}'
51 GET(){ cgilite_value GET $@; }
52 GET_COUNT(){ cgilite_count GET $1; }
54 POST(){ cgilite_value POST $@; }
55 POST_COUNT(){ cgilite_count POST $1; }
57 REF(){ cgilite_value REF $@; }
58 REF_COUNT(){ cgilite_count REF $1; }
62 printf %s " ${HTTP_COOKIE}" \
63 | grep -Eo '[; ]'"$1"'=[^;]*' \
64 | sed -rn "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; s;\\;\\\\;g; s;%;\\x;g; p}'
70 # Prints UTF-8 string as decimal Unicode Code Points
71 # Useful for escaping user input for use in HTML text and attributes
73 | hexdump -ve '/1 "%03o\n"' \
76 [01]??) printf '0000%s' $n;;
77 2??) printf '%s' ${n#2};;
78 3[0123]?) printf '000%s' ${n#3};;
79 34?) printf '00%s' ${n#34};;
80 35?) printf '01%s' ${n#35};;
81 36?) printf '%s' ${n#36};;
84 | sed -r 's;.{7};&\n;g;' \
86 printf '&#%d;' $((0$n))
91 # Code every character in URL escape hex format
92 # except alphanumeric ascii
95 | hexdump -v -e '/1 ",%02X"' \
101 ''|0|session) expire='';;
102 [+-][0-9]*) expire="$(date -R -d @$(($(date +%s) + $1)))";;
103 *) expire="$(date -R -d "$1")";;
107 printf 'Set-Cookie: %s' "$cookie"
108 [ -n "$expire" ] && printf '; Expires=%s' "$expire"
109 [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
114 printf 'Location: %s\r\n\r\n' "$*"