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