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