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