]> git.plutz.net Git - cgilite/blob - cgilite.sh
1d8d30a5af91eff5d65fb6bc60e116525a837708
[cgilite] / cgilite.sh
1 #!/bin/sh
2
3 # Copyright 2017 - 2020 Paul Hänsch
4 #
5 # This is CGIlite.
6 # A collection of posix shell functions for writing CGI scripts.
7
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.
12
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.
17
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/>. 
20
21 # ksh and zsh workaround
22 # set -o posix # ksh, not portable
23 setopt -o OCTAL_ZEROES 2>&-
24
25 CR="\r"
26 BR='
27 '
28 cgilite_timeout=2
29
30 HEADER(){
31   # Read value of header line. Use this instead of
32   # referencing HTTP_* environment variables.
33   if [ -n "${cgilite_headers+x}" ]; then
34     local h="${BR}${cgilite_headers}"
35     [ "${h##*${BR}${1}: }" = "${h}" ] && return 1
36     h="${h##*${BR}${1}: }" h="${h%%${BR}*}"
37     printf %s "${h%${CR}}"
38   else
39     eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
40   fi
41 }
42
43 HEX_DECODE='
44   s;\\;\\\\;g; :HEXDECODE_X; s;%([^0-9A-F]);\\045\1;g; tHEXDECODE_X;
45   # Hexadecimal { %00 - %FF } will be transformed to octal { \000 - \377 } for posix printf
46   s;%[0123].;&\\0;g; s;%[4567].;&\\1;g; s;%[89AB].;&\\2;g; s;%[CDEF].;&\\3;g;
47   s;%[048C][0-7]\\.;&0;g; s;%[048C][89A-F]\\.;&1;g; s;%[159D][0-7]\\.;&2;g; s;%[159D][89A-F]\\.;&3;g;
48   s;%[26AE][0-7]\\.;&4;g; s;%[26AE][89A-F]\\.;&5;g; s;%[37BF][0-7]\\.;&6;g; s;%[37BF][89A-F]\\.;&7;g;
49   s;%.[08](\\..);\10;g; s;%.[19](\\..);\11;g; s;%.[2A](\\..);\12;g; s;%.[3B](\\..);\13;g;
50   s;%.[4C](\\..);\14;g; s;%.[5D](\\..);\15;g; s;%.[6E](\\..);\16;g; s;%.[7F](\\..);\17;g;
51 '
52
53 HEX_DECODE(){
54   printf -- "$(printf %s "$1" |sed -E "$HEX_DECODE")"
55 }
56
57 if [ -z "$REQUEST_METHOD" ]; then
58   # no webserver variables means we are running via inetd / ncat
59   # so use builtin web server
60
61   # Use env from inetd as webserver variables
62   REMOTE_ADDR="${TCPREMOTEIP}"
63   SERVER_NAME="${TCPLOCALIP}"
64   SERVER_PORT="${TCPLOCALPORT}"
65
66   # Wait 2 seconds for request or kill connection through watchdog.
67   # Once Request is received the watchdog will be suspended (killed).
68   # At the end of the loop the watchdog will be restarted to enable
69   # timeout for the subsequent request.
70
71   (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
72   while read REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL; do
73     kill $cgilite_watchdog
74     PATH_INFO="$(HEX_DECODE "${REQUEST_URI%\?*}")"
75     QUERY_STRING="${REQUEST_URI#*\?}"
76     cgilite_headers=''; while read -r hl; do
77       [ "${hl%${CR}}" ] || break
78       cgilite_headers="${cgilite_headers}${hl}${BR}"
79     done
80
81     HTTP_CONTENT_LENGTH="$(HEADER Content-Length)"
82     HTTP_CONTENT_LENGTH="${HTTP_CONTENT_LENGTH##*[^0-9]}"
83
84     export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
85            PATH_INFO QUERY_STRING HTTP_CONTENT_LENGTH
86
87     # Try to serve multiple requests, provided that script serves a
88     # Content-Length header.
89     # Without Content-Length header, connection will terminate after
90     # script.
91
92     cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}";
93     . "$0" | while read -r l; do case $l in
94       Status:*) cgilite_status="${l#Status: }";;
95       Content-Length:*) cgilite_cl="${l}";;
96       $CR) printf '%s %s\r\n%s%s\n\r\n' \
97              'HTTP/1.1' "${cgilite_status%${CR}}" \
98              "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
99            cat || kill $$
100            [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
101       *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
102     esac; done || exit 0;
103     (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
104   done
105   kill $cgilite_watchdog
106   exit 0
107 fi
108
109 if [ "$REQUEST_METHOD" = POST -a "${HTTP_CONTENT_LENGTH:=${CONTENT_LENGTH:=0}}" -gt 0 ]; then
110   cgilite_post="$(head -c "$HTTP_CONTENT_LENGTH")"
111 fi
112
113 [ -n "${DEBUG+x}" ] && env
114
115 cgilite_count(){
116   printf %s "&$1" \
117   | grep -oE '&'"$2"'=[^&]*' \
118   | wc -l
119 }
120
121 cgilite_value(){
122   local str="&$1" name="$2" cnt="${3:-1}"
123   while [ $cnt -gt 0 ]; do
124     str=${str#*&${name}=}
125     cnt=$((cnt - 1))
126   done
127   printf -- "$(printf %s "${str%%&*}" |sed -E 's;\+; ;g;'"$HEX_DECODE")"
128 }
129
130 cgilite_keys(){
131   local str="&$1"
132   while [ "${str#*&}" != "${str}" ]; do
133     str="${str#*&}"
134     printf '%s\n' "${str%%=*}"
135   done \
136   | sort -u
137 }
138
139 GET(){ cgilite_value "${QUERY_STRING}" $@; }
140 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
141 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
142
143 POST(){ cgilite_value "${cgilite_post}" $@; }
144 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
145 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
146
147 REF(){ cgilite_value "${HTTP_REFERER#*\?}" $@; }
148 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
149 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
150
151 COOKIE(){
152   HEX_DECODE "$(
153     HEADER Cookie \
154     | grep -oE '(^|; ?)'"$1"'=[^;]*' \
155     | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
156   )"
157 }
158
159 HTML(){
160   # HTML Entity Coding
161   # Prints UTF-8 string as decimal Unicode Code Points
162   # Useful for escaping user input for use in HTML text and attributes
163   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
164   | hexdump -ve '/1 "%03o\n"' \
165   | while read n; do
166     case $n in
167       # bitbanging octal UTF-8 chains into singular 7 digit octal numbers
168       [01]??) printf '0000%s' $n;; # 7 bit ASCII character, nothing to do
169       2??)    printf '%s' ${n#2};; # tail fragment, append 6 bit
170       3[0123]?) printf '000%s' ${n#3};; # 2 octet (11 bit) chain start
171       34?) printf '00%s' ${n#34};; # 3 octet (16 bit) chain start
172       35?) printf '01%s' ${n#35};; # 3 octet chain start, high
173       36?) printf '%s' ${n#36};;   # 4 octet (21 bit) chain start
174     esac
175   done \
176   | sed -E 's;.{7};&\n;g;' \
177   | while read n; do
178     printf '&#%d;' $((0$n))
179   done
180 }
181
182 URL(){
183   # Code every character in URL escape hex format
184   # except alphanumeric ascii
185
186   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
187   | hexdump -v -e '/1 ",%02X"' \
188   | sed 's;,;%;g; s;%2F;/;g;'
189 }
190
191 PATH(){
192   { [ $# -eq 0 ] && cat || printf %s "$*"; } \
193   | sed -E 's;^.*$;/&/;; s;/+;/;g;
194             :X;
195             s;^/\.\./;/;; s;/\./;/;g;
196             tX;
197             s;/[^/]+/\.\./;/;;
198             tX;
199             s;^(/.*)/$;\1;'
200 }
201
202
203 SET_COOKIE(){
204   local expire cookie
205   case "$1" in
206     ''|0|session) expire='';;
207     [+-][0-9]*)   expire="$(date -R -d @$(($(date +%s) + $1)))";;
208     *)            expire="$(date -R -d "$1")";;
209   esac
210   cookie="$2"
211
212   printf 'Set-Cookie: %s' "$cookie"
213   [ -n "$expire" ] && printf '; Expires=%s' "${expire%+????}${expire:+GMT}"
214   [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
215   printf '\r\n'
216 }
217
218 REDIRECT(){
219   printf '%s: %s\r\n' \
220     Status "303 See Other" \
221     Content-Length 0 \
222     Location "$*"
223   printf '\r\n'
224   exit 0
225 }