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