]> git.plutz.net Git - confetti/blob - cgilite/cgilite.sh
styling for iban assignment
[confetti] / cgilite / cgilite.sh
1 #!/bin/sh
2
3 # This is CGIlite.
4 # A collection of posix shell functions for writing CGI scripts.
5
6 # Copyright 2017 - 2023 Paul Hänsch
7
8 # Permission to use, copy, modify, and/or distribute this software for any
9 # purpose with or without fee is hereby granted, provided that the above
10 # copyright notice and this permission notice appear in all copies.
11
12 # THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
15 # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
18 # IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20 [ -n "$include_cgilite" ] && return 0
21 # guard set after webserver part
22
23 # ksh and zsh workaround
24 # set -o posix # ksh, not portable
25 setopt -o OCTAL_ZEROES 2>&-
26
27 # Integrated webserver request timeout
28 cgilite_timeout=2
29
30 # General environment variables
31 # $_EXEC - directory containing application itself
32 # $_DATA - direcotry where application data may be stored
33 # $_BASE - optional prefix for http path, e.g. "/myapp"
34 #
35 # Programmers should take care to use those variables throughout the
36 # application.
37 # Variables may be set via CLI argument, in environment, or left as default.
38
39 for cgilite_arg in "$@"; do case $cgilite_arg in
40   --exec=*) _EXEC="${cgilite_arg#*=}";;
41   --data=*) _DATA="${cgilite_arg#*=}";;
42   --base=*) _BASE="${cgilite_arg#*=}";;
43 esac; done
44 unset cgilite_arg
45
46 _EXEC="${_EXEC:-${0%/*}}"
47 _DATA="${_DATA:-.}"
48 _EXEC="${_EXEC%/}" _DATA="${_DATA%/}" _BASE="${_BASE%/}"
49
50 export _EXEC _DATA _BASE
51
52 # Carriage Return and Line Break characters for convenience
53 CR="\r"
54 BR='
55 '
56
57 PATH(){ 
58   local str seg out
59   # normalize path
60   # read from stdin if no arguments are provided
61
62   [ $# -eq 0 ] && str="$(cat)" || str="$*"
63   while [ "$str" ]; do
64     seg=${str%%/*}; str="${str#*/}"
65     case $seg in
66       ..) out="${out%/}"; out="${out%/*}/";;
67     .|'') out="${out%/}/";;
68        *) out="${out%/}/${seg}";;
69     esac;
70     [ "$seg" = "$str" ] && break
71   done
72   [ "${str}" -a "${out}" ] && printf %s "$out" || printf %s/ "${out%/}"
73 }
74
75 HEX_DECODE(){
76   local pfx="$1" in="$2" out
77   # Print out Data encoded as Hex
78   #
79   # Arguments:
80   # pfx - required, prefix for a hex tupel, e.g. "\x", "%" "\", may be empty
81   # in - required, string to be decoded
82   #
83   # anything that does not constitute a tupel of valid Hex numerals
84   # will be copied to the output literally
85
86   while [ "$in" ]; do
87     [ "$pfx" ] || case $in in
88       [0-9a-fA-F][0-9a-fA-F]*):;;
89       ?*) out="${out}${in%%"${in#?}"}"
90           in="${in#?}"; continue;;
91     esac
92
93     case $in in
94       "$pfx"[0-9a-fA-F][0-9a-fA-F]*) in="${in#"${pfx}"}";;
95       \\*) in="${in#?}"; out="${out}\\\\"; continue;;
96        %*) in="${in#?}"; out="${out}%%";  continue;;
97         *) att="${in%%"${pfx}"*}"; att="${att%%%*}"; att="${att%%\\*}"
98            out="${out}${att}"; in="${in#"${att}"}"; continue;;
99     esac;
100
101     # Hex escapes for printf (e.g. \x41) are not portable 
102     # The portable way for Hex output is transforming Hex to Octal
103     # (e.g. \x41 = \101)
104     case $in in
105         [0123]?*) out="${out}\\0";;
106         [4567]?*) out="${out}\\1";;
107       [89aAbB]?*) out="${out}\\2";;
108       [c-fC-F]?*) out="${out}\\3";;
109     esac
110     case $in in
111             [048cC][0-7]*) out="${out}0";;
112        [048cC][89a-fA-F]*) out="${out}1";;
113             [159dD][0-7]*) out="${out}2";;
114        [159dD][89a-fA-F]*) out="${out}3";;
115            [26aAeE][0-7]*) out="${out}4";;
116       [26aAeE][89a-fA-F]*) out="${out}5";;
117            [37bBfF][0-7]*) out="${out}6";;
118       [37bBfF][89a-fA-F]*) out="${out}7";;
119     esac
120     case $in in
121        ?[08]*) out="${out}0";;
122        ?[19]*) out="${out}1";;
123       ?[2aA]*) out="${out}2";;
124       ?[3bB]*) out="${out}3";;
125       ?[4cC]*) out="${out}4";;
126       ?[5dD]*) out="${out}5";;
127       ?[6eE]*) out="${out}6";;
128       ?[7fF]*) out="${out}7";;
129     esac
130     in="${in#?}"
131     in="${in#?}"
132   done
133   printf -- "$out"
134 }
135
136 if [ -z "$REQUEST_METHOD" ]; then
137   # no webserver variables means we are running via inetd / ncat
138   # so use builtin web server
139
140   # Use env from inetd as webserver variables
141   REMOTE_ADDR="${TCPREMOTEIP}"
142   SERVER_NAME="${TCPLOCALIP}"
143   SERVER_PORT="${TCPLOCALPORT}"
144
145   # Wait 2 seconds for request or kill connection through watchdog.
146   # Once Request is received the watchdog will be suspended (killed).
147   # At the end of the loop the watchdog will be restarted to enable
148   # timeout for the subsequent request.
149
150   (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
151   while read REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL; do
152     unset PATH_INFO QUERY_STRING cgilite_headers CONTENT_LENGTH CONTENT_TYPE
153
154     [ "${SERVER_PROTOCOL#HTTP/1.[01]${CR}}" ] && break
155     kill $cgilite_watchdog
156
157     SERVER_PROTOCOL="${SERVER_PROTOCOL%${CR}}"
158     PATH_INFO="$(HEX_DECODE % "${REQUEST_URI%\?*}" |PATH)"
159     [ "${REQUEST_URI}" = "${REQUEST_URI#*\?}" ] \
160     && QUERY_STRING='' \
161     || QUERY_STRING="${REQUEST_URI#*\?}"
162     while read -r hl; do
163       hl="${hl%${CR}}"; [ "$hl" ] || break
164       case $hl in
165         'Content-Length: '*) CONTENT_LENGTH="${hl#*: }";;
166           'Content-Type: '*)   CONTENT_TYPE="${hl#*: }";;
167       esac
168       cgilite_headers="${cgilite_headers}${hl}${BR}"
169     done
170
171     export REMOTE_ADDR SERVER_NAME SERVER_PORT REQUEST_METHOD REQUEST_URI SERVER_PROTOCOL \
172            PATH_INFO QUERY_STRING CONTENT_TYPE CONTENT_LENGTH cgilite_headers
173
174     # Try to serve multiple requests, provided that script serves a
175     # Content-Length header.
176     # Without Content-Length header, connection will terminate after
177     # script.
178
179     cgilite_status='200 OK'; cgilite_response=''; cgilite_cl="Connection: close${CR}${BR}";
180     . "$0" | while read -r l; do case $l in
181       Status:*)
182         cgilite_status="${l#Status: }";;
183       Content-Length:*)
184         cgilite_cl=""
185         cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
186       Connection:*)
187         cgilite_cl="${l}${BR}";;
188       $CR) printf '%s %s\r\n%s%s\r\n' \
189              'HTTP/1.1' "${cgilite_status%${CR}}" \
190              "${cgilite_response}${cgilite_response:+${BR}}" "${cgilite_cl}"
191            cat || kill $$
192            [ "${cgilite_cl#Connection}" = "${cgilite_cl}" ]; exit;;
193       *) cgilite_response="${cgilite_response:+${cgilite_response}${BR}}${l}";;
194     esac; done || exit 0;
195     (sleep $cgilite_timeout && kill $$) & cgilite_watchdog=$!
196   done
197   kill $cgilite_watchdog
198   exit 0
199 fi
200
201 include_cgilite="$0"
202
203 if [ "${REQUEST_METHOD}" = POST -a "${CONTENT_LENGTH:-0}" -gt 0 -a \
204      "${CONTENT_TYPE}" = "application/x-www-form-urlencoded" ]; then
205   cgilite_post="$(head -c "$CONTENT_LENGTH")"
206 fi
207
208 PATH_INFO="$(PATH "/${PATH_INFO#${_BASE}}")"
209
210 debug(){ [ $# -gt 0 ] && printf '%s\n' "$@" >&2 || tee -a /dev/stderr; }
211 [ "${DEBUG+x}" ] && env >&2
212
213 # general helper functions, see GET, POST, and REF below
214
215 cgilite_count(){
216   printf %s "&$1" \
217   | grep -oE '&'"$2"'=[^&]*' \
218   | wc -l
219 }
220
221 cgilite_value(){
222   local str="&$1" name="$2" cnt="${3:-1}"
223   while [ $cnt -gt 0 ]; do
224     [ "${str}" = "${str#*&${name}=}" ] && return 1
225     str="${str#*&${name}=}"
226     cnt=$((cnt - 1))
227   done
228   HEX_DECODE % "$(printf %s "${str%%&*}" |tr + \  )"
229 }
230
231 cgilite_keys(){
232   local str="&$1"
233   while [ "${str#*&}" != "${str}" ]; do
234     str="${str#*&}"
235     printf '%s\n' "${str%%=*}"
236   done \
237   | sort -u
238 }
239
240 # Read arguments from GET, POST, or the query string of the referrer (REF).
241 # Example:
242 # GET varname n
243 #
244 # where n is number for the Nth occurence of a variable and defaults to 1
245 #
246 # *_COUNT varname
247 # -> returns number of ocurences
248 # *_KEYS
249 # -> returns list of available varnames
250
251 GET(){ cgilite_value "${QUERY_STRING}" "$@"; }
252 GET_COUNT(){ cgilite_count "${QUERY_STRING}" $1; }
253 GET_KEYS(){ cgilite_keys "${QUERY_STRING}"; }
254
255 POST(){ cgilite_value "${cgilite_post}" "$@"; }
256 POST_COUNT(){ cgilite_count "${cgilite_post}" $1; }
257 POST_KEYS(){ cgilite_keys "${cgilite_post}"; }
258
259 REF(){ cgilite_value "${HTTP_REFERER#*\?}" "$@"; }
260 REF_COUNT(){ cgilite_count "${HTTP_REFERER#*\?}" $1; }
261 REF_KEYS(){ cgilite_keys "${HTTP_REFERER#*\?}"; }
262
263 HEADER(){
264   # Read value of header line. Use this instead of
265   # referencing HTTP_* environment variables.
266   if [ -n "${cgilite_headers+x}" ]; then
267     local str="${BR}${cgilite_headers}"
268     [ "${str}" = "${str#*${BR}${1}: }" ] && return 1
269     str="${str#*${BR}${1}: }"
270     printf %s "${str%%${BR}*}"
271   else
272     local var="HTTP_$(printf %s "$1" |tr a-z- A-Z_)"
273     eval "[ \"\$$var\" ] && printf %s \"\$$var\" || return 1"
274     # eval "printf %s \"\$HTTP_$(printf %s "${1}" |tr a-z A-Z |tr -c A-Z _)\""
275   fi
276 }
277
278 COOKIE(){
279   # Read value of cookie
280   HEX_DECODE % "$(
281     HEADER Cookie \
282     | grep -oE '(^|; ?)'"$1"'=[^;]*' \
283     | sed -En "${2:-1}"'{s;^[^=]+=;;; s;\+; ;g; p;}'
284   )"
285 }
286
287 HTML(){
288   # Escape HTML cahracters
289   # Also escape [, ], and \n for use in html-sh
290   local str out
291   [ $# -eq 0 ] && str="$(cat)" || str="$*"
292   while [ "$str" ]; do case $str in
293     \&*) out="${out}&";       str="${str#?}";;
294     \<*) out="${out}&lt;";        str="${str#?}";;
295     \>*) out="${out}&gt;";        str="${str#?}";;
296     \"*) out="${out}&quot;";      str="${str#?}";;
297     \'*) out="${out}&#x27;";      str="${str#?}";;
298     \[*) out="${out}&#x5B;";      str="${str#?}";;
299     \]*) out="${out}&#x5D;";      str="${str#?}";;
300     "${CR}"*) out="${out}&#x0D;"; str="${str#?}";;
301     "${BR}"*) out="${out}&#x0A;"; str="${str#?}";;
302     *) out="${out}${str%%[]&<>\"\'${CR}${BR}[]*}"; str="${str#"${str%%[]&<>\"\'${CR}${BR}[]*}"}";;
303   esac; done
304   printf %s "$out"
305 }
306
307 URL(){
308   # Escape pathes, so they can be used in link tags and HTTP Headers
309   local str out
310   [ $# -eq 0 ] && str="$(cat)" || str="$*"
311   while [ "$str" ]; do case $str in
312     \&*) out="${out}%26"; str="${str#?}";;
313     \"*) out="${out}%22"; str="${str#?}";;
314     \'*) out="${out}%27"; str="${str#?}";;
315     \`*) out="${out}%60"; str="${str#?}";;
316     \?*) out="${out}%3F"; str="${str#?}";;
317     \#*) out="${out}%23"; str="${str#?}";;
318     \[*) out="${out}%5B"; str="${str#?}";;
319     \]*) out="${out}%5D"; str="${str#?}";;
320     \ *) out="${out}%20"; str="${str#?}";;
321     "   "*) out="${out}%09"; str="${str#?}";;
322     "${CR}"*) out="${out}%0D"; str="${str#?}";;
323     "${BR}"*) out="${out}%0A"; str="${str#?}";;
324     %*) out="${out}%25"; str="${str#?}";;
325     *) out="${out}${str%%[]&\"\'\?#     ${CR}${BR}%[]*}"; str="${str#"${str%%[]&\"\'\?#         ${CR}${BR}%[]*}"}";;
326   esac; done
327   printf %s "$out"
328 }
329
330 SET_COOKIE(){
331   # Param: session | +seconds | [date]
332   # Param: name=value
333   # Param: Path= | Domain= | Secure
334   local expire cookie
335   case "$1" in
336     ''|0|session) expire='';;
337     [+-][0-9]*)   expire="$(date -R -d @$(($(date +%s) + $1)))";;
338     *)            expire="$(date -R -d "$1")";;
339   esac
340   cookie="$2"
341
342   printf 'Set-Cookie: %s; HttpOnly; SameSite=Lax' "$cookie"
343   [ -n "$expire" ] && printf '; Expires=%s' "${expire%+????}${expire:+GMT}"
344   [ $# -ge 3 ] && shift 2 && printf '; %s' "$@"
345   printf '\r\n'
346 }
347
348 REDIRECT(){
349   # Trigger redirct and terminate script
350   printf '%s: %s\r\n' \
351     Status "303 See Other" \
352     Content-Length 0 \
353     Location "$*"
354   printf '\r\n'
355   exit 0
356 }