]> git.plutz.net Git - cgilite/blob - cgilite.sh
much faster hex decode function
[cgilite] / cgilite.sh
1 #!/bin/sh
2
3 # Copyright 2017 - 2021 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 [ -n "$include_cgilite" ] && return 0
22 # guard set after webserver part
23
24 # ksh and zsh workaround
25 # set -o posix # ksh, not portable
26 setopt -o OCTAL_ZEROES 2>&-
27
28 CR="\r"
29 BR='
30 '
31 cgilite_timeout=2
32
33 PATH(){ 
34   local str seg out
35   # normalize path
36   # read from stdin if no arguments are provided
37
38   [ $# -eq 0 ] && str="$(cat)" || str="$*"
39   while [ "$str" ]; do
40     seg=${str%%/*}; str="${str#*/}"
41     case $seg in
42       ..) out="${out%/}"; out="${out%/*}/";;
43     .|'') out="${out%/}/";;
44        *) out="${out%/}/${seg}";;
45     esac;
46     [ "$seg" = "$str" ] && break
47   done
48   [ "${str}" -a "${out}" ] && printf %s "$out" || printf %s/ "${out%/}"
49 }
50
51 HEX_DECODE(){
52   local pfx="$1" in="$2" out
53   # Print out Data encoded as Hex
54   #
55   # Arguments:
56   # pfx - required, prefix for a hex tupel, e.g. "\x", "%" "\", may be empty
57   # in - required, string to be decoded
58   #
59   # anything that does not constitute a tupel of valid Hex numerals
60   # will be copied to the output literally
61
62   while [ "$in" ]; do
63     case $in in
64       "$pfx"[0-9a-fA-F][0-9a-fA-F]*) in="${in#${pfx}}";;
65       \\*) in="${in#?}"; out="${out}\\\\"; continue;;
66        %*) in="${in#?}"; out="${out}%%";  continue;;
67         *) out="${out}${in%"${in#?}"}"; in="${in#?}"; continue;;
68     esac;
69
70     # Hex escaes for printf (e.g. \x41) are not portable 
71     # The portable way for Hex output is transforming Hex to Octal
72     # (e.g. \x41 = \101)
73     case $in in
74         [0123]?*) out="${out}\\0";;
75         [4567]?*) out="${out}\\1";;
76       [89aAbB]?*) out="${out}\\2";;
77       [c-fC-F]?*) out="${out}\\3";;
78     esac
79     case $in in
80             [048cC][0-7]*) out="${out}0";;
81        [048cC][89a-fA-F]*) out="${out}1";;
82             [159dD][0-7]*) out="${out}2";;
83        [159dD][89a-fA-F]*) out="${out}3";;
84            [26aAeE][0-7]*) out="${out}4";;
85       [26aAeE][89a-fA-F]*) out="${out}5";;
86            [37bBfF][0-7]*) out="${out}6";;
87       [37bBfF][89a-fA-F]*) out="${out}7";;
88     esac
89     case $in in
90        ?[08]*) out="${out}0";;
91        ?[19]*) out="${out}1";;
92       ?[2aA]*) out="${out}2";;
93       ?[3bB]*) out="${out}3";;
94       ?[4cC]*) out="${out}4";;
95       ?[5dD]*) out="${out}5";;
96       ?[6eE]*) out="${out}6";;
97       ?[7fF]*) out="${out}7";;
98     esac
99     in="${in#?}"
100     in="${in#?}"
101   done
102   printf -- "$out"
103 }
104
105 if [ -z "$REQUEST_METHOD" ]; then
106   # no webserver variables means we are running via inetd / ncat
107   # so use builtin web server
108
109   # Use env from inetd as webserver variables
110   REMOTE_ADDR="${TCPREMOTEIP}"
111   SERVER_NAME="${TCPLOCALIP}"
112   SERVER_PORT="${TCPLOCALPORT}"
113
114   # Wait 2 seconds for request or kill connection through watchdog.
115   # Once Request is received the watchdog will be suspended (killed).
116   # At the end of the loop the watchdog will be restarted to enable
117   # timeout for the subsequent request.
118
119   (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
120   while read REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL; do
121     [ "${SERVER_PROTOCOL#HTTP/1.[01]${CR}}" ] && break
122     kill $cgilite_watchdog
123
124     SERVER_PROTOCOL="${SERVER_PROTOCOL%${CR}}"
125     PATH_INFO="$(HEX_DECODE % "${REQUEST_URI%\?*}" |PATH)"
126     [ "${REQUEST_URI}" = "${REQUEST_URI#*\?}" ] \
127     && QUERY_STRING='' \
128     || QUERY_STRING="${REQUEST_URI#*\?}"
129     cgilite_headers=''; while read -r hl; do
130       hl="${hl%${CR}}"; [ "$hl" ] || break
131       case $hl in
132         'Content-Length: '*) CONTENT_LENGTH="${hl#*: }";;
133           'Content-Type: '*)   CONTENT_TYPE="${hl#*: }";;
134       esac
135       cgilite_headers="${cgilite_headers}${hl}${BR}"
136     done
137
138     export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
139            PATH_INFO QUERY_STRING CONTENT_TYPE CONTENT_LENGTH
140
141     # Try to serve multiple requests, provided that script serves a
142     # Content-Length header.
143     # Without Content-Length header, connection will terminate after
144     # script.
145
146     cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}${BR}";
147     . "$0" | while read -r l; do case $l in
148       Status:*)
149         cgilite_status="${l#Status: }";;
150       Content-Length:*)
151         cgilite_cl=""
152         cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
153       Connection:*)
154         cgilite_cl="${l}${BR}";;
155       $CR) printf '%s %s\r\n%s%s\r\n' \
156              'HTTP/1.1' "${cgilite_status%${CR}}" \
157              "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
158            cat || kill $$
159            [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
160       *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
161     esac; done || exit 0;
162     (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
163   done
164   kill $cgilite_watchdog
165   exit 0
166 fi
167
168 include_cgilite="$0"
169
170 if [ "${REQUEST_METHOD}" = POST -a "${CONTENT_LENGTH:-0}" -gt 0 -a \
171      "${CONTENT_TYPE}" = "application/x-www-form-urlencoded" ]; then
172   cgilite_post="$(head -c "$CONTENT_LENGTH")"
173 fi
174
175 debug(){ [ $# -gt 0 ] && printf '%s\n' "$@" >&2 || tee -a /dev/stderr; }
176 [ "${DEBUG+x}" ] && env >&2
177
178 cgilite_count(){
179   printf %s "&$1" \
180   | grep -oE '&'"$2"'=[^&]*' \
181   | wc -l
182 }
183
184 cgilite_value(){
185   local str="&$1" name="$2" cnt="${3:-1}"
186   while [ $cnt -gt 0 ]; do
187     [ "${str}" = "${str#*&${name}=}" ] && return 1
188     str="${str#*&${name}=}"
189     cnt=$((cnt - 1))
190   done
191   HEX_DECODE % "$(printf %s "${str%%&*}" |tr + \  )"
192 }
193
194 cgilite_keys(){
195   local str="&$1"
196   while [ "${str#*&}" != "${str}" ]; do
197     str="${str#*&}"
198     printf '%s\n' "${str%%=*}"
199   done \
200   | sort -u
201 }
202
203 GET(){ cgilite_value "${QUERY_STRING}" "$@"; }
204 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
205 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
206
207 POST(){ cgilite_value "${cgilite_post}" "$@"; }
208 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
209 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
210
211 REF(){ cgilite_value "${HTTP_REFERER#*\?}" "$@"; }
212 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
213 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
214
215 HEADER(){
216   # Read value of header line. Use this instead of
217   # referencing HTTP_* environment variables.
218   if [ -n "${cgilite_headers+x}" ]; then
219     local str="${BR}${cgilite_headers}"
220     [ "${str}" = "${str#*${BR}${1}: }" ] && return 1
221     str="${str#*${BR}${1}: }"
222     printf %s "${str%%${BR}*}"
223   else
224     local var="HTTP_$(printf %s "$1" |tr a-z- A-Z-)"
225     eval "[ \"\$$var\" ] && printf %s \"\$$var\" || return 1"
226     # eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
227   fi
228 }
229
230 COOKIE(){
231   HEX_DECODE % "$(
232     HEADER Cookie \
233     | grep -oE '(^|; ?)'"$1"'=[^;]*' \
234     | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
235   )"
236 }
237
238 HTML(){
239   # Escape HTML cahracters
240   # Also escape [, ], and \n for use in html-sh
241   local str out
242   [ $# -eq 0 ] && str="$(cat)" || str="$*"
243   while [ "$str" ]; do
244     case $str in
245       \&*) out="${out}&amp;";;
246       \<*) out="${out}&lt;";;
247       \>*) out="${out}&gt;";;
248       \"*) out="${out}&quot;";;
249       \'*) out="${out}&#x27;";;
250       \[*) out="${out}&#x5B;";;
251       \]*) out="${out}&#x5D;";;
252       "${CR}"*) out="${out}&#x0D;";;
253       "${BR}"*) out="${out}&#x0A;";;
254       *) out="${out}${str%"${str#?}"}";;
255     esac
256     str="${str#?}"
257   done
258   printf %s "$out"
259 }
260
261 URL(){
262   # Escape pathes, so they can be used in link tags and HTTP Headers
263   local str out
264   [ $# -eq 0 ] && str="$(cat)" || str="$*"
265   while [ "$str" ]; do
266     case $str in
267       \&*) out="${out}%26";;
268       \"*) out="${out}%22";;
269       \'*) out="${out}%27";;
270       \?*) out="${out}%3F";;
271       \#*) out="${out}%23";;
272       \[*) out="${out}%5B";;
273       \]*) out="${out}%5D";;
274       \ *) out="${out}%20";;
275       " "*) out="${out}%09";;
276       "${CR}"*) out="${out}%0D";;
277       "${BR}"*) out="${out}%0A";;
278       %*) out="${out}%25";;
279       *) out="${out}${str%"${str#?}"}";;
280     esac
281     str="${str#?}"
282   done
283   printf %s "$out"
284 }
285
286 SET_COOKIE(){
287   # Param: session | +seconds | [date]
288   # Param: name=value
289   # Param: Path= | Domain= | Secure
290   local expire cookie
291   case "$1" in
292     ''|0|session) expire='';;
293     [+-][0-9]*)   expire="$(date -R -d @$(($(date +%s) + $1)))";;
294     *)            expire="$(date -R -d "$1")";;
295   esac
296   cookie="$2"
297
298   printf 'Set-Cookie: %s; HttpOnly; SameSite=Lax' "$cookie"
299   [ -n "$expire" ] && printf '; Expires=%s' "${expire%+????}${expire:+GMT}"
300   [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
301   printf '\r\n'
302 }
303
304 REDIRECT(){
305   printf '%s: %s\r\n' \
306     Status "303 See Other" \
307     Content-Length 0 \
308     Location "$*"
309   printf '\r\n'
310   exit 0
311 }